@hyperdreamer/pi-webui 1.15.0 → 1.15.2
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-BGClPFoI.js → CodeViewer-CHZziPur.js} +1 -1
- package/dist/client/assets/{UnifiedDiffViewer-I9Fc0TRx.js → UnifiedDiffViewer-j1-AFZ8f.js} +1 -1
- package/dist/client/assets/{index-DEhtRZU8.js → index-2RMTbgnM.js} +232 -232
- package/dist/client/index.html +1 -1
- package/package.json +4 -4
|
@@ -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-CHZziPur.js","./vendor-editor-core-vyMPzMNA.js","./vendor-editor-languages-DlEQaRIv.js","./vendor-editor-legacy-CYBnW6ZU.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Y as s,d as c,et as l,f as u,it as d,j as f,l as p,p as m,q as ee,rt as te,tt as ne,u as re}from"./vendor-editor-core-vyMPzMNA.js";import{a as ie,o as ae,s as oe}from"./vendor-editor-languages-DlEQaRIv.js";import{n as se,t as ce}from"./vendor-terminal-D8k4UKM2.js";var le=Object.defineProperty,ue=(e,t)=>{let n={};for(var r in e)le(n,r,{get:e[r],enumerable:!0});return t||le(n,Symbol.toStringTag,{value:`Module`}),n};(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var de=globalThis,fe=de.ShadowRoot&&(de.ShadyCSS===void 0||de.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,pe=Symbol(),me=new WeakMap,he=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==pe)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(fe&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=me.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&me.set(t,e))}return e}toString(){return this.cssText}},ge=e=>new he(typeof e==`string`?e:e+``,void 0,pe),h=(e,...t)=>new he(e.length===1?e[0]:t.reduce((t,n,r)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if(typeof e==`number`)return e;throw Error(`Value passed to 'css' function must be a 'css' function result: `+e+`. Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.`)})(n)+e[r+1],e[0]),e,pe),_e=(e,t)=>{if(fe)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=de.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},ve=fe?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return ge(t)})(e):e,{is:ye,defineProperty:be,getOwnPropertyDescriptor:xe,getOwnPropertyNames:Se,getOwnPropertySymbols:Ce,getPrototypeOf:we}=Object,Te=globalThis,Ee=Te.trustedTypes,De=Ee?Ee.emptyScript:``,Oe=Te.reactiveElementPolyfillSupport,ke=(e,t)=>e,Ae={toAttribute(e,t){switch(t){case Boolean:e=e?De:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let n=e;switch(t){case Boolean:n=e!==null;break;case Number:n=e===null?null:Number(e);break;case Object:case Array:try{n=JSON.parse(e)}catch{n=null}}return n}},je=(e,t)=>!ye(e,t),Me={attribute:!0,type:String,converter:Ae,reflect:!1,useDefault:!1,hasChanged:je};Symbol.metadata??=Symbol(`metadata`),Te.litPropertyMetadata??=new WeakMap;var Ne=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Me){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&be(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=xe(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:r,set(t){let a=r?.call(this);i?.call(this,t),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Me}static _$Ei(){if(this.hasOwnProperty(ke(`elementProperties`)))return;let e=we(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(ke(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(ke(`properties`))){let e=this.properties,t=[...Se(e),...Ce(e)];for(let n of t)this.createProperty(n,e[n])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[e,n]of t)this.elementProperties.set(e,n)}this._$Eh=new Map;for(let[e,t]of this.elementProperties){let n=this._$Eu(e,t);n!==void 0&&this._$Eh.set(n,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let e of n)t.unshift(ve(e))}else e!==void 0&&t.push(ve(e));return t}static _$Eu(e,t){let n=t.attribute;return!1===n?void 0:typeof n==`string`?n:typeof e==`string`?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return _e(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&!0===n.reflect){let i=(n.converter?.toAttribute===void 0?Ae:n.converter).toAttribute(t,n.type);this._$Em=e,i==null?this.removeAttribute(r):this.setAttribute(r,i),this._$Em=null}}_$AK(e,t){let n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){let e=n.getPropertyOptions(r),i=typeof e.converter==`function`?{fromAttribute:e.converter}:e.converter?.fromAttribute===void 0?Ae:e.converter;this._$Em=r;let a=i.fromAttribute(t,e.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(e,t,n,r=!1,i){if(e!==void 0){let a=this.constructor;if(!1===r&&(i=this[e]),n??=a.getPropertyOptions(e),!((n.hasChanged??je)(i,t)||n.useDefault&&n.reflect&&i===this._$Ej?.get(e)&&!this.hasAttribute(a._$Eu(e,n))))return;this.C(e,t,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:r,wrapped:i},a){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,a??t??this[e]),!0!==i||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),!0===r&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}let e=this.constructor.elementProperties;if(e.size>0)for(let[t,n]of e){let{wrapped:e}=n,r=this[t];!0!==e||this._$AL.has(t)||r===void 0||this.C(t,void 0,n,r)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};Ne.elementStyles=[],Ne.shadowRootOptions={mode:`open`},Ne[ke(`elementProperties`)]=new Map,Ne[ke(`finalized`)]=new Map,Oe?.({ReactiveElement:Ne}),(Te.reactiveElementVersions??=[]).push(`2.1.2`);var Pe=globalThis,Fe=e=>e,Ie=Pe.trustedTypes,Le=Ie?Ie.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,Re=`$lit$`,ze=`lit$${Math.random().toFixed(9).slice(2)}$`,Be=`?`+ze,Ve=`<${Be}>`,He=document,Ue=()=>He.createComment(``),We=e=>e===null||typeof e!=`object`&&typeof e!=`function`,Ge=Array.isArray,Ke=e=>Ge(e)||typeof e?.[Symbol.iterator]==`function`,qe=`[
|
|
3
3
|
\f\r]`,Je=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ye=/-->/g,Xe=/>/g,Ze=RegExp(`>|${qe}(?:([^\\s"'>=/]+)(${qe}*=${qe}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),Qe=/'/g,$e=/"/g,et=/^(?:script|style|textarea|title)$/i,tt=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),g=tt(1),_=tt(2),nt=Symbol.for(`lit-noChange`),v=Symbol.for(`lit-nothing`),rt=new WeakMap,it=He.createTreeWalker(He,129);function at(e,t){if(!Ge(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return Le===void 0?t:Le.createHTML(t)}var ot=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=Je;for(let t=0;t<n;t++){let n=e[t],s,c,l=-1,u=0;for(;u<n.length&&(o.lastIndex=u,c=o.exec(n),c!==null);)u=o.lastIndex,o===Je?c[1]===`!--`?o=Ye:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=Ze):(et.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=Ze):o=Xe:o===Ze?c[0]===`>`?(o=i??Je,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?Ze:c[3]===`"`?$e:Qe):o===$e||o===Qe?o=Ze:o===Ye||o===Xe?o=Je:(o=Ze,i=void 0);let d=o===Ze&&e[t+1].startsWith(`/>`)?` `:``;a+=o===Je?n+Ve:l>=0?(r.push(s),n.slice(0,l)+Re+n.slice(l)+ze+d):n+ze+(l===-2?t:d)}return[at(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},st=class e{constructor({strings:t,_$litType$:n},r){let i;this.parts=[];let a=0,o=0,s=t.length-1,c=this.parts,[l,u]=ot(t,n);if(this.el=e.createElement(l,r),it.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=it.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(Re)){let t=u[o++],n=i.getAttribute(e).split(ze),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?ft:r[1]===`?`?pt:r[1]===`@`?mt:dt}),i.removeAttribute(e)}else e.startsWith(ze)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(et.test(i.tagName)){let e=i.textContent.split(ze),t=e.length-1;if(t>0){i.textContent=Ie?Ie.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],Ue()),it.nextNode(),c.push({type:2,index:++a});i.append(e[t],Ue())}}}else if(i.nodeType===8)if(i.data===Be)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(ze,e+1))!==-1;)c.push({type:7,index:a}),e+=ze.length-1}a++}}static createElement(e,t){let n=He.createElement(`template`);return n.innerHTML=e,n}};function ct(e,t,n=e,r){if(t===nt)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=We(t)?void 0:t._$litDirective$;return i?.constructor!==a&&(i?._$AO?.(!1),a===void 0?i=void 0:(i=new a(e),i._$AT(e,n,r)),r===void 0?n._$Cl=i:(n._$Co??=[])[r]=i),i!==void 0&&(t=ct(e,i._$AS(e,t.values),i,r)),t}var lt=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??He).importNode(t,!0);it.currentNode=r;let i=it.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new ut(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new ht(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=it.nextNode(),a++)}return it.currentNode=He,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings===void 0?n._$AI(e[t]):(n._$AI(e,n,t),t+=n.strings.length-2)),t++}},ut=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=v,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=ct(this,e,t),We(e)?e===v||e==null||e===``?(this._$AH!==v&&this._$AR(),this._$AH=v):e!==this._$AH&&e!==nt&&this._(e):e._$litType$===void 0?e.nodeType===void 0?Ke(e)?this.k(e):this._(e):this.T(e):this.$(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==v&&We(this._$AH)?this._$AA.nextSibling.data=e:this.T(He.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n==`number`?this._$AC(e):(n.el===void 0&&(n.el=st.createElement(at(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new lt(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=rt.get(e.strings);return t===void 0&&rt.set(e.strings,t=new st(e)),t}k(t){Ge(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,r,i=0;for(let a of t)i===n.length?n.push(r=new e(this.O(Ue()),this.O(Ue()),this,this.options)):r=n[i],r._$AI(a),i++;i<n.length&&(this._$AR(r&&r._$AB.nextSibling,i),n.length=i)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let t=Fe(e).nextSibling;Fe(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},dt=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=v,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=i,n.length>2||n[0]!==``||n[1]!==``?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=v}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=ct(this,e,t,0),a=!We(e)||e!==this._$AH&&e!==nt,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=ct(this,r[n+o],t,o),s===nt&&(s=this._$AH[o]),a||=!We(s)||s!==this._$AH[o],s===v?e=v:e!==v&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===v?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},ft=class extends dt{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===v?void 0:e}},pt=class extends dt{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==v)}},mt=class extends dt{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=ct(this,e,t,0)??v)===nt)return;let n=this._$AH,r=e===v&&n!==v||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==v&&(n===v||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH==`function`?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},ht=class{constructor(e,t,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){ct(this,e)}},gt={M:Re,P:ze,A:Be,C:1,L:ot,R:lt,D:Ke,V:ct,I:ut,H:dt,N:pt,U:mt,B:ft,F:ht},_t=Pe.litHtmlPolyfillSupport;_t?.(st,ut),(Pe.litHtmlVersions??=[]).push(`3.3.3`);var vt=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new ut(t.insertBefore(Ue(),e),e,void 0,n??{})}return i._$AI(e),i},yt=globalThis,y=class extends Ne{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=vt(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return nt}};y._$litElement$=!0,y.finalized=!0,yt.litElementHydrateSupport?.({LitElement:y});var bt=yt.litElementPolyfillSupport;bt?.({LitElement:y}),(yt.litElementVersions??=[]).push(`4.2.2`);var xt={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},St=e=>(...t)=>({_$litDirective$:e,values:t}),Ct=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}},{I:wt}=gt,Tt=e=>e,Et=()=>document.createComment(``),Dt=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new wt(r.insertBefore(Et(),i),r.insertBefore(Et(),i),e,e.options);else{let t=n._$AB.nextSibling,a=n._$AM,o=a!==e;if(o){let t;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(t=e._$AU)!==a._$AU&&n._$AP(t)}if(t!==i||o){let e=n._$AA;for(;e!==t;){let t=Tt(e).nextSibling;Tt(r).insertBefore(e,i),e=t}}}return n},Ot=(e,t,n=e)=>(e._$AI(t,n),e),kt={},At=(e,t=kt)=>e._$AH=t,jt=e=>e._$AH,Mt=e=>{e._$AR(),e._$AA.remove()},Nt=St(class extends Ct{constructor(){super(...arguments),this.key=v}render(e,t){return this.key=e,t}update(e,[t,n]){return t!==this.key&&(At(e),this.key=t),n}}),b=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},Pt={attribute:!0,type:String,converter:Ae,reflect:!1,hasChanged:je},Ft=(e=Pt,t,n)=>{let{kind:r,metadata:i}=n,a=globalThis.litPropertyMetadata.get(i);if(a===void 0&&globalThis.litPropertyMetadata.set(i,a=new Map),r===`setter`&&((e=Object.create(e)).wrapped=!0),a.set(n.name,e),r===`accessor`){let{name:r}=n;return{set(n){let i=t.get.call(this);t.set.call(this,n),this.requestUpdate(r,i,e,!0,n)},init(t){return t!==void 0&&this.C(r,void 0,e,t),t}}}if(r===`setter`){let{name:r}=n;return function(n){let i=this[r];t.call(this,n),this.requestUpdate(r,i,e,!0,n)}}throw Error(`Unsupported decorator location: `+r)};function x(e){return(t,n)=>typeof n==`object`?Ft(e,t,n):((e,t,n)=>{let r=t.hasOwnProperty(n);return t.constructor.createProperty(n,e),r?Object.getOwnPropertyDescriptor(t,n):void 0})(e,t,n)}function S(e){return x({...e,state:!0,attribute:!1})}var It=(e,t,n)=>(n.configurable=!0,n.enumerable=!0,Reflect.decorate&&typeof t!=`object`&&Object.defineProperty(e,t,n),n);function C(e,t){return(n,r,i)=>{let a=t=>t.renderRoot?.querySelector(e)??null;if(t){let{get:e,set:t}=typeof r==`object`?n:i??(()=>{let e=Symbol();return{get(){return this[e]},set(t){this[e]=t}}})();return It(n,r,{get(){let n=e.call(this);return n===void 0&&(n=a(this),(n!==null||this.hasUpdated)&&t.call(this,n)),n}})}return It(n,r,{get(){return a(this)}})}}var w={sessionsDeleteArchived:`sessions.deleteArchived`,sessionsBulkMutations:`sessions.bulkMutations`,sessionsCleanup:`sessions.cleanup`,sessionsReload:`sessions.reload`,sessionsClearQueue:`sessions.clearQueue`,sessionsMessageActions:`sessions.messageActions`,sessionsSystemPrompt:`sessions.systemPrompt`,sessionsPersistedState:`sessions.persistedState`,sessionsNotifications:`sessions.notifications`,sessionsUnread:`sessions.unread`,promptAttachments:`prompt.attachments`,workspaceFileSuggestions:`workspace.fileSuggestions`,piPackagesManage:`piPackages.manage`,selectedMachineSettings:`settings.selectedMachine`,agentProfileConfig:`settings.agentProfile`,modelTierSettings:`settings.modelTiers`,utilityModelSettings:`settings.utilityModels`,sessionsModelPolicy:`sessions.modelPolicy`,sessionsModelPolicyDefaults:`sessions.modelPolicyDefaults`,sessionsModelPolicyStarterSelection:`sessions.modelPolicyStarterSelection`,sessionsReorder:`sessions.reorder`,projectUsageStatistics:`project.usageStatistics`},Lt=[`economy`,`fast`,`standard`,`advanced`,`capable`,`frontier`],Rt=[`lightweight`,`context`],zt=1e3,Bt=1e3,Vt=32*1024,Ht=8*1024,Ut=1e4;function Wt(e,t=Kt()){let n=new URL(t.viteBaseUrl,t.documentBaseUrl);return new URL(qt(e),n).toString()}function Gt(e,t=Kt()){let n=new URL(Wt(e,t));if(n.protocol===`http:`)n.protocol=`ws:`;else if(n.protocol===`https:`)n.protocol=`wss:`;else throw Error(`Cannot create a WebSocket URL from ${n.protocol}`);return n.toString()}function Kt(){return{viteBaseUrl:`./`,documentBaseUrl:document.baseURI}}function qt(e){return e.startsWith(`/`)?`.${e}`:e}var Jt=class extends Error{constructor(e,t){super(e),this.status=t,this.name=`HttpRequestError`}};async function T(e,t,n){let r=new Headers(n?.headers);n?.body!==void 0&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);let i=await fetch(Wt(e),{...n,headers:r});if(!i.ok)throw new Jt(Yt(await i.json().catch(()=>({})))??i.statusText,i.status);return t(await i.json())}function Yt(e){if(Xt(e))return typeof e.error==`string`?e.error:void 0}function Xt(e){return typeof e==`object`&&!!e}function Zt(e){return(e.split(/[\\/]/u).at(-1)?.toLowerCase()??e.toLowerCase()).replace(/(?:\.[cm]?js|\.exe|\.cmd)$/iu,``)===`pi`}function Qt(e){return!e.includes(`/`)&&!e.includes(`\\`)&&Zt(e)}var $t=new Set([`schemaVersion`,`revision`,`command`,`dir`,`sessionDirEnvKeys`]),en=/^sha256:[0-9a-f]{64}$/u,tn=/^[A-Za-z0-9_][A-Za-z0-9._+-]*$/u,nn=new Set([`PI_WEBUI_AGENT_SESSION_DIR`,`PI_CODING_AGENT_SESSION_DIR`]);function rn(e){if(!ln(e)||Object.keys(e).some(e=>!$t.has(e)))return;let t=e.schemaVersion,n=e.revision,r=e.command,i=e.dir,a=e.sessionDirEnvKeys;if(t===1&&!(typeof n!=`string`||!en.test(n))&&!(typeof r!=`string`||!an(r))&&!(typeof i!=`string`||!on(i))&&cn(a)&&new Set(a).size===a.length&&!(a[0]!==`PI_WEBUI_AGENT_SESSION_DIR`||a.some(e=>!nn.has(e))))return Object.freeze({schemaVersion:t,revision:n,command:r,dir:i,sessionDirEnvKeys:Object.freeze([...a])})}function an(e){return e!==e.trim()||/[\s;&|`$<>]/u.test(e)?!1:on(e)?!e.endsWith(`/`)&&!e.endsWith(`\\`):tn.test(e)}function on(e){if(e===``||e!==e.trim()||sn(e))return!1;let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function sn(e){for(let t of e){let e=t.charCodeAt(0);if(e<32||e===127)return!0}return!1}function cn(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function ln(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var un=Object.values(w),dn=new Set(un);w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsMessageActions,w.sessionsSystemPrompt,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.promptAttachments,w.workspaceFileSuggestions,w.piPackagesManage,w.selectedMachineSettings,w.agentProfileConfig,w.modelTierSettings,w.utilityModelSettings,w.sessionsModelPolicy,w.sessionsModelPolicyDefaults,w.sessionsModelPolicyStarterSelection,w.sessionsReorder,w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsMessageActions,w.sessionsSystemPrompt,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.promptAttachments,w.modelTierSettings,w.utilityModelSettings,w.sessionsModelPolicy,w.sessionsModelPolicyDefaults,w.sessionsModelPolicyStarterSelection,w.sessionsReorder,w.projectUsageStatistics,w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsMessageActions,w.sessionsSystemPrompt,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.promptAttachments,w.workspaceFileSuggestions,w.piPackagesManage,w.selectedMachineSettings,w.agentProfileConfig,w.modelTierSettings,w.utilityModelSettings,w.sessionsModelPolicy,w.sessionsModelPolicyDefaults,w.sessionsModelPolicyStarterSelection,w.sessionsReorder,w.projectUsageStatistics;function fn(e){return typeof e==`string`&&dn.has(e)}function E(e,t){return e?.capabilities?.includes(t)===!0}function pn(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(fn)}var mn=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;function hn(e){return mn.test(e)}function gn(e){try{let t=Intl.getCanonicalLocales(e);return t.length===1?t[0]:void 0}catch{return}}var _n=4e3;function vn(e){return{...e?.voice===void 0?{}:{voice:e.voice},rate:e?.rate??0}}function yn(e){let t=e.replace(/\r\n|\r/gu,`
|
|
4
4
|
`).replace(/(?!\t|\n)\p{Cc}/gu,``),n=t.slice(0,_n);if(n.length===4e3){let e=n.charCodeAt(n.length-1),r=t.charCodeAt(_n);e>=55296&&e<=56319&&r>=56320&&r<=57343&&(n=n.slice(0,-1))}return n.trimEnd()}var bn=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;function xn(e){return bn.test(e)}var Sn=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Cn(e){return Sn.some(t=>t===e)}function wn(e){return e===void 0||e===``?`off`:e}function Tn(e,t){let n=t.length>=2?t:Sn,r=n.length-1,i=wn(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}var En=/^\s*([!#$%&'*+.^_`|~0-9A-Za-z-]+)\/([!#$%&'*+.^_`|~0-9A-Za-z-]+)(?:\s*;\s*([!#$%&'*+.^_`|~0-9A-Za-z-]+)\s*=\s*([!#$%&'*+.^_`|~0-9A-Za-z.-]+))?\s*$/u;function Dn(e){if(e===void 0)return;let t=En.exec(e);if(t===null)return;let n=t[1]?.toLowerCase(),r=t[2]?.toLowerCase(),i=t[3]?.toLowerCase(),a=t[4]?.toLowerCase(),o=n===void 0||r===void 0?void 0:`${n}/${r}`;if(o===`audio/webm`&&i===`codecs`&&a===`opus`)return`audio/webm;codecs=opus`;if(o===`audio/ogg`&&i===`codecs`&&a===`opus`)return`audio/ogg;codecs=opus`;if(o===`audio/mp4`&&i===`codecs`&&a===`mp4a.40.2`)return`audio/mp4;codecs=mp4a.40.2`;if(o===`audio/mp4`&&i===void 0)return`audio/mp4`}function On(e){return typeof e==`object`&&!!e}function D(e){if(!On(e))throw Error(`Expected object response`);return e}function O(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Expected string field: ${t}`);return n}function k(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw Error(`Expected optional string field: ${t}`);return n}}function A(e,t){let n=e[t];if(typeof n!=`number`)throw Error(`Expected number field: ${t}`);return n}function j(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Expected boolean field: ${t}`);return n}function M(e){return t=>{if(!Array.isArray(t))throw Error(`Expected array response`);return t.map(e)}}function kn(e){let t=yr(e,`host speech status`);xr(t,[`available`,`reason`,`voices`],`host speech status`);let n=j(t,`available`),r=Object.hasOwn(t,`reason`)?Ho(t,`reason`):void 0;if(!n&&r===void 0)throw Error(`Unavailable host speech status requires a reason`);let i=An(t.voices);return{available:n,...P(`reason`,r),voices:i}}function An(e){if(!Array.isArray(e))throw Error(`Expected host speech voices array`);let t=e.map(jn),n=new Set;for(let e of t){if(n.has(e.name))throw Error(`Duplicate host speech voice name`);n.add(e.name)}return t}function jn(e){let t=yr(e,`host speech voice`);xr(t,[`name`,`language`,`variant`],`host speech voice`);let n=Object.hasOwn(t,`variant`)?Ho(t,`variant`):void 0;return{name:Ho(t,`name`),language:Ho(t,`language`),...P(`variant`,n)}}function Mn(e){let t=yr(e,`host speech terminal result`);xr(t,[`runId`,`outcome`],`host speech terminal result`);let n=Fn(t,`runId`),r=t.outcome;if(r!==`ended`&&r!==`canceled`)throw Error(`Invalid host speech terminal outcome`);return{runId:n,outcome:r}}function Nn(e){let t=yr(e,`host speech stop response`);return xr(t,[`runId`,`stopped`],`host speech stop response`),{runId:Fn(t,`runId`),stopped:j(t,`stopped`)}}function Pn(e){let t=yr(e,`speech input transcription response`);xr(t,[`text`],`speech input transcription response`);let n=Ho(t,`text`);if(new TextEncoder().encode(n).byteLength>1048576)throw Error(`Speech input transcription exceeds the maximum size`);return{text:n}}function Fn(e,t){let n=O(e,t);if(!xn(n))throw Error(`Invalid host speech run ID field: ${t}`);return n}function In(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function Ln(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function Rn(e){if(!On(e)||typeof e.kind!=`string`)throw Error(`Invalid memory snapshot response`);if(e.kind===`unavailable`)return{kind:`unavailable`};if(e.kind!==`data`)throw Error(`Invalid memory snapshot response`);return{kind:`data`,globalEntries:zn(e.globalEntries),projectEntries:zn(e.projectEntries),...typeof e.projectUnavailableMessage==`string`?{projectUnavailableMessage:e.projectUnavailableMessage}:{}}}function zn(e){if(!Array.isArray(e))throw Error(`Invalid memory snapshot response`);return e.map(e=>{if(!On(e)||typeof e.id!=`string`||typeof e.content!=`string`)throw Error(`Invalid memory snapshot response`);return{id:e.id,content:e.content,...typeof e.category==`string`?{category:e.category}:{},...typeof e.created==`string`?{created:e.created}:{},...typeof e.last==`string`?{last:e.last}:{},...typeof e.failureReason==`string`?{failureReason:e.failureReason}:{}}})}function Bn(e){if(!On(e)||typeof e.kind!=`string`)throw Error(`Invalid learned skills snapshot response`);if(e.kind===`unavailable`)return{kind:`unavailable`};if(e.kind!==`data`)throw Error(`Invalid learned skills snapshot response`);let t=e.projectUnavailableMessage;if(t!==void 0&&typeof t!=`string`)throw Error(`Invalid learned skills snapshot response`);return{kind:`data`,globalSkills:Vn(e.globalSkills),projectSkills:Vn(e.projectSkills),...t===void 0?{}:{projectUnavailableMessage:t}}}function Vn(e){if(!Array.isArray(e))throw Error(`Invalid learned skills snapshot response`);return e.map(Hn)}function Hn(e){let t=D(e),n=N(t,`version`),r=k(t,`created`),i=k(t,`updated`);return{id:O(t,`id`),name:O(t,`name`),description:O(t,`description`),filePath:O(t,`filePath`),...n===void 0?{}:{version:n},...r===void 0?{}:{created:r},...i===void 0?{}:{updated:i}}}function Un(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};let t=D(e);return{messages:In(t.messages),start:A(t,`start`),total:A(t,`total`)}}function Wn(e){let t=D(e);return M(Gn)(t.machines)}function Gn(e){let t=D(e),n=Jn(t,`kind`),r=k(t,`baseUrl`),i=Yn(t,`status`),a=k(t,`statusMessage`);return{id:O(t,`id`),name:O(t,`name`),kind:n,...r===void 0?{}:{baseUrl:r},createdAt:O(t,`createdAt`),updatedAt:O(t,`updatedAt`),...i===void 0?{}:{status:i},...a===void 0?{}:{statusMessage:a}}}function Kn(e){let t=D(e),n=Yn(t,`status`),r=k(t,`error`);return{machineId:O(t,`machineId`),ok:j(t,`ok`),checkedAt:O(t,`checkedAt`),...n===void 0?{}:{status:n},...t.web===void 0?{}:{web:Eo(t.web)},...t.sessiond===void 0?{}:{sessiond:Eo(t.sessiond)},...r===void 0?{}:{error:r}}}function qn(e){let t=D(e),n=k(t,`error`);return{machineId:O(t,`machineId`),ok:j(t,`ok`),checkedAt:O(t,`checkedAt`),...P(`packageName`,k(t,`packageName`)),...P(`generatedAt`,k(t,`generatedAt`)),...t.components===void 0?{}:{components:wo(t.components)},...t.capabilities===void 0?{}:{capabilities:Mo(t.capabilities)},...n===void 0?{}:{error:n}}}function Jn(e,t){let n=O(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function Yn(e,t){let n=k(e,t);if(n!==void 0){if(n!==`unknown`&&n!==`online`&&n!==`offline`&&n!==`error`)throw Error(`Expected machine status field: ${t}`);return n}}function Xn(e){let t=D(e),n=bo(t.pinned,`pinned`);return{id:O(t,`id`),name:O(t,`name`),path:O(t,`path`),createdAt:O(t,`createdAt`),...n===void 0?{}:{pinned:n}}}function Zn(e){let t=D(e),n=O(t,`lastUsedAt`),r=new Date(n);if(!Number.isFinite(r.getTime())||r.toISOString()!==n)throw Error(`Invalid canonical recent project timestamp`);return{id:O(t,`id`),name:O(t,`name`),path:O(t,`path`),lastUsedAt:n}}function Qn(e){let t=Br(e,Zn,20,`recentProjects`),n=new Set,r=new Set;for(let e of t){if(n.has(e.id))throw Error(`Duplicate recent project id`);if(r.has(e.path))throw Error(`Duplicate recent project path`);n.add(e.id),r.add(e.path)}return t}function $n(e){let t=D(e),n=k(t,`branch`);return{id:O(t,`id`),projectId:O(t,`projectId`),path:O(t,`path`),label:O(t,`label`),...n===void 0?{}:{branch:n},isMain:j(t,`isMain`),isGitRepo:j(t,`isGitRepo`),isGitWorktree:j(t,`isGitWorktree`),...P(`effectiveConfig`,er(t.effectiveConfig))}}function er(e){if(e!==void 0){if(!On(e)||Array.isArray(e))throw Error(`Invalid workspace effectiveConfig field`);return{...P(`uploads`,Xa(e.uploads))}}}function tr(e){let t=D(e),n=k(t,`name`),r=bo(t.persisted,`persisted`),i=k(t,`parentSessionPath`),a=k(t,`archivedAt`),o=bo(t.pinned,`pinned`),s=t.creationSource===`session-list-plus`?t.creationSource:void 0,c=t.manualOrder===void 0?void 0:Ur(t,`manualOrder`);return{id:O(t,`id`),path:O(t,`path`),cwd:O(t,`cwd`),...r===void 0?{}:{persisted:r},...n===void 0?{}:{name:n},created:O(t,`created`),modified:O(t,`modified`),messageCount:A(t,`messageCount`),firstMessage:O(t,`firstMessage`),...i===void 0?{}:{parentSessionPath:i},...t.archived===!0?{archived:!0}:{},...a===void 0?{}:{archivedAt:a},...o===void 0?{}:{pinned:o},...s===void 0?{}:{creationSource:s},...c===void 0?{}:{manualOrder:c}}}function nr(e){let t=D(e);return{id:O(t,`id`),cwd:O(t,`cwd`),manualOrder:Ur(t,`manualOrder`)}}function rr(e){let t=D(e);return{orderedSessions:M(nr)(t.orderedSessions)}}function ir(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function ar(e){if(e!==void 0)return{id:O(D(e),`id`)}}function or(e){let t=D(e),n=ar(t.dismiss);return{severity:ir(t.severity),message:O(t,`message`),...P(`source`,k(t,`source`)),...P(`path`,k(t,`path`)),...n===void 0?{}:{dismiss:n}}}function sr(e){return e===void 0?{}:{warnings:M(or)(e)}}function cr(e){let t=D(e);return{sessionId:O(t,`sessionId`),...P(`persisted`,bo(t.persisted,`persisted`)),isStreaming:j(t,`isStreaming`),isCompacting:j(t,`isCompacting`),isBashRunning:j(t,`isBashRunning`),pendingMessageCount:A(t,`pendingMessageCount`),queuedMessages:t.queuedMessages===void 0?[]:M(ni)(t.queuedMessages),...P(`messageCount`,N(t,`messageCount`)),tokens:ri(t.tokens),cost:A(t,`cost`),...Ji(t.generation),...ai(t.model),...P(`modelPolicy`,t.modelPolicy===void 0?void 0:mr(t.modelPolicy)),...Yi(t.contextUsage),...P(`thinkingLevel`,k(t,`thinkingLevel`)),...sr(t.warnings)}}function lr(e){let t=yr(e,`session model policy response`);if(xr(t,[`contractVersion`,`policy`,`session`],`session model policy response`),t.contractVersion!==1)throw Error(`Invalid session model policy contract version`);let n=cr(t.session);if(!Object.hasOwn(t,`policy`)){let e=n.modelPolicy?.blockedReason;if(e===void 0||e.trim()===``)throw Error(`Expected non-blank string field: blockedReason`);return{contractVersion:1,session:n}}return{contractVersion:1,policy:ur(t.policy),session:n}}function ur(e){let t=yr(e,`session model policy`);xr(t,[`mode`,`exact`,`tier`],`session model policy`);let n=_r(t.mode),r=vr(t,`session model policy`);if(n===`tiered`&&r===void 0)throw Error(`Tiered session model policy requires a tier`);return{mode:n,exact:hr(t.exact),...P(`tier`,r)}}function dr(e){let t=yr(e,`starter model policy preference`);xr(t,[`mode`,`tier`],`starter model policy preference`);let n=_r(t.mode),r=vr(t,`starter model policy preference`);if(n===`tiered`&&r===void 0)throw Error(`Tiered starter model policy preference requires a tier`);return{mode:n,...P(`tier`,r)}}function fr(e){let t=yr(e,`starter model policy preference`);return Object.hasOwn(t,`exact`)?pr(t):dr(t)}function pr(e){let t=yr(e,`confirmed starter model policy preference`);xr(t,[`mode`,`exact`,`tier`],`confirmed starter model policy preference`);let n=_r(t.mode),r=vr(t,`confirmed starter model policy preference`);if(n===`tiered`&&r===void 0)throw Error(`Tiered confirmed starter model policy preference requires a tier`);return{mode:n,exact:hr(t.exact),...P(`tier`,r)}}function mr(e){let t=yr(e,`session model policy status`);xr(t,[`mode`,`tier`,`resolved`,`ladderValid`,`blockedReason`],`session model policy status`);let n=_r(t.mode),r=vr(t,`session model policy status`);if(n===`tiered`&&r===void 0)throw Error(`Tiered session model policy status requires a tier`);return{mode:n,...P(`tier`,r),resolved:hr(t.resolved),ladderValid:j(t,`ladderValid`),...P(`blockedReason`,k(t,`blockedReason`))}}function hr(e){let t=yr(e,`exact selection`);return xr(t,[`model`,`thinkingLevel`],`exact selection`),{model:gr(t.model),thinkingLevel:Ho(t,`thinkingLevel`)}}function gr(e){let t=yr(e,`model reference`);return xr(t,[`provider`,`id`],`model reference`),{provider:Ho(t,`provider`),id:Ho(t,`id`)}}function _r(e){if(e!==`exact`&&e!==`tiered`)throw Error(`Invalid session model policy mode`);return e}function vr(e,t){if(!Object.hasOwn(e,`tier`))return;let n=e.tier;if(typeof n!=`string`||!Fa(n))throw Error(`Invalid ${t} tier`);return n}function yr(e,t){if(!br(e))throw Error(`Expected ${t} object`);return e}function br(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Reflect.getPrototypeOf(e);return t===Object.prototype||t===null}function xr(e,t,n){let r=Object.keys(e).find(e=>!t.includes(e));if(r!==void 0)throw Error(`Invalid ${n} field: ${r}`)}function Sr(e){let t=D(e);return{seq:A(t,`seq`),partial:t.partial??null}}function Cr(e){let t=k(D(e),`systemPrompt`);return t===void 0?{}:{systemPrompt:t}}function wr(e){let t=D(e),n=Ur(t,`catalogRevision`),r=Br(t.sessions,Er,Bt,`sessions`);if(Dr(r),Or(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:kr(t,`catalogId`,512),catalogRevision:n,sessions:r}}function Tr(e){let t=D(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=kr(t,`sessionId`,512),r=kr(t,`cwd`,Vt),i=Ar(t,`catalogRevision`),a=t.unread===null?null:Er(t.unread);if(a!==null&&(a.sessionId!==n||a.cwd!==r))throw Error(`Session unread event identity mismatch`);if(a!==null&&a.completionOrder>i)throw Error(`Session unread completion order exceeds catalog revision`);return{type:`sessions.unread`,catalogId:kr(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function Er(e){let t=D(e),n=kr(t,`completedAt`,64),r=new Date(n);if(!Number.isFinite(r.getTime())||r.toISOString()!==n)throw Error(`Invalid canonical session unread completion time`);return{sessionId:kr(t,`sessionId`,512),cwd:kr(t,`cwd`,Vt),completionOrder:Ar(t,`completionOrder`),completedAt:n}}function Dr(e){let t=e.map(e=>JSON.stringify([e.sessionId,e.cwd]));if(new Set(t).size!==t.length)throw Error(`Duplicate session unread identity`);let n=e.map(e=>e.completionOrder);if(new Set(n).size!==n.length)throw Error(`Duplicate session unread completion order`)}function Or(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n===void 0||r===void 0||n.completionOrder<=r.completionOrder)throw Error(`Session unread summaries are not newest-first`)}}function kr(e,t,n){let r=Hr(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function Ar(e,t){let n=Ur(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function jr(e){let t=D(e),n=Nr(t.summary),r=Br(t.notifications,Pr,100,`notifications`);if(Wr(r),Gr(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==qr(r))throw Error(`Notification snapshot severity mismatch`);let i=Fr(t.dismissThrough),a=r[0]?.order??0;if(i.order!==a)throw Error(`Notification snapshot dismiss cutoff mismatch`);if(i.overflowWatermark<n.discardedCount)throw Error(`Notification snapshot overflow cutoff mismatch`);return{daemonInstanceId:Hr(t,`daemonInstanceId`),catalogRevision:Ur(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function Mr(e){let t=D(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=Nr(t.summary),r=Fr(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=Ir(t.delta);if(i.kind===`cleared`&&!Kr(n))throw Error(`Notification clear event summary mismatch`);if(i.kind===`added`&&n.retainedCount===0)throw Error(`Notification add event summary mismatch`);return{type:`notifications.inbox`,daemonInstanceId:Hr(t,`daemonInstanceId`),catalogRevision:Ur(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function Nr(e){let t=D(e),n=Ur(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=Ur(t,`discardedCount`),i=Rr(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:Hr(t,`sessionId`),cwd:Hr(t,`cwd`),inboxRevision:Ur(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function Pr(e){let t=D(e),n=O(t,`message`);if(new TextEncoder().encode(n).byteLength>8192)throw Error(`Notification message exceeds byte limit`);let r=O(t,`receivedAt`);if(!Number.isFinite(Date.parse(r)))throw Error(`Invalid notification receive time`);let i=Ur(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:Hr(t,`id`),message:n,truncated:j(t,`truncated`),severity:Lr(t.severity),receivedAt:r,order:i}}function Fr(e){let t=D(e);return{order:Ur(t,`order`),overflowWatermark:Ur(t,`overflowWatermark`)}}function Ir(e){let t=D(e);switch(t.kind){case`added`:{let e=k(t,`evictedNotificationId`);return{kind:`added`,notification:Pr(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=Br(t.notificationIds,Vr,100,`notificationIds`);if(new Set(e).size!==e.length)throw Error(`Duplicate dismissed notification id`);return{kind:`dismissed`,notificationIds:e}}case`cleared`:return{kind:`cleared`,reason:zr(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function Lr(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function Rr(e){return e===void 0?void 0:Lr(e)}function zr(e){switch(e){case`runtime-close`:case`archive`:case`delete`:case`restore`:case`archive-reconcile`:case`replacement`:case`initialization-failed`:case`service-dispose`:return e;default:throw Error(`Invalid notification clear reason`)}}function Br(e,t,n,r){if(!Array.isArray(e))throw Error(`Expected array field: ${r}`);if(e.length>n)throw Error(`Array field exceeds limit: ${r}`);return e.map(t)}function Vr(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function Hr(e,t){let n=O(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function Ur(e,t){let n=e[t];if(typeof n!=`number`||!Number.isSafeInteger(n)||n<0)throw Error(`Expected non-negative safe integer field: ${t}`);return n}function Wr(e){if(new Set(e.map(e=>e.id)).size!==e.length)throw Error(`Duplicate notification id`);if(new Set(e.map(e=>e.order)).size!==e.length)throw Error(`Duplicate notification order`)}function Gr(e){for(let t=1;t<e.length;t+=1){let n=e[t-1],r=e[t];if(n===void 0||r===void 0||n.order<=r.order)throw Error(`Notifications are not newest-first`)}}function Kr(e){return e.retainedCount===0&&e.discardedCount===0}function qr(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function Jr(e){let t=D(e),n=t.skippedBusySessionIds===void 0?void 0:Ln(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:O(t,`generatedAt`),thresholds:$r(t.thresholds),projects:M(ei)(t.projects),totals:ti(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function Yr(e){let t=D(e);return{...Jr(t),archivedSessionIds:Ln(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:Ln(t.deletedSessionIds,`deletedSessionIds`)}}function Xr(e){let t=D(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:Ln(t.archivedSessionIds,`archivedSessionIds`),failures:M(Qr)(t.failures),generatedAt:O(t,`generatedAt`)}}function Zr(e){let t=D(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:Ln(t.deletedSessionIds,`deletedSessionIds`),failures:M(Qr)(t.failures),generatedAt:O(t,`generatedAt`)}}function Qr(e){let t=D(e);return{sessionId:O(t,`sessionId`),error:O(t,`error`)}}function $r(e){let t=D(e);return{...P(`archiveIdleDays`,N(t,`archiveIdleDays`)),...P(`deleteArchivedDays`,N(t,`deleteArchivedDays`))}}function ei(e){let t=D(e);return{cwd:O(t,`cwd`),archiveCount:A(t,`archiveCount`),deleteCount:A(t,`deleteCount`)}}function ti(e){let t=D(e);return{archiveCount:A(t,`archiveCount`),deleteCount:A(t,`deleteCount`)}}function ni(e){let t=D(e),n=O(t,`kind`);if(n!==`steer`&&n!==`followUp`)throw Error(`Invalid queued message kind`);return{kind:n,text:O(t,`text`)}}function ri(e){let t=D(e);return{input:A(t,`input`),output:A(t,`output`),cacheRead:A(t,`cacheRead`),cacheWrite:A(t,`cacheWrite`),total:A(t,`total`)}}function ii(e){let t=D(e);return{...P(`provider`,k(t,`provider`)),...P(`id`,k(t,`id`)),...P(`name`,k(t,`name`)),...P(`contextWindow`,N(t,`contextWindow`)),...P(`reasoning`,t.reasoning)}}function ai(e){return e===void 0?{}:{model:ii(e)}}function oi(e){let t=D(e);return{models:M(ii)(t.models)}}function si(e){let t=D(e),n=t.starterModelPolicyPreference===void 0?void 0:dr(t.starterModelPolicyPreference),r=k(t,`starterModelPolicyPreferenceError`);if(n!==void 0&&r!==void 0)throw Error(`Session defaults cannot contain both a starter preference and preference error`);return{...t.model===void 0?{}:{model:ii(t.model)},thinkingLevel:O(t,`thinkingLevel`),models:M(ii)(t.models),thinkingLevels:Ln(t.thinkingLevels,`thinkingLevels`),...P(`starterModelPolicyPreference`,n),...P(`starterModelPolicyPreferenceError`,r)}}function ci(e){let t=yr(e,`version-two session defaults response`);if(xr(t,[`starterModelPolicyContractVersion`,`model`,`thinkingLevel`,`models`,`thinkingLevels`,`starterModelPolicyPreference`,`starterModelPolicyPreferenceError`],`version-two session defaults response`),t.starterModelPolicyContractVersion!==2)throw Error(`Invalid starter model policy contract version`);let n=t.starterModelPolicyPreference===void 0?void 0:fr(t.starterModelPolicyPreference),r=k(t,`starterModelPolicyPreferenceError`);if(n!==void 0&&r!==void 0)throw Error(`Session defaults cannot contain both a starter preference and preference error`);return{starterModelPolicyContractVersion:2,...t.model===void 0?{}:{model:ii(t.model)},thinkingLevel:O(t,`thinkingLevel`),models:M(ii)(t.models),thinkingLevels:Ln(t.thinkingLevels,`thinkingLevels`),...P(`starterModelPolicyPreference`,n),...P(`starterModelPolicyPreferenceError`,r)}}function li(e){let t=fi(e,`models configuration`),n=t.providers;if(n===void 0)return{...t,providers:{}};let r=fi(n,`models configuration providers`),i={};for(let[e,t]of Object.entries(r))i[e]=ui(t);return{...t,providers:i}}function ui(e){let t=fi(e,`models configuration provider`),n={};for(let[e,r]of Object.entries(t))n[e]=r;let r=k(t,`baseUrl`);r!==void 0&&(n.baseUrl=r);let i=k(t,`api`);i!==void 0&&(n.api=i);let a=k(t,`apiKey`);a!==void 0&&(n.apiKey=a);let o=pi(t.headers,`models configuration provider headers`);o!==void 0&&(n.headers=mi(o,`models configuration provider headers`));let s=pi(t.compat,`models configuration provider compatibility`);s!==void 0&&(n.compat={...s});let c=pi(t.modelOverrides,`models configuration provider model overrides`);c!==void 0&&(n.modelOverrides={...c});let l=t.models;if(l!==void 0){if(!Array.isArray(l))throw Error(`Expected models configuration models array`);n.models=l.map(di)}return n}function di(e){let t=fi(e,`models configuration model`),n={id:O(t,`id`)};for(let[e,r]of Object.entries(t))n[e]=r;n.id=O(t,`id`);let r=k(t,`name`);r!==void 0&&(n.name=r);let i=k(t,`api`);i!==void 0&&(n.api=i);let a=as(t,`reasoning`);a!==void 0&&(n.reasoning=a);let o=pi(t.thinkingLevelMap,`models configuration thinking level map`);o!==void 0&&(n.thinkingLevelMap=hi(o));let s=t.input;if(s!==void 0){if(!Array.isArray(s)||!s.every(e=>typeof e==`string`))throw Error(`Expected models configuration model input array of strings`);n.input=[...s]}let c=N(t,`contextWindow`);c!==void 0&&(n.contextWindow=c);let l=N(t,`maxTokens`);l!==void 0&&(n.maxTokens=l);let u=pi(t.cost,`models configuration model cost`);u!==void 0&&(n.cost=gi(u));let d=pi(t.compat,`models configuration model compatibility`);return d!==void 0&&(n.compat={...d}),n}function fi(e,t){if(!On(e)||Array.isArray(e))throw Error(`Expected ${t} object`);return e}function pi(e,t){if(e!==void 0)return fi(e,t)}function mi(e,t){let n={};for(let[r,i]of Object.entries(e)){if(typeof i!=`string`)throw Error(`Expected ${t} values to be strings`);n[r]=i}return n}function hi(e){let t={};for(let[n,r]of Object.entries(e)){if(r!==null&&typeof r!=`string`)throw Error(`Expected models configuration thinking level map values to be strings or null`);t[n]=r}return t}function gi(e){let t={};for(let n of[`input`,`output`,`cacheRead`,`cacheWrite`]){let r=e[n];if(r!==void 0){if(typeof r!=`number`)throw Error(`Expected models configuration model cost ${n} to be a number`);t[n]=r}}return t}function _i(e){if(D(e).success!==!0)throw Error(`Expected successful models configuration save`);return{success:!0}}function vi(e){let t=D(e);return{models:M(yi)(t.models)}}function yi(e){let t=D(e),n=O(t,`id`),r=k(t,`name`);return r===void 0?{id:n}:{id:n,name:r}}function bi(e){let t=D(e),n=j(t,`ok`),r=k(t,`error`),i=t.latencyMs===void 0?void 0:A(t,`latencyMs`),a=t.status===void 0?void 0:A(t,`status`),o=k(t,`responseText`);return{ok:n,...r===void 0?{}:{error:r},...i===void 0?{}:{latencyMs:i},...a===void 0?{}:{status:a},...o===void 0?{}:{responseText:o}}}function xi(e){let t=D(e);return{skills:M(Si)(t.skills)}}function Si(e){let t=D(e),n=D(t.sourceInfo),r=k(n,`source`),i=k(n,`scope`);return{name:O(t,`name`),description:O(t,`description`),filePath:O(t,`filePath`),baseDir:O(t,`baseDir`),disableModelInvocation:j(t,`disableModelInvocation`),sourceInfo:{...r===void 0?{}:{source:r},...i===void 0?{}:{scope:i}},...t.install===void 0?{}:{install:Ci(t.install)}}}function Ci(e){let t=D(e),n=k(t,`sourceType`),r=k(t,`skillsShUrl`),i=k(t,`skillPath`),a=k(t,`ref`),o=k(t,`versionHash`);return{package:O(t,`package`),scope:wi(t.scope),source:O(t,`source`),...n===void 0?{}:{sourceType:n},...r===void 0?{}:{skillsShUrl:r},...i===void 0?{}:{skillPath:i},...a===void 0?{}:{ref:a},...o===void 0?{}:{versionHash:o},canCheckForUpdates:j(t,`canCheckForUpdates`)}}function wi(e){if(e!==`global`&&e!==`project`)throw Error(`Expected skill install scope`);return e}function Ti(e){if(D(e).success!==!0)throw Error(`Expected successful Skills mutation`);return{success:!0}}function Ei(e){let t=D(e);return{results:M(Di)(t.results)}}function Di(e){let t=D(e);return{package:O(t,`package`),installs:O(t,`installs`),url:O(t,`url`)}}function Oi(e){let t=D(e);return{updates:M(ki)(t.updates)}}function ki(e){let t=D(e),n=k(t,`currentVersion`),r=k(t,`latestVersion`),i=k(t,`message`);return{package:O(t,`package`),scope:wi(t.scope),state:Ai(t.state),...n===void 0?{}:{currentVersion:n},...r===void 0?{}:{latestVersion:r},...i===void 0?{}:{message:i}}}function Ai(e){if(e!==`up-to-date`&&e!==`update-available`&&e!==`unsupported`&&e!==`error`)throw Error(`Expected skill update state`);return e}function ji(e){let t=D(e);if(t.success!==!0)throw Error(`Expected successful Skills update`);let n=k(t,`output`);return{success:!0,...t.skill===void 0?{}:{skill:Si(t.skill)},...n===void 0?{}:{output:n}}}function Mi(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function Ni(e){let t=D(e);return{levels:M(Mi)(t.levels)}}function Pi(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function Fi(e){if(e!==`stored`&&e!==`runtime`&&e!==`environment`&&e!==`fallback`&&e!==`models_json_key`&&e!==`models_json_command`)throw Error(`Invalid auth status source`);return e}function Ii(e){let t=D(e),n=t.source===void 0?void 0:Fi(t.source);return{configured:j(t,`configured`),...P(`source`,n),...P(`label`,k(t,`label`))}}function Li(e){let t=D(e),n=t.loginFlow;if(n!==void 0&&n!==`interactive`)throw Error(`Invalid auth provider login flow`);return{id:O(t,`id`),name:O(t,`name`),authType:Pi(t.authType),status:Ii(t.status),...n===void 0?{}:{loginFlow:n}}}function Ri(e){let t=D(e);return{providers:M(Li)(t.providers)}}function zi(e){let t=D(e);return{flowId:O(t,`flowId`),providerId:O(t,`providerId`),providerName:O(t,`providerName`),status:Bi(t.status),progress:M(e=>{if(typeof e!=`string`)throw Error(`Expected progress item string`);return e})(t.progress),...P(`error`,k(t,`error`)),...P(`auth`,Vi(t.auth)),...P(`prompt`,Ui(t.prompt)),...P(`select`,Gi(t.select)),...P(`info`,Ki(t.info))}}function Bi(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function Vi(e){if(e===void 0)return;let t=D(e);return{url:O(t,`url`),...P(`instructions`,k(t,`instructions`)),...P(`deviceCode`,Hi(t.deviceCode))}}function Hi(e){if(e===void 0)return;let t=D(e);return{userCode:O(t,`userCode`),...P(`intervalSeconds`,N(t,`intervalSeconds`)),...P(`expiresInSeconds`,N(t,`expiresInSeconds`))}}function Ui(e){if(e===void 0)return;let t=D(e),n=O(t,`kind`);if(n!==`prompt`&&n!==`manual`)throw Error(`Invalid OAuth prompt kind`);let r=t.promptType===void 0?n===`manual`?`manual_code`:`text`:Wi(t.promptType);return{requestId:O(t,`requestId`),message:O(t,`message`),kind:n,promptType:r,...P(`placeholder`,k(t,`placeholder`)),...P(`allowEmpty`,as(t,`allowEmpty`))}}function Wi(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function Gi(e){if(e===void 0)return;let t=D(e);return{requestId:O(t,`requestId`),message:O(t,`message`),options:M(Wo)(t.options)}}function Ki(e){if(e!==void 0)return M(e=>{let t=D(e);return{message:O(t,`message`),...P(`links`,t.links===void 0?void 0:M(qi)(t.links))}})(e)}function qi(e){let t=D(e);return{url:O(t,`url`),...P(`label`,k(t,`label`))}}function Ji(e){if(e===void 0)return{};let t=D(e);return{generation:{outputTokens:A(t,`outputTokens`),...P(`tokensPerSecond`,N(t,`tokensPerSecond`)),...P(`estimated`,as(t,`estimated`))}}}function Yi(e){if(e===void 0)return{};let t=D(e);return{contextUsage:{tokens:os(t,`tokens`),contextWindow:A(t,`contextWindow`),percent:os(t,`percent`)}}}function Xi(e){let t=D(e),n=O(t,`source`);if(n!==`extension`&&n!==`prompt`&&n!==`skill`&&n!==`builtin`)throw Error(`Invalid command source`);return{name:O(t,`name`),source:n,...P(`description`,k(t,`description`))}}function Zi(e){let t=D(e),n=O(t,`kind`);if(n!==`tracked`&&n!==`untracked`&&n!==`other`)throw Error(`Invalid file kind`);return{path:O(t,`path`),kind:n}}function Qi(e){let t=D(e);return{path:O(t,`path`),entries:M($i)(t.entries),scannedAt:O(t,`scannedAt`),truncated:j(t,`truncated`)}}function $i(e){let t=D(e),n=O(t,`type`);if(n!==`file`&&n!==`directory`&&n!==`symlink`)throw Error(`Invalid file tree entry type`);return{name:O(t,`name`),path:O(t,`path`),type:n,...P(`size`,N(t,`size`)),...P(`modifiedAt`,k(t,`modifiedAt`))}}function ea(e){let t=D(e),n=O(t,`encoding`);if(n!==`utf8`)throw Error(`Invalid file encoding`);return{path:O(t,`path`),...P(`language`,k(t,`language`)),...P(`mediaType`,ia(t.mediaType)),...P(`mimeType`,k(t,`mimeType`)),encoding:n,size:A(t,`size`),modifiedAt:O(t,`modifiedAt`),content:O(t,`content`),truncated:j(t,`truncated`),binary:j(t,`binary`)}}function ta(e){let t=D(e);return{path:O(t,`path`),size:A(t,`size`),modifiedAt:O(t,`modifiedAt`),created:j(t,`created`)}}function na(e){let t=D(e);return{path:O(t,`path`),existed:j(t,`existed`)}}function ra(e){let t=D(e);return{fromPath:O(t,`fromPath`),toPath:O(t,`toPath`),size:A(t,`size`),modifiedAt:O(t,`modifiedAt`)}}function ia(e){if(e!==void 0){if(e!==`image`)throw Error(`Invalid file media type`);return e}}function aa(e){let t=D(e);return{isGitRepo:j(t,`isGitRepo`),hash:O(t,`hash`),...P(`branch`,k(t,`branch`)),...P(`latestTag`,k(t,`latestTag`)),...P(`upstream`,k(t,`upstream`)),...P(`ahead`,N(t,`ahead`)),...P(`behind`,N(t,`behind`)),files:M(oa)(t.files)}}function oa(e){let t=D(e);return{path:O(t,`path`),...P(`oldPath`,k(t,`oldPath`)),index:sa(t.index),workingTree:sa(t.workingTree)}}function sa(e){switch(e){case`unmodified`:case`modified`:case`added`:case`deleted`:case`renamed`:case`copied`:case`untracked`:case`ignored`:case`conflicted`:return e;default:throw Error(`Invalid git file state`)}}function ca(e){let t=D(e);return{...P(`path`,k(t,`path`)),staged:j(t,`staged`),hash:O(t,`hash`),diff:O(t,`diff`),truncated:j(t,`truncated`)}}function la(e){let t=D(e);return{id:O(t,`id`),cwd:O(t,`cwd`),name:O(t,`name`),createdAt:O(t,`createdAt`),exited:j(t,`exited`),...P(`exitCode`,N(t,`exitCode`)),...P(`commandRunId`,k(t,`commandRunId`))}}function ua(e){let t=D(e);return{id:O(t,`id`),origin:O(t,`origin`),projectId:O(t,`projectId`),workspaceId:O(t,`workspaceId`),terminalId:O(t,`terminalId`),title:O(t,`title`),command:O(t,`command`),status:da(t.status),...P(`exitCode`,N(t,`exitCode`)),createdAt:O(t,`createdAt`),...P(`startedAt`,k(t,`startedAt`)),...P(`completedAt`,k(t,`completedAt`)),metadata:fa(t.metadata,`metadata`)}}function da(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function fa(e,t){let n=D(e);return Object.fromEntries(Object.entries(n).map(([e,n])=>{if(typeof n!=`string`)throw Error(`Expected string record field: ${t}.${e}`);return[e,n]}))}function pa(e){let t=D(e);return{cwd:O(t,`cwd`),hasSessionActivity:j(t,`hasSessionActivity`),hasTerminalActivity:j(t,`hasTerminalActivity`),updatedAt:O(t,`updatedAt`)}}function ma(e){let t=D(e);return{workspaces:M(pa)(t.workspaces),generatedAt:O(t,`generatedAt`)}}function ha(e){let t=La(e,`utility model settings response`),n=Object.keys(t).find(e=>!va(e));if(n!==void 0)throw Error(`Invalid utility model settings response field: ${n}`);if(t.contractVersion===1)return ga(t);if(t.contractVersion===2)return _a(t);throw Error(`Invalid utility model settings contract version`)}function ga(e){let t=k(e,`configError`);return{contractVersion:1,settings:ya(e.settings),models:M(Sa)(e.models),slots:wa(e.slots),valid:j(e,`valid`),...P(`configError`,t)}}function _a(e){let t=k(e,`configError`);return{contractVersion:2,settings:ba(e.settings),models:M(Ca)(e.models),slots:wa(e.slots),valid:j(e,`valid`),...P(`configError`,t)}}function va(e){return e===`contractVersion`||e===`settings`||e===`models`||e===`slots`||e===`valid`||e===`configError`}function ya(e){let t=La(e,`settings`),n=Object.keys(t).find(e=>!Ea(e));if(n!==void 0)throw Error(`Invalid utility model settings field: settings.${n}`);return{...P(`lightweight`,t.lightweight===void 0?void 0:ja(t.lightweight,`settings.lightweight`)),...P(`context`,t.context===void 0?void 0:ja(t.context,`settings.context`))}}function ba(e){let t=La(e,`settings`),n=Object.keys(t).find(e=>!Ea(e));if(n!==void 0)throw Error(`Invalid utility model settings field: settings.${n}`);return{...P(`lightweight`,t.lightweight===void 0?void 0:xa(t.lightweight,`settings.lightweight`)),...P(`context`,t.context===void 0?void 0:xa(t.context,`settings.context`))}}function xa(e,t){let n=La(e,t),r=Object.keys(n).find(e=>e!==`provider`&&e!==`id`&&e!==`thinkingLevel`);if(r!==void 0)throw Error(`Invalid utility model binding field: ${t}.${r}`);let i=Hr(n,`provider`),a=Hr(n,`id`),o=k(n,`thinkingLevel`);if(o===void 0)return{provider:i,id:a};if(!Cn(o))throw Error(`Invalid utility model thinking level: ${t}.thinkingLevel`);return{provider:i,id:a,thinkingLevel:o}}function Sa(e){let t=La(e,`models`),n=Object.keys(t).find(e=>e!==`model`&&e!==`name`);if(n!==void 0)throw Error(`Invalid utility model option field: models.${n}`);return{model:ja(t.model,`models.model`),...P(`name`,k(t,`name`))}}function Ca(e){let t=La(e,`models`),n=Object.keys(t).find(e=>e!==`model`&&e!==`name`&&e!==`thinkingLevels`);if(n!==void 0)throw Error(`Invalid utility model option field: models.${n}`);let r=Ln(t.thinkingLevels,`models.thinkingLevels`).map(e=>{if(!Cn(e))throw Error(`Invalid utility model thinking levels: models.thinkingLevels`);return e});return{model:ja(t.model,`models.model`),...P(`name`,k(t,`name`)),thinkingLevels:r}}function wa(e){let t=Da(e,`slots`);return{lightweight:Ta(t.lightweight,`slots.lightweight`),context:Ta(t.context,`slots.context`)}}function Ta(e,t){let n=La(e,t),r=Object.keys(n).find(e=>e!==`valid`&&e!==`reason`);if(r!==void 0)throw Error(`Invalid utility model validation field: ${t}.${r}`);return{valid:j(n,`valid`),...P(`reason`,k(n,`reason`))}}function Ea(e){return Rt.some(t=>t===e)}function Da(e,t){let n=La(e,t),r=Object.keys(n).find(e=>!Ea(e));if(r!==void 0)throw Error(`Invalid utility model ${t} field: unknown slot ${r}`);let i=Rt.find(e=>n[e]===void 0);if(i!==void 0)throw Error(`Invalid utility model ${t} field: missing slot ${i}`);return n}function Oa(e){let t=D(e);if(t.contractVersion!==1)throw Error(`Invalid model-tier settings contract version`);let n=t.ladder===void 0?void 0:ka(t.ladder),r=k(t,`configError`);return{contractVersion:1,...P(`ladder`,n),models:M(Ma)(t.models),rows:Na(t.rows),valid:j(t,`valid`),...P(`configError`,r)}}function ka(e){let t=Ia(e,`ladder`);return{economy:Aa(t.economy,`ladder.economy`),fast:Aa(t.fast,`ladder.fast`),standard:Aa(t.standard,`ladder.standard`),advanced:Aa(t.advanced,`ladder.advanced`),capable:Aa(t.capable,`ladder.capable`),frontier:Aa(t.frontier,`ladder.frontier`)}}function Aa(e,t){let n=La(e,t),r=Object.keys(n).find(e=>e!==`model`&&e!==`thinkingLevel`);if(r!==void 0)throw Error(`Invalid model-tier entry field: ${t}.${r}`);return{model:ja(n.model,`${t}.model`),thinkingLevel:Hr(n,`thinkingLevel`)}}function ja(e,t){let n=La(e,t),r=Object.keys(n).find(e=>e!==`provider`&&e!==`id`);if(r!==void 0)throw Error(`Invalid model reference field: ${t}.${r}`);return{provider:Hr(n,`provider`),id:Hr(n,`id`)}}function Ma(e){let t=La(e,`models`);return{model:ja(t.model,`models.model`),...P(`name`,k(t,`name`)),thinkingLevels:Ln(t.thinkingLevels,`models.thinkingLevels`)}}function Na(e){let t=Ia(e,`rows`);return{economy:Pa(t.economy,`rows.economy`),fast:Pa(t.fast,`rows.fast`),standard:Pa(t.standard,`rows.standard`),advanced:Pa(t.advanced,`rows.advanced`),capable:Pa(t.capable,`rows.capable`),frontier:Pa(t.frontier,`rows.frontier`)}}function Pa(e,t){let n=La(e,t),r=Object.keys(n).find(e=>e!==`valid`&&e!==`reason`);if(r!==void 0)throw Error(`Invalid model-tier row field: ${t}.${r}`);return{valid:j(n,`valid`),...P(`reason`,k(n,`reason`))}}function Fa(e){return Lt.some(t=>t===e)}function Ia(e,t){let n=La(e,t),r=Object.keys(n).find(e=>!Fa(e));if(r!==void 0)throw Error(`Invalid model-tier ${t} field: unknown tier ${r}`);let i=Lt.find(e=>n[e]===void 0);if(i!==void 0)throw Error(`Invalid model-tier ${t} field: missing tier ${i}`);return n}function La(e,t){if(!On(e)||Array.isArray(e))throw Error(`Expected object field: ${t}`);return e}function Ra(e){let t=D(e);return{path:O(t,`path`),exists:j(t,`exists`),config:Wa(t.config),effectiveConfig:Wa(t.effectiveConfig),envOverrides:to(t.envOverrides)}}function za(e){let t=yr(e,`speech input settings response`);if(xr(t,[`contractVersion`,`revision`,`settings`,`credential`],`speech input settings response`),t.contractVersion!==1)throw Error(`Invalid speech input settings contract version`);let n=O(t,`revision`);if(!hn(n))throw Error(`Invalid speech input settings revision`);return{contractVersion:1,revision:n,settings:Ba(t.settings),credential:Ua(t.credential)}}function Ba(e){let t=La(e,`speech input settings`);xr(t,[`provider`,`language`,`cloud`],`speech input settings`);let n=t.provider;if(n!==`auto`&&n!==`browser`&&n!==`cloud`)throw Error(`Invalid speech input settings provider`);let r=k(t,`language`);if(r!==void 0&&gn(r)!==r)throw Error(`Invalid speech input settings language`);return{provider:n,...P(`language`,r),cloud:Va(t.cloud)}}function Va(e){let t=La(e,`speech input cloud settings`);xr(t,[`baseUrl`,`model`],`speech input cloud settings`);let n=Ho(t,`baseUrl`);if(!Ha(n))throw Error(`Invalid speech input cloud base URL`);return{baseUrl:n,model:Ho(t,`model`)}}function Ha(e){try{let t=new URL(e);return t.protocol===`https:`&&t.username===``&&t.password===``&&t.search===``&&t.hash===``}catch{return!1}}function Ua(e){let t=La(e,`speech input credential status`);xr(t,[`configured`,`source`,`resolution`],`speech input credential status`);let n=j(t,`configured`),r=t.source,i=t.resolution;if(typeof i!=`string`)throw Error(`Invalid speech input credential status`);if(!n){if(r!==void 0||i!==`missing`)throw Error(`Invalid speech input credential status`);return{configured:!1,resolution:`missing`}}if(r!==`literal`&&r!==`environment`&&r!==`command`)throw Error(`Invalid speech input credential status`);if(r===`command`){if(i!==`unchecked`)throw Error(`Invalid speech input credential status`)}else if(r===`literal`){if(i!==`resolved`)throw Error(`Invalid speech input credential status`)}else if(i!==`resolved`&&i!==`unresolved`)throw Error(`Invalid speech input credential status`);return{configured:!0,source:r,resolution:i}}function Wa(e){let t=D(e);return{...P(`host`,k(t,`host`)),...P(`port`,N(t,`port`)),...P(`allowedHosts`,qa(t.allowedHosts)),...P(`shortcuts`,$a(t.shortcuts)),...P(`plugins`,eo(t.plugins)),...P(`pathAccess`,Ja(t.pathAccess)),...P(`uploads`,Xa(t.uploads)),...P(`maxUploadBytes`,N(t,`maxUploadBytes`)),...P(`agent`,Ga(t.agent)),...P(`tts`,Ka(t.tts)),...P(`spawnSessions`,as(t,`spawnSessions`)),...P(`subsessions`,as(t,`subsessions`))}}function Ga(e){if(e!==void 0){if(!On(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI agent field`);return{...P(`command`,k(e,`command`)),...P(`dir`,k(e,`dir`))}}}function Ka(e){if(e===void 0)return;if(!On(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI tts field`);xr(e,[`voice`,`rate`],`PI WEBUI tts`);let t=k(e,`voice`)?.trim();if(t===``)throw Error(`Invalid PI WEBUI tts voice field`);let n=N(e,`rate`);if(n!==void 0&&(!Number.isInteger(n)||n<-100||n>100))throw Error(`Invalid PI WEBUI tts rate field`);return{...P(`voice`,t),...P(`rate`,n)}}function qa(e){if(e!==void 0){if(e===!0)return!0;if(Za(e))return e;throw Error(`Invalid PI WEBUI allowedHosts field`)}}function Ja(e){if(e===void 0)return;if(!On(e))throw Error(`Invalid PI WEBUI pathAccess field`);let t=e.allowedPaths;return{...P(`allowedPaths`,Ya(t,`pathAccess.allowedPaths`))}}function Ya(e,t){if(e!==void 0){if(Qa(e))return e;throw Error(`Invalid PI WEBUI ${t} field`)}}function Xa(e){if(e!==void 0){if(!On(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI uploads field`);return{...P(`defaultFolder`,k(e,`defaultFolder`))}}}function Za(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Qa(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function $a(e){if(e!==void 0){if(!On(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI shortcuts field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(t!==null&&(typeof t!=`string`||t===``))throw Error(`Invalid PI WEBUI shortcut field`);return[e,t]}))}}function eo(e){if(e!==void 0){if(!On(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!On(t)||Array.isArray(t))throw Error(`Invalid PI WEBUI plugin config field`);let n=t.enabled;if(n!==void 0&&typeof n!=`boolean`)throw Error(`Invalid PI WEBUI plugin enabled field`);let r=t.settings;if(r!==void 0&&(!On(r)||Array.isArray(r)))throw Error(`Invalid PI WEBUI plugin settings field`);return[e,t]}))}}function to(e){let t=D(e);return{host:j(t,`host`),port:j(t,`port`),allowedHosts:j(t,`allowedHosts`),spawnSessions:j(t,`spawnSessions`),subsessions:j(t,`subsessions`),agentCommand:as(t,`agentCommand`)??!1,agentDir:as(t,`agentDir`)??!1,...no(t),agentSessionDir:as(t,`agentSessionDir`)??!1}}function no(e){let t=e.agentDirSource;if(t===void 0)return{};if(t!==`pi-webui`&&t!==`pi-compatibility`)throw Error(`Invalid PI WEBUI agentDirSource field`);return{agentDirSource:t}}function ro(e){let t=D(e);return{packages:M(ao)(t.packages)}}function io(e){let t=D(e),n=k(t,`source`),r=t.scope===void 0?void 0:oo(t.scope),i=bo(t.removed,`removed`);return{action:so(t.action),...P(`source`,n),...P(`scope`,r),...P(`removed`,i),packages:M(ao)(t.packages)}}function ao(e){let t=D(e);return{source:O(t,`source`),scope:oo(t.scope),filtered:j(t,`filtered`),...P(`installedPath`,k(t,`installedPath`))}}function oo(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function so(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function co(e){let t=D(e);return{packages:M(lo)(t.packages),totals:po(t.totals),diagnostics:M(go)(t.diagnostics)}}function lo(e){let t=D(e);return{source:O(t,`source`),scope:uo(t.scope),filtered:j(t,`filtered`),disabled:j(t,`disabled`),...P(`installedPath`,k(t,`installedPath`)),...P(`packageName`,k(t,`packageName`)),...P(`version`,k(t,`version`)),...P(`configuredVersion`,k(t,`configuredVersion`)),counts:po(t.counts),resources:M(mo)(t.resources),status:fo(t.status)}}function uo(e){if(e!==`global`&&e!==`project`)throw Error(`Invalid Pi package plugin scope`);return e}function fo(e){if(e!==`loaded`&&e!==`installed`&&e!==`missing`&&e!==`disabled`)throw Error(`Invalid Pi package plugin status`);return e}function po(e){let t=D(e);return{extensions:A(t,`extensions`),skills:A(t,`skills`),prompts:A(t,`prompts`),themes:A(t,`themes`)}}function mo(e){let t=D(e);return{kind:ho(t.kind),name:O(t,`name`),path:O(t,`path`),relativePath:O(t,`relativePath`)}}function ho(e){if(e!==`extension`&&e!==`skill`&&e!==`prompt`&&e!==`theme`)throw Error(`Invalid Pi package plugin resource kind`);return e}function go(e){let t=D(e),n=t.type;if(n!==`warning`&&n!==`error`)throw Error(`Invalid Pi package plugin diagnostic type`);return{type:n,message:O(t,`message`),...P(`source`,k(t,`source`)),...P(`path`,k(t,`path`))}}function _o(e){let t=D(e);return{plugins:M(vo)(t.plugins)}}function vo(e){let t=D(e);return{id:O(t,`id`),module:O(t,`module`),source:O(t,`source`),scope:yo(t.scope),machineSpecific:bo(t.machineSpecific,`machineSpecific`)??!1,enabled:j(t,`enabled`)}}function yo(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEBUI plugin scope`);return e}function bo(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function xo(e){let t=D(e);return{packageName:O(t,`packageName`),generatedAt:O(t,`generatedAt`),components:Co(t.components),release:Oo(t.release),commands:ko(t.commands),messages:M(Ao)(t.messages)}}function So(e){let t=D(e);return{packageName:O(t,`packageName`),generatedAt:O(t,`generatedAt`),components:wo(t.components),capabilities:Mo(t.capabilities)}}function Co(e){let t=D(e);return{web:Eo(t.web),sessiond:Eo(t.sessiond)}}function wo(e){let t=D(e);return{web:To(t.web),sessiond:To(t.sessiond)}}function To(e){let t=D(e),n=jo(t.component),r=t.activeAgentProfile,i=r===void 0?void 0:rn(r);if(r!==void 0&&(n!==`sessiond`||i===void 0))throw Error(`Invalid active agent profile descriptor`);return{component:n,label:O(t,`label`),...P(`runtimeVersion`,k(t,`runtimeVersion`)),available:j(t,`available`),capabilities:Mo(t.capabilities),...P(`activeAgentProfile`,i),...P(`error`,k(t,`error`))}}function Eo(e){let t=D(e);return{component:jo(t.component),label:O(t,`label`),...P(`runtimeVersion`,k(t,`runtimeVersion`)),...P(`installedVersion`,k(t,`installedVersion`)),stale:j(t,`stale`),available:j(t,`available`),...P(`installation`,Do(t.installation)),...P(`error`,k(t,`error`))}}function Do(e){if(e===void 0)return;let t=D(e),n=O(t,`kind`);if(n!==`pi-package`&&n!==`npm-global`&&n!==`local`&&n!==`docker`&&n!==`unknown`)throw Error(`Invalid PI WEBUI installation kind`);let r=t.scope;if(r!==void 0&&r!==`user`&&r!==`project`)throw Error(`Invalid PI WEBUI installation scope`);let i=t.dockerMode;if(i!==void 0&&i!==`runtime`&&i!==`dev`)throw Error(`Invalid PI WEBUI Docker mode`);return{kind:n,...P(`path`,k(t,`path`)),...P(`source`,k(t,`source`)),...r===void 0?{}:{scope:r},...P(`npmRoot`,k(t,`npmRoot`)),...i===void 0?{}:{dockerMode:i}}}function Oo(e){let t=D(e);return{packageName:O(t,`packageName`),...P(`latestVersion`,k(t,`latestVersion`)),updateAvailable:j(t,`updateAvailable`),...P(`checkedAt`,k(t,`checkedAt`)),...t.skipped===!0?{skipped:!0}:{},...P(`error`,k(t,`error`))}}function ko(e){let t=D(e);return{...P(`update`,k(t,`update`)),...P(`restart`,k(t,`restart`)),...P(`restartWeb`,k(t,`restartWeb`)),...P(`restartSessiond`,k(t,`restartSessiond`)),...P(`status`,k(t,`status`))}}function Ao(e){let t=D(e);return{id:O(t,`id`),severity:No(t.severity),title:O(t,`title`),body:O(t,`body`),...P(`command`,k(t,`command`))}}function jo(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEBUI service component`);return e}function Mo(e){let t=pn(e);if(t===void 0)throw Error(`Invalid PI WEBUI capabilities`);return t}function No(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEBUI status severity`);return e}function Po(e){let t=D(e),n=O(t,`type`);if(n===`unsupported`)return{type:n,message:O(t,`message`)};if(n===`select`)return{type:n,requestId:O(t,`requestId`),title:O(t,`title`),options:M(Wo)(t.options)};if(n===`tree`)return{type:n,tree:Fo(t.tree)};if(n===`done`)return{type:n,...P(`message`,k(t,`message`)),...Go(t.session),...P(`promptDraft`,k(t,`promptDraft`))};throw Error(`Invalid command result type`)}function Fo(e){let t=D(e),n=M(Io)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=Vo(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:Uo(t.activePathIds,`activePathIds`)}}function Io(e){let t=D(e);return{id:Ho(t,`id`),parentId:Vo(t,`parentId`),kind:Lo(t.kind),summary:O(t,`summary`),...P(`timestamp`,k(t,`timestamp`)),...P(`label`,k(t,`label`))}}function Lo(e){switch(e){case`user`:case`assistant`:case`tool-result`:case`bash`:case`custom-message`:case`compaction`:case`branch-summary`:case`model-change`:case`thinking-level-change`:case`session-info`:case`label`:case`custom`:case`other`:return e;default:throw Error(`Invalid session tree node kind`)}}function Ro(e){let t=D(e),n=j(t,`cancelled`);if(Object.hasOwn(t,`summaryEntry`))throw Error(`Invalid session tree navigation result field: summaryEntry`);if(n){Bo(t,`editorText`,`session tree cancellation result`);let e=t.aborted;if(e!==void 0&&typeof e!=`boolean`)throw Error(`Expected optional boolean field: aborted`);return{cancelled:n,...e===void 0?{}:{aborted:e}}}return Bo(t,`aborted`,`session tree navigation result`),{cancelled:n,...P(`editorText`,k(t,`editorText`))}}function zo(e){let t=D(e);return j(t,`cancelled`)?(Bo(t,`session`,`session fork cancellation result`),{cancelled:!0}):{cancelled:!1,session:tr(t.session)}}function Bo(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function Vo(e,t){let n=e[t];if(n!==null&&typeof n!=`string`)throw Error(`Expected string or null field: ${t}`);if(typeof n==`string`&&n.trim()===``)throw Error(`Expected non-blank string or null field: ${t}`);return n}function Ho(e,t){let n=O(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function Uo(e,t){let n=Ln(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function Wo(e){let t=D(e);return{value:O(t,`value`),label:O(t,`label`),...P(`description`,k(t,`description`))}}function Go(e){return e===void 0?{}:{session:tr(e)}}function Ko(e){if(D(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function qo(e){let t=D(e);return M(Jo)(t.attachments)}function Jo(e){let t=D(e);return{path:O(t,`path`),mimeType:O(t,`mimeType`),size:A(t,`size`)}}function Yo(e){if(D(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function Xo(e){if(typeof e!=`string`)throw Error(`Expected string value`);return e}function Zo(e){let t=D(e);return{closedProjectIds:M(Xo)(t.closedProjectIds)}}function Qo(e){if(D(e).aborted!==!0)throw Error(`Expected aborted response`);return{aborted:!0}}function $o(e){if(D(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function es(e){let t=D(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:Ln(t.sessionIds,`sessionIds`),r=N(t,`archivedCount`),i=N(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function ts(e){if(D(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function ns(e){if(D(e).deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0}}function rs(e){if(D(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function is(e){if(D(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function as(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEBUI ${t} field`);return n}}function N(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function os(e,t){let n=e[t];if(n===null)return null;if(typeof n!=`number`)throw Error(`Expected number|null field: ${t}`);return n}function P(e,t){return t===void 0?{}:{[e]:t}}function ss(e){let t=D(e),n=D(t.memory),r=D(t.network);return{generatedAt:O(t,`generatedAt`),memory:{totalBytes:A(n,`totalBytes`),usedBytes:A(n,`usedBytes`),freeBytes:A(n,`freeBytes`),usagePercent:A(n,`usagePercent`)},network:us(r)}}function cs(e){let t=D(e),n=D(t.os),r=D(t.cpu),i=D(t.memory),a=D(t.network),o=t.gpu,s;if(o!=null){let e=D(o),t={name:O(e,`name`)},n=k(e,`driverVersion`);n!==void 0&&(t.driverVersion=n);let r=N(e,`memoryTotalBytes`);r!==void 0&&(t.memoryTotalBytes=r);let i=N(e,`memoryUsedBytes`);i!==void 0&&(t.memoryUsedBytes=i);let a=N(e,`utilizationPercent`);a!==void 0&&(t.utilizationPercent=a);let c=N(e,`temperatureCelsius`);c!==void 0&&(t.temperatureCelsius=c),s=t}let c={generatedAt:O(t,`generatedAt`),os:{platform:O(n,`platform`),release:O(n,`release`),arch:O(n,`arch`),uptimeSeconds:A(n,`uptimeSeconds`)},cpu:{model:O(r,`model`),cores:A(r,`cores`),usagePercent:A(r,`usagePercent`)},memory:{totalBytes:A(i,`totalBytes`),usedBytes:A(i,`usedBytes`),freeBytes:A(i,`freeBytes`),usagePercent:A(i,`usagePercent`)},network:ls(a)};s!==void 0&&(c.gpu=s);let l=k(t,`piVersion`);l!==void 0&&(c.piVersion=l);let u=k(t,`piWebUiVersion`);return u!==void 0&&(c.piWebUiVersion=u),c}function ls(e){let t={hostname:O(e,`hostname`),localIpv4Addresses:Ln(e.localIpv4Addresses,`localIpv4Addresses`),...us(e)},n=k(e,`publicIpv4`);n!==void 0&&(t.publicIpv4=n);let r=k(e,`publicIpv6`);return r!==void 0&&(t.publicIpv6=r),t}function us(e){let t={},n=N(e,`downloadSpeedBytesPerSecond`);n!==void 0&&(t.downloadSpeedBytesPerSecond=n);let r=N(e,`uploadSpeedBytesPerSecond`);return r!==void 0&&(t.uploadSpeedBytesPerSecond=r),t}function ds(e){let t=yr(e,`project usage count response`);return xr(t,[`sessionCount`],`project usage count response`),{sessionCount:Ur(t,`sessionCount`)}}function fs(e){let t=D(e);return{input:A(t,`input`),output:A(t,`output`),cacheRead:A(t,`cacheRead`),cacheWrite:A(t,`cacheWrite`),cost:A(t,`cost`),sessionCount:A(t,`sessionCount`)}}function ps(e){let t=D(e),n=D(t.buckets);return{projectPath:O(t,`projectPath`),buckets:{live:fs(n.live),retired:fs(n.retired),archived:fs(n.archived)},total:fs(t.total),generatedAt:O(t,`generatedAt`)}}function ms(e){return typeof e==`string`?e:e.id}function hs(e){return typeof e==`string`?void 0:e.cwd}function gs(e,t,n,r){let i=new URLSearchParams;r?.path!==void 0&&i.set(`path`,r.path),r?.staged===!0&&i.set(`staged`,`true`);let a=i.toString();return`api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(n)}/git/diff${a?`?${a}`:``}`}function _s(e,t,n=`local`){let r=new URLSearchParams,i=hs(e);i!==void 0&&i!==``&&r.set(`cwd`,i),t?.limit!==void 0&&r.set(`limit`,String(t.limit)),t?.before!==void 0&&r.set(`before`,String(t.before));let a=r.toString();return`api/machines/${encodeURIComponent(n)}/sessions/${encodeURIComponent(ms(e))}/messages${a===``?``:`?${a}`}`}function vs(e,t=`local`){let n=new URLSearchParams,r=hs(e);r!==void 0&&r!==``&&n.set(`cwd`,r);let i=n.toString();return`api/machines/${encodeURIComponent(t)}/sessions/${encodeURIComponent(ms(e))}/export${i===``?``:`?${i}`}`}function ys(e,t,n,r){let i=new URLSearchParams({path:n});return r?.createDirs===!1&&i.set(`createDirs`,`false`),r?.overwrite===!1&&i.set(`overwrite`,`false`),Wt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`)}function bs(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),Wt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`)}var F=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`,xs=e=>e===void 0?void 0:{signal:e};function Ss(e){return typeof e==`string`?e:e.id}function Cs(e){return typeof e==`string`?void 0:e.cwd}function ws(e,t=`local`){return`${F(t)}/sessions/${encodeURIComponent(Ss(e))}`}function I(e,t,n=`local`){return`${ws(e,n)}/${t}`}function Ts(e,t,n=`local`){return`${I(e,t,n)}${Ds(e)}`}function Es(e,t=`local`){return`${ws(e,t)}${Ds(e)}`}function Ds(e){let t=Cs(e);return t===void 0||t===``?``:`?${new URLSearchParams({cwd:t}).toString()}`}function L(e,t={}){let n=Cs(e);return JSON.stringify(n===void 0||n===``?t:{cwd:n,...t})}function Os(e){return JSON.stringify({sessions:e.map(ks)})}function ks(e){let t=Ss(e),n=Cs(e);return n===void 0||n===``?{id:t}:{id:t,cwd:n}}function As(e){return e===`local`?`api/pi-webui/status`:`${F(e)}/pi-webui/status`}var js={piWebUiStatus:(e=`local`)=>T(As(e),xo),checkForUpdates:(e=`local`)=>T(`${As(e)}?refresh=1`,xo,{cache:`no-store`}),piWebUiRuntime:()=>T(`api/pi-webui/runtime`,So),systemInfo:(e=`local`)=>T(`${F(e)}/pi-webui/system-info`,cs),systemMetrics:(e=`local`)=>T(`${F(e)}/pi-webui/system-metrics`,ss,{cache:`no-store`})},Ms={status:()=>T(`api/tts`,kn,{cache:`no-store`}),speak:(e,t)=>T(`api/tts/speak`,Mn,{method:`POST`,body:JSON.stringify(e),...t===void 0?{}:{signal:t}}),stop:e=>T(`api/tts/stop`,Nn,{method:`POST`,body:JSON.stringify({runId:e})})},Ns={settings:()=>T(`api/speech-input/settings`,za,{cache:`no-store`}),saveSettings:e=>T(`api/speech-input/settings`,za,{method:`PUT`,body:JSON.stringify(e)}),transcribe:(e,t,n)=>T(`api/speech-input/transcribe`,Pn,{method:`POST`,body:e,headers:{"content-type":t},...n===void 0?{}:{signal:n}})},Ps={machines:()=>T(`api/machines`,Wn),addMachine:e=>T(`api/machines`,Gn,{method:`POST`,body:JSON.stringify(e)}),deleteMachine:e=>T(`api/machines/${encodeURIComponent(e)}`,e=>e,{method:`DELETE`}),health:e=>T(`api/machines/${encodeURIComponent(e)}/health`,Kn),runtime:(e,t=!1)=>T(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,qn,t?{cache:`no-store`}:{})};function Fs(e,t=`local`){let n=new URLSearchParams({projectPath:e});return`${F(t)}/agent-memory/snapshot?${n.toString()}`}var Is={snapshot:(e,t=`local`)=>T(Fs(e,t),Rn,{cache:`no-store`})};function Ls(e,t=`local`){let n=new URLSearchParams({projectPath:e});return`${F(t)}/agent-skills/snapshot?${n.toString()}`}var Rs={snapshot:(e,t=`local`)=>T(Ls(e,t),Bn,{cache:`no-store`})};function zs(e){return e===void 0?`api/config`:`${F(e)}/config`}function Bs(e){return e===void 0?`api/plugins`:`${F(e)}/plugins`}var Vs={config:e=>T(zs(e),Ra),saveConfig:(e,t)=>T(zs(t),Ra,{method:`PUT`,body:JSON.stringify({config:e})})},Hs={plugins:e=>T(Bs(e),_o)};function Us(e=`local`){return`${F(e)}/models-config`}var Ws={config:(e=`local`)=>T(Us(e),li),save:(e,t=`local`)=>T(Us(t),_i,{method:`PUT`,body:JSON.stringify(e)}),test:(e,t=`local`)=>T(`${Us(t)}/test`,bi,{method:`POST`,body:JSON.stringify(e)}),discover:(e,t=`local`)=>T(`${Us(t)}/discover`,vi,{method:`POST`,body:JSON.stringify(e)})};function Gs(e=`local`){return`${F(e)}/model-tiers`}var Ks={settings:(e=`local`)=>T(Gs(e),Oa),save:(e,t=`local`)=>T(Gs(t),Oa,{method:`PUT`,body:JSON.stringify({ladder:e})})};function qs(e=`local`){return`${F(e)}/utility-models`}function Js(e,t){if(t===2)return e;let n={};for(let t of Rt){if(!Object.prototype.hasOwnProperty.call(e,t))continue;let r=e[t];r===null?n[t]=null:r!==void 0&&(n[t]={provider:r.provider,id:r.id})}return n}var Ys={settings:(e=`local`)=>T(qs(e),ha),save:(e,t,n=`local`)=>T(qs(n),ha,{method:`PUT`,body:JSON.stringify({settings:Js(e,t)})})};function Xs(e=`local`){return`${F(e)}/skills`}function Zs(e,t=`local`){return`${Xs(t)}?${new URLSearchParams({cwd:e}).toString()}`}var Qs={list:(e,t=`local`)=>T(Zs(e,t),xi),toggle:(e,t=`local`)=>T(Xs(t),Ti,{method:`PATCH`,body:JSON.stringify(e)}),search:(e,t=`local`)=>T(`${Xs(t)}/search`,Ei,{method:`POST`,body:JSON.stringify(e)}),install:(e,t=`local`)=>T(`${Xs(t)}/install`,Ti,{method:`POST`,body:JSON.stringify(e)}),check:(e,t=`local`)=>T(`${Xs(t)}/check`,Oi,{method:`POST`,body:JSON.stringify(e)}),update:(e,t=`local`)=>T(`${Xs(t)}/update`,ji,{method:`POST`,body:JSON.stringify(e)})};function $s(e=``,t){let n=t===void 0?`api/pi-packages`:`${F(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var ec={packages:e=>T($s(``,e),ro),install:(e,t)=>{let n={source:e};return T($s(`install`,t),io,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return T($s(`remove`,n),io,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return T($s(`update`,t),io,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}};function tc(e=`local`){return`${F(e)}/package-plugins`}function nc(e,t=`local`){return`${tc(t)}?${new URLSearchParams({cwd:e}).toString()}`}var rc={list:(e,t=`local`)=>T(nc(e,t),co),mutate:(e,t=`local`)=>T(tc(t),co,{method:`POST`,body:JSON.stringify(e)})},ic={workspaceActivity:(e=`local`)=>T(`${F(e)}/activity`,ma)},ac={projects:(e=`local`)=>T(`${F(e)}/projects`,M(Xn)),addProject:(e,t,n,r=`local`)=>T(`${F(r)}/projects`,Xn,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}`,Yo,{method:`DELETE`}),closeProjectTree:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/close-tree`,Zo,{method:`POST`}),pinProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/pin`,M(Xn),{method:`POST`}),unpinProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/unpin`,M(Xn),{method:`POST`}),projectDirectories:(e,t=`local`)=>T(`${F(t)}/project-directories?q=${encodeURIComponent(e)}`,M(Zi)),projectUsageCount:(e,t=`local`)=>T(`${F(t)}/sessions/project-usage/count`,ds,{method:`POST`,body:JSON.stringify(e)}),projectUsage:(e,t=`local`)=>T(`${F(t)}/sessions/project-usage`,ps,{method:`POST`,body:JSON.stringify(e)})},oc={recentProjects:(e=`local`)=>T(`${F(e)}/recent-projects`,Qn),recordRecentProject:(e,t=`local`)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/recent`,Qn,{method:`POST`}),removeRecentProject:(e,t=`local`)=>T(`${F(t)}/recent-projects/${encodeURIComponent(e)}`,Qn,{method:`DELETE`})},sc={workspaces:(e,t=`local`,n)=>T(`${F(t)}/projects/${encodeURIComponent(e)}/workspaces`,M($n),xs(n)),deleteWorkspace:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,ua,{method:`DELETE`}),workspaceTree:(e,t,n=``,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,Qi),workspaceFile:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,ea),writeWorkspaceFile:(e,t,n,r,i,a=`local`)=>{let o=new URLSearchParams({path:n});i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!1&&o.set(`overwrite`,`false`);let s=r instanceof Uint8Array,c=s?new Uint8Array(r):new TextEncoder().encode(r);return T(`${F(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,ta,{method:`PUT`,body:c,headers:{"Content-Type":s?`application/octet-stream`:`text/plain`}})},deleteWorkspaceFile:(e,t,n,r=`local`)=>{let i=new URLSearchParams({path:n});return T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`,na,{method:`DELETE`})},moveWorkspaceFile:(e,t,n,r,i,a=`local`)=>{let o=new URLSearchParams({fromPath:n,toPath:r});return i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!0&&o.set(`overwrite`,`true`),T(`${F(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${o.toString()}`,ra,{method:`POST`})}},cc={sessions:(e,t=`local`,n)=>T(`${F(t)}/sessions?cwd=${encodeURIComponent(e)}`,M(tr),xs(n)),reorder:(e,t,n=`local`)=>T(I(e,`reorder`,n),rr,{method:`POST`,body:JSON.stringify(t)}),unreadCatalog:(e=`local`)=>T(`${F(e)}/sessions/unread`,wr,{cache:`no-store`}),acknowledgeUnread:(e,t,n,r=`local`)=>{let i={cwd:e.cwd,catalogId:t,throughCompletionOrder:n};return T(I(e,`unread/acknowledge`,r),wr,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>T(Ts(e,`notifications`,t),jr),dismissNotification:(e,t,n,r=`local`)=>T(I(e,`notifications/dismiss`,r),jr,{method:`POST`,body:L(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>T(I(e,`notifications/dismiss-all`,r),jr,{method:`POST`,body:L(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`,n)=>T(`${F(t)}/sessions`,tr,{method:`POST`,body:JSON.stringify({cwd:e,...n===void 0?{}:{modelPolicy:n}})}),startPlusSession:(e,t,n=`local`)=>T(`${F(n)}/sessions`,tr,{method:`POST`,body:JSON.stringify({cwd:e,creationSource:`session-list-plus`,initialModelPolicy:t})}),sessionDefaults:(e,t=`local`)=>T(`${F(t)}/session-defaults?cwd=${encodeURIComponent(e)}`,si),sessionDefaultsV2:(e,t=`local`)=>{let n=new URLSearchParams({cwd:e,starterModelPolicyContract:`2`});return T(`${F(t)}/session-defaults?${n.toString()}`,ci)},updateSessionDefaults:(e,t,n=`local`)=>T(`${F(n)}/session-defaults`,si,{method:`PUT`,body:JSON.stringify({cwd:e,...t})}),cleanupPreview:(e,t=`local`)=>T(`${F(t)}/sessions/cleanup/preview`,Jr,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>T(`${F(t)}/sessions/cleanup`,Yr,{method:`POST`,body:JSON.stringify(e)}),forceCleanup:(e=`local`)=>T(`${F(e)}/sessions/cleanup/force`,Yr,{method:`POST`}),archiveMany:(e,t=`local`)=>T(`${F(t)}/sessions/bulk/archive`,Xr,{method:`POST`,body:Os(e)}),deleteArchivedMany:(e,t=`local`)=>T(`${F(t)}/sessions/bulk/delete-archived`,Zr,{method:`POST`,body:Os(e)}),messages:(e,t,n=`local`,r)=>T(_s(e,t,n),Un,xs(r)),status:(e,t=`local`,n)=>T(Ts(e,`status`,t),cr,xs(n)),systemPrompt:(e,t=`local`)=>T(Ts(e,`system-prompt`,t),Cr),streamSnapshot:(e,t=`local`,n)=>T(Ts(e,`stream-snapshot`,t),Sr,xs(n)),clearQueue:(e,t=`local`)=>T(I(e,`queue/clear`,t),cr,{method:`POST`,body:L(e)}),dismissWarning:(e,t,n=`local`)=>T(I(e,`warnings/dismiss`,n),cr,{method:`POST`,body:L(e,{dismissId:t})}),modelPolicy:(e,t=`local`)=>T(Ts(e,`model-policy`,t),lr),rememberCurrentModelPolicy:(e,t=`local`)=>T(Ts(e,`model-policy/remember`,t),pr,{method:`POST`}),setModelPolicy:(e,t,n=`local`)=>T(I(e,`model-policy`,n),lr,{method:`PUT`,body:L(e,{policy:t})}),models:(e,t=`local`)=>T(Ts(e,`models`,t),oi),setModel:(e,t,n,r=`local`)=>T(I(e,`model`,r),cr,{method:`POST`,body:L(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>T(I(e,`model/cycle`,n),cr,{method:`POST`,body:L(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>T(Ts(e,`thinking-levels`,t),Ni),setThinkingLevel:(e,t,n=`local`)=>T(I(e,`thinking-level`,n),cr,{method:`POST`,body:L(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>T(I(e,`thinking-level/cycle`,t),cr,{method:`POST`,body:L(e)}),commands:(e,t=`local`)=>T(Ts(e,`commands`,t),M(Xi)),prompt:(e,t,n,r=`local`,i)=>T(I(e,`prompt`,r),Ko,{method:`POST`,body:L(e,{text:t,...n===void 0?{}:{streamingBehavior:n},...i!==void 0&&i.length>0?{attachments:i}:{}})}),saveAttachments:(e,t,n=`local`,r)=>T(I(e,`attachments`,n),qo,{method:`POST`,body:L(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>T(I(e,`shell`,n),Ko,{method:`POST`,body:L(e,{text:t})}),runCommand:(e,t,n=`local`)=>T(I(e,`commands/run`,n),Po,{method:`POST`,body:L(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>T(I(e,`commands/respond`,r),Po,{method:`POST`,body:L(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>T(I(e,`tree/navigate`,n),Ro,{method:`POST`,body:L(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary})}),editFromHere:(e,t,n=`local`)=>T(I(e,`messages/edit-from-here`,n),Ro,{method:`POST`,body:L(e,{entryId:t})}),forkFromHere:(e,t,n=`local`)=>T(I(e,`messages/fork`,n),zo,{method:`POST`,body:L(e,{entryId:t})}),abort:(e,t=`local`)=>T(I(e,`abort`,t),Qo,{method:`POST`,body:L(e)}),stop:(e,t=`local`)=>T(I(e,`stop`,t),$o,{method:`POST`,body:L(e)}),archive:(e,t=`local`)=>T(I(e,`archive`,t),es,{method:`POST`,body:L(e)}),archiveWithDescendants:(e,t=`local`)=>T(I(e,`archive-tree`,t),es,{method:`POST`,body:L(e)}),restore:(e,t=`local`)=>T(I(e,`restore`,t),ts,{method:`POST`,body:L(e)}),deleteArchived:(e,t=`local`)=>T(Es(e,t),ns,{method:`DELETE`}),detachParent:(e,t=`local`)=>T(I(e,`detach-parent`,t),rs,{method:`POST`,body:L(e)}),reloadSession:(e,t=`local`)=>T(I(e,`reload`,t),is,{method:`POST`,body:L(e)}),pin:(e,t=`local`)=>T(I(e,`pin`,t),tr,{method:`POST`,body:L(e)}),unpin:(e,t=`local`)=>T(I(e,`unpin`,t),tr,{method:`POST`,body:L(e)}),authProviders:e=>{let t=new URLSearchParams;e?.mode!==void 0&&t.set(`mode`,e.mode),e?.authType!==void 0&&t.set(`authType`,e.authType);let n=t.toString();return T(`${F(e?.machineId)}/auth/providers${n===``?``:`?${n}`}`,Ri)},saveApiKey:(e,t,n=`local`)=>T(`${F(n)}/auth/api-key`,Ko,{method:`POST`,body:JSON.stringify({providerId:e,key:t})}),startInteractiveApiKeyLogin:(e,t=`local`)=>T(`${F(t)}/auth/api-key/interactive`,zi,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t=`local`)=>T(`${F(t)}/auth/logout`,Ko,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t=`local`)=>T(`${F(t)}/auth/oauth`,zi,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t=`local`)=>T(`${F(t)}/auth/oauth/${encodeURIComponent(e)}`,zi),respondOAuthFlow:(e,t,n,r=`local`)=>T(`${F(r)}/auth/oauth/${encodeURIComponent(e)}/respond`,zi,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t=`local`)=>T(`${F(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,zi,{method:`POST`})},lc={terminals:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,M(la)),startTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,la,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Yo,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,Yo,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>T(`${F(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,la,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,ua,{method:`POST`,body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t=`local`)=>T(`${F(t)}/terminal-command-runs${dc(e)}`,M(ua)),getCommandRun:(e,t=`local`)=>uc(e,t),cancelCommandRun:(e,t=`local`)=>T(`${F(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,ua,{method:`POST`})};async function uc(e,t){let n=await fetch(Wt(`${F(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(n.status!==404){if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(fc(e)??n.statusText)}return ua(await n.json())}}function dc(e){if(e===void 0)return``;let t=new URLSearchParams;e.projectId!==void 0&&t.set(`projectId`,e.projectId),e.workspaceId!==void 0&&t.set(`workspaceId`,e.workspaceId),e.terminalId!==void 0&&t.set(`terminalId`,e.terminalId),e.statuses!==void 0&&e.statuses.length>0&&t.set(`statuses`,e.statuses.join(`,`)),e.metadata!==void 0&&Object.keys(e.metadata).length>0&&t.set(`metadata`,JSON.stringify(e.metadata));let n=t.toString();return n===``?``:`?${n}`}function fc(e){if(!pc(e))return;let t=e.error;return typeof t==`string`?t:void 0}function pc(e){return typeof e==`object`&&!!e}var mc={files:(e,t,n={})=>{let r=new URLSearchParams({q:t});return n.kind!==void 0&&r.set(`kind`,n.kind),n.mode!==void 0&&r.set(`mode`,n.mode),n.scope!==void 0&&r.set(`scope`,n.scope),n.workspaceScoped===!0&&n.projectId!==void 0&&n.workspaceId!==void 0?T(`${F(n.machineId)}/projects/${encodeURIComponent(n.projectId)}/workspaces/${encodeURIComponent(n.workspaceId)}/files?${r.toString()}`,M(Zi)):(r.set(`cwd`,e),T(`${F(n.machineId)}/files?${r.toString()}`,M(Zi)))}},hc={gitStatus:(e,t,n=`local`)=>T(`${F(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,aa),gitDiff:(e,t,n,r=`local`)=>T(gs(r,e,t,n),ca)},gc={...js,...Ms,...Ps,...Is,learnedSkills:Rs,...Ks,utilityModels:Ys,...Vs,...Hs,...ec,...rc,...ic,...ac,...oc,...sc,...cc,...lc,...mc,...hc};function _c(e,t=`local`){let n=typeof e==`string`?void 0:e.cwd,r=n===void 0||n===``?``:`?${new URLSearchParams({cwd:n}).toString()}`,i=typeof e==`string`?e:e.id;return new WebSocket(Gt(`${bc(t)}/sessions/${encodeURIComponent(i)}/events${r}`))}function vc(e,t,n,r,i=`local`){let a=r===void 0?``:`?${new URLSearchParams({cols:String(r.cols),rows:String(r.rows)}).toString()}`;return new WebSocket(Gt(`${bc(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function yc(e=`local`){return new WebSocket(Gt(`${bc(e)}/events`))}function bc(e){return`api/machines/${encodeURIComponent(e)}`}var xc=`.pi-webui/uploads`,Sc=class extends Error{constructor(e=`Workspace upload cancelled`){super(e),this.name=`WorkspaceUploadCancelledError`}},Cc=class extends Error{constructor(e,t){super(Pc(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function wc(e){return e?.uploads?.defaultFolder??`.pi-webui/uploads`}function Tc(e,t){return e?.uploads?.defaultFolder??t}function Ec(e,t){let n=Lc(e,`upload destination`,{allowEmpty:!0}),r=Lc(t,`upload file name`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function Dc(e,t,n,r={}){let i=r.xhrFactory?.()??new XMLHttpRequest,a=!1,o=!1;return{promise:new Promise((s,c)=>{let l=e=>{a||(a=!0,c(e))},u=e=>{a||(a=!0,s(e))};i.open(`PUT`,ys(e,t,n.path,Ac(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(jc(e,n.file.size))},i.onload=()=>{if(i.status>=200&&i.status<300){try{r.onProgress?.({loaded:n.file.size,total:n.file.size,percent:1,lengthComputable:!0}),u(ta(zc(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(Bc(i)))},i.onerror=()=>{l(Error(`Workspace upload failed`))},i.onabort=()=>{l(new Sc(o?void 0:`Workspace upload aborted`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function Oc(e,t,n,r={}){let i=r.destinationFolder??`.pi-webui/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:Ec(i,e.name),loaded:0,total:e.size,percent:Nc(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(Mc(a,s,a.every(e=>e.done)))};return{promise:(async()=>{let i=[],u=[];for(let d=0;d<n.length;d+=1){if(c.requested)throw new Sc;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=Dc(e,t,{path:p.path,file:f},{...kc(r),onProgress:e=>{p.total=e.total,p.loaded=Math.min(e.loaded,p.total),p.percent=e.percent,p.lengthComputable=e.lengthComputable,l()}});try{let e=await o.promise;p.loaded=p.total,p.percent=1,p.lengthComputable=!0,p.done=!0,i.push(e),l()}catch(e){if(Ic(e,c))throw e;let t=Fc(e);p.loaded=p.total,p.percent=1,p.lengthComputable=!0,p.done=!0,p.error=t,u.push({index:d,name:f.name,path:p.path,error:t}),l()}finally{o=void 0}}}if(u.length>0)throw new Cc(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function kc(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId},...e.xhrFactory===void 0?{}:{xhrFactory:e.xhrFactory}}}function Ac(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function jc(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:Nc(e.loaded,n),lengthComputable:e.lengthComputable}}function Mc(e,t,n){let r=e.reduce((e,t)=>e+t.total,0),i=e.reduce((e,t)=>e+t.loaded,0);return{currentFileIndex:t,files:e.map(e=>({...e})),loaded:i,total:r,percent:Nc(i,r),done:n}}function Nc(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Pc(e){return e.length===1?e[0]?.error??`Workspace upload failed`:`${String(e.length)} files failed to upload`}function Fc(e){return e instanceof Error?e.message:String(e)}function Ic(e,t){return t.requested||e instanceof Sc}function Lc(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(Rc(r))throw Error(`${t} must be workspace-relative`);let i=r.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(i.length===0){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(i.some(e=>e===`..`))throw Error(`${t} must not contain path traversal`);return i.join(`/`)}function Rc(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function zc(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function Bc(e){let t=Vc(e);return Hc(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function Vc(e){try{return zc(e)}catch{return}}function Hc(e){return typeof e==`object`&&!!e}function Uc(e){return e.closesActionPalette===!0}function Wc(e){return{mode:e.mode,exact:Cl(e.exact),...e.tier===void 0?{}:{tier:e.tier}}}function Gc(e){let t=Kc(e);if(t.mode!==`tiered`||t.tier!==void 0)return t;let n=e.catalog?.rows;return n===void 0||!Object.hasOwn(n,`standard`)||!n.standard.valid?t:{...t,tier:`standard`}}function Kc(e){if(e.policy!==void 0)return Wc(e.policy);let t=e.liveResolved;return t===void 0?{mode:`exact`,exact:{model:{provider:``,id:``},thinkingLevel:``}}:{mode:`exact`,exact:Cl(t)}}function qc(e){let t=e.model?.provider,n=e.model?.id;if(!(t===void 0||n===void 0||!Sl(t)||!Sl(n))&&Sl(e.thinkingLevel))return{model:{provider:t,id:n},thinkingLevel:e.thinkingLevel}}function Jc(e){let t=qc(e)??pl(),n=e.starterModelPolicyPreference;return ul(e)?dl(n)?{mode:n.mode,exact:Cl(n.exact),...n.tier===void 0?{}:{tier:n.tier}}:n===void 0?{mode:`tiered`,exact:Cl(t),tier:`standard`}:ll(n,t,n.mode):ll(n,t,`exact`)}function Yc(e,t){let n=qc(t);return n===void 0||e.mode===`tiered`||Zc(e.exact,n)?e:{...e,exact:Cl(n)}}function Xc(e){if(!(e.mode===`tiered`&&e.tier===void 0))return{mode:e.mode,...e.tier===void 0?{}:{tier:e.tier}}}function Zc(e,t){return e.model.provider===t.model.provider&&e.model.id===t.model.id&&e.thinkingLevel===t.thinkingLevel}function Qc(e,t){return{...e,mode:`tiered`,tier:t}}function $c(e){return{...e,mode:`exact`}}function el(e,t){let n=t.thinkingLevels.includes(e.exact.thinkingLevel)?e.exact.thinkingLevel:``;return{...e,exact:{model:{...t.model},thinkingLevel:n}}}function tl(e,t){return{...e,exact:{...e.exact,thinkingLevel:t}}}function nl(e,t){if(e.mode===`exact`)return ol(e.exact,t.models)?{mode:`exact`,exact:Cl(e.exact)}:void 0;let n=e.tier;if(!(n===void 0||!t.valid||!yl(t)||!bl(t,n)))return{mode:`tiered`,tier:n}}function rl(e,t){return t!==void 0&&nl(e,t)!==void 0}function il(e,t,n){let r=ml(e);if(fl(t)||e.mode!==`tiered`||gl(e.exact)||!_l(e.tier)||!yl(n)||!bl(n,e.tier))return r;let i=n.ladder?.[e.tier];return i===void 0||!gl(i)?r:{...r,exact:Cl(i)}}function al(e,t){let n=e.mode===`exact`?sl(e.exact,t):cl(e,t);if(n.kind===`blocked`)return n;let r=hl(e.exact);return r===void 0?{kind:`ready`,initialModelPolicy:{mode:e.mode,exact:Cl(e.exact),...e.tier===void 0?{}:{tier:e.tier}},resolved:Cl(n.resolved)}:{kind:`blocked`,reason:r}}function ol(e,t){return hl(e)===void 0&&t.find(t=>xl(t.model,e.model))?.thinkingLevels.includes(e.thinkingLevel)===!0}function sl(e,t){let n=hl(e);if(n!==void 0)return{kind:`blocked`,reason:n};let r=t.models.find(t=>xl(t.model,e.model));return r===void 0?{kind:`blocked`,reason:`Selected provider/model is unavailable`}:r.thinkingLevels.includes(e.thinkingLevel)?{kind:`ready`,resolved:Cl(e)}:{kind:`blocked`,reason:`Selected thinking level is unsupported by the selected model`}}function cl(e,t){let n=e.tier;if(!_l(n))return{kind:`blocked`,reason:vl(void 0,t)};let r=Object.hasOwn(t.rows,n)?t.rows[n]:void 0;if(r?.valid!==!0)return{kind:`blocked`,reason:vl(r,t)};let i=t.ladder?.[n];return i===void 0||!gl(i)?{kind:`blocked`,reason:vl(r,t)}:{kind:`ready`,resolved:Cl(i)}}function ll(e,t,n){return{mode:e?.mode??n,exact:Cl(t),...e?.tier===void 0?{}:{tier:e.tier}}}function ul(e){return`starterModelPolicyContractVersion`in e}function dl(e){return e!==void 0&&Object.hasOwn(e,`exact`)}function fl(e){return ul(e)&&dl(e.starterModelPolicyPreference)}function pl(){return{model:{provider:``,id:``},thinkingLevel:``}}function ml(e){return{mode:e.mode,exact:Cl(e.exact),...e.tier===void 0?{}:{tier:e.tier}}}function hl(e){return gl(e)?void 0:`Choose a provider, model, and thinking level before starting`}function gl(e){return Sl(e.model.provider)&&Sl(e.model.id)&&Sl(e.thinkingLevel)}function _l(e){return e!==void 0&&Lt.includes(e)}function vl(e,t){return e?.reason!==void 0&&Sl(e.reason)?e.reason:t.configError!==void 0&&Sl(t.configError)?t.configError:`Selected model tier is unavailable`}function yl(e){let t=e.ladder;return t!==void 0&&Lt.every(e=>Object.hasOwn(t,e))}function bl(e,t){return Object.hasOwn(e.rows,t)&&e.rows[t].valid}function xl(e,t){return e.provider===t.provider&&e.id===t.id}function Sl(e){return e.trim()!==``}function Cl(e){return{model:{...e.model},thinkingLevel:e.thinkingLevel}}function wl(e){return{kind:`policy-blocked`,scope:e}}function Tl(e,t,n){return{kind:e,message:t,scope:n}}function El(e,t,n){if(e===void 0||!Ol(e,t))return;let r=e.kind===`policy-blocked`?n:e.message;return r===void 0||r===``?void 0:r}function Dl(e,t,n){return Ol(e,t)?e.kind!==`policy-blocked`||n!==void 0&&n!==``:!1}function Ol(e,t){return t!==void 0&&e.scope.machineId===t.machineId&&e.scope.workspaceId===t.workspaceId}var kl={economy:`Economy`,fast:`Fast`,standard:`Standard`,advanced:`Advanced`,capable:`Capable`,frontier:`Frontier`},Al=Sn;function jl(e){return`${e.provider}/${e.id}`}function Ml(e){let t=e.thinkingLevel.trim()===``?`no thinking level`:e.thinkingLevel;return`${jl(e.model)} · ${t}`}var Nl={off:`No reasoning`,minimal:`Very brief reasoning (~1k tokens)`,low:`Light reasoning (~2k tokens)`,medium:`Moderate reasoning (~8k tokens)`,high:`Deep reasoning (~16k tokens)`,xhigh:`Maximum reasoning (~32k tokens)`};function Pl(e){let t=new Set(e.supported),n=new Set,r=[];for(let t of[...e.supported,...e.all])n.has(t)||(n.add(t),r.push(t));let i=e=>{let t=Al.findIndex(t=>t===e);return t===-1?Al.length:t};return r.map((e,t)=>({level:e,index:t})).sort((e,t)=>{let n=i(e.level)-i(t.level);return n===0?e.index-t.index:n}).map(({level:n})=>({level:n,supported:t.has(n),selected:n===e.selected,...Nl[n]===void 0?{}:{description:Nl[n]}}))}function Fl(){return{sessions:[],projectSessions:[],clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingSessions:!1,selectedNotificationInbox:void 0,treeDialog:void 0,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,memory:{kind:`loading`},learnedSkills:{kind:`loading`},selectedTerminalId:void 0,error:``}}function Il(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],projectSessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,isLoadingSessions:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,availableThinkingLevels:[],modelPolicy:void 0,isLoadingModelPolicy:!1,isSavingModelPolicy:!1,modelPolicyError:void 0,sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},selectedNotificationInbox:void 0,workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,treeDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:`core:workspace.files`,mainView:`chat`,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,memory:{kind:`loading`},learnedSkills:{kind:`loading`},activeTerminalCount:0,selectedTerminalId:void 0,piWebUiStatus:void 0,error:``}}function Ll(e,t){return t?.phase===`active`||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Rl(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}function zl(e,t){return`${e}:${t}`}function Bl(e,t){return`${e}:${t}`}function R(e){return e.selectedMachine?.id??`local`}var Vl=class{constructor(){this.pendingByKey=new Map}request(e,t){let n=this.pendingByKey.get(e);if(n!==void 0)return n.latestRefresh=t,n.started&&(n.trailing=!0),n.promise;let r={promise:Promise.resolve(),latestRefresh:t,started:!1,trailing:!1};return r.promise=Promise.resolve().then(async()=>{let e,t;do{r.trailing=!1;let n=r.latestRefresh;r.started=!0,t=!1;try{await n()}catch(n){e=n,t=!0}}while(this.hasTrailingRequest(r));if(t)throw e}).finally(()=>{this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e)}),this.pendingByKey.set(e,r),r.promise}hasTrailingRequest(e){return e.trailing}},Hl=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new Vl,this.api=n.api??ic,this.onActivityApplied=n.onActivityApplied}refresh(e=R(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,Ul(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=R(this.getState())){let n=this.getState(),r=R(n)===t,i=n.machineActivities[t]??(r?n.workspaceActivities:{});if(!Gl(i,e))return;let a=Wl(i,e);this.setState({machineActivities:{...n.machineActivities,[t]:a},...r?{workspaceActivities:a}:{}}),this.onActivityApplied?.(t)}applyMachineActivitySnapshot(e,t){let n=this.getState();this.setState({machineActivities:{...n.machineActivities,[e]:t},...R(n)===e?{workspaceActivities:t}:{}}),this.onActivityApplied?.(e)}};function Ul(e){let t={};for(let n of e.workspaces)Rl(n)&&(t[n.cwd]=n);return t}function Wl(e,t){let n={...e};return Rl(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}function Gl(e,t){let n=e[t.cwd];return n===void 0?Rl(t):n.hasSessionActivity!==t.hasSessionActivity||n.hasTerminalActivity!==t.hasTerminalActivity}var Kl=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.applyStatus=n,this.oauthOperationGeneration=0,this.pollGeneration=0,this.api=r.api??gc,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=Jl(e);return t===void 0?!1:(t.command===`login`?this.openLogin(t.providerId):this.openLogout(t.providerId),!0)}async openLogin(e){if(e!==void 0&&e!==``){await this.openLoginProvider(e);return}this.setState({authDialog:{step:`method`}})}async chooseLoginMethod(e){try{let{providers:t}=await this.api.authProviders({mode:`login`,authType:e,machineId:R(this.getState())});this.setState({authDialog:{step:`providers`,mode:`login`,authType:e,providers:t}})}catch(e){this.setState({error:String(e)})}}async selectLoginProvider(e,t){let n=this.getState().authDialog;if(n?.step!==`providers`)return;let r=n.providers.find(n=>n.id===e&&(t===void 0||n.authType===t));r!==void 0&&(r.authType===`oauth`||r.loginFlow===`interactive`?await this.startLoginFlow(r):this.setState({authDialog:{step:`apiKey`,provider:r,value:``}}))}updateApiKey(e){let t=this.getState().authDialog;if(t?.step!==`apiKey`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,value:e}})}async saveApiKey(){let e=this.getState().authDialog;if(e?.step!==`apiKey`)return;let t=e.value.trim();if(t===``){this.setState({authDialog:{...e,error:`API key is required`}});return}let n={...e};delete n.error,this.setState({authDialog:{...n,saving:!0}});try{await this.api.saveApiKey(e.provider.id,t,R(this.getState())),this.closeDialog(),this.refreshStatus()}catch(t){this.setState({authDialog:{...e,saving:!1,error:String(t)}})}}async openLogout(e){try{let{providers:t}=await this.api.authProviders({mode:`logout`,machineId:R(this.getState())});if(e!==void 0&&e!==``){let n=t.find(t=>t.id===e);n!==void 0&&!this.rejectRemoteOAuth(`logout`,n)?await this.logoutProvider(n.id):n===void 0&&this.setState({error:`No stored credentials for ${e}`});return}this.setState({authDialog:{step:`logout`,providers:t}})}catch(e){this.setState({error:String(e)})}}async logoutProvider(e){let t=this.getState().authDialog,n=t?.step===`logout`?t.providers.find(t=>t.id===e):void 0;if(!(n!==void 0&&this.rejectRemoteOAuth(`logout`,n)))try{await this.api.logoutProvider(e,R(this.getState())),this.closeDialog(),this.refreshStatus()}catch(e){this.setState({error:String(e)})}}updateOAuthInput(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,inputValue:e}})}async respondOAuth(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n=t.flow.prompt??t.flow.select;if(n===void 0)return;let r=this.oauthOperationGeneration,i=t.flow.flowId,a=n.requestId,o=e??t.inputValue??``,s={...t};delete s.error,this.setState({authDialog:{...s,responding:!0}});try{let e=await this.api.respondOAuthFlow(i,a,o,t.machineId),n=this.currentOAuthDialog(r,i);if(e.flowId!==i||n===void 0||ql(n.flow)!==a)return;this.updateOAuthFlow(e,n.machineId)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||ql(t.flow)!==a)return;this.setState({authDialog:{...t,responding:!1,error:String(e)}})}}async cancelOAuth(){let e=this.getState().authDialog;if(e?.step!==`oauth`){this.closeDialog();return}let t=e.flow.flowId,n=e.machineId;this.closeDialog();try{await this.api.cancelOAuthFlow(t,n)}catch{}}closeDialog(){this.oauthOperationGeneration+=1,this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(e){try{let{providers:t}=await this.api.authProviders({mode:`login`,machineId:R(this.getState())}),n=t.filter(t=>t.id===e);if(n.length===0){this.setState({error:`Auth provider not found: ${e}`});return}if(n.length>1){this.setState({authDialog:{step:`providers`,mode:`login`,providers:n}});return}let r=n[0];if(r===void 0)return;r.authType===`oauth`||r.loginFlow===`interactive`?await this.startLoginFlow(r):this.setState({authDialog:{step:`apiKey`,provider:r,value:``}})}catch(e){this.setState({error:String(e)})}}async startLoginFlow(e){if(this.rejectRemoteOAuth(`login`,e))return;let t=++this.oauthOperationGeneration;this.stopPolling();try{let n=R(this.getState()),r=e.authType===`oauth`?await this.api.startOAuthLogin(e.id,n):await this.api.startInteractiveApiKeyLogin(e.id,n);if(t!==this.oauthOperationGeneration){if(r.status===`running`)try{await this.api.cancelOAuthFlow(r.flowId,n)}catch{}return}this.updateOAuthFlow(r,n),r.status===`running`&&this.startPolling(r.flowId,n)}catch(e){t===this.oauthOperationGeneration&&this.setState({error:String(e)})}}rejectRemoteOAuth(e,t){let n=this.getState().selectedMachine;if(t.authType!==`oauth`||n?.kind!==`remote`)return!1;let r=n.baseUrl??`that remote PI WEBUI instance`;return this.setState({error:`OAuth ${e} for remote machines must be configured directly on ${r}.`}),!0}updateOAuthFlow(e,t){if(e.status===`complete`){this.stopPolling(),this.closeDialog(),this.refreshStatus(t);return}(e.status===`error`||e.status===`cancelled`)&&(this.oauthOperationGeneration+=1,this.stopPolling());let n=this.getState().authDialog,r=n?.step===`oauth`&&n.flow.flowId===e.flowId?n.inputValue??``:``,i=n?.step===`oauth`?ql(n.flow):void 0,a=ql(e),o=i!==void 0&&i===a,s=o?r:``,c=o&&n?.step===`oauth`?n.responding===!0:!1;this.setState({authDialog:{step:`oauth`,flow:e,machineId:t,inputValue:s,responding:c}})}startPolling(e,t){this.stopPolling();let n=this.oauthOperationGeneration,r=this.pollGeneration;this.pollTimer=window.setInterval(()=>{this.poll(e,t,n,r)},this.pollIntervalMs)}stopPolling(){this.pollGeneration+=1,this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(e,t,n,r){if(r!==this.pollGeneration)return;let i=this.currentOAuthDialog(n,e);if(i?.machineId!==t){this.stopPolling();return}let a=ql(i.flow);try{let i=await this.api.oauthFlow(e,t),o=this.currentOAuthDialog(n,e);if(i.flowId!==e||r!==this.pollGeneration||o?.machineId!==t||ql(o.flow)!==a)return;this.updateOAuthFlow(i,t)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o?.machineId!==t||ql(o.flow)!==a)return;this.stopPolling(),this.setState({authDialog:{...o,error:String(i)}})}}currentOAuthDialog(e,t){if(e!==this.oauthOperationGeneration)return;let n=this.getState().authDialog;return n?.step===`oauth`&&n.flow.flowId===t?n:void 0}async refreshStatus(e=R(this.getState())){let t=this.selectedSessionForMachine(e);if(t!==void 0)try{let n=await this.api.status(t,e),r=this.selectedSessionForMachine(e);if(r?.id!==t.id||r.cwd!==t.cwd)return;this.applyStatus(n)}catch{}}selectedSessionForMachine(e){let t=this.getState();if(R(t)!==e)return;let n=t.selectedSession;if(!(n===void 0||n.archived===!0))return n}};function ql(e){return e.prompt?.requestId??e.select?.requestId}function Jl(e){let t=e.trim(),n=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(n===null)return;let r=n[1];if(r!==`login`&&r!==`logout`)return;let i=n[2];return i===void 0||i===``?{command:r}:{command:r,providerId:i}}function Yl(e){return e.replaceAll(`:`,`.`)}function Xl(e){let t=new URLSearchParams(window.location.search),n=`${e}--`,r={};for(let[e,i]of t.entries()){if(!e.startsWith(n))continue;let t=e.slice(n.length),a=r[t];a===void 0?r[t]=i:Array.isArray(a)?a.push(i):r[t]=[a,i]}return r}function Zl(e,t){let n=Xl(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function Ql(e,t,n,r){let i=new URL(window.location.href),a=`${e}--${t}`;if(i.searchParams.delete(a),n!=null&&n!==``)if(Array.isArray(n))for(let e of n)i.searchParams.append(a,String(e));else i.searchParams.set(a,String(n));$l(i,r)}function $l(e,t){`${e.pathname}${e.search}${e.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,e):window.history.pushState({},``,e))}function eu(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:Ec(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:ou(0,r),lengthComputable:!0,status:n===0?`uploading`:`pending`}}),n=t.reduce((e,t)=>e+t.total,0);return{id:e.id,projectId:e.projectId,workspaceId:e.workspaceId,machineId:e.machineId,destinationFolder:e.destinationFolder,overwrite:e.overwrite,createDirs:e.createDirs,files:t,currentFileIndex:t.length===0?-1:0,loaded:0,total:n,percent:ou(0,n),status:`uploading`,startedAt:e.startedAt}}function tu(e,t){let n=new Map(t.files.map(e=>[e.index,e])),r=e.files.map(e=>{let r=n.get(e.index);if(r===void 0)return e;let i={...e,path:r.path,loaded:r.loaded,total:r.total,percent:r.percent,lengthComputable:r.lengthComputable,status:r.error===void 0?r.done?`completed`:t.currentFileIndex===e.index?`uploading`:e.status:`error`};return r.error===void 0?delete i.error:i.error=r.error,i});return{...e,files:r,currentFileIndex:t.currentFileIndex,loaded:t.loaded,total:t.total,percent:t.percent}}function nu(e,t,n){let r=e.files.map((e,n)=>{let r=t[n];return{...e,...r===void 0?{}:{path:r.path,response:r},loaded:e.total,percent:1,lengthComputable:!0,status:`completed`}}),i=au(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function ru(e,t,n){let r=e.files.map(n=>n.status===`completed`||n.status===`error`?n:n.status===`uploading`||n.index===e.currentFileIndex?{...n,status:`error`,error:t}:{...n,status:`cancelled`,error:`Not uploaded because an earlier file failed.`});return{...e,files:r,...au(r),status:`error`,error:t,completedAt:n}}function iu(e,t){let n=`Upload cancelled`,r=e.files.map(e=>e.status===`completed`||e.status===`error`?e:{...e,status:`cancelled`,error:n});return{...e,files:r,...au(r),status:`cancelled`,error:n,completedAt:t}}function au(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function ou(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var su=Yl(`core:workspace.files`),cu=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.updateUrl=n,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??gc,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??Oc,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}async refreshFiles(){let e=this.getState().selectedProject,t=this.getState().selectedWorkspace;if(!(e===void 0||t===void 0))try{let n=R(this.getState()),r=await this.api.workspaceTree(e.id,t.id,``,n),i={...this.getState().expandedDirs};await Promise.all(Object.keys(i).map(async r=>{i[r]=(await this.api.workspaceTree(e.id,t.id,r,n)).entries})),this.setState({fileTree:r.entries,expandedDirs:i,fileTreeStale:!1,error:``})}catch(e){this.setState({error:String(e)})}}async expandDir(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){if(this.getState().expandedDirs[e]!==void 0){this.setState({expandedDirs:fu(this.getState().expandedDirs,e)});return}try{let r=await this.api.workspaceTree(t.id,n.id,e,R(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[e]:r.entries},error:``})}catch(e){this.setState({error:String(e)})}}}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),Ql(su,`file`,e),this.updateUrl({replace:!0}),await this.restoreFile(e)}async restoreFile(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){this.setState({selectedFilePath:e,selectedFileContent:void 0});try{let r=await this.api.workspaceFile(t.id,n.id,e,R(this.getState()));this.getState().selectedFilePath===e&&this.setState({selectedFileContent:r,error:``})}catch(t){if(this.getState().selectedFilePath!==e)return;if(lu(t)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:``}),Ql(su,`file`,void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(t)})}}}startWorkspaceUpload(e,t){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0){this.setState({error:`Select a workspace before uploading files.`});return}if(e.length===0)return;let i=R(this.getState()),a=t.overwrite??!1,o=t.createDirs??!0,s;try{s=eu({id:this.createUploadBatchId(),projectId:n.id,workspaceId:r.id,machineId:i,destinationFolder:t.destinationFolder,overwrite:a,createDirs:o,files:e,startedAt:this.now()})}catch(e){this.setState({error:String(e)});return}this.setUploadBatch(s);let c;try{c=this.uploadWorkspaceFiles(n.id,r.id,e,{destinationFolder:t.destinationFolder,machineId:i,overwrite:a,createDirs:o,onProgress:e=>{this.updateUploadProgress(s.id,e)}})}catch(e){return this.failUploadBatch(s.id,e),{batchId:s.id,done:Promise.resolve()}}this.uploadTasks.set(s.id,c);let l=c.promise.then(async e=>{await this.completeUploadBatch(s.id,e,t)}).catch(async e=>{await this.handleUploadFailure(s.id,e,t)}).finally(()=>{this.uploadTasks.delete(s.id)});return{batchId:s.id,done:l}}cancelWorkspaceUpload(e){let t=this.getUploadBatch(e);t?.status===`uploading`&&(this.setUploadBatch(iu(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:fu(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(tu(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(nu(r,t,this.now()),{error:``}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshFiles();let i=t[0]?.path;n.selectUploadedFile!==!1&&i!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(i)}async handleUploadFailure(e,t,n){let r=this.failUploadBatch(e,t);if(!(t instanceof Cc)||t.responses.length===0||r===void 0||!this.isCurrentWorkspaceBatch(r))return;await this.refreshFiles();let i=t.responses[0]?.path;n.selectUploadedFile!==!1&&i!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(i)}failUploadBatch(e,t){let n=this.getUploadBatch(e);if(n?.status!==`uploading`)return;if(uu(t)){let e=iu(n,this.now());return this.setUploadBatch(e),e}let r=du(t),i=ru(n,r,this.now());return this.setUploadBatch(i,{error:r}),i}getUploadBatch(e){return this.getState().workspaceUploadBatches[e]}setUploadBatch(e,t={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[e.id]:e},...t})}isCurrentWorkspaceBatch(e){let t=this.getState();return t.selectedProject?.id===e.projectId&&t.selectedWorkspace?.id===e.workspaceId&&R(t)===e.machineId}};function lu(e){let t=String(e);return t.includes(`Path does not exist`)||t.includes(`ENOENT`)||t.includes(`no such file or directory`)}function uu(e){return e instanceof Sc}function du(e){return e instanceof Error?e.message:String(e)}function fu(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var pu=Yl(`core:workspace.git`),mu=class{constructor(e,t,n){this.getState=e,this.setState=t,this.updateUrl=n,this.statusRequest=0,this.diffRequest=0}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0,this.pollingScope=void 0,this.statusRequest+=1,this.diffRequest+=1}async refreshGit(e={}){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(t===void 0||n===void 0)return;let r=R(this.getState()),i=++this.statusRequest;this.diffRequest+=1;try{let a=await gc.gitStatus(t.id,n.id,r);if(i!==this.statusRequest||!this.isCurrentWorkspace(t,n,r))return;this.setState({gitStatus:a,gitStale:!1,...e.reportError===!1?{}:{error:``}});let o=this.getState().selectedDiffPath;o!==void 0&&(a.files.some(e=>e.path===o)?await this.refreshDiff(o,e):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),Ql(pu,`diff`,void 0,{replace:!0})))}catch(a){if(i!==this.statusRequest||!this.isCurrentWorkspace(t,n,r))return;e.reportError!==!1&&this.setState({error:String(a)})}}async selectDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:`core:workspace.git`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.git`}),Ql(pu,`diff`,e),this.updateUrl({replace:!0}),await this.refreshDiff(e)}async restoreDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(e)}async refreshDiff(e,t={}){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0)return;let i=R(this.getState()),a=++this.diffRequest;try{let[o,s]=await Promise.all([gc.gitDiff(n.id,r.id,{path:e},i),gc.gitDiff(n.id,r.id,{path:e,staged:!0},i)]);if(a!==this.diffRequest||!this.isCurrentWorkspace(n,r,i))return;this.setState({selectedDiff:o,selectedStagedDiff:s,...t.reportError===!1?{}:{error:``}})}catch(e){if(a!==this.diffRequest||!this.isCurrentWorkspace(n,r,i))return;t.reportError!==!1&&this.setState({error:String(e)})}}updatePolling(){let e=this.currentPollingScope();e===this.pollingScope&&this.pollTimer!==void 0||(this.dispose(),e!==void 0&&(this.pollingScope=e,this.refreshGit({reportError:!1}),this.pollTimer=window.setInterval(()=>{this.refreshGit({reportError:!1})},8e3)))}currentPollingScope(){let e=this.getState();if(!(e.selectedProject===void 0||e.selectedWorkspace?.isGitRepo!==!0))return JSON.stringify([R(e),e.selectedProject.id,e.selectedWorkspace.id])}isCurrentWorkspace(e,t,n){let r=this.getState();return R(r)===n&&r.selectedProject?.id===e.id&&r.selectedWorkspace?.id===t.id&&r.selectedWorkspace.projectId===t.projectId}},hu=3e4,gu={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},_u=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.generation=0,this.nextRequestId=0,this.observing=!1,this.fetchSnapshot=n.snapshot??Rs.snapshot,this.timer=n.timer??gu,this.pollIntervalMs=n.pollIntervalMs??hu}updatePolling(e=!0){if(!e){this.stopObserving();return}this.observing=!0;let t=this.currentScope();if(t===void 0){this.invalidateScope();return}if(this.scope?.key!==t.key){this.startScope(t);return}this.inFlight?.generation===this.generation&&this.inFlight.scopeKey===t.key||this.pollTimer===void 0&&this.startRequest(t)}async refresh(){if(!this.observing)return;let e=this.currentScope();if(e===void 0){this.invalidateScope();return}if(this.scope?.key!==e.key){await this.startScope(e);return}this.clearPollTimer(),await this.startRequest(e)}dispose(){this.observing=!1,this.invalidateScope()}startScope(e){return this.invalidateScope(),this.scope=e,this.setState({learnedSkills:{kind:`loading`}}),this.startRequest(e)}startRequest(e){let t=this.inFlight;if(t?.generation===this.generation&&t.scopeKey===e.key)return t.promise;let n=this.generation,r=++this.nextRequestId,i={generation:n,requestId:r,scopeKey:e.key,promise:Promise.resolve()};this.inFlight=i;let a=this.load(e,n,r);return i.promise=a,a}async load(e,t,n){try{let n=await this.fetchSnapshot(e.workspacePath,e.machineId);if(!this.isCurrent(e,t))return;let r=vu(n);this.setState({learnedSkills:r}),r.kind===`unavailable`&&this.stopObserving()}catch(n){if(!this.isCurrent(e,t))return;this.applyFailure(String(n))}finally{let r=this.inFlight?.requestId===n;r&&(this.inFlight=void 0),r&&this.isCurrent(e,t)&&this.scheduleNext(e,t)}}applyFailure(e){let t=this.getState().learnedSkills;if(t.kind===`data`){this.setState({learnedSkills:{...t,refreshError:e}});return}this.setState({learnedSkills:{kind:`error`,message:e}})}scheduleNext(e,t){this.clearPollTimer(),this.pollTimer=this.timer.setTimeout(()=>{this.pollTimer=void 0,!(!this.observing||!this.isCurrent(e,t))&&this.startRequest(e)},this.pollIntervalMs)}stopObserving(){this.observing&&(this.observing=!1,this.invalidateScope())}invalidateScope(){this.clearPollTimer(),this.scope=void 0,this.inFlight=void 0,this.generation+=1}clearPollTimer(){this.pollTimer!==void 0&&(this.timer.clearTimeout(this.pollTimer),this.pollTimer=void 0)}currentScope(){let e=this.getState(),t=e.selectedProject,n=e.selectedWorkspace;if(t===void 0||n===void 0)return;let r=R(e);return{key:JSON.stringify([r,t.id,n.id,n.path]),machineId:r,projectId:t.id,workspaceId:n.id,workspacePath:n.path}}isCurrent(e,t){if(!this.observing||t!==this.generation||this.scope?.key!==e.key)return!1;let n=this.currentScope();return n?.machineId===e.machineId&&n.projectId===e.projectId&&n.workspaceId===e.workspaceId&&n.workspacePath===e.workspacePath}};function vu(e){return e.kind===`unavailable`?{kind:`unavailable`}:{kind:`data`,globalSkills:e.globalSkills,projectSkills:e.projectSkills,...e.projectUnavailableMessage===void 0?{}:{projectUnavailableMessage:e.projectUnavailableMessage}}}var yu=3e4,bu={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},xu=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.generation=0,this.nextRequestId=0,this.observing=!1,this.fetchSnapshot=n.snapshot??Is.snapshot,this.timer=n.timer??bu,this.pollIntervalMs=n.pollIntervalMs??yu}updatePolling(e=!0){if(!e){this.stopObserving();return}this.observing=!0;let t=this.currentScope();if(t===void 0){this.invalidateScope();return}if(this.scope?.key!==t.key){this.startScope(t);return}this.inFlight?.generation===this.generation&&this.inFlight.scopeKey===t.key||this.pollTimer===void 0&&this.startRequest(t)}async refresh(){if(!this.observing)return;let e=this.currentScope();if(e===void 0){this.invalidateScope();return}if(this.scope?.key!==e.key){await this.startScope(e);return}this.clearPollTimer(),await this.startRequest(e)}dispose(){this.observing=!1,this.invalidateScope()}startScope(e){return this.invalidateScope(),this.scope=e,this.setState({memory:{kind:`loading`}}),this.startRequest(e)}startRequest(e){let t=this.inFlight;if(t?.generation===this.generation&&t.scopeKey===e.key)return t.promise;let n=this.generation,r=++this.nextRequestId,i={generation:n,requestId:r,scopeKey:e.key,promise:Promise.resolve()};this.inFlight=i;let a=this.load(e,n,r);return i.promise=a,a}async load(e,t,n){try{let n=await this.fetchSnapshot(e.workspacePath,e.machineId);if(!this.isCurrent(e,t))return;let r=Su(n);this.setState({memory:r}),r.kind===`unavailable`&&this.stopObserving()}catch(n){if(!this.isCurrent(e,t))return;this.applyFailure(String(n))}finally{let r=this.inFlight?.requestId===n;r&&(this.inFlight=void 0),r&&this.isCurrent(e,t)&&this.scheduleNext(e,t)}}applyFailure(e){let t=this.getState().memory;if(t.kind===`data`){this.setState({memory:{...t,refreshError:e}});return}this.setState({memory:{kind:`error`,message:e}})}scheduleNext(e,t){this.clearPollTimer(),this.pollTimer=this.timer.setTimeout(()=>{this.pollTimer=void 0,!(!this.observing||!this.isCurrent(e,t))&&this.startRequest(e)},this.pollIntervalMs)}stopObserving(){this.observing&&(this.observing=!1,this.invalidateScope())}invalidateScope(){this.clearPollTimer(),this.scope=void 0,this.inFlight=void 0,this.generation+=1}clearPollTimer(){this.pollTimer!==void 0&&(this.timer.clearTimeout(this.pollTimer),this.pollTimer=void 0)}currentScope(){let e=this.getState(),t=e.selectedProject,n=e.selectedWorkspace;if(t===void 0||n===void 0)return;let r=R(e);return{key:JSON.stringify([r,t.id,n.id,n.path]),machineId:r,projectId:t.id,workspaceId:n.id,workspacePath:n.path}}isCurrent(e,t){if(!this.observing||t!==this.generation||this.scope?.key!==e.key)return!1;let n=this.currentScope();return n?.machineId===e.machineId&&n.projectId===e.projectId&&n.workspaceId===e.workspaceId&&n.workspacePath===e.workspacePath}};function Su(e){return e.kind===`unavailable`?{kind:`unavailable`}:{kind:`data`,globalEntries:e.globalEntries,projectEntries:e.projectEntries,...e.projectUnavailableMessage===void 0?{}:{projectUnavailableMessage:e.projectUnavailableMessage}}}function Cu(e){let t=[],n=[];for(let r of e)ku(r.index)&&t.push(Ou(r,`staged`,r.index)),Au(r.workingTree)&&n.push(Ou(r,`unstaged`,r.workingTree));return{staged:t,unstaged:n}}function wu(e){let t=Cu(e);return new Set([...t.staged,...t.unstaged].map(e=>e.path)).size}function Tu(e){switch(e){case`modified`:return`M`;case`added`:return`A`;case`deleted`:return`D`;case`renamed`:return`R`;case`copied`:return`C`;case`untracked`:return`?`;case`conflicted`:return`U`;case`ignored`:return`!`;case`unmodified`:return``}}function Eu(e){switch(e){case`modified`:return`Modified`;case`added`:return`Added`;case`deleted`:return`Deleted`;case`renamed`:return`Renamed`;case`copied`:return`Copied`;case`untracked`:return`Untracked`;case`conflicted`:return`Conflicted`;case`ignored`:return`Ignored`;case`unmodified`:return`Unmodified`}}function Du(e){return e.oldPath===void 0?e.path:`${e.oldPath} → ${e.path}`}function Ou(e,t,n){return{id:`${t}:${e.path}`,path:e.path,...e.oldPath===void 0?{}:{oldPath:e.oldPath},scope:t,state:n}}function ku(e){return e!==`unmodified`&&e!==`untracked`&&e!==`ignored`&&e!==`conflicted`}function Au(e){return e!==`unmodified`&&e!==`ignored`}var ju=class{constructor(e,t,n,r){this.getState=e,this.setState=t,this.updateUrl=n,this.projects=r,this.runtimeRefreshSeqByMachine=new Map}async loadMachines(e){this.setState({error:``,isLoadingMachines:!0});try{let t=await gc.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));this.setState({machines:t,selectedMachine:n,machineActivities:Nu(this.getState().machineActivities,r),machineRuntimes:Nu(this.getState().machineRuntimes,r)}),this.refreshMachineHealthFor(t),this.refreshMachineRuntimeFor(t)}catch(e){this.setState({error:String(e)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(e,t={}){this.getState().selectedMachine?.id!==e.id&&(this.setState({selectedMachine:e,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...Fl()}),t.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(e.id),this.refreshMachineRuntime(e.id))}async addMachine(e){this.setState({error:``});try{let t=await gc.addMachine(e);return this.setState({machines:[...this.getState().machines.filter(e=>e.id!==t.id),t]}),await this.selectMachine(t),t}catch(e){this.setState({error:String(e)});return}}async deleteMachine(e=this.getState().selectedMachine,t={}){if(e!==void 0){if(e.kind===`local`){this.setState({error:`The local machine cannot be removed.`});return}try{let n=this.getState().selectedMachine?.id===e.id;await gc.deleteMachine(e.id);let r=this.getState().machines.filter(t=>t.id!==e.id),i=r.find(e=>e.id===`local`)??r[0];return this.setState({machines:r,machineStatuses:Mu(this.getState().machineStatuses,e.id),machineRuntimes:Mu(this.getState().machineRuntimes,e.id),machineActivities:Mu(this.getState().machineActivities,e.id)}),n&&i!==void 0?(t.selectFallback===!1||await this.selectMachine(i),i):void 0}catch(e){this.setState({error:String(e)});return}}}async refreshMachineHealth(e=this.getState().selectedMachine?.id??`local`){try{let t=await gc.health(e);return this.setState({machineStatuses:{...this.getState().machineStatuses,[t.machineId]:t}}),t}catch(e){this.setState({error:String(e)});return}}async refreshMachineRuntime(e=this.getState().selectedMachine?.id??`local`){let t=(this.runtimeRefreshSeqByMachine.get(e)??0)+1;this.runtimeRefreshSeqByMachine.set(e,t);try{let n=await gc.runtime(e,!0);return this.runtimeRefreshSeqByMachine.get(e)===t?(this.setState({machineRuntimes:{...this.getState().machineRuntimes,[n.machineId]:n}}),n):void 0}catch(n){this.runtimeRefreshSeqByMachine.get(e)===t&&this.setState({error:String(n)});return}}async selectInitialMachine(e,t){let n=e.find(e=>e.id===(t??`local`));if(n===void 0)return this.localMachine(e);if(n.kind!==`remote`)return n;let r=await this.safeRemoteHealth(n);return this.setState({machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r},...r.ok?{}:{error:`${n.name} is unavailable; reconnecting…`}}),n}async safeRemoteHealth(e){try{return await gc.health(e.id)}catch(t){return{machineId:e.id,ok:!1,checkedAt:new Date().toISOString(),status:`offline`,error:t instanceof Error?t.message:String(t)}}}localMachine(e){return e.find(e=>e.id===`local`)??e[0]}async refreshMachineHealthFor(e){let t=await Promise.allSettled(e.map(e=>gc.health(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...n}})}async refreshMachineRuntimeFor(e){let t=await Promise.allSettled(e.map(e=>gc.runtime(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...n}})}};function Mu(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Nu(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var Pu=`~/workspace`,Fu=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.projectCatalogOperationSequence=0,this.pinMutationQueueByMachine=new Map,this.latestPinMutationOrderByMachine=new Map,this.api=r.api??gc,this.onProjectsApplied=r.onProjectsApplied}async loadProjects(){let e=R(this.getState()),t=++this.projectCatalogOperationSequence;this.setState({error:``,isLoadingProjects:!0});try{let n=await this.api.projects(e);if(!this.isCurrentProjectCatalogOperation(e,t))return!1;let r;if(n.length===0){if(r=await this.api.addProject(Pu,void 0,!0,e),!this.isCurrentProjectCatalogOperation(e,t))return!1;n=[r]}let i=new Set(n.map(e=>e.id)),a=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([e])=>i.has(e))),o=this.getState().selectedProject,s=o!==void 0&&n.some(e=>e.id===o.id&&e.path!==o.path);return this.setState({projects:n,workspacesByProjectId:a}),s&&this.workspaces.clearSelection(),this.onProjectsApplied?.(e),r!==void 0&&await this.workspaces.selectProject(r),!0}catch(n){return this.isCurrentProjectCatalogOperation(e,t)&&this.setState({error:String(n)}),!1}finally{this.isCurrentProjectCatalogOperation(e,t)&&this.setState({isLoadingProjects:!1})}}async addProject(e,t){if(e.trim()===``)return;let n=R(this.getState()),r=++this.projectCatalogOperationSequence;this.setState({isLoadingProjects:!1});try{let i=await this.api.addProject(e.trim(),void 0,t,n);if(R(this.getState())!==n)return;if(!this.isCurrentProjectCatalogOperation(n,r)){this.setState({projectDialogOpen:!1}),await this.loadProjects();return}let a=this.getState().projects;this.setState({projects:[...a.filter(e=>e.id!==i.id),i],projectDialogOpen:!1}),this.onProjectsApplied?.(n),await this.workspaces.selectProject(i)}catch(e){this.isCurrentProjectCatalogOperation(n,r)&&this.setState({error:String(e)})}}async addRegisteredProject(e,t){if(e.trim()===``)throw Error(`Project path is required`);let n=R(this.getState()),r=++this.projectCatalogOperationSequence;this.setState({isLoadingProjects:!1});try{let i=await this.api.addProject(e,t,!1,n);if(R(this.getState())!==n)return i;if(!this.isCurrentProjectCatalogOperation(n,r))return await this.loadProjects(),i;let a=this.getState().projects;return this.setState({projects:[...a.filter(e=>e.id!==i.id),i]}),this.onProjectsApplied?.(n),await this.workspaces.selectProject(i),i}catch(e){throw e instanceof Error?e:Error(String(e))}}async closeProject(e){let t=R(this.getState());try{if(await this.api.closeProject(e,t),R(this.getState())!==t)return;this.workspaces.forgetProject(e);let n=this.getState();this.setState({projects:n.projects.filter(t=>t.id!==e)}),this.onProjectsApplied?.(t),n.selectedProject?.id===e&&this.workspaces.clearSelection()}catch(e){R(this.getState())===t&&this.setState({error:String(e)})}}async closeProjectTree(e){let t=R(this.getState()),n=++this.projectCatalogOperationSequence;this.setState({isLoadingProjects:!1});try{let{closedProjectIds:r}=await this.api.closeProjectTree(e,t);if(R(this.getState())!==t)return;for(let e of r)this.workspaces.forgetProject(e);let i=this.getState(),a=new Set(r);this.setState({projects:i.projects.filter(e=>!a.has(e.id))}),this.onProjectsApplied?.(t),i.selectedProject!==void 0&&a.has(i.selectedProject.id)&&this.workspaces.clearSelection(),this.isCurrentProjectCatalogOperation(t,n)||await this.loadProjects()}catch(e){this.isCurrentProjectCatalogOperation(t,n)&&this.setState({error:String(e)})}}async pinProject(e){await this.applyPinChange(e,t=>this.api.pinProject(e,t))}async unpinProject(e){await this.applyPinChange(e,t=>this.api.unpinProject(e,t))}async applyPinChange(e,t){let n=R(this.getState()),r=++this.projectCatalogOperationSequence;this.setState({isLoadingProjects:!1});let i=(this.latestPinMutationOrderByMachine.get(n)??0)+1;this.latestPinMutationOrderByMachine.set(n,i);let a=this.pinMutationQueueByMachine.get(n),o=a===void 0?this.runPinChange(n,r,i,t):a.catch(()=>void 0).then(async()=>{await this.runPinChange(n,r,i,t)});this.pinMutationQueueByMachine.set(n,o);try{await o}finally{this.cleanupPinMutationQueue(n,i,o)}}async runPinChange(e,t,n,r){try{let i=await r(e);if(!this.isLatestPinMutation(e,n))return;this.isCurrentProjectCatalogOperation(e,t)?this.setState({projects:i}):R(this.getState())===e&&await this.loadProjects()}catch(r){this.isCurrentPinMutation(e,t,n)&&this.setState({error:String(r)})}}isCurrentProjectCatalogOperation(e,t){return R(this.getState())===e&&this.projectCatalogOperationSequence===t}isLatestPinMutation(e,t){return this.latestPinMutationOrderByMachine.get(e)===t}isCurrentPinMutation(e,t,n){return this.isCurrentProjectCatalogOperation(e,t)&&this.isLatestPinMutation(e,n)}cleanupPinMutationQueue(e,t,n){this.pinMutationQueueByMachine.get(e)===n&&(this.pinMutationQueueByMachine.delete(e),this.latestPinMutationOrderByMachine.get(e)===t&&this.latestPinMutationOrderByMachine.delete(e))}},Iu=5e3,Lu=`reconcile selected project catalog`,Ru={setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>{window.clearTimeout(e)}},zu=class{constructor(e,t){this.getState=e,this.generation=0,this.nextRequestId=0,this.observing=!1,this.listWorkspaces=t.workspaces??sc.workspaces,this.applySnapshot=t.applySnapshot,this.timer=t.timer??Ru,this.pollIntervalMs=t.pollIntervalMs??Iu,this.onBackgroundError=t.onBackgroundError,this.captureTopologyRequest=t.captureTopologyRequest}updatePolling(e=!0){if(!e){this.stopObserving();return}this.observing=!0;let t=this.currentScope();if(t===void 0){this.invalidateScope();return}let n=this.retargetScope(t);this.inFlight===void 0&&(!n&&this.pollTimer!==void 0||this.scheduleNext(t,this.generation))}refresh(){if(!this.observing)return Promise.resolve();let e=this.currentScope();if(e===void 0)return this.invalidateScope(),Promise.resolve();this.retargetScope(e),this.clearPollTimer();let t=this.generation,n=this.inFlight;return n===void 0?this.startRequest(e,t):n.generation===t&&n.scopeKey===e.key?n.promise:this.queueImmediateRefresh(e,t)}dispose(){this.observing=!1,this.invalidateScope()}retargetScope(e){return this.scope?.key===e.key?(this.scope=e,!1):(this.clearPollTimer(),this.clearQueuedImmediateRefresh(),this.scope=e,this.generation+=1,!0)}startRequest(e,t){let n=this.inFlight;if(n!==void 0)return n.generation===t&&n.scopeKey===e.key?n.promise:this.queueImmediateRefresh(e,t);let r=++this.nextRequestId,i,a=new Promise(e=>{i=e});if(i===void 0)throw Error(`Project catalog request promise was not initialized`);return this.inFlight={generation:t,requestId:r,scopeKey:e.key,promise:a},this.load(e,t,r).then(i,i),a}async load(e,t,n){try{let n=this.captureTopologyRequest?.({machineId:e.machineId,projectId:e.project.id,projectPath:e.project.path}),r=await this.listWorkspaces(e.project.id,e.machineId);if(!this.isCurrent(e,t))return;await this.applySnapshot({machineId:e.machineId,project:e.project,workspaces:r,...n===void 0?{}:{topologyRequest:n}})}catch(n){this.isCurrent(e,t)&&this.reportBackgroundError(n)}finally{this.finishRequest(n)}}finishRequest(e){if(this.inFlight?.requestId!==e)return;this.inFlight=void 0;let t=this.queuedImmediateRefresh;if(t!==void 0){if(this.queuedImmediateRefresh=void 0,this.isCurrent(t.scope,t.generation)){this.startRequest(t.scope,t.generation).then(()=>{t.resolve()},()=>{t.resolve()});return}t.resolve()}let n=this.scope;n!==void 0&&this.isCurrent(n,this.generation)&&this.scheduleNext(n,this.generation)}queueImmediateRefresh(e,t){let n=this.queuedImmediateRefresh;if(n?.generation===t&&n.scope.key===e.key)return n.promise;this.clearQueuedImmediateRefresh();let r,i=new Promise(e=>{r=e});if(r===void 0)throw Error(`Queued project catalog refresh promise was not initialized`);return this.queuedImmediateRefresh={generation:t,scope:e,promise:i,resolve:r},i}scheduleNext(e,t){this.isCurrent(e,t)&&(this.clearPollTimer(),this.pollTimer=this.timer.setTimeout(()=>{this.pollTimer=void 0,!(!this.isCurrent(e,t)||this.inFlight!==void 0)&&this.startRequest(e,t)},this.pollIntervalMs))}stopObserving(){this.observing=!1,this.invalidateScope()}invalidateScope(){this.clearPollTimer(),this.clearQueuedImmediateRefresh(),this.scope=void 0,this.generation+=1}clearPollTimer(){this.pollTimer!==void 0&&(this.timer.clearTimeout(this.pollTimer),this.pollTimer=void 0)}clearQueuedImmediateRefresh(){let e=this.queuedImmediateRefresh;this.queuedImmediateRefresh=void 0,e?.resolve()}currentScope(){let e=this.getState(),t=e.selectedProject;if(t===void 0||e.isLoadingWorkspaces)return;let n=R(e);return{key:JSON.stringify([n,t.id,t.path]),machineId:n,project:t}}isCurrent(e,t){return!this.observing||t!==this.generation||this.scope?.key!==e.key?!1:this.currentScope()?.key===e.key}reportBackgroundError(e){if(this.onBackgroundError!==void 0)try{this.onBackgroundError(Lu,e)}catch{}}},Bu=`record recent project`,Vu=class{constructor(e){this.deps=e,this.current={kind:`loading`},this.queuesByMachine=new Map,this.authoritativeProjectIdByMachine=new Map,this.latestIntentByMachine=new Map,this.generation=0,this.api=e.api??oc}get state(){return this.current}async load(){let e=this.deps.machineId(),t=++this.generation;this.latestIntentByMachine.delete(e),this.authoritativeProjectIdByMachine.delete(e),this.publish({kind:`loading`}),await this.enqueue(e,async()=>{this.authoritativeProjectIdByMachine.delete(e);try{let n=await this.api.recentProjects(e);if(this.isStale(t,e))return;this.publish({kind:`ready`,entries:n})}catch(n){if(this.isStale(t,e))return;this.publish({kind:`failed`,message:Hu(n)})}})}retry(){return this.load()}recordWork(e,t=this.deps.machineId()){if(this.latestIntentByMachine.get(t)?.projectId===e)return;let n={projectId:e};this.latestIntentByMachine.set(t,n);let r=this.generation;this.enqueue(t,async()=>{if(this.authoritativeProjectIdByMachine.get(t)!==e)try{let n=await this.api.recordRecentProject(e,t);if(this.authoritativeProjectIdByMachine.set(t,e),this.isStale(r,t))return;this.publish({kind:`ready`,entries:n})}catch(e){this.latestIntentByMachine.get(t)===n&&this.latestIntentByMachine.delete(t),this.deps.onBackgroundError?.(Bu,e)}})}async removeEntry(e){let t=this.deps.machineId();this.latestIntentByMachine.delete(t),this.authoritativeProjectIdByMachine.delete(t);let n=this.generation,r;if(await this.enqueue(t,async()=>{try{let r=await this.api.removeRecentProject(e,t);this.authoritativeProjectIdByMachine.delete(t),this.isStale(n,t)||this.publish({kind:`ready`,entries:r})}catch(e){r=e instanceof Error?e:Error(String(e))}}),r!==void 0)throw r;return{kind:`removed`}}enqueue(e,t){let n=(this.queuesByMachine.get(e)??Promise.resolve()).then(t,t),r=n.catch(()=>void 0);return this.queuesByMachine.set(e,r),r.then(()=>{this.queuesByMachine.get(e)===r&&this.queuesByMachine.delete(e)}),n}isStale(e,t){return e!==this.generation||t!==this.deps.machineId()}publish(e){this.current=e,this.deps.onChange(e)}};function Hu(e){return e instanceof Error?e.message:String(e)}function Uu(e,t){return t[e.path]}function Wu(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function Gu(e,t,n){return Ju(Yu(e,t,n))}function Ku(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function qu(e){return Ju(Object.values(e??{}))}function Ju(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function Yu(e,t,n){return Object.values(n).filter(n=>Ku(e,t,n.cwd))}var Xu=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.machineGeneration=0,this.activityMachineGeneration=-1,this.projectTopologyGeneration=0,this.nextCwdActivation=0,this.observedActiveCwds=new Set,this.cwdActivations=new Map,this.attemptedCwdActivations=new Map,this.api=n.api??sc,this.onProjectTopology=n.onProjectTopology,this.captureTopologyRequest=n.captureTopologyRequest,this.onError=n.onError}handleActivityApplied(e){return R(this.getState())===e?(this.activityMachineGeneration=this.machineGeneration,this.reconcile(e)):Promise.resolve()}handleProjectsApplied(e){return R(this.getState())!==e||(this.projectTopologyGeneration+=1,this.attemptedCwdActivations.clear(),this.activePass=void 0,this.activityMachineGeneration!==this.machineGeneration)?Promise.resolve():this.reconcile(e)}handleSelectedMachineChanged(){this.machineGeneration+=1,this.projectTopologyGeneration+=1,this.observedActiveCwds.clear(),this.cwdActivations.clear(),this.attemptedCwdActivations.clear(),this.activePass=void 0}reconcile(e){let t=this.getState();if(R(t)!==e)return Promise.resolve();let n=this.syncActiveCwds(t),r=new Map([...n].filter(([e,n])=>!Zu(t.projects,t.workspacesByProjectId,e)&&this.attemptedCwdActivations.get(e)!==n)),i=this.activePass;if(i!==void 0)return(i.machineGeneration!==this.machineGeneration||i.projectTopologyGeneration!==this.projectTopologyGeneration||[...r].some(([e,t])=>i.cwdActivations.get(e)!==t))&&(i.trailingRequested=!0),i.promise;if(r.size===0||t.projects.length===0)return Promise.resolve();let a={machineGeneration:this.machineGeneration,projectTopologyGeneration:this.projectTopologyGeneration,machineId:e,projects:t.projects.map(e=>({id:e.id,path:e.path,startingWorkspaces:t.workspacesByProjectId[e.id]})),cwdActivations:r,trailingRequested:!1,promise:Promise.resolve()};return this.activePass=a,a.promise=this.runPass(a),a.promise}async runPass(e){if(await Promise.all(e.projects.map(async t=>{try{let n=this.captureTopologyRequest?.({machineId:e.machineId,projectId:t.id,projectPath:t.path}),r=await this.api.workspaces(t.id,e.machineId);await this.applyProjectWorkspaces(e,t,r,n)}catch(n){this.isPassScopeCurrent(e)&&this.reportError({machineId:e.machineId,projectId:t.id,error:n})}})),this.activePass!==e)return;let t=this.getState(),n=this.syncActiveCwds(t);for(let[r,i]of e.cwdActivations)n.get(r)===i&&!Zu(t.projects,t.workspacesByProjectId,r)&&this.attemptedCwdActivations.set(r,i);let r=e.trailingRequested;this.activePass=void 0,r&&await this.reconcile(R(this.getState()))}async applyProjectWorkspaces(e,t,n,r){if(this.activePass!==e||!this.isPassScopeCurrent(e))return;let i=this.getState();if(i.projects.find(e=>e.id===t.id)?.path===t.path&&!(r===void 0&&i.workspacesByProjectId[t.id]!==t.startingWorkspaces)){if(this.onProjectTopology!==void 0){await this.onProjectTopology({machineId:e.machineId,projectId:t.id,projectPath:t.path,workspaces:n,...r===void 0?{}:{topologyRequest:r}});return}this.setState({workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:n}})}}isPassScopeCurrent(e){return e.machineGeneration===this.machineGeneration&&e.projectTopologyGeneration===this.projectTopologyGeneration&&R(this.getState())===e.machineId}syncActiveCwds(e){let t=new Set(Object.values(e.workspaceActivities).filter(Rl).map(e=>e.cwd));for(let e of this.observedActiveCwds)t.has(e)||(this.cwdActivations.delete(e),this.attemptedCwdActivations.delete(e));for(let e of t)this.observedActiveCwds.has(e)||(this.nextCwdActivation+=1,this.cwdActivations.set(e,this.nextCwdActivation),this.attemptedCwdActivations.delete(e));return this.observedActiveCwds=t,new Map([...t].map(e=>[e,this.cwdActivations.get(e)??0]))}reportError(e){if(this.onError!==void 0)try{this.onError(e)}catch{}}};function Zu(e,t,n){return e.some(e=>Ku(e,t[e.id]??[],n))}var Qu=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??js,this.onRefreshError=n.onRefreshError??(()=>void 0)}async refresh(){let e=R(this.getState());if(this.pendingUpdateCheck?.machineId===e)return;let t=++this.requestSequence;try{let n=await this.api.piWebUiStatus(e);this.isCurrent(e,t)&&this.setState({piWebUiStatus:n})}catch(n){if(!this.isCurrent(e,t))return;this.setState({piWebUiStatus:void 0}),this.onRefreshError(e,n)}}checkForUpdates(){let e=R(this.getState()),t=this.pendingUpdateCheck;if(t?.machineId===e)return t.promise;let n=++this.requestSequence,r=this.api.checkForUpdates(e).then(t=>{this.isCurrent(e,n)&&(this.setState({piWebUiStatus:t}),$u(t))}).catch(t=>{if(this.isCurrent(e,n))throw t}).finally(()=>{this.pendingUpdateCheck?.requestSequence===n&&(this.pendingUpdateCheck=void 0)});return this.pendingUpdateCheck={machineId:e,requestSequence:n,promise:r},r}isCurrent(e,t){return R(this.getState())===e&&t===this.requestSequence}};function $u(e){if(e.release.error!==void 0)throw Error(`PI WEBUI update check failed: ${e.release.error}`);if(e.release.skipped===!0)throw Error(`PI WEBUI update check was skipped because remote version checks are disabled by offline/version-check settings`)}var ed=`pi-webui:cached-new-sessions:v1`,td=`browserCachedNew`,nd=`local`;function rd(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function id(e,t=nd,n=rd()){if(e.messageCount!==0||e.archived===!0)return;let r=ud(n).filter(n=>n.id!==e.id||n.machineId!==t);dd([ad(e,t),...r],n)}function ad(e,t=nd){return{...e,browserCachedNew:!0,machineId:t}}function od(e,t=nd,n=rd()){dd(ud(n).filter(n=>n.id!==e||n.machineId!==t),n)}function sd(e,t,n=nd,r=rd()){let i=new Set(t.map(e=>e.id)),a=ud(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&dd(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function cd(e){return e!==void 0&&pd(e)&&e.browserCachedNew===!0}function ld(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.persisted===void 0?{}:{persisted:e.persisted},...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},...`machineId`in e&&typeof e.machineId==`string`?{machineId:e.machineId}:{machineId:nd},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt},...e.creationSource===void 0?{}:{creationSource:e.creationSource}}}function ud(e=rd()){try{let t=e?.getItem(ed);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>fd(e)):[]}catch{return[]}}function dd(e,t=rd()){try{e.length===0?t?.removeItem(ed):t?.setItem(ed,JSON.stringify(e))}catch{}}function fd(e){if(!md(e))return[];let t=hd(e,`id`),n=hd(e,`path`),r=hd(e,`cwd`),i=hd(e,`created`),a=hd(e,`modified`),o=hd(e,`firstMessage`),s=_d(e,`messageCount`);if(t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||s!==0)return[];let c=gd(e,`name`),l=gd(e,`parentSessionPath`),u=gd(e,`machineId`)??nd,d=e.creationSource===`session-list-plus`?e.creationSource:void 0;return[{id:t,path:n,cwd:r,...c===void 0?{}:{name:c},created:i,modified:a,messageCount:s,firstMessage:o,...l===void 0?{}:{parentSessionPath:l},...d===void 0?{}:{creationSource:d},machineId:u,browserCachedNew:!0}]}function pd(e){return td in e}function md(e){return typeof e==`object`&&!!e}function hd(e,t){let n=e[t];return typeof n==`string`?n:void 0}function gd(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function _d(e,t){let n=e[t];return typeof n==`number`?n:void 0}function vd(e){return Ld(e.flatMap(Cd)).filter(e=>e.parts.length>0)}function yd(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function bd(e,t){let n=kd(t),r=z(t,`entryId`),i=z(t,`previousAssistantEntryId`),a=Kd(t,`canFork`);return{...e,...n===void 0?{}:{meta:n},...r===void 0?{}:{entryId:r},...i===void 0?{}:{previousAssistantEntryId:i},...a===void 0?{}:{canFork:a}}}function xd(e,t,n){if(n===``)return e;let r=e.at(-1),i=r?.parts.at(-1);return r?.role===t&&i?.type===`text`?[...e.slice(0,-1),{...r,parts:[...r.parts.slice(0,-1),{...i,text:i.text+n}]}]:r?.role===t?[...e.slice(0,-1),{...r,parts:[...r.parts,{type:`text`,text:n}]}]:[...e,yd(t,n)]}function Sd(e,t){if(t===``)return e;let n=e.at(-1),r=n?.parts.at(-1);return n?.role===`assistant`&&r?.type===`thinking`?[...e.slice(0,-1),{...n,parts:[...n.parts.slice(0,-1),{...r,text:r.text+t}]}]:n?.role===`assistant`?[...e.slice(0,-1),{...n,parts:[...n.parts,{type:`thinking`,text:t}]}]:[...e,{role:`assistant`,parts:[{type:`thinking`,text:t}]}]}function Cd(e){if(Td(e))return[e];if(z(e,`role`)===`bashExecution`)return[bd(Md(e),e)];let t=Nd(z(e,`role`)),n=Pd(Gd(e,`content`),e),r=t===`user`?Ed(n):void 0;if(r!==void 0)return r.map(t=>bd(t,e));let i=Od(e);if(t===`tool`)return[bd({role:t,parts:n,...i===void 0?{}:{source:i}},e)];let a=n.filter(e=>e.type!==`empty`),o=t===`assistant`&&a.length>0&&a.every(e=>e.type===`skillRead`)?`skill`:t,s=a.length>0?[bd({role:o,parts:a,...i===void 0?{}:{source:i}},e)]:[],c=wd(e);return c===void 0?s:[...s,bd(c,e)]}function wd(e){if(z(e,`role`)!==`assistant`||z(e,`stopReason`)!==`error`)return;let t=z(e,`errorMessage`)?.trim();return yd(`system`,`Model response failed: ${t===void 0||t===``?`The model returned an error.`:t}`)}function Td(e){let t=z(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(Gd(e,`parts`))}function Ed(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=Dd(e[0].text);if(t!==void 0)return[{role:`user`,parts:[{type:`skillInvocation`,name:t.name,location:t.location,content:t.content}]},...t.userMessage===void 0?[]:[{role:`user`,parts:[{type:`text`,text:t.userMessage}]}]]}function Dd(e){let t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;let n=t[4]?.trim();return{name:t[1]??`skill`,location:t[2]??``,content:t[3]??``,...n===void 0||n===``?{}:{userMessage:n}}}function Od(e){let t=z(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function kd(e){let t=Ad(Gd(e,`timestamp`)),n=jd(e);if(!(t===void 0&&n===void 0))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n}}}function Ad(e){if(typeof e==`number`&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!=`string`||e===``)return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function jd(e){if(z(e,`role`)!==`assistant`)return;let t=z(e,`provider`),n=z(e,`model`),r=z(e,`responseModel`);if(!((t===void 0||t===``)&&(n===void 0||n===``)&&(r===void 0||r===``)))return{...t===void 0||t===``?{}:{provider:t},...n===void 0||n===``?{}:{id:n},...r===void 0||r===``?{}:{responseId:r}}}function Md(e){let t=z(e,`command`)??``,n=Kd(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=Gd(e,`output`);r!=null&&n.push(``,Jd(r));let i=Gd(e,`exitCode`);i!=null&&n.push(``,`exit ${Jd(i)}`),Kd(e,`cancelled`)===!0&&n.push(``,`cancelled`),Kd(e,`truncated`)===!0&&n.push(``,`output truncated`);let a=z(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`full output: ${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
|
|
@@ -1211,7 +1211,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1211
1211
|
.review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1212
1212
|
.dialog-error { border: 1px solid var(--pi-danger); border-radius: 8px; background: color-mix(in srgb, var(--pi-danger) 10%, transparent); color: var(--pi-danger); padding: 9px; line-height: 1.35; overflow-wrap: anywhere; }
|
|
1213
1213
|
footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
|
|
1214
|
-
`]}};H([x({attribute:!1})],cb.prototype,`context`,void 0),H([C(`#workspace-upload-input`)],cb.prototype,`uploadInput`,void 0),H([S()],cb.prototype,`pendingUpload`,void 0),H([S()],cb.prototype,`destinationFolder`,void 0),H([S()],cb.prototype,`overwrite`,void 0),H([S()],cb.prototype,`createDirs`,void 0),H([S()],cb.prototype,`formError`,void 0),H([S()],cb.prototype,`dragActive`,void 0),cb=H([b(`workspace-files-panel`)],cb);function lb(e,t){return Object.values(e).filter(e=>e.projectId===t.projectId&&e.workspaceId===t.workspaceId&&e.machineId===t.machineId).sort((e,t)=>t.startedAt.localeCompare(e.startedAt))}function ub(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{Ec(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function db(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function fb(e){let t=e.selectedFileContent;if(e.selectedFilePath===void 0||e.selectedFilePath===``)return`Select a file.`;if(t===void 0)return`Loading ${e.selectedFilePath}…`;if(t.mediaType!==`image`&&t.binary)return`Binary file: ${t.path} · ${Tb(t.size)}`}function pb(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function mb(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function hb(e){return e==null?[]:Array.from(e)}function gb(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function _b(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function vb(e){let t=e.files.length,n=t===1?`file`:`files`;switch(e.status){case`completed`:return`Uploaded ${String(t)} ${n}`;case`error`:return`Upload failed for ${String(t)} ${n}`;case`cancelled`:return`Upload cancelled for ${String(t)} ${n}`;case`uploading`:return`Uploading ${String(t)} ${n}`}}function yb(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return Cb(e.percent)}}function bb(e){return e.status===`uploading`?e.percent:1}function xb(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return Cb(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function Sb(e){return e.error===void 0?e.response===void 0?`${e.path} · ${Tb(e.loaded)} / ${Tb(e.total)}`:`Wrote ${e.response.path}`:e.error}function Cb(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function wb(){sb(()=>import(`./CodeViewer-
|
|
1214
|
+
`]}};H([x({attribute:!1})],cb.prototype,`context`,void 0),H([C(`#workspace-upload-input`)],cb.prototype,`uploadInput`,void 0),H([S()],cb.prototype,`pendingUpload`,void 0),H([S()],cb.prototype,`destinationFolder`,void 0),H([S()],cb.prototype,`overwrite`,void 0),H([S()],cb.prototype,`createDirs`,void 0),H([S()],cb.prototype,`formError`,void 0),H([S()],cb.prototype,`dragActive`,void 0),cb=H([b(`workspace-files-panel`)],cb);function lb(e,t){return Object.values(e).filter(e=>e.projectId===t.projectId&&e.workspaceId===t.workspaceId&&e.machineId===t.machineId).sort((e,t)=>t.startedAt.localeCompare(e.startedAt))}function ub(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{Ec(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function db(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function fb(e){let t=e.selectedFileContent;if(e.selectedFilePath===void 0||e.selectedFilePath===``)return`Select a file.`;if(t===void 0)return`Loading ${e.selectedFilePath}…`;if(t.mediaType!==`image`&&t.binary)return`Binary file: ${t.path} · ${Tb(t.size)}`}function pb(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function mb(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function hb(e){return e==null?[]:Array.from(e)}function gb(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function _b(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function vb(e){let t=e.files.length,n=t===1?`file`:`files`;switch(e.status){case`completed`:return`Uploaded ${String(t)} ${n}`;case`error`:return`Upload failed for ${String(t)} ${n}`;case`cancelled`:return`Upload cancelled for ${String(t)} ${n}`;case`uploading`:return`Uploading ${String(t)} ${n}`}}function yb(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return Cb(e.percent)}}function bb(e){return e.status===`uploading`?e.percent:1}function xb(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return Cb(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function Sb(e){return e.error===void 0?e.response===void 0?`${e.path} · ${Tb(e.loaded)} / ${Tb(e.total)}`:`Wrote ${e.response.path}`:e.error}function Cb(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function wb(){sb(()=>import(`./CodeViewer-CHZziPur.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function Tb(e){if(!Number.isFinite(e)||e<0)return`0 B`;if(e<1024)return`${String(e)} B`;let t=e/1024;if(t<1024)return`${Eb(t)} KB`;let n=t/1024;return n<1024?`${Eb(n)} MB`:`${Eb(n/1024)} GB`}function Eb(e){return e>=10?String(Math.round(e)):e.toFixed(1)}var Db=2e3,Ob=class extends y{constructor(...e){super(...e),this.loading=!1,this.error=``,this.dynamicMetricsRequest=0,this.dynamicMetricsRefreshInFlight=!1}willUpdate(e){if(!e.has(`context`))return;let t=this.context?.machine.id;if(t===void 0){this.stopDynamicMetricsPolling(),this.machineId=void 0;return}t!==this.machineId&&(this.stopDynamicMetricsPolling(),this.machineId=t,this.loadSystemInfo(t))}async loadSystemInfo(e=this.machineId){if(e!==void 0){this.loading=!0,this.error=``;try{let t=await js.systemInfo(e);this.isCurrentMachine(e)&&(this.systemInfo=t,this.isConnected&&this.startDynamicMetricsPolling())}catch(t){this.isCurrentMachine(e)&&(this.error=t instanceof Error?t.message:String(t))}finally{this.isCurrentMachine(e)&&(this.loading=!1)}}}connectedCallback(){super.connectedCallback(),this.startDynamicMetricsPolling()}disconnectedCallback(){this.stopDynamicMetricsPolling(),super.disconnectedCallback()}startDynamicMetricsPolling(){let e=this.machineId;e===void 0||this.systemInfo===void 0||this.dynamicMetricsTimer!==void 0||(this.dynamicMetricsPollingMachineId=e,this.dynamicMetricsTimer=window.setInterval(()=>{this.refreshDynamicMetrics(e)},Db))}stopDynamicMetricsPolling(){this.dynamicMetricsTimer!==void 0&&window.clearInterval(this.dynamicMetricsTimer),this.dynamicMetricsTimer=void 0,this.dynamicMetricsPollingMachineId=void 0,this.dynamicMetricsRequest+=1,this.dynamicMetricsRefreshInFlight=!1}async refreshDynamicMetrics(e){if(this.loading||this.error!==``||this.dynamicMetricsRefreshInFlight||this.dynamicMetricsPollingMachineId!==e)return;this.dynamicMetricsRefreshInFlight=!0;let t=++this.dynamicMetricsRequest;try{let n=await js.systemMetrics(e);if(!this.isCurrentDynamicMetricsRequest(e,t))return;this.applyDynamicMetrics(n)}catch{}finally{t===this.dynamicMetricsRequest&&(this.dynamicMetricsRefreshInFlight=!1)}}isCurrentDynamicMetricsRequest(e,t){return t===this.dynamicMetricsRequest&&this.dynamicMetricsPollingMachineId===e&&this.isCurrentMachine(e)}applyDynamicMetrics(e){let t=this.systemInfo;t!==void 0&&(this.systemInfo={...t,memory:e.memory,network:{...t.network,...e.network}})}isCurrentMachine(e){return this.machineId===e&&this.context?.machine.id===e}render(){if(this.loading)return g`<section class="info-panel"><p class="muted">Loading system information…</p></section>`;if(this.error!==``)return g`<section class="info-panel">
|
|
1215
1215
|
<p class="error-text">Failed to load system information: ${this.error}</p>
|
|
1216
1216
|
<button @click=${()=>{this.loadSystemInfo()}}>Retry</button>
|
|
1217
1217
|
</section>`;let e=this.systemInfo;return e===void 0?g`<section class="info-panel"><p class="muted">System information unavailable.</p></section>`:g`<section class="info-panel">
|
|
@@ -1465,7 +1465,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1465
1465
|
<div class="viewer-header"><strong>${e.path??`diff`}</strong><small>${e.staged?`staged`:`unstaged`}${e.truncated?` · truncated`:``}</small></div>
|
|
1466
1466
|
<unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
|
|
1467
1467
|
</section>
|
|
1468
|
-
`}function Vb(){sb(()=>import(`./UnifiedDiffViewer-
|
|
1468
|
+
`}function Vb(){sb(()=>import(`./UnifiedDiffViewer-j1-AFZ8f.js`),[],import.meta.url)}function Hb(){sb(()=>Promise.resolve().then(()=>EI),void 0,import.meta.url)}function Ub(e){return g`<workspace-info-panel .context=${e}></workspace-info-panel>`}function Wb(e){let t=Gb(e);return g`
|
|
1469
1469
|
<p class="summary">
|
|
1470
1470
|
<span class="summary-branch">${t.branch}</span>
|
|
1471
1471
|
${t.latestTag===void 0?null:g`<span class="summary-tag" aria-label=${`Latest tag ${t.latestTag}`}>${t.latestTag}</span>`}
|
|
@@ -3356,14 +3356,14 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3356
3356
|
.host-speech-action:disabled:hover, .host-speech-action:disabled:focus { color: var(--pi-dim); border-color: var(--pi-border); }
|
|
3357
3357
|
.host-speech-error { box-sizing: border-box; flex: 0 0 auto; margin: 0; padding: 8px 16px; color: var(--pi-warning); font-size: 12px; }
|
|
3358
3358
|
@media (hover: none) { .msg-speech-action { opacity: 1; } }
|
|
3359
|
-
`]}};H([x({attribute:!1})],G.prototype,`messages`,void 0),H([x()],G.prototype,`sessionId`,void 0),H([x({type:Number})],G.prototype,`messageStart`,void 0),H([x({type:Number})],G.prototype,`messageEnd`,void 0),H([x({type:Number})],G.prototype,`messageTotal`,void 0),H([x({type:Boolean})],G.prototype,`hasMore`,void 0),H([x({type:Boolean})],G.prototype,`loadingMore`,void 0),H([x({type:Boolean})],G.prototype,`isSendingPrompt`,void 0),H([x({type:Boolean})],G.prototype,`isCompacting`,void 0),H([x({type:Number})],G.prototype,`pendingMessageCount`,void 0),H([x({attribute:!1})],G.prototype,`clientQueuedMessages`,void 0),H([x({attribute:!1})],G.prototype,`status`,void 0),H([x({type:Number})],G.prototype,`warningCount`,void 0),H([x({type:Boolean})],G.prototype,`warningsExpanded`,void 0),H([x({attribute:!1})],G.prototype,`onToggleWarnings`,void 0),H([x({attribute:!1})],G.prototype,`activity`,void 0),H([x({attribute:!1})],G.prototype,`sessionInfo`,void 0),H([x({attribute:!1})],G.prototype,`notificationInbox`,void 0),H([x({type:Boolean})],G.prototype,`canClearServerQueue`,void 0),H([x({type:Boolean})],G.prototype,`canMessageActions`,void 0),H([x({attribute:!1})],G.prototype,`onEditFromHere`,void 0),H([x({attribute:!1})],G.prototype,`onForkFromHere`,void 0),H([x({attribute:!1})],G.prototype,`hostSpeechStatus`,void 0),H([x()],G.prototype,`activeHostSpeechMessageKey`,void 0),H([x()],G.prototype,`hostSpeechError`,void 0),H([x({attribute:!1})],G.prototype,`onToggleHostSpeech`,void 0),H([x({attribute:!1})],G.prototype,`onClearServerQueue`,void 0),H([x({attribute:!1})],G.prototype,`onDismissWarning`,void 0),H([x({attribute:!1})],G.prototype,`onDismissNotification`,void 0),H([x({attribute:!1})],G.prototype,`onDismissAllNotifications`,void 0),H([x({type:Boolean})],G.prototype,`warningsVisible`,void 0),H([x({attribute:!1})],G.prototype,`onLoadMore`,void 0),H([C(`.chat`)],G.prototype,`chat`,void 0),H([C(`chat-minimap`)],G.prototype,`_minimap`,void 0),H([C(`dialog.image-zoom`)],G.prototype,`imageZoomDialog`,void 0),H([S()],G.prototype,`pinnedToBottom`,void 0),H([S()],G.prototype,`zoomedImage`,void 0),H([S()],G.prototype,`expandedMetaKey`,void 0),H([S()],G.prototype,`copiedMessageKey`,void 0),H([S()],G.prototype,`forkingEntryId`,void 0),H([S()],G.prototype,`collapsedNotificationTargetKeys`,void 0),H([S()],G.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),H([S()],G.prototype,`renderedGroupStart`,void 0),H([S()],G.prototype,`expandedLiveEventGroups`,void 0),H([S()],G.prototype,`loadMoreRequested`,void 0),H([S()],G.prototype,`sessionInfoOpen`,void 0),H([S()],G.prototype,`_minimapMarkers`,void 0),H([S()],G.prototype,`_minimapVisible`,void 0),G=H([b(`chat-view`)],G);var hO=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function gO(e){return typeof e==`string`&&hO.has(e)}function _O(e){switch(e){case`image/jpeg`:return`jpg`;case`image/png`:return`png`;case`image/gif`:return`gif`;case`image/webp`:return`webp`;default:return`bin`}}var vO=`application/octet-stream`,yO=`Failed to read an attachment.`;async function bO(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(wO(i,e))}catch{r=yO}return{attachments:n,...r===void 0?{}:{error:r}}}function xO(e){return e.kind===`image`&&gO(e.mimeType)}function SO(e){return e.every(e=>xO(e))}function CO(e,t){return SO(t)?e:`folder`}function wO(e,t){return gO(e.type)?{kind:`image`,name:EO(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:EO(e),mimeType:TO(e),data:t,size:e.size}}function TO(e){let t=e.type.trim();return t===``?vO:t}function EO(e){return e.name===``?gO(e.type)?`pasted-image.${_O(e.type)}`:`pasted-file.bin`:e.name}var DO=`pi-webui:attachment-delivery`;function OO(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function kO(e=OO()){try{return e?.getItem(DO)===`folder`?`folder`:`inline`}catch{return`inline`}}function AO(e,t=OO()){try{t?.setItem(DO,e)}catch{}}var jO=`(pointer: coarse), (max-width: 760px)`,MO=`pi-webui.promptEnterPreference`;function NO(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(jO):void 0}function PO(e){return e===`send`||e===`newline`?e:`auto`}function FO(e=BO()){if(e===void 0)return`auto`;try{return PO(e.getItem(MO))}catch{return`auto`}}function IO(e,t=BO()){if(t!==void 0)try{t.setItem(MO,e)}catch{}}function LO(e=NO(),t=FO()){return t===`send`||t!==`newline`&&e?.matches!==!0}function RO(e,t,n=NO()){return e?n?.matches!==!0||t:!1}function zO(e,t=NO(),n=FO()){let r=LO(t,n);return e?!r:r}function BO(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var VO=new Set([`(`,`[`,`{`]),HO=new Set([`.`,`,`,`;`,`:`,`!`,`?`,`%`,`)`,`]`,`}`]);function UO(e){return e!==void 0&&!/\s/u.test(e)}function WO(e,t){let n=e.credential.resolution;return n===`missing`?`Cloud credential is not configured`:n===`unresolved`?`Cloud credential is unresolved`:t.cloud.available?`Cloud is unavailable`:t.cloud.reason}function GO(e,t){let n=e.credential.resolution;return t.cloud.available&&(n===`resolved`||n===`unchecked`)}function KO(e,t){let n=e.settings.provider;return n===`browser`?t.browser.available?{available:!0,provider:`browser`}:{available:!1,reason:t.browser.reason}:n===`cloud`?GO(e,t)?{available:!0,provider:`cloud`}:{available:!1,reason:WO(e,t)}:t.browser.available?{available:!0,provider:`browser`}:GO(e,t)?{available:!0,provider:`cloud`}:{available:!1,reason:`${t.browser.reason}; ${WO(e,t)}`}}var qO=new TextEncoder;function JO(e,t,n){if(!Number.isInteger(e.from)||!Number.isInteger(e.to)||e.from<0||e.to<e.from||e.to>e.text.length||t!==e.text)return{ok:!1,reason:`changed`};let r=n.trim();if(r===``)return{ok:!1,reason:`empty`};if(qO.encode(r).byteLength>1048576)return{ok:!1,reason:`too-large`};let i=e.text[e.from-1],a=e.text[e.to],o=r[0],s=r[r.length-1],c=UO(i)&&UO(o)&&!VO.has(i)&&!HO.has(o),l=UO(s)&&UO(a)&&!VO.has(s)&&!HO.has(a),u=(c?` `:``)+r+(l?` `:``);return{ok:!0,insert:u,from:e.from,to:e.to,caret:e.from+u.length}}function YO(e){return[`audio/webm;codecs=opus`,`audio/ogg;codecs=opus`,`audio/mp4;codecs=mp4a.40.2`,`audio/mp4`].find(t=>e(t))}var XO=1e3,ZO=`Speech input requires a secure browser context`,QO=`No accepted recorder format`,$O={code:`permission-denied`,message:`Microphone permission denied`},ek={code:`microphone-unavailable`,message:`Microphone is unavailable`},tk={code:`no-speech`,message:`No speech detected`},nk={code:`unsupported`,message:QO},rk={code:`recording-limit`,message:`Speech recording exceeded the 20 MiB limit`},ik={code:`provider`,message:`Speech transcription is busy. Try again.`},ak={code:`provider`,message:`Speech transcription is unavailable.`},ok={code:`provider`,message:`Speech transcription timed out.`},sk={code:`network`,message:`Speech transcription network error`},ck={code:`provider`,message:`Speech transcription failed`},lk=class{constructor(e){this.recorder=e,this.mimeType=e.mimeType}onStart(e){let t=()=>{e()};return this.recorder.addEventListener(`start`,t),()=>{this.recorder.removeEventListener(`start`,t)}}onData(e){let t=t=>{e(t.data)};return this.recorder.addEventListener(`dataavailable`,t),()=>{this.recorder.removeEventListener(`dataavailable`,t)}}onStop(e){let t=()=>{e()};return this.recorder.addEventListener(`stop`,t),()=>{this.recorder.removeEventListener(`stop`,t)}}onError(e){let t=t=>{e(t)};return this.recorder.addEventListener(`error`,t),()=>{this.recorder.removeEventListener(`error`,t)}}start(e){this.recorder.start(e)}stop(){this.recorder.stop()}},uk=class{constructor(e){this.nativeStream=e}getTracks(){return this.nativeStream.getTracks()}};function dk(e){return typeof e==`object`&&!!e&&typeof Reflect.get(e,`getUserMedia`)==`function`}function fk(){let e=Reflect.get(globalThis,`navigator`);if(typeof e!=`object`||!e)return;let t=Reflect.get(e,`mediaDevices`);return dk(t)?t:void 0}function pk(){return fk()!==void 0&&typeof MediaRecorder<`u`}function mk(){return{secureContext:globalThis.isSecureContext,getUserMedia:async()=>{let e=fk();if(e===void 0)throw Error(`Browser microphone capture is unavailable`);return new uk(await e.getUserMedia({audio:!0}))},isTypeSupported:e=>{if(!pk())return!1;try{return MediaRecorder.isTypeSupported(e)}catch{return!1}},createRecorder:(e,t)=>{if(!(e instanceof uk))throw Error(`Expected browser media stream`);return new lk(new MediaRecorder(e.nativeStream,{mimeType:t}))},transcribe:(e,t,n)=>Ns.transcribe(e,t,n)}}function hk(e){try{return YO(t=>e.isTypeSupported(t))}catch{return}}function gk(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`name`);return t===`NotAllowedError`||t===`PermissionDeniedError`}function _k(e){if(e instanceof Jt)switch(e.status){case 413:return rk;case 429:return ik;case 503:return ak;case 504:return ok;default:return ck}return sk}function vk(e){if(typeof e!=`object`||!e)return;let t=Reflect.get(e,`text`);return typeof t==`string`?t:void 0}function yk(e){if(e===void 0)return;let t=new Set;for(let n of e.getTracks())if(!t.has(n)){t.add(n);try{n.stop()}catch{}}}var bk={stop:()=>void 0,cancel:()=>void 0},xk=class{constructor(e=mk()){this.id=`cloud`,this.host=e}availability(){return this.host.secureContext?hk(this.host)===void 0?{available:!1,reason:QO}:{available:!0}:{available:!1,reason:ZO}}start(e){let t=e.callbacks;if(!this.host.secureContext)return t.onError({code:`unsupported`,message:ZO}),bk;let n=hk(this.host);if(n===void 0)return t.onError(nk),bk;let r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l,u,d,f=0,p=[],m,ee,te=[],ne=(e={})=>{if(r)return!1;r=!0;let t=te.splice(0);for(let e of t)try{e()}catch{}let n=ee;if(ee=void 0,e.abortUpload===!0)try{n?.abort()}catch{}let i=u;if(u=void 0,i!==void 0&&!a&&!o){a=!0;try{i.stop()}catch{}}let s=l;return l=void 0,yk(s),p=[],f=0,m=void 0,d=void 0,!0},re=e=>{ne({abortUpload:!0})&&t.onError(e)},ie=e=>{ne()&&t.onComplete(e)},ae=()=>{r||s||(s=!0,t.onTranscribing())},oe=()=>{if(r||a)return;let e=u;if(e!==void 0){a=!0;try{e.stop()}catch{re(ek)}}},se=()=>{r||i||o||(i=!0,u!==void 0&&(ae(),oe()))},ce=()=>{if(r||c)return;c=!0;let e=d;if(e===void 0){re(nk);return}if(f===0||p.length===0){re(tk);return}m=new Blob(p,{type:e});let t=m,n=new AbortController;ee=n;let i;try{i=this.host.transcribe(t,e,n.signal)}catch(e){re(_k(e));return}Promise.resolve(i).then(e=>{if(r||n.signal.aborted)return;let t=vk(e);t===void 0?re(ck):t.trim()===``?re(tk):ie(t)},e=>{r||n.signal.aborted||re(_k(e))})},le=()=>{!r&&!i&&t.onListening()},ue=e=>{if(r||e.size===0)return;let t=f+e.size;if(t>20971520){p=[],f=0,m=void 0,re(rk);return}p.push(e),f=t,f===20971520&&se()},de=()=>{if(r)return;o=!0;let e=l;l=void 0,yk(e),ae(),ce()},fe=()=>{r||re(ek)},pe=e=>{if(r){yk(e);return}l=e;let t;try{t=this.host.createRecorder(e,n)}catch{re(ek);return}u=t;let a=Dn(t.mimeType);if(a===void 0){re(nk);return}d=a;try{te.push(t.onStart(le)),te.push(t.onData(ue)),te.push(t.onStop(de)),te.push(t.onError(fe)),t.start(XO)}catch{re(ek);return}i&&(ae(),oe())},me;try{me=this.host.getUserMedia()}catch(e){return re(gk(e)?$O:ek),{stop:se,cancel:()=>void 0}}return Promise.resolve(me).then(pe,e=>{r||re(gk(e)?$O:ek)}),{stop:se,cancel:()=>{ne({abortUpload:!0})}}}},Sk=2e3,Ck=`Speech input requires a secure browser context`,wk=`Speech recognition is not supported in this browser`,Tk={code:`permission-denied`,message:`Microphone permission denied`},Ek={code:`no-speech`,message:`No speech detected`},Dk={code:`microphone-unavailable`,message:`Microphone is unavailable`},Ok={code:`network`,message:`Speech recognition network error`},kk={code:`unsupported`,message:`The selected language is not supported`},Ak={code:`provider`,message:`Speech recognition failed`};function jk(e){return typeof e==`function`}function Mk(){let e=Reflect.get(globalThis,`SpeechRecognition`);if(jk(e))return e;let t=Reflect.get(globalThis,`webkitSpeechRecognition`);if(jk(t))return t}function Nk(e,t){let n=globalThis.setTimeout(e,t);return()=>{globalThis.clearTimeout(n)}}function Pk(e){switch(e){case`not-allowed`:case`service-not-allowed`:return Tk;case`no-speech`:case`no-match`:return Ek;case`network`:return Ok;case`audio-capture`:return Dk;case`language-not-supported`:return kk;default:return Ak}}var Fk={stop:()=>void 0,cancel:()=>void 0},Ik=class{constructor(e){this.id=`browser`,this.isSecureContext=e.isSecureContext,this.lookupConstructor=e.recognitionConstructorLookup??Mk,this.scheduleDeadline=e.scheduleDeadline??Nk}availability(){if(!this.isSecureContext)return{available:!1,reason:Ck};let e;try{e=this.lookupConstructor()}catch{e=void 0}return e===void 0?{available:!1,reason:wk}:{available:!0}}start(e){let t=e.callbacks,n;try{n=this.lookupConstructor()}catch{n=void 0}if(n===void 0)return t.onError({code:`unsupported`,message:wk}),Fk;let r;try{r=new n}catch{return t.onError({code:`unsupported`,message:wk}),Fk}let i={recognition:r,callbacks:t,finalText:``,resultIndex:0,publishedInterim:``,terminal:!1,stopping:!1,deadlineCancel:void 0},a=()=>{i.deadlineCancel?.(),i.deadlineCancel=void 0},o=e=>{i.terminal||(i.terminal=!0,a(),t.onError(e))},s=()=>{let e=i.finalText.trim();e===``?t.onError(Ek):t.onComplete(e)},c=()=>{i.terminal||(i.terminal=!0,a(),s())};r.onstart=()=>{i.terminal||t.onListening()},r.onresult=e=>{if(i.terminal)return;let n=e.results,r=``;for(let e=i.resultIndex;e<n.length;e++){let t=n[e];if(t===void 0)continue;let a=t[0]?.transcript??``;t.isFinal?(i.finalText+=a,i.resultIndex=e+1):r+=a}r!==i.publishedInterim&&(i.publishedInterim=r,t.onInterim(r))},r.onend=()=>{c()},r.onerror=e=>{o(Pk(e.error))},r.continuous=!0,r.interimResults=!0,e.language!==void 0&&e.language!==``&&(r.lang=e.language);try{r.start()}catch{o(Dk)}return{stop:()=>{if(!(i.terminal||i.stopping)){i.stopping=!0,i.deadlineCancel=this.scheduleDeadline(()=>{if(i.deadlineCancel?.(),i.deadlineCancel=void 0,!i.terminal){i.terminal=!0;try{i.recognition.abort()}catch{}s()}},Sk);try{i.recognition.stop()}catch{o(Dk)}}},cancel:()=>{if(!i.terminal){i.terminal=!0,a();try{i.recognition.abort()}catch{}}}}}},Lk=600*1e3,Rk=130*1e3,zk=1e3,Bk=`Speech settings are still loading.`,Vk=`No speech detected`,Hk=`Dictation was canceled because the draft changed.`,Uk=`Dictated speech is too large.`,Wk=`Speech transcription timed out.`,Gk=`Speech input failed.`,Kk=`Speech input is unavailable.`,qk=class{constructor(e){this.stateValue={kind:`idle`,unavailableReason:Bk},this.nextGeneration=0,this.disposed=!1,this.browser=e.browser,this.cloud=e.cloud,this.callbacks=e.callbacks,this.createRunId=e.createRunId??rA,this.now=e.now??eA,this.scheduleInterval=e.scheduleInterval??tA,this.scheduleDeadline=e.scheduleDeadline??nA}get state(){return{...this.stateValue}}configure(e){this.disposed||(this.settingsValue=e===void 0?void 0:Yk(e),this.active===void 0&&this.publishIdle(this.stateValue.kind===`idle`?this.stateValue.error:void 0))}start(e){if(this.disposed||this.active!==void 0)return;let t=this.settingsValue;if(t===void 0){this.publishIdle(this.stateValue.kind===`idle`?this.stateValue.error:void 0);return}let n=KO(t,this.availability());if(!n.available){this.publishIdle(this.stateValue.kind===`idle`?this.stateValue.error:void 0);return}let r=n.provider,i={generation:++this.nextGeneration,runId:this.createRunId(),provider:r,adapter:r===`browser`?this.browser:this.cloud,target:Xk(e),language:t.settings.language,run:void 0,captureStartedAt:void 0,captureDeadlineCancel:void 0,elapsedIntervalCancel:void 0,transcriptionDeadlineCancel:void 0,stopRequested:!1,transcribing:!1,interimText:void 0};if(this.active=i,this.publish({kind:`requesting-permission`,runId:i.runId,provider:r}),!this.isCurrent(i))return;let a=this.providerCallbacks(i),o;try{o=r===`browser`?i.adapter.start({...i.language===void 0?{}:{language:i.language},callbacks:a}):i.adapter.start({callbacks:a})}catch{this.isCurrent(i)&&this.settleTerminal(i,{error:Gk});return}if(!this.isCurrent(i)){this.cancelRun(o);return}i.run=o,i.stopRequested&&this.stopRun(i)}stop(){if(this.disposed)return;let e=this.active;if(e!==void 0){if(this.stateValue.kind!==`listening`){this.cancel();return}this.requestStop(e)}}cancel(){if(this.disposed)return!1;let e=this.active;return e===void 0?!1:(this.settleTerminal(e,{cancelAdapter:!0}),!0)}dispose(){if(this.disposed)return;this.disposed=!0;let e=this.active;e!==void 0&&this.settleTerminal(e,{cancelAdapter:!0,publish:!1})}providerCallbacks(e){let t=e.generation;return{onListening:()=>{this.handleListening(t)},onInterim:e=>{this.handleInterim(t,e)},onTranscribing:()=>{this.handleTranscribing(t)},onComplete:e=>{this.handleComplete(t,e)},onError:e=>{this.handleError(t,e)}}}handleListening(e){let t=this.currentForGeneration(e);t===void 0||t.transcribing||t.captureStartedAt!==void 0||(t.captureStartedAt=this.monotonicNow(),this.publish({kind:`listening`,runId:t.runId,provider:t.provider,elapsedMs:0}),this.isCurrent(t)&&(this.armElapsedInterval(t),this.isCurrent(t)&&this.armCaptureDeadline(t)))}handleInterim(e,t){let n=this.currentForGeneration(e);if(!(n===void 0||this.stateValue.kind!==`listening`)){n.interimText=t;try{this.callbacks.onInterim(Xk(n.target),t)}catch{this.isCurrent(n)&&this.settleTerminal(n,{error:Gk,cancelAdapter:!0});return}this.isCurrent(n)&&this.publish({kind:`listening`,runId:n.runId,provider:n.provider,elapsedMs:this.elapsed(n),...t===``?{}:{interimText:t}})}}handleTranscribing(e){let t=this.currentForGeneration(e);if(t===void 0||t.provider!==`cloud`||t.transcribing)return;t.transcribing=!0,this.clearCaptureTimers(t);let n=this.elapsed(t);this.armTranscriptionDeadline(t)&&this.isCurrent(t)&&this.publish({kind:`transcribing`,runId:t.runId,provider:`cloud`,elapsedMs:n})}handleComplete(e,t){let n=this.currentForGeneration(e);n!==void 0&&this.settleTerminal(n,{finalText:t})}handleError(e,t){let n=this.currentForGeneration(e);n!==void 0&&this.settleTerminal(n,{error:Zk(t)})}armElapsedInterval(e){let t;try{t=this.scheduleInterval(()=>{!this.isCurrent(e)||this.stateValue.kind!==`listening`||this.publish({kind:`listening`,runId:e.runId,provider:e.provider,elapsedMs:this.elapsed(e),...e.interimText===void 0||e.interimText===``?{}:{interimText:e.interimText}})},zk)}catch{this.isCurrent(e)&&this.settleTerminal(e,{error:Gk,cancelAdapter:!0});return}if(!this.isCurrent(e)||this.stateValue.kind!==`listening`){t();return}e.elapsedIntervalCancel=t}armCaptureDeadline(e){let t;try{t=this.scheduleDeadline(()=>{!this.isCurrent(e)||this.stateValue.kind!==`listening`||this.requestStop(e)},Lk)}catch{this.isCurrent(e)&&this.settleTerminal(e,{error:Gk,cancelAdapter:!0});return}if(!this.isCurrent(e)||this.stateValue.kind!==`listening`){t();return}e.captureDeadlineCancel=t}armTranscriptionDeadline(e){let t;try{t=this.scheduleDeadline(()=>{!this.isCurrent(e)||!e.transcribing||this.settleTerminal(e,{error:Wk,cancelAdapter:!0})},Rk)}catch{return this.isCurrent(e)&&this.settleTerminal(e,{error:Gk,cancelAdapter:!0}),!1}return!this.isCurrent(e)||!e.transcribing?(t(),!1):(e.transcriptionDeadlineCancel=t,!0)}requestStop(e){!this.isCurrent(e)||e.stopRequested||e.transcribing||(e.stopRequested=!0,this.stopRun(e))}stopRun(e){if(!this.isCurrent(e))return;let t=e.run;if(t!==void 0)try{t.stop()}catch{this.isCurrent(e)&&this.settleTerminal(e,{error:Gk,cancelAdapter:!0})}}settleTerminal(e,t){if(this.active!==e)return;this.active=void 0,this.clearAllTimers(e),this.clearInterim();let n=t.error;if(t.finalText!==void 0)try{n=$k(this.callbacks.onFinal(Xk(e.target),t.finalText))}catch{n=Gk}t.publish!==!1&&!this.disposed&&!this.hasActiveRun()?this.publishIdle(n):t.publish===!1&&!this.hasActiveRun()&&(this.stateValue=this.idleState(n)),t.cancelAdapter===!0&&this.cancelRun(e.run)}clearAllTimers(e){this.clearCaptureTimers(e);let t=e.transcriptionDeadlineCancel;e.transcriptionDeadlineCancel=void 0,t?.()}clearCaptureTimers(e){let t=e.elapsedIntervalCancel;e.elapsedIntervalCancel=void 0,t?.();let n=e.captureDeadlineCancel;e.captureDeadlineCancel=void 0,n?.()}clearInterim(){try{this.callbacks.onClearInterim()}catch{}}cancelRun(e){if(e!==void 0)try{e.cancel()}catch{}}currentForGeneration(e){let t=this.active;return!this.disposed&&t?.generation===e?t:void 0}isCurrent(e){return!this.disposed&&this.active===e}hasActiveRun(){return this.active!==void 0}elapsed(e){let t=e.captureStartedAt;return t===void 0?0:Math.max(0,this.monotonicNow()-t)}monotonicNow(){try{let e=this.now();return Number.isFinite(e)?e:0}catch{return 0}}availability(){return{browser:this.adapterAvailability(this.browser),cloud:this.adapterAvailability(this.cloud)}}adapterAvailability(e){try{let t=e.availability();return t.available?{available:!0}:{available:!1,reason:Qk(t.reason)}}catch{return{available:!1,reason:Kk}}}idleState(e){let t=this.settingsValue;if(t===void 0)return{kind:`idle`,unavailableReason:Bk,...e===void 0?{}:{error:e}};let n=KO(t,this.availability());return n.available?{kind:`idle`,provider:n.provider,...e===void 0?{}:{error:e}}:{kind:`idle`,unavailableReason:n.reason,...e===void 0?{}:{error:e}}}publishIdle(e){this.publish(this.idleState(e))}publish(e){this.stateValue=e,this.disposed||this.callbacks.onStateChange(this.state)}};function Jk(e){return new qk({browser:new Ik({isSecureContext:globalThis.isSecureContext}),cloud:new xk,callbacks:e})}function Yk(e){return{contractVersion:e.contractVersion,revision:e.revision,settings:{provider:e.settings.provider,...e.settings.language===void 0?{}:{language:e.settings.language},cloud:{...e.settings.cloud}},credential:{...e.credential}}}function Xk(e){return{identity:{...e.identity},text:e.text,from:e.from,to:e.to}}function Zk(e){let t=e.message.trim();return t===``?Gk:t}function Qk(e){let t=e.trim();return t===``?Kk:t}function $k(e){switch(e){case`inserted`:return;case`empty`:return Vk;case`changed`:return Hk;case`too-large`:return Uk}}function eA(){return globalThis.performance.now()}function tA(e,t){let n=globalThis.setInterval(e,t);return()=>{globalThis.clearInterval(n)}}function nA(e,t){let n=globalThis.setTimeout(e,t);return()=>{globalThis.clearTimeout(n)}}function rA(){let e=globalThis.crypto;if(typeof e.randomUUID==`function`)return e.randomUUID();let t=e.getRandomValues(new Uint8Array(16));return`r${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}var iA=te.define(),aA=te.define(),oA=class extends s{constructor(e){super(),this.text=e}eq(e){return this.text===e.text}toDOM(){let e=document.createElement(`span`);return e.className=`prompt-speech-interim`,e.textContent=this.text,e.setAttribute(`aria-hidden`,`true`),e}},sA=d.define({create:()=>ee.none,update:(e,t)=>{let n=e.map(t.changes);for(let e of t.effects){if(e.is(aA)){n=ee.none;continue}if(!e.is(iA))continue;let{from:r,to:i,text:a}=e.value;if(!Number.isInteger(r)||!Number.isInteger(i)||r<0||i<r||i>t.state.doc.length){n=ee.none;continue}let o=new oA(a);n=ee.set([r===i?ee.widget({widget:o,side:1}).range(r):ee.replace({widget:o}).range(r,i)])}return n},provide:e=>n.decorations.from(e)});function cA(){return _`
|
|
3359
|
+
`]}};H([x({attribute:!1})],G.prototype,`messages`,void 0),H([x()],G.prototype,`sessionId`,void 0),H([x({type:Number})],G.prototype,`messageStart`,void 0),H([x({type:Number})],G.prototype,`messageEnd`,void 0),H([x({type:Number})],G.prototype,`messageTotal`,void 0),H([x({type:Boolean})],G.prototype,`hasMore`,void 0),H([x({type:Boolean})],G.prototype,`loadingMore`,void 0),H([x({type:Boolean})],G.prototype,`isSendingPrompt`,void 0),H([x({type:Boolean})],G.prototype,`isCompacting`,void 0),H([x({type:Number})],G.prototype,`pendingMessageCount`,void 0),H([x({attribute:!1})],G.prototype,`clientQueuedMessages`,void 0),H([x({attribute:!1})],G.prototype,`status`,void 0),H([x({type:Number})],G.prototype,`warningCount`,void 0),H([x({type:Boolean})],G.prototype,`warningsExpanded`,void 0),H([x({attribute:!1})],G.prototype,`onToggleWarnings`,void 0),H([x({attribute:!1})],G.prototype,`activity`,void 0),H([x({attribute:!1})],G.prototype,`sessionInfo`,void 0),H([x({attribute:!1})],G.prototype,`notificationInbox`,void 0),H([x({type:Boolean})],G.prototype,`canClearServerQueue`,void 0),H([x({type:Boolean})],G.prototype,`canMessageActions`,void 0),H([x({attribute:!1})],G.prototype,`onEditFromHere`,void 0),H([x({attribute:!1})],G.prototype,`onForkFromHere`,void 0),H([x({attribute:!1})],G.prototype,`hostSpeechStatus`,void 0),H([x()],G.prototype,`activeHostSpeechMessageKey`,void 0),H([x()],G.prototype,`hostSpeechError`,void 0),H([x({attribute:!1})],G.prototype,`onToggleHostSpeech`,void 0),H([x({attribute:!1})],G.prototype,`onClearServerQueue`,void 0),H([x({attribute:!1})],G.prototype,`onDismissWarning`,void 0),H([x({attribute:!1})],G.prototype,`onDismissNotification`,void 0),H([x({attribute:!1})],G.prototype,`onDismissAllNotifications`,void 0),H([x({type:Boolean})],G.prototype,`warningsVisible`,void 0),H([x({attribute:!1})],G.prototype,`onLoadMore`,void 0),H([C(`.chat`)],G.prototype,`chat`,void 0),H([C(`chat-minimap`)],G.prototype,`_minimap`,void 0),H([C(`dialog.image-zoom`)],G.prototype,`imageZoomDialog`,void 0),H([S()],G.prototype,`pinnedToBottom`,void 0),H([S()],G.prototype,`zoomedImage`,void 0),H([S()],G.prototype,`expandedMetaKey`,void 0),H([S()],G.prototype,`copiedMessageKey`,void 0),H([S()],G.prototype,`forkingEntryId`,void 0),H([S()],G.prototype,`collapsedNotificationTargetKeys`,void 0),H([S()],G.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),H([S()],G.prototype,`renderedGroupStart`,void 0),H([S()],G.prototype,`expandedLiveEventGroups`,void 0),H([S()],G.prototype,`loadMoreRequested`,void 0),H([S()],G.prototype,`sessionInfoOpen`,void 0),H([S()],G.prototype,`_minimapMarkers`,void 0),H([S()],G.prototype,`_minimapVisible`,void 0),G=H([b(`chat-view`)],G);var hO=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function gO(e){return typeof e==`string`&&hO.has(e)}function _O(e){switch(e){case`image/jpeg`:return`jpg`;case`image/png`:return`png`;case`image/gif`:return`gif`;case`image/webp`:return`webp`;default:return`bin`}}var vO=`application/octet-stream`,yO=`Failed to read an attachment.`;async function bO(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(wO(i,e))}catch{r=yO}return{attachments:n,...r===void 0?{}:{error:r}}}function xO(e){return e.kind===`image`&&gO(e.mimeType)}function SO(e){return e.every(e=>xO(e))}function CO(e,t){return SO(t)?e:`folder`}function wO(e,t){return gO(e.type)?{kind:`image`,name:EO(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:EO(e),mimeType:TO(e),data:t,size:e.size}}function TO(e){let t=e.type.trim();return t===``?vO:t}function EO(e){return e.name===``?gO(e.type)?`pasted-image.${_O(e.type)}`:`pasted-file.bin`:e.name}var DO=`pi-webui:attachment-delivery`;function OO(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function kO(e=OO()){try{return e?.getItem(DO)===`folder`?`folder`:`inline`}catch{return`inline`}}function AO(e,t=OO()){try{t?.setItem(DO,e)}catch{}}var jO=`(pointer: coarse), (max-width: 760px)`,MO=`pi-webui.promptEnterPreference`;function NO(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(jO):void 0}function PO(e){return e===`send`||e===`newline`?e:`auto`}function FO(e=BO()){if(e===void 0)return`auto`;try{return PO(e.getItem(MO))}catch{return`auto`}}function IO(e,t=BO()){if(t!==void 0)try{t.setItem(MO,e)}catch{}}function LO(e=NO(),t=FO()){return t===`send`||t!==`newline`&&e?.matches!==!0}function RO(e,t,n=NO()){return e?n?.matches!==!0||t:!1}function zO(e,t=NO(),n=FO()){let r=LO(t,n);return e?!r:r}function BO(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var VO=new Set([`(`,`[`,`{`]),HO=new Set([`.`,`,`,`;`,`:`,`!`,`?`,`%`,`)`,`]`,`}`]);function UO(e){return e!==void 0&&!/\s/u.test(e)}function WO(e,t){let n=e.credential.resolution;return n===`missing`?`Cloud credential is not configured`:n===`unresolved`?`Cloud credential is unresolved`:t.cloud.available?`Cloud is unavailable`:t.cloud.reason}function GO(e,t){let n=e.credential.resolution;return t.cloud.available&&(n===`resolved`||n===`unchecked`)}function KO(e,t){let n=e.settings.provider;return n===`browser`?t.browser.available?{available:!0,provider:`browser`}:{available:!1,reason:t.browser.reason}:n===`cloud`?GO(e,t)?{available:!0,provider:`cloud`}:{available:!1,reason:WO(e,t)}:t.browser.available?{available:!0,provider:`browser`}:GO(e,t)?{available:!0,provider:`cloud`}:{available:!1,reason:`${t.browser.reason}; ${WO(e,t)}`}}var qO=new TextEncoder;function JO(e,t,n){if(!Number.isInteger(e.from)||!Number.isInteger(e.to)||e.from<0||e.to<e.from||e.to>e.text.length||t!==e.text)return{ok:!1,reason:`changed`};let r=n.trim();if(r===``)return{ok:!1,reason:`empty`};if(qO.encode(r).byteLength>1048576)return{ok:!1,reason:`too-large`};let i=e.text[e.from-1],a=e.text[e.to],o=r[0],s=r[r.length-1],c=UO(i)&&UO(o)&&!VO.has(i)&&!HO.has(o),l=UO(s)&&UO(a)&&!VO.has(s)&&!HO.has(a),u=(c?` `:``)+r+(l?` `:``);return{ok:!0,insert:u,from:e.from,to:e.to,caret:e.from+u.length}}function YO(e){return[`audio/webm;codecs=opus`,`audio/ogg;codecs=opus`,`audio/mp4;codecs=mp4a.40.2`,`audio/mp4`].find(t=>e(t))}var XO=1e3,ZO=`Speech input requires a secure browser context`,QO=`No accepted recorder format`,$O={code:`permission-denied`,message:`Microphone permission denied`},ek={code:`microphone-unavailable`,message:`Microphone is unavailable`},tk={code:`no-speech`,message:`No speech detected`},nk={code:`unsupported`,message:QO},rk={code:`recording-limit`,message:`Speech recording exceeded the 20 MiB limit`},ik={code:`provider`,message:`Speech transcription is busy. Try again.`},ak={code:`provider`,message:`Speech transcription is unavailable.`},ok={code:`provider`,message:`Speech transcription timed out.`},sk={code:`network`,message:`Speech transcription network error`},ck={code:`provider`,message:`Speech transcription failed`},lk=class{constructor(e){this.recorder=e,this.mimeType=e.mimeType}onStart(e){let t=()=>{e()};return this.recorder.addEventListener(`start`,t),()=>{this.recorder.removeEventListener(`start`,t)}}onData(e){let t=t=>{e(t.data)};return this.recorder.addEventListener(`dataavailable`,t),()=>{this.recorder.removeEventListener(`dataavailable`,t)}}onStop(e){let t=()=>{e()};return this.recorder.addEventListener(`stop`,t),()=>{this.recorder.removeEventListener(`stop`,t)}}onError(e){let t=t=>{e(t)};return this.recorder.addEventListener(`error`,t),()=>{this.recorder.removeEventListener(`error`,t)}}start(e){this.recorder.start(e)}stop(){this.recorder.stop()}},uk=class{constructor(e){this.nativeStream=e}getTracks(){return this.nativeStream.getTracks()}};function dk(e){return typeof e==`object`&&!!e&&typeof Reflect.get(e,`getUserMedia`)==`function`}function fk(){let e=Reflect.get(globalThis,`navigator`);if(typeof e!=`object`||!e)return;let t=Reflect.get(e,`mediaDevices`);return dk(t)?t:void 0}function pk(){return fk()!==void 0&&typeof MediaRecorder<`u`}function mk(){return{secureContext:globalThis.isSecureContext,getUserMedia:async()=>{let e=fk();if(e===void 0)throw Error(`Browser microphone capture is unavailable`);return new uk(await e.getUserMedia({audio:!0}))},isTypeSupported:e=>{if(!pk())return!1;try{return MediaRecorder.isTypeSupported(e)}catch{return!1}},createRecorder:(e,t)=>{if(!(e instanceof uk))throw Error(`Expected browser media stream`);return new lk(new MediaRecorder(e.nativeStream,{mimeType:t}))},transcribe:(e,t,n)=>Ns.transcribe(e,t,n)}}function hk(e){try{return YO(t=>e.isTypeSupported(t))}catch{return}}function gk(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`name`);return t===`NotAllowedError`||t===`PermissionDeniedError`}function _k(e){if(e instanceof Jt)switch(e.status){case 413:return rk;case 429:return ik;case 503:return ak;case 504:return ok;default:return ck}return sk}function vk(e){if(typeof e!=`object`||!e)return;let t=Reflect.get(e,`text`);return typeof t==`string`?t:void 0}function yk(e){if(e===void 0)return;let t=new Set;for(let n of e.getTracks())if(!t.has(n)){t.add(n);try{n.stop()}catch{}}}var bk={stop:()=>void 0,cancel:()=>void 0},xk=class{constructor(e=mk()){this.id=`cloud`,this.host=e}availability(){return this.host.secureContext?hk(this.host)===void 0?{available:!1,reason:QO}:{available:!0}:{available:!1,reason:ZO}}start(e){let t=e.callbacks;if(!this.host.secureContext)return t.onError({code:`unsupported`,message:ZO}),bk;let n=hk(this.host);if(n===void 0)return t.onError(nk),bk;let r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l,u,d,f=0,p=[],m,ee,te=[],ne=(e={})=>{if(r)return!1;r=!0;let t=te.splice(0);for(let e of t)try{e()}catch{}let n=ee;if(ee=void 0,e.abortUpload===!0)try{n?.abort()}catch{}let i=u;if(u=void 0,i!==void 0&&!a&&!o){a=!0;try{i.stop()}catch{}}let s=l;return l=void 0,yk(s),p=[],f=0,m=void 0,d=void 0,!0},re=e=>{ne({abortUpload:!0})&&t.onError(e)},ie=e=>{ne()&&t.onComplete(e)},ae=()=>{r||s||(s=!0,t.onTranscribing())},oe=()=>{if(r||a)return;let e=u;if(e!==void 0){a=!0;try{e.stop()}catch{re(ek)}}},se=()=>{r||i||o||(i=!0,u!==void 0&&(ae(),oe()))},ce=()=>{if(r||c)return;c=!0;let e=d;if(e===void 0){re(nk);return}if(f===0||p.length===0){re(tk);return}m=new Blob(p,{type:e});let t=m,n=new AbortController;ee=n;let i;try{i=this.host.transcribe(t,e,n.signal)}catch(e){re(_k(e));return}Promise.resolve(i).then(e=>{if(r||n.signal.aborted)return;let t=vk(e);t===void 0?re(ck):t.trim()===``?re(tk):ie(t)},e=>{r||n.signal.aborted||re(_k(e))})},le=()=>{!r&&!i&&t.onListening()},ue=e=>{if(r||e.size===0)return;let t=f+e.size;if(t>20971520){p=[],f=0,m=void 0,re(rk);return}p.push(e),f=t,f===20971520&&se()},de=()=>{if(r)return;o=!0;let e=l;l=void 0,yk(e),ae(),ce()},fe=()=>{r||re(ek)},pe=e=>{if(r){yk(e);return}l=e;let t;try{t=this.host.createRecorder(e,n)}catch{re(ek);return}u=t;let a=Dn(t.mimeType);if(a===void 0){re(nk);return}d=a;try{te.push(t.onStart(le)),te.push(t.onData(ue)),te.push(t.onStop(de)),te.push(t.onError(fe)),t.start(XO)}catch{re(ek);return}i&&(ae(),oe())},me;try{me=this.host.getUserMedia()}catch(e){return re(gk(e)?$O:ek),{stop:se,cancel:()=>void 0}}return Promise.resolve(me).then(pe,e=>{r||re(gk(e)?$O:ek)}),{stop:se,cancel:()=>{ne({abortUpload:!0})}}}},Sk=2e3,Ck=`Speech input requires a secure browser context`,wk=`Speech recognition is not supported in this browser`,Tk={code:`permission-denied`,message:`Microphone permission denied`},Ek={code:`no-speech`,message:`No speech detected`},Dk={code:`microphone-unavailable`,message:`Microphone is unavailable`},Ok={code:`network`,message:`Speech recognition network error`},kk={code:`unsupported`,message:`The selected language is not supported`},Ak={code:`provider`,message:`Speech recognition failed`};function jk(e){return typeof e==`function`}function Mk(){let e=Reflect.get(globalThis,`SpeechRecognition`);if(jk(e))return e;let t=Reflect.get(globalThis,`webkitSpeechRecognition`);if(jk(t))return t}function Nk(e,t){let n=globalThis.setTimeout(e,t);return()=>{globalThis.clearTimeout(n)}}function Pk(e){switch(e){case`not-allowed`:case`service-not-allowed`:return Tk;case`no-speech`:case`no-match`:return Ek;case`network`:return Ok;case`audio-capture`:return Dk;case`language-not-supported`:return kk;default:return Ak}}var Fk={stop:()=>void 0,cancel:()=>void 0},Ik=class{constructor(e){this.id=`browser`,this.isSecureContext=e.isSecureContext,this.lookupConstructor=e.recognitionConstructorLookup??Mk,this.scheduleDeadline=e.scheduleDeadline??Nk}availability(){if(!this.isSecureContext)return{available:!1,reason:Ck};let e;try{e=this.lookupConstructor()}catch{e=void 0}return e===void 0?{available:!1,reason:wk}:{available:!0}}start(e){let t=e.callbacks,n;try{n=this.lookupConstructor()}catch{n=void 0}if(n===void 0)return t.onError({code:`unsupported`,message:wk}),Fk;let r;try{r=new n}catch{return t.onError({code:`unsupported`,message:wk}),Fk}let i={recognition:r,callbacks:t,finalText:``,resultIndex:0,publishedInterim:``,terminal:!1,stopping:!1,deadlineCancel:void 0},a=()=>{i.deadlineCancel?.(),i.deadlineCancel=void 0},o=e=>{i.terminal||(i.terminal=!0,a(),t.onError(e))},s=()=>{let e=i.finalText.trim();e===``?t.onError(Ek):t.onComplete(e)},c=()=>{i.terminal||(i.terminal=!0,a(),s())};r.onstart=()=>{i.terminal||t.onListening()},r.onresult=e=>{if(i.terminal)return;let n=e.results,r=``;for(let e=i.resultIndex;e<n.length;e++){let t=n[e];if(t===void 0)continue;let a=t[0]?.transcript??``;t.isFinal?(i.finalText+=a,i.resultIndex=e+1):r+=a}r!==i.publishedInterim&&(i.publishedInterim=r,t.onInterim(r))},r.onend=()=>{c()},r.onerror=e=>{o(Pk(e.error))},r.continuous=!0,r.interimResults=!0,e.language!==void 0&&e.language!==``&&(r.lang=e.language);try{r.start()}catch{o(Dk)}return{stop:()=>{if(!(i.terminal||i.stopping)){i.stopping=!0,i.deadlineCancel=this.scheduleDeadline(()=>{if(i.deadlineCancel?.(),i.deadlineCancel=void 0,!i.terminal){i.terminal=!0;try{i.recognition.abort()}catch{}s()}},Sk);try{i.recognition.stop()}catch{o(Dk)}}},cancel:()=>{if(!i.terminal){i.terminal=!0,a();try{i.recognition.abort()}catch{}}}}}},Lk=600*1e3,Rk=130*1e3,zk=1e3,Bk=5e3,Vk=`Speech settings are still loading.`,Hk=`No speech detected`,Uk=`Dictation was canceled because the draft changed.`,Wk=`Dictated speech is too large.`,Gk=`Speech transcription timed out.`,Kk=`Speech input failed.`,qk=`Speech input is unavailable.`,Jk=class{constructor(e){this.stateValue={kind:`idle`,unavailableReason:Vk},this.errorClearSequence=0,this.nextGeneration=0,this.disposed=!1,this.browser=e.browser,this.cloud=e.cloud,this.callbacks=e.callbacks,this.createRunId=e.createRunId??iA,this.now=e.now??tA,this.scheduleInterval=e.scheduleInterval??nA,this.scheduleDeadline=e.scheduleDeadline??rA}get state(){return{...this.stateValue}}configure(e){this.disposed||(this.settingsValue=e===void 0?void 0:Xk(e),this.active===void 0&&this.publishIdle(this.stateValue.kind===`idle`?this.stateValue.error:void 0))}start(e){if(this.disposed||this.active!==void 0)return;let t=this.settingsValue;if(t===void 0){this.publishIdle(this.stateValue.kind===`idle`?this.stateValue.error:void 0);return}let n=KO(t,this.availability());if(!n.available){this.publishIdle(this.stateValue.kind===`idle`?this.stateValue.error:void 0);return}let r=n.provider;this.clearErrorClear();let i={generation:++this.nextGeneration,runId:this.createRunId(),provider:r,adapter:r===`browser`?this.browser:this.cloud,target:Zk(e),language:t.settings.language,run:void 0,captureStartedAt:void 0,captureDeadlineCancel:void 0,elapsedIntervalCancel:void 0,transcriptionDeadlineCancel:void 0,stopRequested:!1,transcribing:!1,interimText:void 0};if(this.active=i,this.publish({kind:`requesting-permission`,runId:i.runId,provider:r}),!this.isCurrent(i))return;let a=this.providerCallbacks(i),o;try{o=r===`browser`?i.adapter.start({...i.language===void 0?{}:{language:i.language},callbacks:a}):i.adapter.start({callbacks:a})}catch{this.isCurrent(i)&&this.settleTerminal(i,{error:Kk});return}if(!this.isCurrent(i)){this.cancelRun(o);return}i.run=o,i.stopRequested&&this.stopRun(i)}stop(){if(this.disposed)return;let e=this.active;if(e!==void 0){if(this.stateValue.kind!==`listening`){this.cancel();return}this.requestStop(e)}}cancel(){if(this.disposed)return!1;let e=this.active;return e===void 0?!1:(this.settleTerminal(e,{cancelAdapter:!0}),!0)}dispose(){if(this.disposed)return;this.disposed=!0,this.clearErrorClear();let e=this.active;e!==void 0&&this.settleTerminal(e,{cancelAdapter:!0,publish:!1})}providerCallbacks(e){let t=e.generation;return{onListening:()=>{this.handleListening(t)},onInterim:e=>{this.handleInterim(t,e)},onTranscribing:()=>{this.handleTranscribing(t)},onComplete:e=>{this.handleComplete(t,e)},onError:e=>{this.handleError(t,e)}}}handleListening(e){let t=this.currentForGeneration(e);t===void 0||t.transcribing||t.captureStartedAt!==void 0||(t.captureStartedAt=this.monotonicNow(),this.publish({kind:`listening`,runId:t.runId,provider:t.provider,elapsedMs:0}),this.isCurrent(t)&&(this.armElapsedInterval(t),this.isCurrent(t)&&this.armCaptureDeadline(t)))}handleInterim(e,t){let n=this.currentForGeneration(e);if(!(n===void 0||this.stateValue.kind!==`listening`)){n.interimText=t;try{this.callbacks.onInterim(Zk(n.target),t)}catch{this.isCurrent(n)&&this.settleTerminal(n,{error:Kk,cancelAdapter:!0});return}this.isCurrent(n)&&this.publish({kind:`listening`,runId:n.runId,provider:n.provider,elapsedMs:this.elapsed(n),...t===``?{}:{interimText:t}})}}handleTranscribing(e){let t=this.currentForGeneration(e);if(t===void 0||t.provider!==`cloud`||t.transcribing)return;t.transcribing=!0,this.clearCaptureTimers(t);let n=this.elapsed(t);this.armTranscriptionDeadline(t)&&this.isCurrent(t)&&this.publish({kind:`transcribing`,runId:t.runId,provider:`cloud`,elapsedMs:n})}handleComplete(e,t){let n=this.currentForGeneration(e);n!==void 0&&this.settleTerminal(n,{finalText:t})}handleError(e,t){let n=this.currentForGeneration(e);n!==void 0&&this.settleTerminal(n,{error:Qk(t)})}armElapsedInterval(e){let t;try{t=this.scheduleInterval(()=>{!this.isCurrent(e)||this.stateValue.kind!==`listening`||this.publish({kind:`listening`,runId:e.runId,provider:e.provider,elapsedMs:this.elapsed(e),...e.interimText===void 0||e.interimText===``?{}:{interimText:e.interimText}})},zk)}catch{this.isCurrent(e)&&this.settleTerminal(e,{error:Kk,cancelAdapter:!0});return}if(!this.isCurrent(e)||this.stateValue.kind!==`listening`){t();return}e.elapsedIntervalCancel=t}armCaptureDeadline(e){let t;try{t=this.scheduleDeadline(()=>{!this.isCurrent(e)||this.stateValue.kind!==`listening`||this.requestStop(e)},Lk)}catch{this.isCurrent(e)&&this.settleTerminal(e,{error:Kk,cancelAdapter:!0});return}if(!this.isCurrent(e)||this.stateValue.kind!==`listening`){t();return}e.captureDeadlineCancel=t}armTranscriptionDeadline(e){let t;try{t=this.scheduleDeadline(()=>{!this.isCurrent(e)||!e.transcribing||this.settleTerminal(e,{error:Gk,cancelAdapter:!0})},Rk)}catch{return this.isCurrent(e)&&this.settleTerminal(e,{error:Kk,cancelAdapter:!0}),!1}return!this.isCurrent(e)||!e.transcribing?(t(),!1):(e.transcriptionDeadlineCancel=t,!0)}requestStop(e){!this.isCurrent(e)||e.stopRequested||e.transcribing||(e.stopRequested=!0,this.stopRun(e))}stopRun(e){if(!this.isCurrent(e))return;let t=e.run;if(t!==void 0)try{t.stop()}catch{this.isCurrent(e)&&this.settleTerminal(e,{error:Kk,cancelAdapter:!0})}}settleTerminal(e,t){if(this.active!==e)return;this.active=void 0,this.clearAllTimers(e),this.clearInterim();let n=t.error;if(t.finalText!==void 0)try{n=eA(this.callbacks.onFinal(Zk(e.target),t.finalText))}catch{n=Kk}t.publish!==!1&&!this.disposed&&!this.hasActiveRun()?this.publishTerminalIdle(n):t.publish===!1&&!this.hasActiveRun()&&(this.stateValue=this.idleState(n)),t.cancelAdapter===!0&&this.cancelRun(e.run)}clearAllTimers(e){this.clearCaptureTimers(e);let t=e.transcriptionDeadlineCancel;e.transcriptionDeadlineCancel=void 0,t?.()}clearCaptureTimers(e){let t=e.elapsedIntervalCancel;e.elapsedIntervalCancel=void 0,t?.();let n=e.captureDeadlineCancel;e.captureDeadlineCancel=void 0,n?.()}clearInterim(){try{this.callbacks.onClearInterim()}catch{}}cancelRun(e){if(e!==void 0)try{e.cancel()}catch{}}currentForGeneration(e){let t=this.active;return!this.disposed&&t?.generation===e?t:void 0}isCurrent(e){return!this.disposed&&this.active===e}hasActiveRun(){return this.active!==void 0}elapsed(e){let t=e.captureStartedAt;return t===void 0?0:Math.max(0,this.monotonicNow()-t)}monotonicNow(){try{let e=this.now();return Number.isFinite(e)?e:0}catch{return 0}}availability(){return{browser:this.adapterAvailability(this.browser),cloud:this.adapterAvailability(this.cloud)}}adapterAvailability(e){try{let t=e.availability();return t.available?{available:!0}:{available:!1,reason:$k(t.reason)}}catch{return{available:!1,reason:qk}}}idleState(e){let t=this.settingsValue;if(t===void 0)return{kind:`idle`,unavailableReason:Vk,...e===void 0?{}:{error:e}};let n=KO(t,this.availability());return n.available?{kind:`idle`,provider:n.provider,...e===void 0?{}:{error:e}}:{kind:`idle`,unavailableReason:n.reason,...e===void 0?{}:{error:e}}}publishIdle(e){this.publish(this.idleState(e))}clearErrorClear(){let e=this.errorClearCancel;this.errorClearCancel=void 0,this.errorClearSequence+=1;try{e?.()}catch{}}armErrorClear(){let e=++this.errorClearSequence,t;try{t=this.scheduleDeadline(()=>{this.disposed||e!==this.errorClearSequence||this.active!==void 0||this.stateValue.kind!==`idle`||this.stateValue.error===void 0||(this.errorClearCancel=void 0,this.errorClearSequence+=1,this.publishIdle(void 0))},Bk)}catch{return}if(this.disposed||e!==this.errorClearSequence||this.active!==void 0||this.stateValue.kind!==`idle`||this.stateValue.error===void 0){try{t()}catch{}return}this.errorClearCancel=t}publishTerminalIdle(e){this.clearErrorClear(),this.publishIdle(e),e!==void 0&&this.active===void 0&&this.stateValue.kind===`idle`&&this.stateValue.error===e&&this.armErrorClear()}publish(e){this.stateValue=e,this.disposed||this.callbacks.onStateChange(this.state)}};function Yk(e){return new Jk({browser:new Ik({isSecureContext:globalThis.isSecureContext}),cloud:new xk,callbacks:e})}function Xk(e){return{contractVersion:e.contractVersion,revision:e.revision,settings:{provider:e.settings.provider,...e.settings.language===void 0?{}:{language:e.settings.language},cloud:{...e.settings.cloud}},credential:{...e.credential}}}function Zk(e){return{identity:{...e.identity},text:e.text,from:e.from,to:e.to}}function Qk(e){let t=e.message.trim();return t===``?Kk:t}function $k(e){let t=e.trim();return t===``?qk:t}function eA(e){switch(e){case`inserted`:return;case`empty`:return Hk;case`changed`:return Uk;case`too-large`:return Wk}}function tA(){return globalThis.performance.now()}function nA(e,t){let n=globalThis.setInterval(e,t);return()=>{globalThis.clearInterval(n)}}function rA(e,t){let n=globalThis.setTimeout(e,t);return()=>{globalThis.clearTimeout(n)}}function iA(){let e=globalThis.crypto;if(typeof e.randomUUID==`function`)return e.randomUUID();let t=e.getRandomValues(new Uint8Array(16));return`r${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}var aA=te.define(),oA=te.define(),sA=class extends s{constructor(e){super(),this.text=e}eq(e){return this.text===e.text}toDOM(){let e=document.createElement(`span`);return e.className=`prompt-speech-interim`,e.textContent=this.text,e.setAttribute(`aria-hidden`,`true`),e}},cA=d.define({create:()=>ee.none,update:(e,t)=>{let n=e.map(t.changes);for(let e of t.effects){if(e.is(oA)){n=ee.none;continue}if(!e.is(aA))continue;let{from:r,to:i,text:a}=e.value;if(!Number.isInteger(r)||!Number.isInteger(i)||r<0||i<r||i>t.state.doc.length){n=ee.none;continue}let o=new sA(a);n=ee.set([r===i?ee.widget({widget:o,side:1}).range(r):ee.replace({widget:o}).range(r,i)])}return n},provide:e=>n.decorations.from(e)});function lA(){return _`
|
|
3360
3360
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3361
3361
|
<rect x="9" y="3" width="6" height="11" rx="3"></rect>
|
|
3362
3362
|
<path d="M6 11a6 6 0 0 0 12 0"></path>
|
|
3363
3363
|
<path d="M12 17v4"></path>
|
|
3364
3364
|
<path d="M8.5 21h7"></path>
|
|
3365
3365
|
</svg>
|
|
3366
|
-
`}function
|
|
3366
|
+
`}function uA(){return _`
|
|
3367
3367
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3368
3368
|
<path d="M4 12h2"></path>
|
|
3369
3369
|
<path d="M8 8v8"></path>
|
|
@@ -3371,55 +3371,55 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3371
3371
|
<path d="M16 8v8"></path>
|
|
3372
3372
|
<path d="M18 12h2"></path>
|
|
3373
3373
|
</svg>
|
|
3374
|
-
`}function
|
|
3374
|
+
`}function dA(){return _`
|
|
3375
3375
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3376
3376
|
<path d="M20 11.5 12.5 19a4 4 0 0 1-5.66-5.66l7.07-7.07a2.5 2.5 0 0 1 3.54 3.54l-7.07 7.07a1 1 0 0 1-1.42-1.42l6.37-6.36"></path>
|
|
3377
3377
|
</svg>
|
|
3378
|
-
`}function
|
|
3378
|
+
`}function fA(){return _`
|
|
3379
3379
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3380
3380
|
<polyline points="4 14 10 14 10 20"></polyline>
|
|
3381
3381
|
<polyline points="20 10 14 10 14 4"></polyline>
|
|
3382
3382
|
<line x1="10" y1="14" x2="3" y2="21"></line>
|
|
3383
3383
|
<line x1="21" y1="3" x2="14" y2="10"></line>
|
|
3384
3384
|
</svg>
|
|
3385
|
-
`}function
|
|
3385
|
+
`}function pA(){return _`
|
|
3386
3386
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3387
3387
|
<path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
|
|
3388
3388
|
<path d="M21 3 11.5 12.5"></path>
|
|
3389
3389
|
</svg>
|
|
3390
|
-
`}function
|
|
3390
|
+
`}function mA(){return _`
|
|
3391
3391
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3392
3392
|
<path d="M4 7h11"></path>
|
|
3393
3393
|
<path d="M4 12h7"></path>
|
|
3394
3394
|
<path d="M4 17h7"></path>
|
|
3395
3395
|
<path d="m15 14 5 3-5 3z"></path>
|
|
3396
3396
|
</svg>
|
|
3397
|
-
`}function
|
|
3397
|
+
`}function hA(){return pA()}function gA(){return _`
|
|
3398
3398
|
<svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3399
3399
|
<rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
|
|
3400
3400
|
</svg>
|
|
3401
|
-
`}function
|
|
3401
|
+
`}function _A(e){let t=Math.max(e.total,1),n=t>1?1.4:0,r=(18-n*(t-1))/t,i=Math.min(r,5),a=3+(18-(i*t+n*(t-1)))/2,o=Math.min(.75,i*.3);return _`
|
|
3402
3402
|
<svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3403
3403
|
${Array.from({length:t},(r,s)=>{let c=a+s*(i+n),l=5+(t===1?1:s/(t-1))*13,u=21-l;return _`<rect class=${s<e.filled?`gauge-bar gauge-bar-active`:`gauge-bar`} x=${c} y=${u} width=${i} height=${l} rx=${o}></rect>`})}
|
|
3404
3404
|
</svg>
|
|
3405
|
-
`}var
|
|
3405
|
+
`}var vA=St(class extends Ct{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===xt.ELEMENT}update(e,[t,n]){if(!this.isElementPart)throw Error(`scrollWhenSelected must be used on an element`);if(t&&(!this.wasSelected||n!==this.previousKey)){let t=`element`in e?e.element:void 0;requestAnimationFrame(()=>{t instanceof HTMLElement&&typeof t.scrollIntoView==`function`&&t.scrollIntoView({block:`nearest`})})}this.wasSelected=t,this.previousKey=n}render(e,t){}}),yA=class extends y{constructor(...e){super(...e),this.items=[],this.selectedIndex=0}render(){return this.items.length?g`
|
|
3406
3406
|
<div class="menu">
|
|
3407
3407
|
${this.items.map((e,t)=>g`
|
|
3408
|
-
<button class=${t===this.selectedIndex?`selected`:``} ${
|
|
3408
|
+
<button class=${t===this.selectedIndex?`selected`:``} ${vA(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
|
|
3409
3409
|
<strong>${e.insertText}</strong>
|
|
3410
3410
|
<span>${e.detail}</span>
|
|
3411
3411
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
3412
3412
|
</button>
|
|
3413
3413
|
`)}
|
|
3414
3414
|
</div>
|
|
3415
|
-
`:null}static{this.styles=eb}};H([x({attribute:!1})],
|
|
3415
|
+
`:null}static{this.styles=eb}};H([x({attribute:!1})],yA.prototype,`items`,void 0),H([x({type:Number})],yA.prototype,`selectedIndex`,void 0),H([x({attribute:!1})],yA.prototype,`onPick`,void 0),yA=H([b(`autocomplete-menu`)],yA);var bA=`Model tier ladder is invalid. Tiered mode stays unavailable until the ladder is fixed in Settings → Model tiers.`,xA=class extends y{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.editable=!1,this.error=``,this.menuOpen=!1,this.menuStyle=``,this.onDocumentClick=e=>{!this.menuOpen||xC(e,this.renderRoot)||(this.menuOpen=!1)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick,!0)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick,!0),super.disconnectedCallback()}render(){let e=this.effectiveStatus();if(e===void 0)return v;let t=e.mode===`tiered`?`Tiered`:`Exact`,n=this.compactDiagnostic(e);return g`
|
|
3416
3416
|
<button
|
|
3417
3417
|
type="button"
|
|
3418
3418
|
class="policy-trigger action-menu"
|
|
3419
3419
|
aria-label=${`Session model mode: ${t}`}
|
|
3420
3420
|
aria-haspopup="menu"
|
|
3421
3421
|
aria-expanded=${String(this.menuOpen)}
|
|
3422
|
-
title=${
|
|
3422
|
+
title=${SA(e,t)}
|
|
3423
3423
|
@click=${e=>{this.toggleModeMenu(e.currentTarget)}}
|
|
3424
3424
|
>
|
|
3425
3425
|
<span class="policy-mode">${t}</span>
|
|
@@ -3449,7 +3449,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3449
3449
|
<span class="policy-mode-hint">${n}</span>
|
|
3450
3450
|
<span class="policy-mode-check" aria-hidden="true">${i?`✓`:v}</span>
|
|
3451
3451
|
</button>
|
|
3452
|
-
`}toggleModeMenu(e){if(!this.canMutate()){this.menuOpen=!1;return}if(this.menuOpen){this.menuOpen=!1;return}this.menuStyle=SC(e,{constrainTo:`viewport`}),this.menuOpen=!0}selectMode(e){if(!this.canMutate()){this.menuOpen=!1;return}this.menuOpen=!1,this.onSelectMode?.(e)}handleMenuKeydown(e){!this.menuOpen||e.key!==`Escape`||(e.preventDefault(),e.stopPropagation(),this.menuOpen=!1,this.updateComplete.then(()=>{this.isConnected&&this.renderRoot.querySelector(`.policy-trigger`)?.focus()}))}compactDiagnostic(e){let t=this.blockedReason();if(t!==void 0)return t;if(e.mode===`tiered`&&!e.ladderValid)return
|
|
3452
|
+
`}toggleModeMenu(e){if(!this.canMutate()){this.menuOpen=!1;return}if(this.menuOpen){this.menuOpen=!1;return}this.menuStyle=SC(e,{constrainTo:`viewport`}),this.menuOpen=!0}selectMode(e){if(!this.canMutate()){this.menuOpen=!1;return}this.menuOpen=!1,this.onSelectMode?.(e)}handleMenuKeydown(e){!this.menuOpen||e.key!==`Escape`||(e.preventDefault(),e.stopPropagation(),this.menuOpen=!1,this.updateComplete.then(()=>{this.isConnected&&this.renderRoot.querySelector(`.policy-trigger`)?.focus()}))}compactDiagnostic(e){let t=this.blockedReason();if(t!==void 0)return t;if(e.mode===`tiered`&&!e.ladderValid)return bA;let n=this.error.trim();return n===``?void 0:n}effectiveStatus(){return this.status}blockedReason(){let e=this.effectiveStatus()?.blockedReason;return e===void 0||e.trim()===``?void 0:e}canMutate(){return this.editable&&!this.loading&&!this.saving}static{this.styles=h`
|
|
3453
3453
|
:host { position: relative; min-width: 0; display: inline-flex; align-items: center; gap: 6px; font: inherit; }
|
|
3454
3454
|
* { box-sizing: border-box; }
|
|
3455
3455
|
.policy-trigger { flex: 1 1 auto; min-width: 0; max-width: 100%; overflow: hidden; display: inline-flex; align-items: baseline; gap: 6px; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 4px 9px; font: inherit; font-size: 12px; line-height: 1.3; cursor: pointer; }
|
|
@@ -3463,7 +3463,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3463
3463
|
.policy-mode-hint { min-width: 0; color: var(--pi-muted); font-size: 11px; line-height: 1.3; }
|
|
3464
3464
|
.policy-mode-check { grid-column: 2; grid-row: 1 / span 2; width: 18px; color: var(--pi-accent); font-weight: 700; text-align: center; }
|
|
3465
3465
|
.policy-diagnostic { min-width: 0; max-width: 22ch; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--pi-danger); font-size: 11px; }
|
|
3466
|
-
`}};H([x({attribute:!1})],
|
|
3466
|
+
`}};H([x({attribute:!1})],xA.prototype,`status`,void 0),H([x({attribute:!1})],xA.prototype,`catalog`,void 0),H([x({type:Boolean})],xA.prototype,`loading`,void 0),H([x({type:Boolean})],xA.prototype,`saving`,void 0),H([x({type:Boolean})],xA.prototype,`editable`,void 0),H([x()],xA.prototype,`error`,void 0),H([x({attribute:!1})],xA.prototype,`onSelectMode`,void 0),H([S()],xA.prototype,`menuOpen`,void 0),H([S()],xA.prototype,`menuStyle`,void 0),xA=H([b(`session-model-policy-control`)],xA);function SA(e,t){let n=e.tier;return`Session model mode: ${t}${e.mode===`tiered`&&n!==void 0?` · ${kl[n]}`:``} · ${Ml(e.resolved)}`}var CA=class extends y{constructor(...e){super(...e),this.options=[],this.label=``,this.editable=!1,this.menuOpen=!1,this.menuStyle=``,this.onDocumentClick=e=>{!this.menuOpen||xC(e,this.renderRoot)||(this.menuOpen=!1)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick,!0)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick,!0),super.disconnectedCallback()}render(){return g`
|
|
3467
3467
|
<button
|
|
3468
3468
|
type="button"
|
|
3469
3469
|
class="thinking-trigger action-menu"
|
|
@@ -3473,7 +3473,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3473
3473
|
title=${this.label}
|
|
3474
3474
|
@click=${e=>{this.toggleMenu(e.currentTarget)}}
|
|
3475
3475
|
>
|
|
3476
|
-
<span class="thinking-trigger-gauge">${
|
|
3476
|
+
<span class="thinking-trigger-gauge">${_A(this.triggerGauge())}</span>
|
|
3477
3477
|
<span class="thinking-chevron" aria-hidden="true">▾</span>
|
|
3478
3478
|
</button>
|
|
3479
3479
|
${this.menuOpen?this.renderMenu():null}
|
|
@@ -3524,7 +3524,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3524
3524
|
.thinking-item-unsupported { cursor: not-allowed; opacity: 0.72; }
|
|
3525
3525
|
.thinking-item-unsupported:hover, .thinking-item-unsupported:focus-visible { background: transparent; }
|
|
3526
3526
|
.thinking-item-check { grid-column: 2; grid-row: 1 / span 3; width: 18px; color: var(--pi-accent); font-weight: 700; text-align: center; }
|
|
3527
|
-
`}};H([x({attribute:!1})],
|
|
3527
|
+
`}};H([x({attribute:!1})],CA.prototype,`options`,void 0),H([x()],CA.prototype,`label`,void 0),H([x({type:Boolean})],CA.prototype,`editable`,void 0),H([x({attribute:!1})],CA.prototype,`onSelectLevel`,void 0),H([S()],CA.prototype,`menuOpen`,void 0),H([S()],CA.prototype,`menuStyle`,void 0),CA=H([b(`session-thinking-menu`)],CA);var wA=class extends y{constructor(...e){super(...e),this.label=``,this.editable=!1,this.menuOpen=!1,this.menuStyle=``,this.onDocumentClick=e=>{!this.menuOpen||xC(e,this.renderRoot)||(this.menuOpen=!1)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick,!0)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick,!0),super.disconnectedCallback()}render(){let e=this.selectedTier===void 0?void 0:this.catalog?.ladder?.[this.selectedTier];return g`
|
|
3528
3528
|
<button
|
|
3529
3529
|
type="button"
|
|
3530
3530
|
class="tier-trigger action-menu"
|
|
@@ -3581,12 +3581,12 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3581
3581
|
.tier-item-invalid:hover, .tier-item-invalid:focus-visible { background: transparent; }
|
|
3582
3582
|
.tier-item-reason { color: var(--pi-danger); }
|
|
3583
3583
|
.tier-item-check { grid-column: 2; grid-row: 1 / span 2; width: 18px; color: var(--pi-accent); font-weight: 700; text-align: center; }
|
|
3584
|
-
`}};H([x({attribute:!1})],
|
|
3584
|
+
`}};H([x({attribute:!1})],wA.prototype,`catalog`,void 0),H([x()],wA.prototype,`selectedTier`,void 0),H([x()],wA.prototype,`label`,void 0),H([x({type:Boolean})],wA.prototype,`editable`,void 0),H([x({attribute:!1})],wA.prototype,`onSelectTier`,void 0),H([S()],wA.prototype,`menuOpen`,void 0),H([S()],wA.prototype,`menuStyle`,void 0),wA=H([b(`session-tier-menu`)],wA);var K=class extends y{constructor(...t){super(...t),this.disabled=!1,this.sendDisabled=!1,this.machineId=`local`,this.workspaceScopedFileSuggestions=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.showSessionConfiguration=!1,this.policyThinkingOptions=[],this.modelPolicyLoading=!1,this.modelPolicySaving=!1,this.modelPolicyError=``,this.availableThinkingLevels=[],this.attachmentDrafts=Yd,this.draft=``,this.currentInputMode={kind:`normal`},this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=kO(),this.attachmentError=void 0,this.speechInputState={kind:`idle`,unavailableReason:`Speech settings are still loading.`},this.requestVersion=0,this.editableCompartment=new e,this.readOnlyCompartment=new e,this.mobilePromptEnterMedia=NO(),this.explicitShiftKeyActive=!1,this.speechInputController=Yk({onStateChange:e=>{this.handleSpeechInputStateChange(e)},onInterim:(e,t)=>{this.applySpeechInputInterim(e,t)},onFinal:(e,t)=>this.applySpeechInputFinal(e,t),onClearInterim:()=>{this.clearSpeechInputInterim()}})}willUpdate(e){if(e.has(`disabled`)&&this.disabled&&this.speechInputActive()&&this.cancelSpeechInput(),(e.has(`sessionId`)||e.has(`machineId`)||e.has(`projectId`)||e.has(`workspaceId`))&&(this.cancelSpeechInput(),!e.has(`sessionId`)&&!e.has(`machineId`))||!e.has(`sessionId`)&&!e.has(`machineId`))return;let t=e.has(`sessionId`)?e.get(`sessionId`):this.sessionId,n=MA(e.has(`machineId`)?e.get(`machineId`):this.machineId,t),r=this.attachmentScope??(n===void 0?void 0:this.attachmentDrafts.findScope(n));n!==void 0&&ef(n,this.draft);let i=MA(this.machineId,this.sessionId);n!==void 0&&n!==i&&r?.currentKey()===n&&(this.attachments.length>0||this.attachmentError!==void 0)&&r.write(this.currentAttachmentDraft()),this.draft=i===void 0?``:$d(i);let a=i===void 0?void 0:this.attachmentDrafts.openScope(i);this.attachmentScope=a,this.adoptAttachmentDraft(a?.read()??{attachments:[]}),this.currentInputMode=dp(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){if(e.has(`status`)&&[...e.keys()].every(e=>e===`status`||e===`modelPolicyStatus`)){let t=kA(e.get(`status`),this.status),n=!e.has(`modelPolicyStatus`)||AA(e.get(`modelPolicyStatus`),this.modelPolicyStatus);return!t||!n}return!0}firstUpdated(){this.createEditor()}updated(e){e.has(`speechInputSettings`)&&this.speechInputController.configure(this.speechInputSettings),(e.has(`disabled`)||e.has(`speechInputState`))&&this.updateEditorDisabledState(),(e.has(`sessionId`)||e.has(`machineId`))&&this.syncEditorDoc()}disconnectedCallback(){this.cancelSpeechInput(),this.speechInputController.dispose(),this.clearSpeechInputInterim(),this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){let e=this.currentInputMode.kind===`shell`?this.currentInputMode:void 0,t=e!==void 0,n=this.canSteer||this.isCompacting,r=this.speechInputActive(),i=this.disabled||this.sending||r,a=i||this.sendDisabled,o=i||this.canSteer||this.isCompacting||this.canStop;return g`
|
|
3585
3585
|
<footer class=${t?`shell-mode`:``} @paste=${e=>{this.handlePaste(e)}} @dragover=${e=>{this.handleDragOver(e)}} @drop=${e=>{this.handleDrop(e)}}>
|
|
3586
3586
|
<div class="editor-wrap">
|
|
3587
3587
|
<div class=${`markdown-editor${this.disabled?` markdown-editor-disabled`:``}`} aria-label="Message pi" aria-disabled=${this.disabled?`true`:`false`} aria-readonly=${r?`true`:v}></div>
|
|
3588
3588
|
<input class="attachment-input" type="file" multiple hidden @change=${e=>{this.handleFileInput(e)}} />
|
|
3589
|
-
<button class="editor-attach icon-button" ?disabled=${i} title="Attach files" aria-label="Attach files" @click=${()=>{this.speechInputActive()||this.attachmentInput?.click()}}>${
|
|
3589
|
+
<button class="editor-attach icon-button" ?disabled=${i} title="Attach files" aria-label="Attach files" @click=${()=>{this.speechInputActive()||this.attachmentInput?.click()}}>${dA()}</button>
|
|
3590
3590
|
${t?g`<div class="mode-hint">Shell command${e.excludeFromContext?` · excluded from context`:``}</div>`:null}
|
|
3591
3591
|
${this.isCompacting&&!t?g`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
|
|
3592
3592
|
${this.renderAttachments()}
|
|
@@ -3595,15 +3595,15 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3595
3595
|
<div class="actions">
|
|
3596
3596
|
${this.renderCompactStatus()}
|
|
3597
3597
|
${this.renderSpeechInputStatus()}
|
|
3598
|
-
${this.onCompact===void 0?null:g`<button class="compact-button" ?disabled=${o} title="Compact context" aria-label="Compact context" @click=${()=>{this.speechInputActive()||this.onCompact?.()}}>${
|
|
3598
|
+
${this.onCompact===void 0?null:g`<button class="compact-button" ?disabled=${o} title="Compact context" aria-label="Compact context" @click=${()=>{this.speechInputActive()||this.onCompact?.()}}>${fA()}<span>Compact</span></button>`}
|
|
3599
3599
|
${this.renderSpeechInputButton()}
|
|
3600
|
-
<button class="icon-button send-button" ?disabled=${a} title=${n?`Queue until the current activity finishes`:`Send message`} aria-label=${n?`Queue message`:`Send message`} @click=${()=>{this.send(`followUp`)}}>${n?
|
|
3601
|
-
${this.canSteer&&!this.isCompacting?g`<button class="icon-button steer-button" ?disabled=${a} title="Steer the current response before the next model call" aria-label="Steer current response" @click=${()=>{this.send(`steer`)}}>${
|
|
3602
|
-
<button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?`Stop current work and clear queued messages`:`Nothing running`} aria-label="Stop current work" @click=${()=>this.onStop?.()}>${
|
|
3600
|
+
<button class="icon-button send-button" ?disabled=${a} title=${n?`Queue until the current activity finishes`:`Send message`} aria-label=${n?`Queue message`:`Send message`} @click=${()=>{this.send(`followUp`)}}>${n?mA():pA()}</button>
|
|
3601
|
+
${this.canSteer&&!this.isCompacting?g`<button class="icon-button steer-button" ?disabled=${a} title="Steer the current response before the next model call" aria-label="Steer current response" @click=${()=>{this.send(`steer`)}}>${hA()}</button>`:null}
|
|
3602
|
+
<button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?`Stop current work and clear queued messages`:`Nothing running`} aria-label="Stop current work" @click=${()=>this.onStop?.()}>${gA()}</button>
|
|
3603
3603
|
</div>
|
|
3604
3604
|
${this.renderSpeechInputError()}
|
|
3605
3605
|
</footer>
|
|
3606
|
-
`}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=
|
|
3606
|
+
`}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=MA(this.machineId,this.sessionId);t!==void 0&&ef(t,e);let n=this.editor;if(n!==void 0){let t=n.state.doc.toString();n.dispatch({...t===e?{}:{changes:{from:0,to:t.length,insert:e}},selection:l.cursor(e.length)})}this.requestVersion+=1,this.currentInputMode=dp(e),this.completions=[],this.selectedIndex=0}get view(){return this.editor}cancelSpeechInput(){return this.speechInputController.cancel()}speechInputActive(){return this.speechInputState.kind!==`idle`}handleSpeechInputStateChange(e){let t=this.speechInputActive();this.speechInputState=e,this.updateEditorDisabledState(),t&&e.kind===`idle`&&queueMicrotask(()=>{this.speechInputActive()||this.editor?.focus()})}handleSpeechInputControl(){switch(this.speechInputState.kind){case`idle`:this.disabled||this.startSpeechInput();return;case`listening`:this.speechInputController.stop();return;case`requesting-permission`:case`transcribing`:this.cancelSpeechInput();return}}startSpeechInput(){if(this.disabled)return;this.requestVersion+=1,this.completions=[],this.selectedIndex=0,this.clearSpeechInputInterim();let e=this.captureSpeechInputTarget();if(e===void 0){this.speechInputState={kind:`idle`,...this.speechInputState.provider===void 0?{}:{provider:this.speechInputState.provider},error:`Speech input is unavailable for this composer.`};return}this.speechInputController.start(e)}captureSpeechInputTarget(){let e=this.editor,t=this.speechInputComposerIdentity();if(e===void 0||t===void 0)return;let n=e.state.selection.main;return{identity:t,text:e.state.doc.toString(),from:n.from,to:n.to}}speechInputComposerIdentity(){let e=TA(this.machineId),t=TA(this.projectId),n=TA(this.workspaceId);if(e===void 0||t===void 0||n===void 0)return;let r=this.sessionId;if(r===void 0||r===``)return{kind:`starter`,machineId:e,projectId:t,workspaceId:n};if(typeof r==`string`)return{kind:`session`,machineId:e,projectId:t,workspaceId:n,sessionId:r}}speechInputTargetIsCurrent(e){let t=this.speechInputComposerIdentity(),n=this.editor;return!this.disabled&&t!==void 0&&n!==void 0&&EA(t,e.identity)&&n.state.doc.toString()===e.text}applySpeechInputInterim(e,t){this.speechInputTargetIsCurrent(e)&&this.editor?.dispatch({effects:t===``?oA.of(void 0):aA.of({from:e.from,to:e.to,text:t})})}applySpeechInputFinal(e,t){let n=this.editor;if(n===void 0||!this.speechInputTargetIsCurrent(e))return`changed`;let r=JO(e,n.state.doc.toString(),t);return r.ok?(n.dispatch({changes:{from:r.from,to:r.to,insert:r.insert},selection:l.cursor(r.caret),effects:oA.of(void 0)}),`inserted`):r.reason}clearSpeechInputInterim(){this.editor?.dispatch({effects:oA.of(void 0)})}renderSpeechInputButton(){let e=this.speechInputState;if(e.kind===`idle`){let t=this.disabled?`Dictation is unavailable while this prompt is disabled.`:e.unavailableReason,n=t??(e.provider===void 0?`Start dictation`:`Start dictation · ${DA(e.provider)}`);return g`<button class="icon-button speech-input-button speech-input-idle" ?disabled=${t!==void 0} title=${n} aria-label=${n} @click=${()=>{this.handleSpeechInputControl()}}>${lA()}</button>`}if(e.kind===`requesting-permission`){let t=`Cancel dictation · ${DA(e.provider)}`;return g`<button class="icon-button speech-input-button speech-input-requesting" title=${t} aria-label=${t} @click=${()=>{this.handleSpeechInputControl()}}>${lA()}</button>`}if(e.kind===`listening`){let t=`Stop dictation · ${DA(e.provider)}`;return g`<button class="icon-button speech-input-button speech-input-listening" title=${t} aria-label=${t} @click=${()=>{this.handleSpeechInputControl()}}>${gA()}</button>`}let t=`Cancel transcription · Cloud`;return g`<button class="icon-button speech-input-button speech-input-transcribing" title=${t} aria-label=${t} @click=${()=>{this.handleSpeechInputControl()}}>${uA()}</button>`}renderSpeechInputStatus(){let e=this.speechInputState;if(e.kind===`idle`)return null;if(e.kind===`requesting-permission`)return g`<div class="speech-input-status">Requesting microphone permission · ${DA(e.provider)}</div>`;if(e.kind===`listening`){let t=e.provider===`cloud`?` · ${OA(e.elapsedMs)}`:``;return g`<div class="speech-input-status">Listening · ${DA(e.provider)}${t}</div>`}return g`<div class="speech-input-status">Transcribing · Cloud</div>`}renderSpeechInputError(){let e=this.speechInputState.kind===`idle`?this.speechInputState.error:void 0;return e===void 0||e===``?null:g`<div class="speech-input-error" aria-live="polite">${e}</div>`}renderCompactStatus(){let e=this.status===void 0&&this.showSessionConfiguration,t=this.status??(e?this.sessionConfiguration:void 0);if(t===void 0&&!e)return null;let n=this.modelPolicyStatus??this.status?.modelPolicy,r=t?.model?.id??(e?`Choose default model`:`no model`),i=t?.model?.provider!==void 0&&t.model.provider!==``?`${t.model.provider}/`:``,a=e?`Default thinking level: ${wn(t?.thinkingLevel)}`:`Thinking level: ${wn(t?.thinkingLevel)}`,o=!this.disabled&&!this.speechInputActive()&&!this.modelPolicySaving&&!jA(this.status);return g`
|
|
3607
3607
|
<div class="compact-status" aria-label=${e?`Session defaults`:`Session status`}>
|
|
3608
3608
|
${n===void 0?null:g`
|
|
3609
3609
|
<session-model-policy-control
|
|
@@ -3627,7 +3627,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3627
3627
|
`:g`
|
|
3628
3628
|
<button class="select-model" ?disabled=${this.onSelectModel===void 0||this.speechInputActive()} title="Select model" @click=${()=>{this.speechInputActive()||this.onSelectModel?.()}}>${i}${r}</button>
|
|
3629
3629
|
${n===void 0?g`
|
|
3630
|
-
<button class="select-thinking icon-button" ?disabled=${this.onSelectThinking===void 0||this.speechInputActive()} title=${a} aria-label=${a} @click=${()=>{this.speechInputActive()||this.onSelectThinking?.()}}>${
|
|
3630
|
+
<button class="select-thinking icon-button" ?disabled=${this.onSelectThinking===void 0||this.speechInputActive()} title=${a} aria-label=${a} @click=${()=>{this.speechInputActive()||this.onSelectThinking?.()}}>${_A(Tn(t?.thinkingLevel,this.availableThinkingLevels))}</button>
|
|
3631
3631
|
`:g`
|
|
3632
3632
|
<session-thinking-menu
|
|
3633
3633
|
.options=${this.policyThinkingOptions}
|
|
@@ -3657,9 +3657,9 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3657
3657
|
${this.attachmentError===void 0?null:g`<div class="attachment-error">${this.attachmentError}</div>`}
|
|
3658
3658
|
</div>
|
|
3659
3659
|
`}renderAttachmentPreview(e){return xO(e)?g`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:g`
|
|
3660
|
-
<div class="attachment-file-preview" aria-hidden="true">${
|
|
3660
|
+
<div class="attachment-file-preview" aria-hidden="true">${RA(e.name)}</div>
|
|
3661
3661
|
<span class="attachment-file-name">${e.name}</span>
|
|
3662
|
-
`}changeDelivery(e){if(this.speechInputActive()||!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;if(t===`inline`&&!SO(this.attachments)){e.target.value=`folder`;return}this.attachmentDelivery=t,AO(this.attachmentDelivery)}attachmentScopeKey(){return jA(this.machineId,this.sessionId)}activeAttachmentScope(){let e=this.attachmentScopeKey();if(e!==void 0)return this.attachmentScope?.currentKey()===void 0&&(this.attachmentScope=this.attachmentDrafts.openScope(e)),this.attachmentScope}currentAttachmentDraft(){return{attachments:this.attachments,...this.attachmentError===void 0?{}:{error:this.attachmentError}}}adoptAttachmentDraft(e){this.attachments=[...e.attachments],this.attachmentError=e.error}persistAttachmentDraft(){let e=this.activeAttachmentScope();e!==void 0&&e.write(this.currentAttachmentDraft())}removeAttachment(e){this.speechInputActive()||(this.attachments=this.attachments.filter(t=>t.id!==e),this.persistAttachmentDraft())}async handlePaste(e){if(this.speechInputActive())return;let t=PA(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){this.speechInputActive()||e.dataTransfer!==null&&FA(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){if(this.speechInputActive())return;let t=PA(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(this.speechInputActive()||!(e.target instanceof HTMLInputElement)||e.target.files===null)return;let t=Array.from(e.target.files);e.target.value=``,await this.addAttachmentFiles(t)}async addAttachmentFiles(e){if(this.speechInputActive())return;let t=this.activeAttachmentScope();if(t===void 0){this.attachmentError=void 0;let t=await bO(e,RA);t.attachments.length>0&&(this.attachments=[...this.attachments,...t.attachments.map(e=>({id:this.attachmentDrafts.nextAttachmentId(),...e}))]),this.attachmentError=t.error;return}this.attachmentError=void 0;let n=t.beginCapture(),{attachments:r,error:i}=await bO(e,RA),a=n.complete(r,i);a!==void 0&&t.currentKey()===this.attachmentScopeKey()&&this.adoptAttachmentDraft(a)}currentAttachments(){return this.attachments.map(e=>IA(e))}effectiveAttachmentDelivery(){return CO(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new n({parent:this.editorHost,state:ne.create({doc:this.draft,extensions:[re(),oe(),t(),f.of(` `),r(a,{fallback:!0}),n.lineWrapping,n.contentAttributes.of(e=>VA(e.state.sliceDoc(0,e.state.selection.main.head))),n.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),i(`Message pi... Use / for commands, @ for tracked files, @ space for all files`),sA,this.editableCompartment.of(n.editable.of(!(this.disabled||this.speechInputState.kind!==`idle`))),this.readOnlyCompartment.of(ne.readOnly.of(this.disabled||this.speechInputState.kind!==`idle`)),n.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),o.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:`ArrowDown`,run:()=>this.moveCompletion(1)},{key:`ArrowUp`,run:()=>this.moveCompletion(-1)},{key:`Escape`,run:()=>this.closeCompletions()},{key:`Tab`,run:e=>this.handleEditorTab(e)},{key:`Shift-Tab`,run:e=>u.shift?.(e)??!1},{key:`Backspace`,run:e=>ie(e)},...c,...p])]})}))}syncEditorDoc(){let e=this.editor;if(!e)return;let t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:l.cursor(this.draft.length)})}updateEditorDisabledState(){let e=this.disabled||this.speechInputState.kind!==`idle`;this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(n.editable.of(!e)),this.readOnlyCompartment.reconfigure(ne.readOnly.of(e))]})}updateDraft(e){this.draft=e;let t=jA(this.machineId,this.sessionId);t!==void 0&&ef(t,this.draft);let n=dp(this.draft);pp(n,this.currentInputMode)||(this.currentInputMode=n),this.refreshCompletions()}async refreshCompletions(){let e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind===`command`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await gc.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(MA);if(t!==this.requestVersion)return;this.completions=n.filter(t=>t.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(t=>({kind:`command`,replaceFrom:e.from,replaceTo:e.to,insertText:`/${t.name}`,detail:t.source,...t.description===void 0?{}:{description:t.description}}))}else if(e.kind===`file`&&this.cwd!==void 0&&this.cwd!==``){let n=await gc.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(NA);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=op(t.path,e.quoted===!0,t.path.endsWith(`/`)?e.allPrefix:void 0);return{kind:`file`,replaceFrom:e.from,replaceTo:e.to,insertText:n,detail:t.kind,...t.path.endsWith(`/`)&&n.endsWith(`"`)?{cursorOffset:n.length-1}:{}}})}}currentTrigger(){return ap(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorKeyDown(e,t){if(this.speechInputActive()&&(e.key===`Enter`||e.key===`Tab`))return!0;if(e.key===`Shift`)return this.explicitShiftKeyActive=!0,!1;if(e.key!==`Enter`)return this.explicitShiftKeyActive=!1,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;let n=RO(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);return this.explicitShiftKeyActive=!1,this.handleEditorEnter(t,n)}handleEditorKeyUp(e){return e.key===`Shift`&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorEnter(e,t){if(this.speechInputActive())return!0;if(!t&&this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return zO(t,this.mobilePromptEnterMedia,FO())?(this.send(this.canSteer||this.isCompacting?`followUp`:void 0),!0):ae(e)||m(e)}handleEditorTab(e){if(this.speechInputActive())return!0;if(this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.currentTrigger()?.kind===`file`?(this.refreshCompletions(),!0):u.run?.(e)??!1}pick(e){if(this.speechInputActive())return;let t=this.editor;if(!t)return;let n=e.kind===`file`&&(e.insertText.endsWith(`/`)||e.cursorOffset!==void 0)?``:` `,r=e.replaceFrom+(e.cursorOffset??e.insertText.length)+n.length,i=e.insertText.endsWith(`"`)&&this.draft.slice(e.replaceTo).startsWith(`"`)?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:i,insert:`${e.insertText}${n}`},selection:l.cursor(r),scrollIntoView:!0}),this.completions=[]}send(e){if(this.speechInputActive()||this.disabled||this.sending||this.sendDisabled)return;let t=this.draft.trim(),n=this.attachments;if(t===``&&n.length===0)return;let r=this.canSteer||this.isCompacting?e:void 0,i=n.length>0?this.currentAttachments():void 0,a=this.effectiveAttachmentDelivery();this.resetComposer(),this.onSend?.(t,r,i,i===void 0?void 0:a)}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=jA(this.machineId,this.sessionId);e!==void 0&&tf(e);let t=e===void 0?void 0:this.activeAttachmentScope();t!==void 0&&t.clear(),this.attachmentScope=void 0,this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=rb}};H([x({type:Boolean})],K.prototype,`disabled`,void 0),H([x({type:Boolean})],K.prototype,`sendDisabled`,void 0),H([x()],K.prototype,`sessionId`,void 0),H([x()],K.prototype,`cwd`,void 0),H([x()],K.prototype,`machineId`,void 0),H([x()],K.prototype,`projectId`,void 0),H([x()],K.prototype,`workspaceId`,void 0),H([x({type:Boolean})],K.prototype,`workspaceScopedFileSuggestions`,void 0),H([x({type:Boolean})],K.prototype,`canSteer`,void 0),H([x({type:Boolean})],K.prototype,`isCompacting`,void 0),H([x({type:Boolean})],K.prototype,`canStop`,void 0),H([x({attribute:!1})],K.prototype,`status`,void 0),H([x({type:Boolean})],K.prototype,`sending`,void 0),H([x({attribute:!1})],K.prototype,`onSend`,void 0),H([x({attribute:!1})],K.prototype,`onStop`,void 0),H([x({attribute:!1})],K.prototype,`onSelectModel`,void 0),H([x({attribute:!1})],K.prototype,`onSelectThinking`,void 0),H([x({attribute:!1})],K.prototype,`onCompact`,void 0),H([x({type:Boolean})],K.prototype,`showSessionConfiguration`,void 0),H([x({attribute:!1})],K.prototype,`sessionConfiguration`,void 0),H([x({attribute:!1})],K.prototype,`modelPolicyStatus`,void 0),H([x({attribute:!1})],K.prototype,`modelTierCatalog`,void 0),H([x({attribute:!1})],K.prototype,`onSelectPolicyMode`,void 0),H([x({attribute:!1})],K.prototype,`onSelectPolicyTier`,void 0),H([x({attribute:!1})],K.prototype,`onSelectPolicyThinking`,void 0),H([x({attribute:!1})],K.prototype,`policyThinkingOptions`,void 0),H([x({type:Boolean})],K.prototype,`modelPolicyLoading`,void 0),H([x({type:Boolean})],K.prototype,`modelPolicySaving`,void 0),H([x()],K.prototype,`modelPolicyError`,void 0),H([x({attribute:!1})],K.prototype,`availableThinkingLevels`,void 0),H([x({attribute:!1})],K.prototype,`speechInputSettings`,void 0),H([x({attribute:!1})],K.prototype,`attachmentDrafts`,void 0),H([C(`.markdown-editor`)],K.prototype,`editorHost`,void 0),H([C(`.attachment-input`)],K.prototype,`attachmentInput`,void 0),H([S()],K.prototype,`currentInputMode`,void 0),H([S()],K.prototype,`completions`,void 0),H([S()],K.prototype,`selectedIndex`,void 0),H([S()],K.prototype,`attachments`,void 0),H([S()],K.prototype,`attachmentDelivery`,void 0),H([S()],K.prototype,`attachmentError`,void 0),H([S()],K.prototype,`speechInputState`,void 0),K=H([b(`prompt-editor`)],K);function wA(e){return typeof e==`string`&&e!==``?e:void 0}function TA(e,t){return e.kind!==t.kind||e.machineId!==t.machineId||e.projectId!==t.projectId||e.workspaceId!==t.workspaceId?!1:e.kind===`starter`||t.kind===`session`&&e.sessionId===t.sessionId}function EA(e){return e===`browser`?`Browser`:`Cloud`}function DA(e){let t=Math.floor(Math.max(0,e)/1e3),n=Math.floor(t/60),r=t%60;return`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}function OA(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.model?.id===t.model?.id&&e.model?.provider===t.model?.provider&&e.thinkingLevel===t.thinkingLevel&&kA(e.modelPolicy,t.modelPolicy)&&AA(e)===AA(t)}function kA(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.mode===t.mode&&e.tier===t.tier&&e.resolved.model.provider===t.resolved.model.provider&&e.resolved.model.id===t.resolved.model.id&&e.resolved.thinkingLevel===t.resolved.thinkingLevel&&e.ladderValid===t.ladderValid&&e.blockedReason===t.blockedReason}function AA(e){return e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function jA(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return Bl(e,t)}function MA(){return[]}function NA(){return[]}function PA(e){return e===null?[]:Array.from(e.files)}function FA(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function IA(e){return e.kind===`image`?{kind:`image`,mimeType:e.mimeType,data:e.data,name:e.name}:{kind:`file`,mimeType:e.mimeType,data:e.data,name:e.name}}function LA(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`FILE`}function RA(e){return new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>{n(r.error??Error(`Failed to read file`))},r.onload=()=>{let e=r.result;if(typeof e!=`string`){n(Error(`Unexpected file reader result`));return}let i=e.indexOf(`,`);t(i===-1?e:e.slice(i+1))},r.readAsDataURL(e)})}var zA={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},BA={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function VA(e){return dp(e).kind===`normal`?zA:BA}var HA=class extends y{constructor(...e){super(...e),this.title=`Select`,this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=``}render(){let e=this.filteredOptions();return g`
|
|
3662
|
+
`}changeDelivery(e){if(this.speechInputActive()||!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;if(t===`inline`&&!SO(this.attachments)){e.target.value=`folder`;return}this.attachmentDelivery=t,AO(this.attachmentDelivery)}attachmentScopeKey(){return MA(this.machineId,this.sessionId)}activeAttachmentScope(){let e=this.attachmentScopeKey();if(e!==void 0)return this.attachmentScope?.currentKey()===void 0&&(this.attachmentScope=this.attachmentDrafts.openScope(e)),this.attachmentScope}currentAttachmentDraft(){return{attachments:this.attachments,...this.attachmentError===void 0?{}:{error:this.attachmentError}}}adoptAttachmentDraft(e){this.attachments=[...e.attachments],this.attachmentError=e.error}persistAttachmentDraft(){let e=this.activeAttachmentScope();e!==void 0&&e.write(this.currentAttachmentDraft())}removeAttachment(e){this.speechInputActive()||(this.attachments=this.attachments.filter(t=>t.id!==e),this.persistAttachmentDraft())}async handlePaste(e){if(this.speechInputActive())return;let t=FA(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){this.speechInputActive()||e.dataTransfer!==null&&IA(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){if(this.speechInputActive())return;let t=FA(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(this.speechInputActive()||!(e.target instanceof HTMLInputElement)||e.target.files===null)return;let t=Array.from(e.target.files);e.target.value=``,await this.addAttachmentFiles(t)}async addAttachmentFiles(e){if(this.speechInputActive())return;let t=this.activeAttachmentScope();if(t===void 0){this.attachmentError=void 0;let t=await bO(e,zA);t.attachments.length>0&&(this.attachments=[...this.attachments,...t.attachments.map(e=>({id:this.attachmentDrafts.nextAttachmentId(),...e}))]),this.attachmentError=t.error;return}this.attachmentError=void 0;let n=t.beginCapture(),{attachments:r,error:i}=await bO(e,zA),a=n.complete(r,i);a!==void 0&&t.currentKey()===this.attachmentScopeKey()&&this.adoptAttachmentDraft(a)}currentAttachments(){return this.attachments.map(e=>LA(e))}effectiveAttachmentDelivery(){return CO(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new n({parent:this.editorHost,state:ne.create({doc:this.draft,extensions:[re(),oe(),t(),f.of(` `),r(a,{fallback:!0}),n.lineWrapping,n.contentAttributes.of(e=>HA(e.state.sliceDoc(0,e.state.selection.main.head))),n.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),i(`Message pi... Use / for commands, @ for tracked files, @ space for all files`),cA,this.editableCompartment.of(n.editable.of(!(this.disabled||this.speechInputState.kind!==`idle`))),this.readOnlyCompartment.of(ne.readOnly.of(this.disabled||this.speechInputState.kind!==`idle`)),n.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),o.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:`ArrowDown`,run:()=>this.moveCompletion(1)},{key:`ArrowUp`,run:()=>this.moveCompletion(-1)},{key:`Escape`,run:()=>this.closeCompletions()},{key:`Tab`,run:e=>this.handleEditorTab(e)},{key:`Shift-Tab`,run:e=>u.shift?.(e)??!1},{key:`Backspace`,run:e=>ie(e)},...c,...p])]})}))}syncEditorDoc(){let e=this.editor;if(!e)return;let t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:l.cursor(this.draft.length)})}updateEditorDisabledState(){let e=this.disabled||this.speechInputState.kind!==`idle`;this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(n.editable.of(!e)),this.readOnlyCompartment.reconfigure(ne.readOnly.of(e))]})}updateDraft(e){this.draft=e;let t=MA(this.machineId,this.sessionId);t!==void 0&&ef(t,this.draft);let n=dp(this.draft);pp(n,this.currentInputMode)||(this.currentInputMode=n),this.refreshCompletions()}async refreshCompletions(){let e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind===`command`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await gc.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(NA);if(t!==this.requestVersion)return;this.completions=n.filter(t=>t.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(t=>({kind:`command`,replaceFrom:e.from,replaceTo:e.to,insertText:`/${t.name}`,detail:t.source,...t.description===void 0?{}:{description:t.description}}))}else if(e.kind===`file`&&this.cwd!==void 0&&this.cwd!==``){let n=await gc.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(PA);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=op(t.path,e.quoted===!0,t.path.endsWith(`/`)?e.allPrefix:void 0);return{kind:`file`,replaceFrom:e.from,replaceTo:e.to,insertText:n,detail:t.kind,...t.path.endsWith(`/`)&&n.endsWith(`"`)?{cursorOffset:n.length-1}:{}}})}}currentTrigger(){return ap(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorKeyDown(e,t){if(this.speechInputActive()&&(e.key===`Enter`||e.key===`Tab`))return!0;if(e.key===`Shift`)return this.explicitShiftKeyActive=!0,!1;if(e.key!==`Enter`)return this.explicitShiftKeyActive=!1,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;let n=RO(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);return this.explicitShiftKeyActive=!1,this.handleEditorEnter(t,n)}handleEditorKeyUp(e){return e.key===`Shift`&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorEnter(e,t){if(this.speechInputActive())return!0;if(!t&&this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return zO(t,this.mobilePromptEnterMedia,FO())?(this.send(this.canSteer||this.isCompacting?`followUp`:void 0),!0):ae(e)||m(e)}handleEditorTab(e){if(this.speechInputActive())return!0;if(this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.currentTrigger()?.kind===`file`?(this.refreshCompletions(),!0):u.run?.(e)??!1}pick(e){if(this.speechInputActive())return;let t=this.editor;if(!t)return;let n=e.kind===`file`&&(e.insertText.endsWith(`/`)||e.cursorOffset!==void 0)?``:` `,r=e.replaceFrom+(e.cursorOffset??e.insertText.length)+n.length,i=e.insertText.endsWith(`"`)&&this.draft.slice(e.replaceTo).startsWith(`"`)?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:i,insert:`${e.insertText}${n}`},selection:l.cursor(r),scrollIntoView:!0}),this.completions=[]}send(e){if(this.speechInputActive()||this.disabled||this.sending||this.sendDisabled)return;let t=this.draft.trim(),n=this.attachments;if(t===``&&n.length===0)return;let r=this.canSteer||this.isCompacting?e:void 0,i=n.length>0?this.currentAttachments():void 0,a=this.effectiveAttachmentDelivery();this.resetComposer(),this.onSend?.(t,r,i,i===void 0?void 0:a)}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=MA(this.machineId,this.sessionId);e!==void 0&&tf(e);let t=e===void 0?void 0:this.activeAttachmentScope();t!==void 0&&t.clear(),this.attachmentScope=void 0,this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=rb}};H([x({type:Boolean})],K.prototype,`disabled`,void 0),H([x({type:Boolean})],K.prototype,`sendDisabled`,void 0),H([x()],K.prototype,`sessionId`,void 0),H([x()],K.prototype,`cwd`,void 0),H([x()],K.prototype,`machineId`,void 0),H([x()],K.prototype,`projectId`,void 0),H([x()],K.prototype,`workspaceId`,void 0),H([x({type:Boolean})],K.prototype,`workspaceScopedFileSuggestions`,void 0),H([x({type:Boolean})],K.prototype,`canSteer`,void 0),H([x({type:Boolean})],K.prototype,`isCompacting`,void 0),H([x({type:Boolean})],K.prototype,`canStop`,void 0),H([x({attribute:!1})],K.prototype,`status`,void 0),H([x({type:Boolean})],K.prototype,`sending`,void 0),H([x({attribute:!1})],K.prototype,`onSend`,void 0),H([x({attribute:!1})],K.prototype,`onStop`,void 0),H([x({attribute:!1})],K.prototype,`onSelectModel`,void 0),H([x({attribute:!1})],K.prototype,`onSelectThinking`,void 0),H([x({attribute:!1})],K.prototype,`onCompact`,void 0),H([x({type:Boolean})],K.prototype,`showSessionConfiguration`,void 0),H([x({attribute:!1})],K.prototype,`sessionConfiguration`,void 0),H([x({attribute:!1})],K.prototype,`modelPolicyStatus`,void 0),H([x({attribute:!1})],K.prototype,`modelTierCatalog`,void 0),H([x({attribute:!1})],K.prototype,`onSelectPolicyMode`,void 0),H([x({attribute:!1})],K.prototype,`onSelectPolicyTier`,void 0),H([x({attribute:!1})],K.prototype,`onSelectPolicyThinking`,void 0),H([x({attribute:!1})],K.prototype,`policyThinkingOptions`,void 0),H([x({type:Boolean})],K.prototype,`modelPolicyLoading`,void 0),H([x({type:Boolean})],K.prototype,`modelPolicySaving`,void 0),H([x()],K.prototype,`modelPolicyError`,void 0),H([x({attribute:!1})],K.prototype,`availableThinkingLevels`,void 0),H([x({attribute:!1})],K.prototype,`speechInputSettings`,void 0),H([x({attribute:!1})],K.prototype,`attachmentDrafts`,void 0),H([C(`.markdown-editor`)],K.prototype,`editorHost`,void 0),H([C(`.attachment-input`)],K.prototype,`attachmentInput`,void 0),H([S()],K.prototype,`currentInputMode`,void 0),H([S()],K.prototype,`completions`,void 0),H([S()],K.prototype,`selectedIndex`,void 0),H([S()],K.prototype,`attachments`,void 0),H([S()],K.prototype,`attachmentDelivery`,void 0),H([S()],K.prototype,`attachmentError`,void 0),H([S()],K.prototype,`speechInputState`,void 0),K=H([b(`prompt-editor`)],K);function TA(e){return typeof e==`string`&&e!==``?e:void 0}function EA(e,t){return e.kind!==t.kind||e.machineId!==t.machineId||e.projectId!==t.projectId||e.workspaceId!==t.workspaceId?!1:e.kind===`starter`||t.kind===`session`&&e.sessionId===t.sessionId}function DA(e){return e===`browser`?`Browser`:`Cloud`}function OA(e){let t=Math.floor(Math.max(0,e)/1e3),n=Math.floor(t/60),r=t%60;return`${String(n).padStart(2,`0`)}:${String(r).padStart(2,`0`)}`}function kA(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.model?.id===t.model?.id&&e.model?.provider===t.model?.provider&&e.thinkingLevel===t.thinkingLevel&&AA(e.modelPolicy,t.modelPolicy)&&jA(e)===jA(t)}function AA(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.mode===t.mode&&e.tier===t.tier&&e.resolved.model.provider===t.resolved.model.provider&&e.resolved.model.id===t.resolved.model.id&&e.resolved.thinkingLevel===t.resolved.thinkingLevel&&e.ladderValid===t.ladderValid&&e.blockedReason===t.blockedReason}function jA(e){return e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function MA(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return Bl(e,t)}function NA(){return[]}function PA(){return[]}function FA(e){return e===null?[]:Array.from(e.files)}function IA(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function LA(e){return e.kind===`image`?{kind:`image`,mimeType:e.mimeType,data:e.data,name:e.name}:{kind:`file`,mimeType:e.mimeType,data:e.data,name:e.name}}function RA(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`FILE`}function zA(e){return new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>{n(r.error??Error(`Failed to read file`))},r.onload=()=>{let e=r.result;if(typeof e!=`string`){n(Error(`Unexpected file reader result`));return}let i=e.indexOf(`,`);t(i===-1?e:e.slice(i+1))},r.readAsDataURL(e)})}var BA={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},VA={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function HA(e){return dp(e).kind===`normal`?BA:VA}var UA=class extends y{constructor(...e){super(...e),this.title=`Select`,this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=``}render(){let e=this.filteredOptions();return g`
|
|
3663
3663
|
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
3664
3664
|
<section
|
|
3665
3665
|
role="dialog"
|
|
@@ -3682,12 +3682,12 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3682
3682
|
`}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?`input`:`.options`)?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;let e=this.filteredOptions().findIndex(e=>e.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){let e=this.query.trim().toLowerCase();return e===``?this.options:this.options.filter(t=>`${t.label} ${t.description??``} ${t.value}`.toLowerCase().includes(e))}renderGroupedOptions(e){let t=[];for(let[n,r]of e.entries()){let e=t[t.length-1];e!==void 0&&e.group===r.group?e.items.push({option:r,index:n}):t.push({group:r.group,items:[{option:r,index:n}]})}return t.map(e=>{let t=e.group!==void 0&&e.group!==``;return g`
|
|
3683
3683
|
${t?g`<div class="group-header">${e.group}</div>`:null}
|
|
3684
3684
|
${e.items.map(({option:e,index:n})=>g`
|
|
3685
|
-
<button class="${n===this.selectedIndex?`selected`:``}${t?` grouped`:``}" ${
|
|
3685
|
+
<button class="${n===this.selectedIndex?`selected`:``}${t?` grouped`:``}" ${vA(n===this.selectedIndex,e.value)} @click=${()=>this.onPick?.(e.value)}>
|
|
3686
3686
|
<span>${e.label}</span>
|
|
3687
3687
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
3688
3688
|
</button>
|
|
3689
3689
|
`)}
|
|
3690
|
-
`})}handleDialogKeyDown(e){if(e.key===`Tab`){e.stopPropagation(),this.trapTabFocus(e);return}if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.onCancel?.();return}let t=e.target;!(t instanceof HTMLInputElement)&&!(t instanceof Element&&t.closest(`.options`)!==null)||this.handleOptionKeyDown(e)}trapTabFocus(e){let t=[...this.renderRoot.querySelectorAll(`button:not(:disabled), input:not(:disabled), [tabindex='0']`)];if(t.length===0){e.preventDefault(),this.renderRoot.querySelector(`section[role='dialog']`)?.focus();return}let n=t.findIndex(e=>e===this.shadowRoot?.activeElement),r=!e.shiftKey&&n===t.length-1,i=e.shiftKey&&n<=0;!r&&!i&&!(n<0)||(e.preventDefault(),(e.shiftKey?t.at(-1):t[0])?.focus())}handleOptionKeyDown(e){let t=this.filteredOptions();if(e.key===`ArrowDown`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key===`ArrowUp`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key===`Enter`){e.preventDefault();let n=t[this.selectedIndex];n&&this.onPick?.(n.value)}}static{this.styles=tb}};H([x()],
|
|
3690
|
+
`})}handleDialogKeyDown(e){if(e.key===`Tab`){e.stopPropagation(),this.trapTabFocus(e);return}if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.onCancel?.();return}let t=e.target;!(t instanceof HTMLInputElement)&&!(t instanceof Element&&t.closest(`.options`)!==null)||this.handleOptionKeyDown(e)}trapTabFocus(e){let t=[...this.renderRoot.querySelectorAll(`button:not(:disabled), input:not(:disabled), [tabindex='0']`)];if(t.length===0){e.preventDefault(),this.renderRoot.querySelector(`section[role='dialog']`)?.focus();return}let n=t.findIndex(e=>e===this.shadowRoot?.activeElement),r=!e.shiftKey&&n===t.length-1,i=e.shiftKey&&n<=0;!r&&!i&&!(n<0)||(e.preventDefault(),(e.shiftKey?t.at(-1):t[0])?.focus())}handleOptionKeyDown(e){let t=this.filteredOptions();if(e.key===`ArrowDown`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key===`ArrowUp`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key===`Enter`){e.preventDefault();let n=t[this.selectedIndex];n&&this.onPick?.(n.value)}}static{this.styles=tb}};H([x()],UA.prototype,`title`,void 0),H([x({type:Boolean})],UA.prototype,`searchable`,void 0),H([x({attribute:!1})],UA.prototype,`options`,void 0),H([x({attribute:!1})],UA.prototype,`selectedValue`,void 0),H([x({attribute:!1})],UA.prototype,`onPick`,void 0),H([x({attribute:!1})],UA.prototype,`onCancel`,void 0),H([S()],UA.prototype,`selectedIndex`,void 0),H([S()],UA.prototype,`query`,void 0),UA=H([b(`command-picker`)],UA);var WA=class extends y{constructor(...e){super(...e),this.actions=[],this.queryText=``,this.selectedIndex=0}render(){let e=this.filteredActions();return g`
|
|
3691
3691
|
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
3692
3692
|
<section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
3693
3693
|
<header>
|
|
@@ -3700,7 +3700,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3700
3700
|
</header>
|
|
3701
3701
|
<div class="options">
|
|
3702
3702
|
${e.length===0?g`<div class="empty">No actions found.</div>`:e.map((e,t)=>g`
|
|
3703
|
-
<button class=${`${t===this.selectedIndex?`selected`:``} ${e.enabled===!1?`disabled`:``}`} ?disabled=${e.enabled===!1} title=${e.disabledReason??e.title} ${
|
|
3703
|
+
<button class=${`${t===this.selectedIndex?`selected`:``} ${e.enabled===!1?`disabled`:``}`} ?disabled=${e.enabled===!1} title=${e.disabledReason??e.title} ${vA(t===this.selectedIndex,e.id)} @click=${()=>{this.run(e)}}>
|
|
3704
3704
|
<span class="main">
|
|
3705
3705
|
<strong>${e.title}</strong>
|
|
3706
3706
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
@@ -3713,7 +3713,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3713
3713
|
</div>
|
|
3714
3714
|
</section>
|
|
3715
3715
|
</div>
|
|
3716
|
-
`}firstUpdated(){this.input?.focus()}updated(e){if(!e.has(`actions`)&&!e.has(`queryText`))return;let t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){return
|
|
3716
|
+
`}firstUpdated(){this.input?.focus()}updated(e){if(!e.has(`actions`)&&!e.has(`queryText`))return;let t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){return GA(this.actions,this.queryText)}handleKeyDown(e){let t=this.filteredActions();if(e.key===`Escape`)e.preventDefault(),this.onCancel?.();else if(e.key===`ArrowDown`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key===`ArrowUp`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key===`Enter`){e.preventDefault();let n=t[this.selectedIndex];n!==void 0&&this.run(n)}}run(e){e.enabled!==!1&&this.onRun?.(e)}static{this.styles=nb}};H([x({attribute:!1})],WA.prototype,`actions`,void 0),H([x({attribute:!1})],WA.prototype,`onRun`,void 0),H([x({attribute:!1})],WA.prototype,`onCancel`,void 0),H([C(`input`)],WA.prototype,`input`,void 0),H([S()],WA.prototype,`queryText`,void 0),H([S()],WA.prototype,`selectedIndex`,void 0),WA=H([b(`action-palette`)],WA);function GA(e,t){let n=t.trim().toLowerCase();return e.filter(e=>e.enabled!==!1||e.disabledReason!==void 0).filter(e=>n===``||[e.title,e.description??``,e.disabledReason??``,e.group??``,e.shortcut??``].join(` `).toLowerCase().includes(n))}var KA=class extends y{render(){let e=this.state;return e===void 0?null:g`
|
|
3717
3717
|
<div class="backdrop" @mousedown=${()=>{this.cancel()}}>
|
|
3718
3718
|
<section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
3719
3719
|
<header>
|
|
@@ -3736,13 +3736,13 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3736
3736
|
<div class="actions"><button @click=${()=>{this.cancel()}}>Cancel</button><button class="primary" ?disabled=${e.saving===!0} @click=${()=>{this.onSaveApiKey?.()}}>${e.saving===!0?`Saving…`:`Save API key`}</button></div>
|
|
3737
3737
|
</div>
|
|
3738
3738
|
`;case`oauth`:return this.renderOAuth(e);case`logout`:return g`<div class="options">${e.providers.length===0?g`<div class="empty">No stored credentials. Environment variables and models.json settings are unchanged.</div>`:e.providers.map(e=>g`
|
|
3739
|
-
<button @click=${()=>{this.onLogoutProvider?.(e.id)}}><span>${e.name}</span><small>${e.id} · ${
|
|
3739
|
+
<button @click=${()=>{this.onLogoutProvider?.(e.id)}}><span>${e.name}</span><small>${e.id} · ${JA(e.authType)}</small></button>
|
|
3740
3740
|
`)}</div>`}}renderProviderButton(e){return g`
|
|
3741
3741
|
<button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
|
|
3742
|
-
<span>${e.name}${e.status.source===void 0?null:g` <em>${
|
|
3743
|
-
<small>${e.id} · ${
|
|
3742
|
+
<span>${e.name}${e.status.source===void 0?null:g` <em>${XA(e)}</em>`}</span>
|
|
3743
|
+
<small>${e.id} · ${JA(e.authType)}</small>
|
|
3744
3744
|
</button>
|
|
3745
|
-
`}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=
|
|
3745
|
+
`}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=qA(n?.promptType);return g`
|
|
3746
3746
|
<div class="form">
|
|
3747
3747
|
${t.auth===void 0?g`<p>Starting login flow…</p>`:g`
|
|
3748
3748
|
<p>Open this authorization link:</p>
|
|
@@ -3775,7 +3775,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3775
3775
|
${t.status===`error`||t.status===`cancelled`?g`<div class="error-text">${t.error??t.status}</div><div class="actions"><button @click=${()=>{this.cancel()}}>Close</button></div>`:null}
|
|
3776
3776
|
${n===void 0&&r===void 0&&t.status===`running`?g`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
|
|
3777
3777
|
</div>
|
|
3778
|
-
`}focusInputIfNeeded(){let e=
|
|
3778
|
+
`}focusInputIfNeeded(){let e=YA(this.state);if(e===void 0){this.lastFocusedInputKey=void 0;return}e!==this.lastFocusedInputKey&&(this.lastFocusedInputKey=e,this.input?.focus())}handleKeyDown(e){if(e.key===`Escape`){e.preventDefault(),this.cancel();return}if(e.key!==`Enter`)return;let t=this.state;t?.step===`apiKey`?(e.preventDefault(),this.onSaveApiKey?.()):t?.step===`oauth`&&t.flow.prompt!==void 0&&(e.preventDefault(),this.onOAuthRespond?.())}cancel(){this.state?.step===`oauth`?this.onOAuthCancel?.():this.onCancel?.()}static{this.styles=[tb,h`
|
|
3779
3779
|
.form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
|
|
3780
3780
|
.form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
|
|
3781
3781
|
.form a { color: var(--pi-accent); overflow-wrap: anywhere; }
|
|
@@ -3793,7 +3793,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3793
3793
|
.inline-options button { display: grid; gap: 2px; text-align: left; }
|
|
3794
3794
|
.inline-options small { color: var(--pi-muted); }
|
|
3795
3795
|
em { color: var(--pi-success); font-style: normal; font-size: 12px; }
|
|
3796
|
-
`]}};H([x({attribute:!1})],
|
|
3796
|
+
`]}};H([x({attribute:!1})],KA.prototype,`state`,void 0),H([x({attribute:!1})],KA.prototype,`onChooseMethod`,void 0),H([x({attribute:!1})],KA.prototype,`onSelectProvider`,void 0),H([x({attribute:!1})],KA.prototype,`onApiKeyInput`,void 0),H([x({attribute:!1})],KA.prototype,`onSaveApiKey`,void 0),H([x({attribute:!1})],KA.prototype,`onLogoutProvider`,void 0),H([x({attribute:!1})],KA.prototype,`onOAuthInput`,void 0),H([x({attribute:!1})],KA.prototype,`onOAuthRespond`,void 0),H([x({attribute:!1})],KA.prototype,`onOAuthCancel`,void 0),H([x({attribute:!1})],KA.prototype,`onCancel`,void 0),H([C(`input`)],KA.prototype,`input`,void 0),KA=H([b(`auth-dialog`)],KA);function qA(e){return e===`secret`?`password`:`text`}function JA(e){return e===`oauth`?`subscription`:`credentials`}function YA(e){if(e?.step===`apiKey`)return`api-key:${e.provider.authType}:${e.provider.id}`;if(e?.step===`oauth`&&e.flow.prompt!==void 0)return`oauth:${e.flow.flowId}:${e.flow.prompt.requestId}`}function XA(e){if(e.status.source===void 0)return``;switch(e.status.source){case`stored`:return`✓ configured`;case`environment`:return`✓ env${e.status.label===void 0?``:`: ${e.status.label}`}`;case`runtime`:return`✓ runtime`;case`fallback`:return`✓ custom key`;case`models_json_key`:return`✓ models.json key`;case`models_json_command`:return`✓ models.json command`;default:return``}}var ZA=[`openai-completions`,`openai-responses`,`anthropic-messages`,`google-generative-ai`];function QA(e){return ZA.map(t=>({api:t,selected:t===e}))}function $A(e,t){return e.map(e=>({candidate:e,selected:e.id===t}))}var ej=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function tj(e){let t=e.providers??{},n=fj(t);return{config:lj(e,{...t,[n]:{api:`openai-completions`}}),providerName:n}}function nj(e,t,n){let r=n.trim(),i=e.providers??{};if(r===``)return{config:e,error:`Provider name is required.`};if(t===r)return{config:e};if(i[t]===void 0)return{config:e,error:`Provider "${t}" no longer exists.`};if(i[r]!==void 0)return{config:e,error:`A provider named "${r}" already exists.`};let a={};for(let[e,n]of Object.entries(i))a[e===t?r:e]=n;return{config:lj(e,a)}}function rj(e,t,n){let r=e.providers??{};return r[t]===void 0?e:lj(e,{...r,[t]:n})}function ij(e,t){let n=e.providers??{};return n[t]===void 0?e:lj(e,uj(n,t))}function aj(e,t){let n=e.providers?.[t];if(n===void 0)return e;let r=[...n.models??[],{id:``}];return rj(e,t,{...n,models:r})}function oj(e,t,n,r){let i=e.providers?.[t],a=i?.models;if(i===void 0||a===void 0||n<0||n>=a.length)return e;let o=[...a];return o[n]=r,rj(e,t,{...i,models:o})}function sj(e,t,n){let r=e.providers?.[t],i=r?.models;if(r===void 0||i===void 0||n<0||n>=i.length)return e;let a=i.filter((e,t)=>t!==n);if(a.length===0){let n={...r};return delete n.models,rj(e,t,n)}return rj(e,t,{...r,models:a})}function cj(e,t,n,r){let i=n==="default"?dj(e??{},t):{...e??{}};if(n===`disabled`&&(i[t]=null),n===`custom`){let e=r?.trim();i[t]=e===void 0||e===``?t:e}return Object.keys(i).length===0?void 0:i}function lj(e,t){return{...e,providers:t}}function uj(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function dj(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function fj(e){let t=`new-provider`,n=1;for(;e[t]!==void 0;)t=`new-provider-${String(n++)}`;return t}var pj={thinkingFormat:`deepseek`,requiresReasoningContentOnAssistantMessages:!0},mj=class extends y{constructor(...e){super(...e),this.modelsApi=Ws,this.config={providers:{}},this.loading=!0,this.saving=!1,this.error=``,this.savedMessage=``,this.providerNameDraft=``,this.renameError=``,this.advancedErrors={},this.modelTests={},this.discoveredModels={},this.loadRequestSequence=0,this.modelDiscoverySequence=0,this.modelDiscoveryRequestSequences=new Map}connectedCallback(){super.connectedCallback(),this.loadConfig()}disconnectedCallback(){this.savedMessageTimer!==void 0&&clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}updated(e){e.has(`machine`)&&_j(e.get(`machine`))!==this.machineId()&&(this.resetForMachineChange(),this.isConnected&&this.loadConfig())}render(){return g`
|
|
3797
3797
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
3798
3798
|
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="models-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
3799
3799
|
<header>
|
|
@@ -3804,10 +3804,10 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3804
3804
|
</div>
|
|
3805
3805
|
<div class="header-actions">
|
|
3806
3806
|
<button class="icon-button" type="button" title="Reload models configuration" aria-label="Reload models configuration" ?disabled=${this.loading} @click=${()=>{this.loadConfig()}}>
|
|
3807
|
-
${
|
|
3807
|
+
${Gj()}
|
|
3808
3808
|
</button>
|
|
3809
3809
|
<button class="icon-button" type="button" title="Close models configuration" aria-label="Close models configuration" @click=${()=>{this.close()}}>
|
|
3810
|
-
${
|
|
3810
|
+
${Kj()}
|
|
3811
3811
|
</button>
|
|
3812
3812
|
</div>
|
|
3813
3813
|
</header>
|
|
@@ -3825,7 +3825,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3825
3825
|
${this.savedMessage===``?null:g`<span class="saved-message">${this.savedMessage}</span>`}
|
|
3826
3826
|
</div>
|
|
3827
3827
|
<button type="button" class="secondary" @click=${()=>{this.configureAuth()}}>
|
|
3828
|
-
${
|
|
3828
|
+
${qj()} Authentication
|
|
3829
3829
|
</button>
|
|
3830
3830
|
<button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
|
|
3831
3831
|
<button type="button" class="primary" ?disabled=${this.saving||this.loading} @click=${()=>{this.saveConfig()}}>
|
|
@@ -3846,28 +3846,28 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3846
3846
|
</div>
|
|
3847
3847
|
<div class="tree-actions">
|
|
3848
3848
|
<button type="button" class="add-provider" @click=${()=>{this.addCustomProvider()}}>
|
|
3849
|
-
${
|
|
3849
|
+
${Uj()} Add provider
|
|
3850
3850
|
</button>
|
|
3851
3851
|
<button type="button" class="auth-link" @click=${()=>{this.configureAuth()}}>
|
|
3852
|
-
${
|
|
3852
|
+
${qj()} Configure authentication
|
|
3853
3853
|
</button>
|
|
3854
3854
|
</div>
|
|
3855
3855
|
</aside>
|
|
3856
3856
|
`}renderProviderTreeNode(e,t){let n=this.selection?.type===`provider`&&this.selection.providerName===e,r=t.models??[];return g`
|
|
3857
3857
|
<div class="provider-node">
|
|
3858
3858
|
<button class="tree-row provider-row ${n?`selected`:``}" type="button" @click=${()=>{this.selectProvider(e)}}>
|
|
3859
|
-
${
|
|
3859
|
+
${Vj()}
|
|
3860
3860
|
<span class="tree-label">${e}</span>
|
|
3861
3861
|
</button>
|
|
3862
3862
|
${r.map((t,n)=>g`
|
|
3863
3863
|
<button class="tree-row model-row ${this.selection?.type===`model`&&this.selection.providerName===e&&this.selection.index===n?`selected`:``}" type="button" @click=${()=>{this.selectModel(e,n)}}>
|
|
3864
|
-
${
|
|
3864
|
+
${Hj()}
|
|
3865
3865
|
<span class="tree-label">${t.id.trim()===``?`new model`:t.id}</span>
|
|
3866
3866
|
${t.reasoning===!0?g`<span class="thinking-mark" title="Reasoning enabled">T</span>`:null}
|
|
3867
3867
|
</button>
|
|
3868
3868
|
`)}
|
|
3869
3869
|
<button class="tree-row add-model" type="button" @click=${()=>{this.addModel(e)}}>
|
|
3870
|
-
${
|
|
3870
|
+
${Uj()} <span>Add model</span>
|
|
3871
3871
|
</button>
|
|
3872
3872
|
</div>
|
|
3873
3873
|
`}renderDetail(){let e=this.selection;if(e===void 0)return g`
|
|
@@ -3884,16 +3884,16 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3884
3884
|
</div>
|
|
3885
3885
|
<div class="provider-actions">
|
|
3886
3886
|
<button type="button" class="secondary" ?disabled=${!r||n?.phase===`discovering`} @click=${()=>{this.discoverModels(e)}}>
|
|
3887
|
-
${n?.phase===`discovering`?
|
|
3887
|
+
${n?.phase===`discovering`?Yj():Gj()} ${n===void 0?`Fetch models`:n.phase===`discovering`?`Fetching models...`:`Refresh models`}
|
|
3888
3888
|
</button>
|
|
3889
|
-
<button type="button" class="danger" @click=${()=>{this.deleteProvider(e)}}>${
|
|
3889
|
+
<button type="button" class="danger" @click=${()=>{this.deleteProvider(e)}}>${Wj()} Delete provider</button>
|
|
3890
3890
|
</div>
|
|
3891
3891
|
</div>
|
|
3892
3892
|
|
|
3893
3893
|
<div class="field-stack provider-name-field">
|
|
3894
3894
|
<label for="provider-name">Provider name</label>
|
|
3895
3895
|
<div class="inline-field">
|
|
3896
|
-
<input id="provider-name" class="mono" .value=${this.providerNameDraft} placeholder="provider-name" @input=${e=>{this.providerNameDraft=
|
|
3896
|
+
<input id="provider-name" class="mono" .value=${this.providerNameDraft} placeholder="provider-name" @input=${e=>{this.providerNameDraft=yj(e),this.renameError=``}}>
|
|
3897
3897
|
<button type="button" class="secondary" ?disabled=${this.providerNameDraft.trim()===``||this.providerNameDraft===e} @click=${()=>{this.renameSelectedProvider(e)}}>Rename</button>
|
|
3898
3898
|
</div>
|
|
3899
3899
|
${this.renameError===``?null:g`<span class="field-error">${this.renameError}</span>`}
|
|
@@ -3901,19 +3901,19 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3901
3901
|
|
|
3902
3902
|
<div class="field-stack">
|
|
3903
3903
|
<label for="provider-base-url">Base URL</label>
|
|
3904
|
-
<input id="provider-base-url" class="mono" .value=${t.baseUrl??``} placeholder="https://api.example.com/v1" @input=${n=>{this.replaceProvider(e,{...t,baseUrl:
|
|
3904
|
+
<input id="provider-base-url" class="mono" .value=${t.baseUrl??``} placeholder="https://api.example.com/v1" @input=${n=>{this.replaceProvider(e,{...t,baseUrl:vj(yj(n))})}}>
|
|
3905
3905
|
</div>
|
|
3906
3906
|
|
|
3907
3907
|
<div class="field-stack">
|
|
3908
3908
|
<label for="provider-api-key">API key source</label>
|
|
3909
|
-
<input id="provider-api-key" class="mono" type="password" autocomplete="off" .value=${t.apiKey??``} placeholder="ENV_VAR_NAME, !command, or literal key" @input=${n=>{this.replaceProvider(e,{...t,apiKey:
|
|
3909
|
+
<input id="provider-api-key" class="mono" type="password" autocomplete="off" .value=${t.apiKey??``} placeholder="ENV_VAR_NAME, !command, or literal key" @input=${n=>{this.replaceProvider(e,{...t,apiKey:vj(yj(n))})}}>
|
|
3910
3910
|
<span class="help-text">Use an environment variable name, prefix a command with <code>!</code>, or configure built-in provider credentials through Authentication.</span>
|
|
3911
3911
|
</div>
|
|
3912
3912
|
|
|
3913
3913
|
<div class="field-stack">
|
|
3914
3914
|
<label for="provider-api">API format</label>
|
|
3915
|
-
<select id="provider-api" .value=${i} @change=${n=>{this.replaceProvider(e,{...t,api:
|
|
3916
|
-
${
|
|
3915
|
+
<select id="provider-api" .value=${i} @change=${n=>{this.replaceProvider(e,{...t,api:yj(n)})}}>
|
|
3916
|
+
${QA(i).map(({api:e,selected:t})=>g`<option value=${e} .selected=${t}>${e}</option>`)}
|
|
3917
3917
|
</select>
|
|
3918
3918
|
</div>
|
|
3919
3919
|
|
|
@@ -3928,7 +3928,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3928
3928
|
</div>
|
|
3929
3929
|
</details>
|
|
3930
3930
|
</div>
|
|
3931
|
-
`}renderModelDetail(e,t,n,r){let i=this.modelTests[
|
|
3931
|
+
`}renderModelDetail(e,t,n,r){let i=this.modelTests[Mj(e,r)];return g`
|
|
3932
3932
|
<div class="detail-content">
|
|
3933
3933
|
<div class="detail-heading">
|
|
3934
3934
|
<div>
|
|
@@ -3936,35 +3936,35 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3936
3936
|
<h2>${n.id.trim()===``?`New model`:n.id}</h2>
|
|
3937
3937
|
</div>
|
|
3938
3938
|
<div class="model-actions">
|
|
3939
|
-
${i===void 0?null:g`<span class="connection-state ${i.phase}">${
|
|
3939
|
+
${i===void 0?null:g`<span class="connection-state ${i.phase}">${Lj(i)}</span>`}
|
|
3940
3940
|
<button type="button" class="secondary" ?disabled=${n.id.trim()===``||i?.phase===`testing`} @click=${()=>{this.testModel(e,r)}}>
|
|
3941
|
-
${i?.phase===`testing`?
|
|
3941
|
+
${i?.phase===`testing`?Yj():Jj()} ${i?.phase===`testing`?`Testing...`:`Test`}
|
|
3942
3942
|
</button>
|
|
3943
|
-
<button type="button" class="danger" @click=${()=>{this.deleteModel(e,r)}}>${
|
|
3943
|
+
<button type="button" class="danger" @click=${()=>{this.deleteModel(e,r)}}>${Wj()} Remove</button>
|
|
3944
3944
|
</div>
|
|
3945
3945
|
</div>
|
|
3946
3946
|
|
|
3947
|
-
${i===void 0?null:g`<div class="connection-detail ${i.phase}">${
|
|
3947
|
+
${i===void 0?null:g`<div class="connection-detail ${i.phase}">${Rj(i)}</div>`}
|
|
3948
3948
|
|
|
3949
3949
|
<div class="field-grid two-columns">
|
|
3950
3950
|
${this.renderModelIdField(e,n,r)}
|
|
3951
3951
|
<div class="field-stack">
|
|
3952
3952
|
<label for="model-name">Display name</label>
|
|
3953
|
-
<input id="model-name" .value=${n.name??``} placeholder="Display name" @input=${t=>{this.replaceModel(e,r,{...n,name:
|
|
3953
|
+
<input id="model-name" .value=${n.name??``} placeholder="Display name" @input=${t=>{this.replaceModel(e,r,{...n,name:vj(yj(t))})}}>
|
|
3954
3954
|
</div>
|
|
3955
3955
|
</div>
|
|
3956
3956
|
|
|
3957
3957
|
<div class="field-stack">
|
|
3958
3958
|
<label for="model-api">API override</label>
|
|
3959
|
-
<select id="model-api" .value=${n.api??``} @change=${t=>{this.replaceModel(e,r,{...n,api:
|
|
3959
|
+
<select id="model-api" .value=${n.api??``} @change=${t=>{this.replaceModel(e,r,{...n,api:vj(yj(t))})}}>
|
|
3960
3960
|
<option value="">Inherit provider API</option>
|
|
3961
|
-
${
|
|
3961
|
+
${QA(n.api).map(({api:e,selected:t})=>g`<option value=${e} .selected=${t}>${e}</option>`)}
|
|
3962
3962
|
</select>
|
|
3963
3963
|
</div>
|
|
3964
3964
|
|
|
3965
3965
|
<div class="switch-row">
|
|
3966
3966
|
${this.renderCheck(`Reasoning / thinking`,n.reasoning===!0,t=>{this.replaceModel(e,r,{...n,reasoning:t||void 0})})}
|
|
3967
|
-
${this.renderCheck(`Image input`,n.input?.includes(`image`)===!0,t=>{this.replaceModel(e,r,{...n,input:t?
|
|
3967
|
+
${this.renderCheck(`Image input`,n.input?.includes(`image`)===!0,t=>{this.replaceModel(e,r,{...n,input:t?wj(n.input):Tj(n.input)})})}
|
|
3968
3968
|
</div>
|
|
3969
3969
|
|
|
3970
3970
|
${n.reasoning===!0?g`
|
|
@@ -3974,10 +3974,10 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3974
3974
|
<span class="section-label">Thinking configuration</span>
|
|
3975
3975
|
<p>Map Pi thinking levels to values accepted by this model, or disable a level.</p>
|
|
3976
3976
|
</div>
|
|
3977
|
-
${this.renderCheck(`DeepSeek thinking compatibility`,
|
|
3977
|
+
${this.renderCheck(`DeepSeek thinking compatibility`,Ej(n),t=>{this.replaceModel(e,r,Dj(n,t))})}
|
|
3978
3978
|
</div>
|
|
3979
3979
|
<div class="thinking-map">
|
|
3980
|
-
${
|
|
3980
|
+
${ej.map(t=>this.renderThinkingLevel(e,r,n,t))}
|
|
3981
3981
|
</div>
|
|
3982
3982
|
</section>
|
|
3983
3983
|
`:null}
|
|
@@ -3985,11 +3985,11 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
3985
3985
|
<div class="field-grid two-columns">
|
|
3986
3986
|
<div class="field-stack">
|
|
3987
3987
|
<label for="context-window">Context window (tokens)</label>
|
|
3988
|
-
<input id="context-window" type="number" min="0" inputmode="numeric" .value=${
|
|
3988
|
+
<input id="context-window" type="number" min="0" inputmode="numeric" .value=${xj(n.contextWindow)} placeholder="128000" @input=${t=>{this.replaceModel(e,r,{...n,contextWindow:Sj(yj(t))})}}>
|
|
3989
3989
|
</div>
|
|
3990
3990
|
<div class="field-stack">
|
|
3991
3991
|
<label for="max-tokens">Max output tokens</label>
|
|
3992
|
-
<input id="max-tokens" type="number" min="0" inputmode="numeric" .value=${
|
|
3992
|
+
<input id="max-tokens" type="number" min="0" inputmode="numeric" .value=${xj(n.maxTokens)} placeholder="16384" @input=${t=>{this.replaceModel(e,r,{...n,maxTokens:Sj(yj(t))})}}>
|
|
3993
3993
|
</div>
|
|
3994
3994
|
</div>
|
|
3995
3995
|
|
|
@@ -4016,14 +4016,14 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4016
4016
|
`}renderModelIdField(e,t,n){let r=this.discoveredModels[e]?.models;if(r===void 0)return g`
|
|
4017
4017
|
<div class="field-stack">
|
|
4018
4018
|
<label for="model-id">Model ID <span aria-hidden="true">*</span></label>
|
|
4019
|
-
<input id="model-id" class="mono" .value=${t.id} placeholder="model-id" @input=${r=>{this.replaceModel(e,n,{...t,id:
|
|
4019
|
+
<input id="model-id" class="mono" .value=${t.id} placeholder="model-id" @input=${r=>{this.replaceModel(e,n,{...t,id:yj(r)})}}>
|
|
4020
4020
|
</div>
|
|
4021
4021
|
`;let i=t.id.trim()===``||r.some(e=>e.id===t.id)?r:[{id:t.id,...t.name===void 0?{}:{name:t.name}},...r];return g`
|
|
4022
4022
|
<div class="field-stack">
|
|
4023
4023
|
<label for="model-id">Model ID <span aria-hidden="true">*</span></label>
|
|
4024
|
-
<select id="model-id" class="mono" .value=${t.id} @change=${t=>{this.selectDiscoveredModel(e,n,
|
|
4024
|
+
<select id="model-id" class="mono" .value=${t.id} @change=${t=>{this.selectDiscoveredModel(e,n,yj(t))}}>
|
|
4025
4025
|
${t.id.trim()===``?g`<option value="" disabled>Select a model</option>`:null}
|
|
4026
|
-
${
|
|
4026
|
+
${$A(i,t.id).map(({candidate:e,selected:t})=>g`<option value=${e.id} .selected=${t}>${e.name===void 0?e.id:`${e.name} (${e.id})`}</option>`)}
|
|
4027
4027
|
</select>
|
|
4028
4028
|
</div>
|
|
4029
4029
|
`}renderThinkingLevel(e,t,n,r){let i=n.thinkingLevelMap?.[r],a=i===void 0?`default`:i===null?`disabled`:`custom`,o=typeof i==`string`?i:``;return g`
|
|
@@ -4035,26 +4035,26 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4035
4035
|
</div>
|
|
4036
4036
|
<label class="custom-thinking">
|
|
4037
4037
|
<span>Custom</span>
|
|
4038
|
-
<input class="mono" .value=${o} placeholder=${r} @focus=${()=>{this.setThinkingLevel(e,t,n,r,`custom`,o||r)}} @input=${i=>{this.setThinkingLevel(e,t,n,r,`custom`,
|
|
4038
|
+
<input class="mono" .value=${o} placeholder=${r} @focus=${()=>{this.setThinkingLevel(e,t,n,r,`custom`,o||r)}} @input=${i=>{this.setThinkingLevel(e,t,n,r,`custom`,yj(i))}}>
|
|
4039
4039
|
</label>
|
|
4040
4040
|
</div>
|
|
4041
4041
|
`}renderCostField(e,t,n,r,i){let a=`cost-${t}`;return g`
|
|
4042
4042
|
<div class="field-stack">
|
|
4043
4043
|
<label for=${a}>${e}</label>
|
|
4044
|
-
<input id=${a} type="number" min="0" step="any" inputmode="decimal" .value=${
|
|
4044
|
+
<input id=${a} type="number" min="0" step="any" inputmode="decimal" .value=${xj(i.cost?.[t])} placeholder="0" @input=${e=>{this.setCost(n,r,i,t,Cj(yj(e)))}}>
|
|
4045
4045
|
</div>
|
|
4046
4046
|
`}renderCheck(e,t,n){return g`
|
|
4047
4047
|
<label class="check-row">
|
|
4048
|
-
<input type="checkbox" .checked=${t} @change=${e=>{n(
|
|
4048
|
+
<input type="checkbox" .checked=${t} @change=${e=>{n(bj(e))}}>
|
|
4049
4049
|
<span>${e}</span>
|
|
4050
4050
|
</label>
|
|
4051
4051
|
`}renderJsonField(e,t,n,r){let i=`advanced-${t}`,a=this.advancedErrors[t];return g`
|
|
4052
4052
|
<div class="field-stack">
|
|
4053
4053
|
<label for=${i}>${e} (JSON object)</label>
|
|
4054
|
-
<textarea id=${i} class="mono" rows="4" .value=${
|
|
4054
|
+
<textarea id=${i} class="mono" rows="4" .value=${kj(n)} @change=${e=>{r(yj(e))}}></textarea>
|
|
4055
4055
|
${a===void 0?null:g`<span class="field-error">${a}</span>`}
|
|
4056
4056
|
</div>
|
|
4057
|
-
`}async loadConfig(){let e=++this.loadRequestSequence,t=this.machineId();this.modelDiscoveryRequestSequences.clear(),this.discoveredModels={},this.loading=!0,this.error=``,this.savedMessage=``;try{let n=
|
|
4057
|
+
`}async loadConfig(){let e=++this.loadRequestSequence,t=this.machineId();this.modelDiscoveryRequestSequences.clear(),this.discoveredModels={},this.loading=!0,this.error=``,this.savedMessage=``;try{let n=hj(await this.modelsApi.config(t));if(!this.isCurrentLoad(e,t))return;this.config=n,this.selection=gj(this.selection,n),this.providerNameDraft=this.selection?.type===`provider`?this.selection.providerName:``,this.renameError=``,this.advancedErrors={},this.modelTests={}}catch(n){this.isCurrentLoad(e,t)&&(this.error=`Failed to load models configuration: ${Bj(n)}`)}finally{this.isCurrentLoad(e,t)&&(this.loading=!1)}}async saveConfig(){if(this.saving||this.loading)return;let e=this.machineId();this.saving=!0,this.error=``,this.savedMessage=``;try{if(await this.modelsApi.save(this.config,e),e!==this.machineId())return;this.setSavedMessage(`Saved and reloaded models for ${this.machineLabel()}.`),this.onSaved?.()}catch(t){e===this.machineId()&&(this.error=`Failed to save models configuration: ${Bj(t)}`)}finally{e===this.machineId()&&(this.saving=!1)}}async testModel(e,t){let n=this.config.providers?.[e],r=n?.models?.[t];if(n===void 0||r===void 0)return;let i=Mj(e,t);if(r.id.trim()===``){this.modelTests={...this.modelTests,[i]:{phase:`error`,message:`Model ID is required.`}};return}let a=this.machineId();this.modelTests={...this.modelTests,[i]:{phase:`testing`}};try{let t=await this.modelsApi.test({providerName:e,provider:n,model:r},a);if(a!==this.machineId())return;this.modelTests={...this.modelTests,[i]:t.ok?{phase:`success`,result:t}:Ij(t)}}catch(e){a===this.machineId()&&(this.modelTests={...this.modelTests,[i]:{phase:`error`,message:Bj(e)}})}}async discoverModels(e){let t=this.config.providers?.[e];if(t===void 0)return;let n=this.nextModelDiscoveryRequest(e),r=this.machineId(),i=this.discoveredModels[e];this.error=``,this.discoveredModels={...this.discoveredModels,[e]:i?.models===void 0?{phase:`discovering`}:{phase:`discovering`,models:i.models}};try{let i=await this.modelsApi.discover({providerName:e,provider:t},r);if(!this.isCurrentModelDiscovery(n,r,e,t))return;this.discoveredModels={...this.discoveredModels,[e]:{phase:`ready`,models:i.models}}}catch(a){if(!this.isCurrentModelDiscovery(n,r,e,t))return;this.discoveredModels=i===void 0?Fj(this.discoveredModels,e):{...this.discoveredModels,[e]:i},this.error=`Failed to fetch models for ${e}: ${Bj(a)}`}}selectProvider(e){this.selection={type:`provider`,providerName:e},this.providerNameDraft=e,this.renameError=``}selectModel(e,t){this.selection={type:`model`,providerName:e,index:t},this.providerNameDraft=``,this.renameError=``}addCustomProvider(){let e=tj(this.config);this.config=e.config,this.selectProvider(e.providerName)}deleteProvider(e){this.clearProviderDiscovery(e),this.config=ij(this.config,e),this.modelTests=Nj(this.modelTests,e);let t=Object.keys(this.config.providers??{})[0];t===void 0?(this.selection=void 0,this.providerNameDraft=``):this.selectProvider(t)}renameSelectedProvider(e){let t=nj(this.config,e,this.providerNameDraft);if(`error`in t){this.renameError=t.error;return}let n=this.providerNameDraft.trim();this.clearProviderDiscovery(e),this.config=t.config,this.modelTests=Pj(this.modelTests,e,n),this.selectProvider(n)}replaceProvider(e,t){this.invalidateProviderDiscovery(e),this.config=rj(this.config,e,t),this.modelTests=Nj(this.modelTests,e)}addModel(e){let t=this.config.providers?.[e]?.models?.length??0;this.config=aj(this.config,e),this.selectModel(e,t)}deleteModel(e,t){this.config=sj(this.config,e,t),this.modelTests=Nj(this.modelTests,e),this.selectProvider(e)}replaceModel(e,t,n){this.config=oj(this.config,e,t,n);let r=Mj(e,t);this.modelTests[r]!==void 0&&(this.modelTests=Fj(this.modelTests,r))}selectDiscoveredModel(e,t,n){let r=this.config.providers?.[e]?.models?.[t],i=this.discoveredModels[e]?.models?.find(e=>e.id===n);r===void 0||i===void 0||this.replaceModel(e,t,{...r,id:i.id,name:i.name??i.id})}invalidateProviderDiscovery(e){this.nextModelDiscoveryRequest(e);let t=this.discoveredModels[e];if(t?.phase===`discovering`){if(t.models===void 0){this.discoveredModels=Fj(this.discoveredModels,e);return}this.discoveredModels={...this.discoveredModels,[e]:{phase:`ready`,models:t.models}}}}clearProviderDiscovery(e){this.nextModelDiscoveryRequest(e),this.discoveredModels[e]!==void 0&&(this.discoveredModels=Fj(this.discoveredModels,e))}setThinkingLevel(e,t,n,r,i,a){this.replaceModel(e,t,{...n,thinkingLevelMap:cj(n.thinkingLevelMap,r,i,a)})}setCost(e,t,n,r,i){let a={...n.cost??{},[r]:i};if(Object.values(a).every(e=>e===void 0)){this.replaceModel(e,t,{...n,cost:void 0});return}this.replaceModel(e,t,{...n,cost:a})}updateProviderHeaders(e,t,n){let r=Oj(n),i=`headers`;if(!r.ok){this.setAdvancedError(i,r.error);return}if(r.value!==void 0&&!Aj(r.value)){this.setAdvancedError(i,`Headers must map string names to string values.`);return}this.clearAdvancedError(i),this.replaceProvider(e,{...t,headers:r.value===void 0?void 0:jj(r.value)})}updateProviderObject(e,t,n,r){let i=Oj(r),a=n===`compat`?`compat`:`model-overrides`;if(!i.ok){this.setAdvancedError(a,i.error);return}this.clearAdvancedError(a),this.replaceProvider(e,{...t,[n]:i.value})}updateModelObject(e,t,n,r,i){let a=Oj(i),o=`model-compat`;if(!a.ok){this.setAdvancedError(o,a.error);return}this.clearAdvancedError(o),this.replaceModel(e,t,{...n,[r]:a.value})}setAdvancedError(e,t){this.advancedErrors={...this.advancedErrors,[e]:t}}clearAdvancedError(e){this.advancedErrors[e]!==void 0&&(this.advancedErrors=Fj(this.advancedErrors,e))}configureAuth(){this.onConfigureAuth?.()}close(){this.onClose?.()}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}resetForMachineChange(){this.loadRequestSequence+=1,this.modelDiscoveryRequestSequences.clear(),this.config={providers:{}},this.loading=!0,this.saving=!1,this.error=``,this.savedMessage=``,this.selection=void 0,this.providerNameDraft=``,this.renameError=``,this.advancedErrors={},this.modelTests={},this.discoveredModels={}}machineId(){return _j(this.machine)}machineLabel(){let e=this.machine?.name;return e===void 0||e===``?`local machine`:e}isCurrentLoad(e,t){return e===this.loadRequestSequence&&t===this.machineId()}isCurrentModelDiscovery(e,t,n,r){return e===this.modelDiscoveryRequestSequences.get(n)&&t===this.machineId()&&this.config.providers?.[n]===r}nextModelDiscoveryRequest(e){let t=++this.modelDiscoverySequence;return this.modelDiscoveryRequestSequences.set(e,t),t}setSavedMessage(e){this.savedMessageTimer!==void 0&&clearTimeout(this.savedMessageTimer),this.savedMessage=e,this.savedMessageTimer=setTimeout(()=>{this.savedMessage=``,this.savedMessageTimer=void 0},3e3)}static{this.styles=h`
|
|
4058
4058
|
:host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
|
|
4059
4059
|
.backdrop { position: absolute; inset: 0; display: grid; place-items: center; box-sizing: border-box; padding: max(16px, env(safe-area-inset-top)) max(16px, env(safe-area-inset-right)) max(16px, env(safe-area-inset-bottom)) max(16px, env(safe-area-inset-left)); background: var(--pi-overlay); }
|
|
4060
4060
|
.dialog { width: min(920px, 100%); height: min(78dvh, 760px); max-height: 100%; display: flex; flex-direction: column; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); }
|
|
@@ -4162,16 +4162,16 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4162
4162
|
.thinking-row { grid-template-columns: 58px minmax(0, 1fr); }
|
|
4163
4163
|
.custom-thinking { grid-column: 1 / -1; }
|
|
4164
4164
|
}
|
|
4165
|
-
`}};H([x({attribute:!1})],
|
|
4165
|
+
`}};H([x({attribute:!1})],mj.prototype,`machine`,void 0),H([x({attribute:!1})],mj.prototype,`modelsApi`,void 0),H([x({attribute:!1})],mj.prototype,`onClose`,void 0),H([x({attribute:!1})],mj.prototype,`onConfigureAuth`,void 0),H([x({attribute:!1})],mj.prototype,`onSaved`,void 0),H([S()],mj.prototype,`config`,void 0),H([S()],mj.prototype,`loading`,void 0),H([S()],mj.prototype,`saving`,void 0),H([S()],mj.prototype,`error`,void 0),H([S()],mj.prototype,`savedMessage`,void 0),H([S()],mj.prototype,`selection`,void 0),H([S()],mj.prototype,`providerNameDraft`,void 0),H([S()],mj.prototype,`renameError`,void 0),H([S()],mj.prototype,`advancedErrors`,void 0),H([S()],mj.prototype,`modelTests`,void 0),H([S()],mj.prototype,`discoveredModels`,void 0),mj=H([b(`models-config-dialog`)],mj);function hj(e){return e.providers===void 0?{...e,providers:{}}:e}function gj(e,t){if(e?.type===`provider`&&t.providers?.[e.providerName]!==void 0||e?.type===`model`&&t.providers?.[e.providerName]?.models?.[e.index]!==void 0)return e;let n=Object.keys(t.providers??{})[0];return n===void 0?void 0:{type:`provider`,providerName:n}}function _j(e){if(!zj(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function vj(e){return e.trim()===``?void 0:e}function yj(e){let t=e.target;return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.value:``}function bj(e){return e.target instanceof HTMLInputElement&&e.target.checked}function xj(e){return e===void 0?``:String(e)}function Sj(e){let t=e.trim();if(t===``)return;let n=Number(t);return Number.isInteger(n)&&n>=0?n:void 0}function Cj(e){let t=e.trim();if(t===``)return;let n=Number(t);return Number.isFinite(n)&&n>=0?n:void 0}function wj(e){let t=e??[`text`];return t.includes(`image`)?[...t]:[...t,`image`]}function Tj(e){let t=(e??[]).filter(e=>e!==`image`);return t.length===0?void 0:t}function Ej(e){return e.compat?.thinkingFormat===`deepseek`}function Dj(e,t){if(t)return{...e,compat:{...e.compat??{},...pj}};if(e.compat===void 0)return e;let n={...e.compat};return delete n.thinkingFormat,delete n.requiresReasoningContentOnAssistantMessages,{...e,compat:Object.keys(n).length===0?void 0:n}}function Oj(e){if(e.trim()===``)return{ok:!0,value:void 0};try{let t=JSON.parse(e);return zj(t)?{ok:!0,value:t}:{ok:!1,error:`Value must be a JSON object.`}}catch(e){return{ok:!1,error:`Invalid JSON: ${Bj(e)}`}}}function kj(e){return e===void 0?``:JSON.stringify(e,null,2)}function Aj(e){return Object.values(e).every(e=>typeof e==`string`)}function jj(e){let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(t[n]=r);return t}function Mj(e,t){return`${e}\u0000${String(t)}`}function Nj(e,t){let n=`${t}\u0000`,r={};for(let[t,i]of Object.entries(e))t.startsWith(n)||(r[t]=i);return r}function Pj(e,t,n){let r=`${t}\u0000`,i=`${n}\u0000`,a={};for(let[t,n]of Object.entries(e)){let e=t.startsWith(r)?`${i}${t.slice(r.length)}`:t;a[e]=n}return a}function Fj(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function Ij(e){return{phase:`error`,message:e.error??`Model returned an error.`,...e.latencyMs===void 0?{}:{latencyMs:e.latencyMs},...e.status===void 0?{}:{status:e.status}}}function Lj(e){return e.phase===`testing`?`Testing connection`:e.phase===`success`?e.result.latencyMs===void 0?`Connected`:`Connected in ${String(e.result.latencyMs)} ms`:`Connection failed`}function Rj(e){if(e.phase===`testing`)return`Sending a small test request...`;if(e.phase===`success`){let t=[e.result.status===void 0?void 0:`HTTP ${String(e.result.status)}`,e.result.latencyMs===void 0?void 0:`${String(e.result.latencyMs)} ms`,e.result.responseText===void 0||e.result.responseText===``?void 0:e.result.responseText].filter(e=>e!==void 0);return t.length===0?`Connection succeeded.`:t.join(` - `)}return[e.status===void 0?void 0:`HTTP ${String(e.status)}`,e.latencyMs===void 0?void 0:`${String(e.latencyMs)} ms`,e.message].filter(e=>e!==void 0).join(` - `)}function zj(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Bj(e){return e instanceof Error?e.message:String(e)}function Vj(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="4" y="4" width="16" height="16" rx="2"></rect><rect x="9" y="9" width="6" height="6"></rect><path d="M9 1v3m6-3v3M9 20v3m6-3v3M20 9h3m-3 5h3M1 9h3m-3 5h3"></path></svg>`}function Hj(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="7"></circle><path d="M12 8v4l3 2"></path></svg>`}function Uj(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function Wj(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M4 7h16M10 11v6m4-6v6M9 7l1-3h4l1 3m-9 0 1 13h10l1-13"></path></svg>`}function Gj(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M20 11a8 8 0 1 0 2 5.5"></path><path d="M20 4v7h-7"></path></svg>`}function Kj(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="m6 6 12 12M18 6 6 18"></path></svg>`}function qj(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="8" cy="15" r="4"></circle><path d="m11 12 9-9m-3 0h3v3"></path></svg>`}function Jj(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 22v-5M8 4v5m8-5v5M7 9h10v3a5 5 0 0 1-10 0V9Z"></path></svg>`}function Yj(){return _`<svg class="svg-icon spin" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="8" opacity=".25"></circle><path d="M20 12a8 8 0 0 0-8-8"></path></svg>`}var q=class extends y{constructor(...e){super(...e),this.cwd=``,this.skillsApi=Qs,this.skills=[],this.loading=!0,this.loadError=``,this.togglingPaths=new Set,this.saveError=``,this.addMode=!1,this.searchQuery=``,this.searchResults=[],this.searching=!1,this.searchError=``,this.installError=``,this.newlyInstalledKeys=new Set,this.installScope=`global`,this.updateStatuses={},this.checkingUpdateKeys=new Set,this.checkingAll=!1,this.updateError=``,this.loadRequestSequence=0}connectedCallback(){super.connectedCallback(),this.loadSkills()}updated(e){let t=e.has(`machine`)&&Xj(e.get(`machine`))!==this.machineId(),n=e.has(`cwd`)&&e.get(`cwd`)!==this.cwd;(t||n)&&(this.resetForTargetChange(),this.isConnected&&this.loadSkills())}render(){let e=this.selectedSkill();return g`
|
|
4166
4166
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
4167
4167
|
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="skills-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
4168
4168
|
<header>
|
|
4169
4169
|
<div class="title-block">
|
|
4170
4170
|
<h1 id="skills-dialog-title">Skills</h1>
|
|
4171
|
-
<span class="target"><code>${
|
|
4171
|
+
<span class="target"><code>${eM(this.cwd)}</code> on ${this.machineLabel()}</span>
|
|
4172
4172
|
</div>
|
|
4173
4173
|
<button class="icon-button" type="button" title="Close skills configuration" aria-label="Close skills configuration" @click=${()=>{this.close()}}>
|
|
4174
|
-
${
|
|
4174
|
+
${hM()}
|
|
4175
4175
|
</button>
|
|
4176
4176
|
</header>
|
|
4177
4177
|
|
|
@@ -4197,21 +4197,21 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4197
4197
|
</div>
|
|
4198
4198
|
<div class="skill-list-actions">
|
|
4199
4199
|
<button class="add-skill" type="button" ?aria-pressed=${this.addMode} @click=${()=>{this.openAddMode()}}>
|
|
4200
|
-
${
|
|
4200
|
+
${mM()} Add skill
|
|
4201
4201
|
</button>
|
|
4202
4202
|
</div>
|
|
4203
4203
|
</aside>
|
|
4204
|
-
`}renderSkillListItem(e){let t=!this.addMode&&e.filePath===this.selectedFilePath,n=
|
|
4204
|
+
`}renderSkillListItem(e){let t=!this.addMode&&e.filePath===this.selectedFilePath,n=iM(e,this.updateStatuses);return g`
|
|
4205
4205
|
<button class="skill-row ${t?`selected`:``}" type="button" @click=${()=>{this.selectSkill(e)}}>
|
|
4206
4206
|
<span class="skill-indicator ${e.disableModelInvocation?`disabled`:``}" aria-hidden="true"></span>
|
|
4207
4207
|
<span class="skill-name">${e.name}</span>
|
|
4208
4208
|
${n?.state===`update-available`?g`<span class="update-available-mark" title="Update available" aria-label="Update available">↑</span>`:null}
|
|
4209
4209
|
</button>
|
|
4210
|
-
`}renderSkillDetail(e){let t=
|
|
4210
|
+
`}renderSkillDetail(e){let t=Qj(e),n=rM(e),r=n===void 0?void 0:this.updateStatuses[n],i=n!==void 0&&this.checkingUpdateKeys.has(n),a=n!==void 0&&this.updatingKey===n,o=!e.disableModelInvocation;return g`
|
|
4211
4211
|
<div class="detail-content">
|
|
4212
4212
|
<div class="skill-meta-row">
|
|
4213
4213
|
<span class="scope-tag ${t}">${t}</span>
|
|
4214
|
-
<code class="skill-path" title=${e.filePath}>${
|
|
4214
|
+
<code class="skill-path" title=${e.filePath}>${$j(e,this.cwd)}</code>
|
|
4215
4215
|
<button
|
|
4216
4216
|
class="skill-toggle ${o?`enabled`:``}"
|
|
4217
4217
|
type="button"
|
|
@@ -4229,7 +4229,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4229
4229
|
<section class="detail-section">
|
|
4230
4230
|
<h2>Source</h2>
|
|
4231
4231
|
<a class="source-link" href=${e.install.skillsShUrl} target="_blank" rel="noreferrer" title=${e.install.skillsShUrl}>
|
|
4232
|
-
<code>${
|
|
4232
|
+
<code>${tM(e.install.skillsShUrl)} ↗</code>
|
|
4233
4233
|
</a>
|
|
4234
4234
|
</section>
|
|
4235
4235
|
`}
|
|
@@ -4238,13 +4238,13 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4238
4238
|
<section class="detail-section">
|
|
4239
4239
|
<h2>Version</h2>
|
|
4240
4240
|
<div class="version-row">
|
|
4241
|
-
<code>${
|
|
4241
|
+
<code>${nM(r?.currentVersion??e.install.versionHash)}</code>
|
|
4242
4242
|
${e.install.canCheckForUpdates?g`
|
|
4243
4243
|
<button type="button" class="secondary compact-button" ?disabled=${i||a} @click=${()=>{this.checkForUpdates(e)}}>
|
|
4244
4244
|
${i?`Checking...`:`Check`}
|
|
4245
4245
|
</button>
|
|
4246
4246
|
`:null}
|
|
4247
|
-
${r?.state===`update-available`?g`<code class="update-version">${
|
|
4247
|
+
${r?.state===`update-available`?g`<code class="update-version">${nM(r.latestVersion)}</code>`:null}
|
|
4248
4248
|
${this.renderUpdateStatus(r,i)}
|
|
4249
4249
|
${r?.state===`update-available`?g`
|
|
4250
4250
|
<button type="button" class="primary compact-button" ?disabled=${a||i} @click=${()=>{this.updateInstalledSkill(e)}}>
|
|
@@ -4266,7 +4266,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4266
4266
|
<p>${e.description}</p>
|
|
4267
4267
|
</section>
|
|
4268
4268
|
</div>
|
|
4269
|
-
`}renderUpdateStatus(e,t){if(!t&&(e===void 0||e.state===`update-available`))return null;let n=t?`Checking...`:e?.state===`up-to-date`?`Up to date`:e?.state===`unsupported`?`Automatic checks unavailable`:e?.message??`Check failed`;return g`<span class="update-state ${t?`checking`:e?.state??`error`}">${n}</span>`}renderAddPanel(){let e=this.installScope===`global`?`~/.pi/agent/skills/`:`${
|
|
4269
|
+
`}renderUpdateStatus(e,t){if(!t&&(e===void 0||e.state===`update-available`))return null;let n=t?`Checking...`:e?.state===`up-to-date`?`Up to date`:e?.state===`unsupported`?`Automatic checks unavailable`:e?.message??`Check failed`;return g`<span class="update-state ${t?`checking`:e?.state??`error`}">${n}</span>`}renderAddPanel(){let e=this.installScope===`global`?`~/.pi/agent/skills/`:`${eM(this.cwd)}/.pi/skills/`;return g`
|
|
4270
4270
|
<div class="detail-content add-panel">
|
|
4271
4271
|
<div class="add-heading">
|
|
4272
4272
|
<h2>Add Skill</h2>
|
|
@@ -4278,7 +4278,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4278
4278
|
id="skill-search"
|
|
4279
4279
|
.value=${this.searchQuery}
|
|
4280
4280
|
placeholder="e.g. react, testing, deploy"
|
|
4281
|
-
@input=${e=>{this.searchQuery=
|
|
4281
|
+
@input=${e=>{this.searchQuery=dM(e)}}
|
|
4282
4282
|
@keydown=${e=>{e.key===`Enter`&&(e.preventDefault(),this.searchSkills())}}
|
|
4283
4283
|
>
|
|
4284
4284
|
<button type="button" class="primary" ?disabled=${this.searching||this.searchQuery.trim()===``} @click=${()=>{this.searchSkills()}}>
|
|
@@ -4300,7 +4300,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4300
4300
|
|
|
4301
4301
|
${this.searchResults.length>0?g`<div class="search-results">${this.searchResults.map(e=>this.renderSearchResult(e))}</div>`:this.searching||this.searchError!==``?null:g`<p class="search-hint">Search <a href="https://skills.sh" target="_blank" rel="noreferrer">skills.sh</a> to discover and install skills for your agent.</p>`}
|
|
4302
4302
|
</div>
|
|
4303
|
-
`}renderSearchResult(e){let t=this.isInstalled(e.package,this.installScope),n=this.installingPackage===e.package,r=
|
|
4303
|
+
`}renderSearchResult(e){let t=this.isInstalled(e.package,this.installScope),n=this.installingPackage===e.package,r=oM(e.package);return g`
|
|
4304
4304
|
<article class="search-result">
|
|
4305
4305
|
<div class="search-result-copy">
|
|
4306
4306
|
<strong>${r.skill??r.repository}</strong>
|
|
@@ -4329,7 +4329,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4329
4329
|
</div>
|
|
4330
4330
|
<button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
|
|
4331
4331
|
</footer>
|
|
4332
|
-
`}async loadSkills(){let e=this.target();if(e===void 0){this.loading=!1,this.loadError=`A selected workspace is required to manage skills.`;return}let t=++this.loadRequestSequence;this.loading=!0,this.loadError=``;try{let n=await this.skillsApi.list(e.cwd,e.machineId);if(!this.isCurrentTarget(e)||t!==this.loadRequestSequence)return;this.skills=n.skills,this.selectedFilePath=
|
|
4332
|
+
`}async loadSkills(){let e=this.target();if(e===void 0){this.loading=!1,this.loadError=`A selected workspace is required to manage skills.`;return}let t=++this.loadRequestSequence;this.loading=!0,this.loadError=``;try{let n=await this.skillsApi.list(e.cwd,e.machineId);if(!this.isCurrentTarget(e)||t!==this.loadRequestSequence)return;this.skills=n.skills,this.selectedFilePath=Zj(this.selectedFilePath,n.skills)}catch(n){this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loadError=`Failed to load skills: ${fM(n)}`)}finally{this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loading=!1)}}async toggleSkill(e){let t=this.target();if(t===void 0||this.togglingPaths.has(e.filePath))return;let n=!e.disableModelInvocation;this.togglingPaths=sM(this.togglingPaths,e.filePath),this.saveError=``;try{if(await this.skillsApi.toggle({cwd:t.cwd,filePath:e.filePath,disableModelInvocation:n},t.machineId),!this.isCurrentTarget(t))return;this.skills=this.skills.map(t=>t.filePath===e.filePath?{...t,disableModelInvocation:n}:t)}catch(e){this.isCurrentTarget(t)&&(this.saveError=fM(e))}finally{this.isCurrentTarget(t)&&(this.togglingPaths=lM(this.togglingPaths,e.filePath))}}async searchSkills(){let e=this.searchQuery.trim();if(e===``||this.searching)return;let t=this.machineId();this.searching=!0,this.searchError=``,this.searchResults=[];try{let n=await this.skillsApi.search({query:e},t);if(t!==this.machineId())return;this.searchResults=n.results,n.results.length===0&&(this.searchError=`No skills found`)}catch(e){t===this.machineId()&&(this.searchError=fM(e))}finally{t===this.machineId()&&(this.searching=!1)}}async installSkill(e){let t=this.target();if(t===void 0||this.installingPackage!==void 0)return;let n=this.installScope;this.installingPackage=e,this.installError=``;try{if(await this.skillsApi.install({cwd:t.cwd,package:e,scope:n},t.machineId),!this.isCurrentTarget(t))return;this.newlyInstalledKeys=sM(this.newlyInstalledKeys,aM(n,e)),await this.loadSkills()}catch(e){this.isCurrentTarget(t)&&(this.installError=fM(e))}finally{this.isCurrentTarget(t)&&(this.installingPackage=void 0)}}async checkForUpdates(e){let t=this.target();if(t===void 0)return;let n=(e===void 0?this.skills.filter(e=>e.install!==void 0):[e]).flatMap(e=>{let t=rM(e);return t===void 0?[]:[t]});if(n.length!==0){this.updateError=``,this.checkingUpdateKeys=cM(this.checkingUpdateKeys,n),e===void 0&&(this.checkingAll=!0);try{let n=e?.install,r=await this.skillsApi.check(n===void 0?{cwd:t.cwd}:{cwd:t.cwd,package:n.package,scope:n.scope},t.machineId);if(!this.isCurrentTarget(t))return;let i={...this.updateStatuses};for(let e of r.updates)i[`${e.scope}\0${e.package}`]=e;this.updateStatuses=i}catch(e){this.isCurrentTarget(t)&&(this.updateError=fM(e))}finally{this.isCurrentTarget(t)&&(this.checkingUpdateKeys=uM(this.checkingUpdateKeys,n),e===void 0&&(this.checkingAll=!1))}}}async updateInstalledSkill(e){let t=this.target(),n=e.install,r=rM(e);if(!(t===void 0||n===void 0||r===void 0||this.updatingKey!==void 0)){this.updatingKey=r,this.updateError=``;try{let e=await this.skillsApi.update({cwd:t.cwd,package:n.package,scope:n.scope},t.machineId);if(!this.isCurrentTarget(t)||(await this.loadSkills(),!this.isCurrentTarget(t)))return;let i=e.skill?.install?.versionHash;this.updateStatuses={...this.updateStatuses,[r]:{package:n.package,scope:n.scope,state:`up-to-date`,...i===void 0?{}:{currentVersion:i,latestVersion:i}}}}catch(e){this.isCurrentTarget(t)&&(this.updateError=fM(e))}finally{this.isCurrentTarget(t)&&(this.updatingKey=void 0)}}}selectSkill(e){this.selectedFilePath=e.filePath,this.addMode=!1,this.saveError=``,this.updateError=``}openAddMode(){this.addMode=!0,this.updateComplete.then(()=>{this.searchInput?.focus()})}selectedSkill(){return this.skills.find(e=>e.filePath===this.selectedFilePath)}skillGroups(){return[{label:`project / skills.sh`,matches:e=>Qj(e)===`project`&&e.install?.skillsShUrl!==void 0},{label:`project`,matches:e=>Qj(e)===`project`&&e.install?.skillsShUrl===void 0},{label:`global / skills.sh`,matches:e=>Qj(e)===`global`&&e.install?.skillsShUrl!==void 0},{label:`global`,matches:e=>Qj(e)===`global`&&e.install?.skillsShUrl===void 0},{label:`path`,matches:e=>Qj(e)===`path`}].flatMap(e=>{let t=this.skills.filter(e.matches);return t.length===0?[]:[{label:e.label,skills:t}]})}isInstalled(e,t){return this.skills.some(n=>n.install?.scope===t&&n.install.package===e)||this.newlyInstalledKeys.has(aM(t,e))}target(){return this.cwd===``?void 0:{cwd:this.cwd,machineId:this.machineId()}}isCurrentTarget(e){return e.cwd===this.cwd&&e.machineId===this.machineId()}machineId(){return Xj(this.machine)}machineLabel(){let e=this.machine?.name;return e===void 0||e===``?`local machine`:e}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}close(){this.onClose?.()}resetForTargetChange(){this.loadRequestSequence+=1,this.skills=[],this.loading=!0,this.loadError=``,this.selectedFilePath=void 0,this.togglingPaths=new Set,this.saveError=``,this.addMode=!1,this.searchQuery=``,this.searchResults=[],this.searching=!1,this.searchError=``,this.installingPackage=void 0,this.installError=``,this.newlyInstalledKeys=new Set,this.installScope=`global`,this.updateStatuses={},this.checkingUpdateKeys=new Set,this.checkingAll=!1,this.updatingKey=void 0,this.updateError=``}static{this.styles=h`
|
|
4333
4333
|
:host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
|
|
4334
4334
|
.backdrop { position: absolute; inset: 0; display: grid; place-items: center; box-sizing: border-box; padding: max(16px, env(safe-area-inset-top)) max(16px, env(safe-area-inset-right)) max(16px, env(safe-area-inset-bottom)) max(16px, env(safe-area-inset-left)); background: var(--pi-overlay); }
|
|
4335
4335
|
.dialog { width: min(860px, 100%); height: min(78dvh, 760px); max-height: 100%; display: flex; flex-direction: column; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); }
|
|
@@ -4430,16 +4430,16 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4430
4430
|
.scope-row { align-items: flex-start; flex-direction: column; gap: 6px; }
|
|
4431
4431
|
.search-result { align-items: flex-start; }
|
|
4432
4432
|
}
|
|
4433
|
-
`}};H([x({attribute:!1})],q.prototype,`machine`,void 0),H([x({type:String})],q.prototype,`cwd`,void 0),H([x({attribute:!1})],q.prototype,`skillsApi`,void 0),H([x({attribute:!1})],q.prototype,`onClose`,void 0),H([S()],q.prototype,`skills`,void 0),H([S()],q.prototype,`loading`,void 0),H([S()],q.prototype,`loadError`,void 0),H([S()],q.prototype,`selectedFilePath`,void 0),H([S()],q.prototype,`togglingPaths`,void 0),H([S()],q.prototype,`saveError`,void 0),H([S()],q.prototype,`addMode`,void 0),H([S()],q.prototype,`searchQuery`,void 0),H([S()],q.prototype,`searchResults`,void 0),H([S()],q.prototype,`searching`,void 0),H([S()],q.prototype,`searchError`,void 0),H([S()],q.prototype,`installingPackage`,void 0),H([S()],q.prototype,`installError`,void 0),H([S()],q.prototype,`newlyInstalledKeys`,void 0),H([S()],q.prototype,`installScope`,void 0),H([S()],q.prototype,`updateStatuses`,void 0),H([S()],q.prototype,`checkingUpdateKeys`,void 0),H([S()],q.prototype,`checkingAll`,void 0),H([S()],q.prototype,`updatingKey`,void 0),H([S()],q.prototype,`updateError`,void 0),H([C(`#skill-search`)],q.prototype,`searchInput`,void 0),q=H([b(`skills-config-dialog`)],q);function
|
|
4433
|
+
`}};H([x({attribute:!1})],q.prototype,`machine`,void 0),H([x({type:String})],q.prototype,`cwd`,void 0),H([x({attribute:!1})],q.prototype,`skillsApi`,void 0),H([x({attribute:!1})],q.prototype,`onClose`,void 0),H([S()],q.prototype,`skills`,void 0),H([S()],q.prototype,`loading`,void 0),H([S()],q.prototype,`loadError`,void 0),H([S()],q.prototype,`selectedFilePath`,void 0),H([S()],q.prototype,`togglingPaths`,void 0),H([S()],q.prototype,`saveError`,void 0),H([S()],q.prototype,`addMode`,void 0),H([S()],q.prototype,`searchQuery`,void 0),H([S()],q.prototype,`searchResults`,void 0),H([S()],q.prototype,`searching`,void 0),H([S()],q.prototype,`searchError`,void 0),H([S()],q.prototype,`installingPackage`,void 0),H([S()],q.prototype,`installError`,void 0),H([S()],q.prototype,`newlyInstalledKeys`,void 0),H([S()],q.prototype,`installScope`,void 0),H([S()],q.prototype,`updateStatuses`,void 0),H([S()],q.prototype,`checkingUpdateKeys`,void 0),H([S()],q.prototype,`checkingAll`,void 0),H([S()],q.prototype,`updatingKey`,void 0),H([S()],q.prototype,`updateError`,void 0),H([C(`#skill-search`)],q.prototype,`searchInput`,void 0),q=H([b(`skills-config-dialog`)],q);function Xj(e){if(!pM(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function Zj(e,t){return e!==void 0&&t.some(t=>t.filePath===e)?e:t[0]?.filePath}function Qj(e){let t=e.sourceInfo.source,n=e.sourceInfo.scope;return n===`user`||t===`user`?`global`:n===`project`||t===`project`?`project`:`path`}function $j(e,t){return Qj(e)===`project`&&e.filePath.startsWith(t)?`./${e.filePath.slice(t.length).replace(/^[/\\]/u,``)}`:eM(e.filePath)}function eM(e){return e.replace(/^\/(?:Users|home)\/[^/]+/u,`~`)}function tM(e){return e.replace(/^https?:\/\//u,``)}function nM(e){return e===void 0||e===``?`unknown`:e.slice(0,8)}function rM(e){return e.install===void 0?void 0:`${e.install.scope}\0${e.install.package}`}function iM(e,t){let n=rM(e);return n===void 0?void 0:t[n]}function aM(e,t){return`${e}\0${t}`}function oM(e){let t=e.lastIndexOf(`@`);return t<0?{repository:e,skill:void 0}:{repository:e.slice(0,t),skill:e.slice(t+1)}}function sM(e,t){return new Set([...e,t])}function cM(e,t){return new Set([...e,...t])}function lM(e,t){let n=new Set(e);return n.delete(t),n}function uM(e,t){let n=new Set(e);for(let e of t)n.delete(e);return n}function dM(e){let t=e.target;return t instanceof HTMLInputElement?t.value:``}function fM(e){return e instanceof Error?e.message:String(e)}function pM(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mM(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function hM(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="m6 6 12 12M18 6 6 18"></path></svg>`}var gM=class extends y{constructor(...e){super(...e),this.cwd=``,this.pluginsApi=rc,this.sessionsApi=cc,this.loading=!0,this.loadError=``,this.addMode=!1,this.installSource=``,this.installScope=`global`,this.actionError=``,this.actionMessage=``,this.loadRequestSequence=0}connectedCallback(){super.connectedCallback(),this.loadPlugins()}updated(e){let t=e.has(`machine`)&&wM(e.get(`machine`))!==this.machineId(),n=e.has(`cwd`)&&e.get(`cwd`)!==this.cwd;!t&&!n||(this.resetForTargetChange(),this.isConnected&&this.loadPlugins())}render(){let e=this.selectedPackage();return g`
|
|
4434
4434
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
4435
4435
|
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="plugins-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
4436
4436
|
<header>
|
|
4437
4437
|
<div class="title-block">
|
|
4438
4438
|
<h1 id="plugins-dialog-title">Plugins</h1>
|
|
4439
|
-
<span class="target"><code>${
|
|
4439
|
+
<span class="target"><code>${TM(this.cwd)}</code> on ${this.machineLabel()}</span>
|
|
4440
4440
|
</div>
|
|
4441
4441
|
<button class="icon-button" type="button" title="Close Plugins configuration" aria-label="Close Plugins configuration" @click=${()=>{this.close()}}>
|
|
4442
|
-
${
|
|
4442
|
+
${jM()}
|
|
4443
4443
|
</button>
|
|
4444
4444
|
</header>
|
|
4445
4445
|
|
|
@@ -4465,20 +4465,20 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4465
4465
|
</div>
|
|
4466
4466
|
<div class="package-list-actions">
|
|
4467
4467
|
<button class="add-plugin" type="button" aria-pressed=${String(this.addMode)} @click=${()=>{this.openAddMode()}}>
|
|
4468
|
-
${
|
|
4468
|
+
${AM()} Add plugin
|
|
4469
4469
|
</button>
|
|
4470
4470
|
</div>
|
|
4471
4471
|
</aside>
|
|
4472
|
-
`}renderPackageListItem(e){let t=
|
|
4472
|
+
`}renderPackageListItem(e){let t=_M(e),n=!this.addMode&&t===this.selectedKey;return g`
|
|
4473
4473
|
<button class="package-row ${n?`selected`:``}" type="button" aria-pressed=${String(n)} @click=${()=>{this.selectPackage(e)}}>
|
|
4474
|
-
<span class="package-indicator" style=${`background:${
|
|
4474
|
+
<span class="package-indicator" style=${`background:${SM(e.status)}`} aria-hidden="true"></span>
|
|
4475
4475
|
<span class="package-copy">
|
|
4476
4476
|
<strong>${e.source}</strong>
|
|
4477
|
-
<small>${
|
|
4478
|
-
${e.version===void 0&&e.configuredVersion===void 0?null:g`<small>${
|
|
4477
|
+
<small>${bM(e)}</small>
|
|
4478
|
+
${e.version===void 0&&e.configuredVersion===void 0?null:g`<small>${xM(e)}</small>`}
|
|
4479
4479
|
</span>
|
|
4480
4480
|
</button>
|
|
4481
|
-
`}renderPackageDetail(e){let t=
|
|
4481
|
+
`}renderPackageDetail(e){let t=_M(e),n=this.busyKey?.endsWith(t)??!1,r=this.busyKey===`reload`,i=!e.disabled;return g`
|
|
4482
4482
|
<div class="detail-content">
|
|
4483
4483
|
<div class="detail-heading">
|
|
4484
4484
|
<div class="package-title-row">
|
|
@@ -4510,12 +4510,12 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4510
4510
|
</div>
|
|
4511
4511
|
|
|
4512
4512
|
<dl class="metadata-grid">
|
|
4513
|
-
<dt>Status</dt><dd style=${`color:${
|
|
4514
|
-
<dt>Version</dt><dd><code>${
|
|
4513
|
+
<dt>Status</dt><dd style=${`color:${SM(e.status)}`}>${e.status}</dd>
|
|
4514
|
+
<dt>Version</dt><dd><code>${xM(e)}</code></dd>
|
|
4515
4515
|
<dt>Package</dt><dd><code>${e.packageName??`Unknown`}</code></dd>
|
|
4516
|
-
<dt>Resources</dt><dd>${
|
|
4517
|
-
<dt>Installed path</dt><dd class=${e.installedPath===void 0?`missing`:``}><code>${e.installedPath===void 0?`Not found`:
|
|
4518
|
-
<dt>Workspace</dt><dd><code>${
|
|
4516
|
+
<dt>Resources</dt><dd>${bM(e)}</dd>
|
|
4517
|
+
<dt>Installed path</dt><dd class=${e.installedPath===void 0?`missing`:``}><code>${e.installedPath===void 0?`Not found`:TM(e.installedPath)}</code></dd>
|
|
4518
|
+
<dt>Workspace</dt><dd><code>${TM(this.cwd)}</code></dd>
|
|
4519
4519
|
</dl>
|
|
4520
4520
|
|
|
4521
4521
|
<section class="resource-section">
|
|
@@ -4544,7 +4544,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4544
4544
|
<div class="detail-content add-panel">
|
|
4545
4545
|
<div class="add-heading">
|
|
4546
4546
|
<h2>Add Plugin</h2>
|
|
4547
|
-
<code>${this.installScope===`project`?`${
|
|
4547
|
+
<code>${this.installScope===`project`?`${TM(this.cwd)}/.pi/agent/{npm,git}`:`~/.pi/agent/{npm,git}`}</code>
|
|
4548
4548
|
</div>
|
|
4549
4549
|
|
|
4550
4550
|
<div class="field-stack">
|
|
@@ -4553,7 +4553,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4553
4553
|
id="plugin-source"
|
|
4554
4554
|
.value=${this.installSource}
|
|
4555
4555
|
placeholder="npm:@scope/package"
|
|
4556
|
-
@input=${e=>{this.installSource=
|
|
4556
|
+
@input=${e=>{this.installSource=DM(e)}}
|
|
4557
4557
|
@keydown=${t=>{t.key!==`Enter`||this.installSource.trim()===``||e||(t.preventDefault(),this.installPlugin())}}
|
|
4558
4558
|
>
|
|
4559
4559
|
</div>
|
|
@@ -4580,7 +4580,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4580
4580
|
`}renderFooter(){let e=this.data,t=e?.diagnostics??[],n=this.busyKey!==void 0;return g`
|
|
4581
4581
|
<footer>
|
|
4582
4582
|
<div class="footer-summary">
|
|
4583
|
-
${t.length>0?g`<span class=${t.some(e=>e.type===`error`)?`error-message`:`warning-message`} title=${t.map(
|
|
4583
|
+
${t.length>0?g`<span class=${t.some(e=>e.type===`error`)?`error-message`:`warning-message`} title=${t.map(EM).join(`
|
|
4584
4584
|
`)}>
|
|
4585
4585
|
${String(t.length)} diagnostic${t.length===1?``:`s`}
|
|
4586
4586
|
</span>`:e===void 0?null:g`<span>${String(e.totals.extensions)} ext · ${String(e.totals.skills)} skills · ${String(e.totals.prompts)} prompts · ${String(e.totals.themes)} themes</span>`}
|
|
@@ -4588,7 +4588,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4588
4588
|
<button type="button" class="secondary" ?disabled=${this.loading||n} @click=${()=>{this.loadPlugins()}}>Refresh</button>
|
|
4589
4589
|
<button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
|
|
4590
4590
|
</footer>
|
|
4591
|
-
`}async loadPlugins(){let e=this.target();if(e===void 0){this.loading=!1,this.loadError=`A selected workspace is required to manage plugins.`;return}let t=++this.loadRequestSequence;this.loading=!0,this.loadError=``;try{let n=await this.pluginsApi.list(e.cwd,e.machineId);if(!this.isCurrentTarget(e)||t!==this.loadRequestSequence)return;this.data=n,this.addMode=n.packages.length===0||this.addMode,this.selectedKey=
|
|
4591
|
+
`}async loadPlugins(){let e=this.target();if(e===void 0){this.loading=!1,this.loadError=`A selected workspace is required to manage plugins.`;return}let t=++this.loadRequestSequence;this.loading=!0,this.loadError=``;try{let n=await this.pluginsApi.list(e.cwd,e.machineId);if(!this.isCurrentTarget(e)||t!==this.loadRequestSequence)return;this.data=n,this.addMode=n.packages.length===0||this.addMode,this.selectedKey=vM(this.selectedKey,n.packages)}catch(n){this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loadError=`Failed to load plugins: ${OM(n)}`)}finally{this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loading=!1)}}async runAction(e,t){let n=this.target();if(n===void 0||this.busyKey!==void 0)return;let r=_M(t);this.busyKey=`${e}:${r}`,this.actionError=``,this.actionMessage=``;try{let r=await this.pluginsApi.mutate({action:e,source:t.source,scope:t.scope,cwd:n.cwd},n.machineId);if(!this.isCurrentTarget(n))return;this.data=r,e===`remove`?(this.selectedKey=vM(void 0,r.packages),r.packages.length===0&&(this.addMode=!0),this.actionMessage=`Package removed.`):this.actionMessage=CM(e)}catch(e){this.isCurrentTarget(n)&&(this.actionError=OM(e))}finally{this.isCurrentTarget(n)&&(this.busyKey=void 0)}}async installPlugin(){let e=this.target(),t=this.installSource.trim();if(e===void 0||t===``||this.busyKey!==void 0)return;let n=this.installScope,r=`${n}\0${t}`;this.busyKey=`install:${r}`,this.actionError=``,this.actionMessage=``;try{let i=await this.pluginsApi.mutate({action:`install`,source:t,scope:n,cwd:e.cwd},e.machineId);if(!this.isCurrentTarget(e))return;this.data=i;let a=yM(i.packages,t,n);this.selectedKey=a===void 0?r:_M(a),this.addMode=!1,this.installSource=``,this.actionMessage=`Package installed.`}catch(t){this.isCurrentTarget(e)&&(this.actionError=OM(t))}finally{this.isCurrentTarget(e)&&(this.busyKey=void 0)}}async reloadSession(){let e=this.target(),t=this.session;if(!(e===void 0||t===void 0||this.busyKey!==void 0)){this.busyKey=`reload`,this.actionError=``,this.actionMessage=``;try{let n=await this.sessionsApi.runCommand(t,`/reload`,e.machineId);if(n.type!==`done`)throw Error(n.type===`unsupported`?n.message:`Session runtime reload did not complete.`);if(!this.isCurrentTarget(e)||(await this.onReloaded?.(),await this.loadPlugins(),!this.isCurrentTarget(e)))return;this.actionMessage=`Session reloaded.`}catch(t){this.isCurrentTarget(e)&&(this.actionError=OM(t))}finally{this.isCurrentTarget(e)&&(this.busyKey=void 0)}}}packageGroups(){let e=this.data?.packages??[];return[`project`,`global`].flatMap(t=>{let n=e.filter(e=>e.scope===t);return n.length===0?[]:[{scope:t,packages:n}]})}selectedPackage(){return(this.data?.packages??[]).find(e=>_M(e)===this.selectedKey)}selectPackage(e){this.selectedKey=_M(e),this.addMode=!1,this.actionError=``,this.actionMessage=``}openAddMode(){this.addMode=!0,this.actionError=``,this.actionMessage=``,this.updateComplete.then(()=>{this.pluginSourceInput?.focus()})}target(){return this.cwd===``?void 0:{cwd:this.cwd,machineId:this.machineId()}}isCurrentTarget(e){return e.cwd===this.cwd&&e.machineId===this.machineId()}machineId(){return wM(this.machine)}machineLabel(){let e=this.machine?.name;return e===void 0||e===``?`local machine`:e}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}close(){this.onClose?.()}resetForTargetChange(){this.loadRequestSequence+=1,this.data=void 0,this.loading=!0,this.loadError=``,this.selectedKey=void 0,this.addMode=!1,this.installSource=``,this.installScope=`global`,this.busyKey=void 0,this.actionError=``,this.actionMessage=``}static{this.styles=h`
|
|
4592
4592
|
:host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
|
|
4593
4593
|
.backdrop { position: absolute; inset: 0; display: grid; box-sizing: border-box; place-items: center; padding: max(16px, env(safe-area-inset-top)) max(16px, env(safe-area-inset-right)) max(16px, env(safe-area-inset-bottom)) max(16px, env(safe-area-inset-left)); background: var(--pi-overlay); }
|
|
4594
4594
|
.dialog { display: flex; width: min(860px, 100%); height: min(78dvh, 760px); max-height: 100%; flex-direction: column; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); }
|
|
@@ -4690,7 +4690,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4690
4690
|
.package-actions { width: 100%; }
|
|
4691
4691
|
.metadata-grid { grid-template-columns: 96px minmax(0, 1fr); }
|
|
4692
4692
|
}
|
|
4693
|
-
`}};H([x({attribute:!1})],
|
|
4693
|
+
`}};H([x({attribute:!1})],gM.prototype,`machine`,void 0),H([x({type:String})],gM.prototype,`cwd`,void 0),H([x({attribute:!1})],gM.prototype,`session`,void 0),H([x({attribute:!1})],gM.prototype,`pluginsApi`,void 0),H([x({attribute:!1})],gM.prototype,`sessionsApi`,void 0),H([x({attribute:!1})],gM.prototype,`onClose`,void 0),H([x({attribute:!1})],gM.prototype,`onReloaded`,void 0),H([S()],gM.prototype,`data`,void 0),H([S()],gM.prototype,`loading`,void 0),H([S()],gM.prototype,`loadError`,void 0),H([S()],gM.prototype,`selectedKey`,void 0),H([S()],gM.prototype,`addMode`,void 0),H([S()],gM.prototype,`installSource`,void 0),H([S()],gM.prototype,`installScope`,void 0),H([S()],gM.prototype,`busyKey`,void 0),H([S()],gM.prototype,`actionError`,void 0),H([S()],gM.prototype,`actionMessage`,void 0),H([C(`#plugin-source`)],gM.prototype,`pluginSourceInput`,void 0),gM=H([b(`plugins-config-dialog`)],gM);function _M(e){return`${e.scope}\0${e.source}`}function vM(e,t){return e!==void 0&&t.some(t=>_M(t)===e)?e:t[0]===void 0?void 0:_M(t[0])}function yM(e,t,n){let r=t.trim(),i=r.startsWith(`npm:`)?r.slice(4):r;return e.find(e=>e.scope===n&&e.source===r)??e.find(e=>e.scope===n&&e.source===`npm:${i}`)??e.find(e=>e.scope===n&&e.installedPath===r)??e.find(e=>e.scope===n&&e.source.endsWith(r))}function bM(e){if(e.disabled)return`Disabled`;let t=[e.counts.extensions===0?``:`${String(e.counts.extensions)} ext`,e.counts.skills===0?``:`${String(e.counts.skills)} skills`,e.counts.prompts===0?``:`${String(e.counts.prompts)} prompts`,e.counts.themes===0?``:`${String(e.counts.themes)} themes`].filter(e=>e!==``);return t.length===0?`No resources`:t.join(` · `)}function xM(e){let t=[e.version===void 0?void 0:`installed ${e.version}`,e.configuredVersion===void 0?void 0:`configured ${e.configuredVersion}`].filter(e=>e!==void 0);return t.length===0?`Unknown`:t.join(` · `)}function SM(e){return e===`loaded`?`var(--pi-accent)`:e===`installed`?`#d97706`:e===`disabled`?`var(--pi-muted)`:`var(--pi-danger)`}function CM(e){switch(e){case`install`:return`Package installed.`;case`update`:return`Package updated.`;case`disable`:return`Package disabled.`;case`enable`:return`Package enabled.`}}function wM(e){if(!kM(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function TM(e){return e.replace(/^\/(?:Users|home)\/[^/]+/u,`~`)}function EM(e){return`${e.type}: ${e.source===void 0?``:`${e.source}: `}${e.message}`}function DM(e){return e.target instanceof HTMLInputElement?e.target.value:``}function OM(e){return e instanceof Error?e.message:String(e)}function kM(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function AM(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function jM(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="m6 6 12 12M18 6 6 18"></path></svg>`}var MM=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.path=``,this.createMissing=!0,this.suggestions=[],this.selected=0,this.loading=!1,this.requestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}firstUpdated(){this.pathInput?.focus()}async loadSuggestions(){let e=++this.requestId;this.loading=!0;try{let t=await gc.projectDirectories(this.path,this.machineId);if(e!==this.requestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.requestId&&(this.suggestions=[])}finally{e===this.requestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.loadSuggestions()}pick(e){this.setPath(e.path)}submit(){this.path.trim()!==``&&this.onSubmit?.(this.path,this.createMissing)}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}onKeyDown(e){if(e.key===`Escape`)e.preventDefault(),this.onCancel?.();else if(e.key===`Enter`)e.preventDefault(),this.submit();else if(e.key===`ArrowDown`)e.preventDefault(),this.selected=Math.min(this.selected+1,Math.max(0,this.suggestions.length-1));else if(e.key===`ArrowUp`)e.preventDefault(),this.selected=Math.max(0,this.selected-1);else if(e.key===`Tab`){let t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return g`
|
|
4694
4694
|
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
4695
4695
|
<section @click=${e=>{e.stopPropagation()}}>
|
|
4696
4696
|
<header>
|
|
@@ -4740,7 +4740,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4740
4740
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
4741
4741
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
4742
4742
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
4743
|
-
`}};H([x({attribute:!1})],
|
|
4743
|
+
`}};H([x({attribute:!1})],MM.prototype,`onSubmit`,void 0),H([x({attribute:!1})],MM.prototype,`onCancel`,void 0),H([x()],MM.prototype,`machineId`,void 0),H([S()],MM.prototype,`path`,void 0),H([S()],MM.prototype,`createMissing`,void 0),H([S()],MM.prototype,`suggestions`,void 0),H([S()],MM.prototype,`selected`,void 0),H([S()],MM.prototype,`loading`,void 0),H([C(`input`)],MM.prototype,`pathInput`,void 0),MM=H([b(`project-dialog`)],MM);var NM=class extends y{constructor(...e){super(...e),this.error=``,this.url=``,this.name=``,this.token=``,this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=``}firstUpdated(){this.urlInput?.focus()}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;let t=e.target.value,n=PM(t);(!this.nameEdited||this.name.trim()===``||this.name===this.previousSuggestedName)&&(this.name=n),this.previousSuggestedName=n,this.url=t}handleNameInput(e){e.target instanceof HTMLInputElement&&(this.nameEdited=!0,this.name=e.target.value)}handleTokenInput(e){e.target instanceof HTMLInputElement&&(this.token=e.target.value)}handleKeyDown(e){if(e.key===`Escape`){e.preventDefault(),this.onCancel?.();return}e.key===`Enter`&&e.target instanceof HTMLInputElement&&e.target.name===`baseUrl`&&FM(this.url)===void 0&&(e.preventDefault(),this.updateComplete.then(()=>{this.nameInput?.focus(),this.nameInput?.select()}))}handleSubmit(e){e.preventDefault(),this.submit()}async submit(){let e=this.validInput();if(!(e===void 0||this.submitting)){this.submitting=!0;try{await this.onSubmit?.(e)}finally{this.isConnected&&(this.submitting=!1)}}}validInput(){let e=this.url.trim(),t=this.name.trim();if(e===``||t===``||FM(e)!==void 0)return;let n=this.token.trim();return{name:t,baseUrl:e,...n===``?{}:{token:n}}}render(){let e=this.url.trim()!==``,t=e?FM(this.url):void 0,n=this.validInput()!==void 0&&!this.submitting;return g`
|
|
4744
4744
|
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
4745
4745
|
<section @click=${e=>{e.stopPropagation()}}>
|
|
4746
4746
|
<form @submit=${e=>{this.handleSubmit(e)}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
@@ -4795,7 +4795,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4795
4795
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
4796
4796
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
4797
4797
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
4798
|
-
`}};H([x({attribute:!1})],
|
|
4798
|
+
`}};H([x({attribute:!1})],NM.prototype,`onSubmit`,void 0),H([x({attribute:!1})],NM.prototype,`onCancel`,void 0),H([x()],NM.prototype,`error`,void 0),H([S()],NM.prototype,`url`,void 0),H([S()],NM.prototype,`name`,void 0),H([S()],NM.prototype,`token`,void 0),H([S()],NM.prototype,`submitting`,void 0),H([C(`input[name='baseUrl']`)],NM.prototype,`urlInput`,void 0),H([C(`input[name='name']`)],NM.prototype,`nameInput`,void 0),NM=H([b(`machine-dialog`)],NM);function PM(e){let t=e.trim();if(t===``)return``;let n=IM(t)??IM(`http://${t.replace(/^\/+/u,``)}`);return n!==void 0&&n.hostname!==``?n.hostname.replace(/^\[(.*)\]$/u,`$1`):LM(t)}function FM(e){let t=e.trim();if(t===``)return`Remote PI WEBUI URL is required.`;let n;try{n=new URL(t)}catch{return`Enter a valid URL including http:// or https://.`}if(n.protocol!==`http:`&&n.protocol!==`https:`)return`Use an http:// or https:// URL.`;if(n.username!==``||n.password!==``)return`Do not include credentials in the machine URL.`;if(n.search!==``||n.hash!==``)return`Do not include a query string or fragment.`}function IM(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:void 0}catch{return}}function LM(e){let t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,``),n=t.slice(t.lastIndexOf(`@`)+1).split(/[/?#]/u)[0]??``;return n.startsWith(`[`)&&n.includes(`]`)?n.slice(1,n.indexOf(`]`)):n.replace(/:\d+$/u,``)}var RM={availability:`error`,error:`error`,success:`success`,security:`warning`,warning:`warning`,info:`info`};function zM(e){return e.tone??RM[e.type]}var BM=class extends y{constructor(...e){super(...e),this.heading=``,this.description=``,this.actionLabel=``,this.actionTitle=``,this.actionDisabled=!1,this.notices=[]}render(){return g`
|
|
4799
4799
|
<section class="panel" aria-label=${this.heading||`Settings panel`}>
|
|
4800
4800
|
<header class="section-heading">
|
|
4801
4801
|
<div class="heading-copy">
|
|
@@ -4818,7 +4818,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4818
4818
|
<div class="notice-stack" aria-label="Settings notices">
|
|
4819
4819
|
${this.notices.map(e=>this.renderNotice(e))}
|
|
4820
4820
|
</div>
|
|
4821
|
-
`}renderNotice(e){let t=
|
|
4821
|
+
`}renderNotice(e){let t=zM(e),n=e.role??VM(t),r=e.title;return g`
|
|
4822
4822
|
<article class=${`notice ${t}`} role=${n}>
|
|
4823
4823
|
${r===void 0||r===``?v:g`<strong class="notice-title">${r}</strong>`}
|
|
4824
4824
|
<div class="notice-content">${e.content}</div>
|
|
@@ -4851,13 +4851,13 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4851
4851
|
.section-heading { display: grid; gap: 12px; }
|
|
4852
4852
|
.heading-actions { justify-self: start; }
|
|
4853
4853
|
}
|
|
4854
|
-
`}};H([x()],
|
|
4855
|
-
`):``}}function
|
|
4856
|
-
`)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function
|
|
4857
|
-
`).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!
|
|
4854
|
+
`}};H([x()],BM.prototype,`heading`,void 0),H([x({attribute:!1})],BM.prototype,`description`,void 0),H([x()],BM.prototype,`actionLabel`,void 0),H([x()],BM.prototype,`actionTitle`,void 0),H([x({type:Boolean})],BM.prototype,`actionDisabled`,void 0),H([x({attribute:!1})],BM.prototype,`notices`,void 0),H([x({attribute:!1})],BM.prototype,`onAction`,void 0),BM=H([b(`settings-panel-frame`)],BM);function VM(e){switch(e){case`error`:return`alert`;case`success`:return`status`;case`warning`:case`info`:return`note`}}function HM(){return{host:``,port:``,allowedHostsMode:`list`,allowedHostsText:``}}function UM(){return{allowedPathsText:``,uploadDefaultFolder:``}}function WM(){return{command:``,dir:``}}function GM(){return{voice:``,rate:``}}function KM(e){return{host:e.host??``,port:e.port===void 0?``:String(e.port),allowedHostsMode:e.allowedHosts===!0?`all`:`list`,allowedHostsText:Array.isArray(e.allowedHosts)?e.allowedHosts.join(`
|
|
4855
|
+
`):``}}function qM(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
|
|
4856
|
+
`)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function JM(e){return{command:e.agent?.command??``,dir:e.agent?.dir??``}}function YM(e){return{voice:e.tts?.voice??``,rate:String(e.tts?.rate??0)}}function XM(e){return{provider:e.settings.provider,language:e.settings.language??``,baseUrl:e.settings.cloud.baseUrl,model:e.settings.cloud.model}}function ZM(e,t,n){return{expectedRevision:t,settings:{provider:e.provider,...e.language===``?{}:{language:e.language},cloud:{baseUrl:e.baseUrl,model:e.model}},credential:n}}function QM(e){let t=e.command.trim(),n=e.dir.trim();return{agent:{...t===``?{}:{command:t},...n===``?{}:{dir:n}}}}function $M(e,t){let n=QM(e).agent??{},r=t.agent??{};return n.command===r.command&&n.dir===r.dir}function eN(e,t={}){let n=e.voice.trim(),r=oN(e.rate);return{...t,tts:{...n===``?{}:{voice:n},...r===0?{}:{rate:r}}}}function tN(e,t){try{let n=eN(e).tts??{},r=t.tts??{};return n.voice===r.voice&&(n.rate??0)===(r.rate??0)}catch{return!1}}function nN(e,t={}){let n=iN(t),r=e.host.trim(),i=e.port.trim();if(r!==``&&(n.host=r),i!==``){let e=Number(i);if(!Number.isInteger(e)||e<1||e>65535)throw Error(`Port must be an integer from 1 to 65535.`);n.port=e}return n.allowedHosts=e.allowedHostsMode===`all`||aN(e.allowedHostsText),n}function rN(e){let t=sN(e.allowedPathsText),n=cN(e.uploadDefaultFolder);return{pathAccess:{allowedPaths:t},uploads:n===``?{}:{defaultFolder:n}}}function iN(e){return{...e.shortcuts===void 0?{}:{shortcuts:e.shortcuts},...e.plugins===void 0?{}:{plugins:e.plugins},...e.pathAccess===void 0?{}:{pathAccess:e.pathAccess},...e.uploads===void 0?{}:{uploads:e.uploads},...e.maxUploadBytes===void 0?{}:{maxUploadBytes:e.maxUploadBytes},...e.spawnSessions===void 0?{}:{spawnSessions:e.spawnSessions},...e.subsessions===void 0?{}:{subsessions:e.subsessions},...e.agent===void 0?{}:{agent:e.agent},...e.tts===void 0?{}:{tts:e.tts}}}function aN(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e!==``)}function oN(e){let t=e.trim();if(t===``)return 0;let n=Number(t);if(!Number.isInteger(n)||n<-100||n>100)throw Error(`Speech rate must be an integer from -100 to 100.`);return n}function sN(e){let t=e.split(`
|
|
4857
|
+
`).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!lN(e));if(n!==void 0)throw Error(`Allowed external paths must be absolute paths or start with ~: ${n}`);return t}function cN(e){let t=e.trim();if(t===``)return``;if(uN(t))throw Error(`Upload default folder must be workspace-relative.`);let n=t.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(n.length===0)return``;if(n.some(e=>e===`..`))throw Error(`Upload default folder must not contain path traversal.`);return n.join(`/`)}function lN(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)||e.startsWith(`/`)||e.startsWith(`\\`)||/^[A-Za-z]:[\\/]/u.test(e)}function uN(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function dN(e){return g`Gateway server fields edit this local gateway. File access and upload defaults edit ${e}.`}var J=class extends y{constructor(...e){super(...e),this.loading=!1,this.machineLoading=!1,this.saving=!1,this.error=``,this.machineError=``,this.savedMessage=``,this.targetLabel=`selected machine`,this.showHostSpeechSettings=!1,this.hostSpeechStatusLoading=!1,this.speechInputAdoptionGeneration=0,this.speechInputCredentialClearGeneration=0,this.gatewayDraft=HM(),this.hostSpeechDraft=GM(),this.machineDraft=UM(),this.speechInputDraft=fN(),this.speechInputDraftDirty=!1,this.credentialEntryDirty=!1,this.speechInputStale=!1,this.speechInputLocalError=``,this.appliedSpeechInputAdoptionGeneration=0,this.appliedSpeechInputCredentialClearGeneration=0,this.gatewayLocalError=``,this.hostSpeechDraftDirty=!1,this.hostSpeechLocalError=``,this.machineLocalError=``}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.gatewayDraft=KM(this.configResponse.config),this.gatewayLocalError=``),e.has(`configResponse`)&&(this.configResponse===void 0?(this.hostSpeechDraft=GM(),this.hostSpeechDraftDirty=!1,this.hostSpeechLocalError=``):(!this.hostSpeechDraftDirty||tN(this.hostSpeechDraft,this.configResponse.config))&&(this.hostSpeechDraft=YM(this.configResponse.config),this.hostSpeechDraftDirty=!1,this.hostSpeechLocalError=``)),e.has(`machineConfigResponse`)&&this.machineConfigResponse!==void 0&&(this.machineDraft=qM(this.machineConfigResponse.config),this.machineLocalError=``),(e.has(`speechInputSettings`)||e.has(`speechInputAdoptionGeneration`)||e.has(`speechInputCredentialClearGeneration`))&&this.adoptSpeechInputProperties()}render(){return g`
|
|
4858
4858
|
<settings-panel-frame
|
|
4859
4859
|
heading="General configuration"
|
|
4860
|
-
.description=${
|
|
4860
|
+
.description=${dN(this.targetLabel)}
|
|
4861
4861
|
actionLabel="Reload"
|
|
4862
4862
|
.actionDisabled=${this.loading||this.machineLoading}
|
|
4863
4863
|
.notices=${this.panelNotices()}
|
|
@@ -4888,7 +4888,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4888
4888
|
<span>Host</span>
|
|
4889
4889
|
${this.renderOverrideBadge(`host`)}
|
|
4890
4890
|
</span>
|
|
4891
|
-
<input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:
|
|
4891
|
+
<input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:bN(e)})}}>
|
|
4892
4892
|
<small>Address the web server should bind to. Leave empty to use PI WEBUI's default.</small>
|
|
4893
4893
|
</label>
|
|
4894
4894
|
|
|
@@ -4897,7 +4897,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4897
4897
|
<span>Port</span>
|
|
4898
4898
|
${this.renderOverrideBadge(`port`)}
|
|
4899
4899
|
</span>
|
|
4900
|
-
<input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8808" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:
|
|
4900
|
+
<input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8808" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:bN(e)})}}>
|
|
4901
4901
|
<small>TCP port from 1 to 65535. Leave empty to use PI WEBUI's default.</small>
|
|
4902
4902
|
</label>
|
|
4903
4903
|
|
|
@@ -4906,11 +4906,11 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4906
4906
|
<span>Allowed hosts</span>
|
|
4907
4907
|
${this.renderOverrideBadge(`allowedHosts`)}
|
|
4908
4908
|
</span>
|
|
4909
|
-
<select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:
|
|
4909
|
+
<select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:xN(e)===`all`?`all`:`list`})}}>
|
|
4910
4910
|
<option value="list">Only listed hosts</option>
|
|
4911
4911
|
<option value="all">Allow every host</option>
|
|
4912
4912
|
</select>
|
|
4913
|
-
<textarea .value=${this.gatewayDraft.allowedHostsText} ?disabled=${this.gatewayDraft.allowedHostsMode===`all`} rows="4" placeholder="example.local 192.168.1.20" spellcheck="false" @input=${e=>{this.updateGatewayDraft({allowedHostsText:
|
|
4913
|
+
<textarea .value=${this.gatewayDraft.allowedHostsText} ?disabled=${this.gatewayDraft.allowedHostsMode===`all`} rows="4" placeholder="example.local 192.168.1.20" spellcheck="false" @input=${e=>{this.updateGatewayDraft({allowedHostsText:SN(e)})}}></textarea>
|
|
4914
4914
|
<small>Enter one host per line, or choose “Allow every host” to write <code>true</code>.</small>
|
|
4915
4915
|
</div>
|
|
4916
4916
|
|
|
@@ -4922,7 +4922,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4922
4922
|
</form>
|
|
4923
4923
|
`}
|
|
4924
4924
|
</section>
|
|
4925
|
-
`}renderSpeechInputSettings(){let e=this.speechInputSavedResponse??this.speechInputSettings,t=this.saving||this.speechInputStale||e===void 0,n=t||!
|
|
4925
|
+
`}renderSpeechInputSettings(){let e=this.speechInputSavedResponse??this.speechInputSettings,t=this.saving||this.speechInputStale||e===void 0,n=t||!pN(e);return g`
|
|
4926
4926
|
<section class="settings-card speech-input-card" aria-label="Speech input settings">
|
|
4927
4927
|
<div class="card-heading">
|
|
4928
4928
|
<h3>Speech input</h3>
|
|
@@ -4930,7 +4930,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4930
4930
|
<p class="speech-input-boundary">Browser recognition may be processed by the browser vendor's speech service. Cloud sends audio to the configured HTTPS endpoint through the gateway. Cloud audio and the resolved credential go only to that endpoint, with redirects disabled. Gateway access is administrative because PI WEBUI adds no authentication.</p>
|
|
4931
4931
|
</div>
|
|
4932
4932
|
${this.isSpeechInputSecureContext()?e===void 0?g`<div class="loading-card">${this.loading?`Loading speech input settings…`:`Speech input settings are unavailable. Reload before saving.`}</div>`:g`
|
|
4933
|
-
<div class="speech-input-status" role="status">${
|
|
4933
|
+
<div class="speech-input-status" role="status">${mN(e.credential)}</div>
|
|
4934
4934
|
${this.speechInputLocalError===``?null:g`<div class="message error-message" role="alert">${this.speechInputLocalError}</div>`}
|
|
4935
4935
|
<form class="config-form" @submit=${e=>{this.saveSpeechInputSettings(e)}}>
|
|
4936
4936
|
<label class="field">
|
|
@@ -4938,7 +4938,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4938
4938
|
<select
|
|
4939
4939
|
.value=${this.speechInputDraft.provider}
|
|
4940
4940
|
?disabled=${t}
|
|
4941
|
-
@change=${e=>{let t=
|
|
4941
|
+
@change=${e=>{let t=xN(e);this.updateSpeechInputDraft({provider:t===`browser`||t===`cloud`?t:`auto`})}}
|
|
4942
4942
|
>
|
|
4943
4943
|
<option value="auto">Auto</option>
|
|
4944
4944
|
<option value="browser">Browser</option>
|
|
@@ -4948,16 +4948,16 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4948
4948
|
</label>
|
|
4949
4949
|
<label class="field">
|
|
4950
4950
|
<span class="field-heading"><span>Language</span></span>
|
|
4951
|
-
<input .value=${this.speechInputDraft.language} ?disabled=${t} placeholder="Auto" autocomplete="off" spellcheck="false" @input=${e=>{this.updateSpeechInputDraft({language:
|
|
4951
|
+
<input .value=${this.speechInputDraft.language} ?disabled=${t} placeholder="Auto" autocomplete="off" spellcheck="false" @input=${e=>{this.updateSpeechInputDraft({language:bN(e)})}}>
|
|
4952
4952
|
<small>Leave empty for the provider default.</small>
|
|
4953
4953
|
</label>
|
|
4954
4954
|
<label class="field">
|
|
4955
4955
|
<span class="field-heading"><span>Cloud base URL</span></span>
|
|
4956
|
-
<input .value=${this.speechInputDraft.baseUrl} ?disabled=${t} type="url" autocomplete="off" spellcheck="false" @input=${e=>{this.updateSpeechInputDraft({baseUrl:
|
|
4956
|
+
<input .value=${this.speechInputDraft.baseUrl} ?disabled=${t} type="url" autocomplete="off" spellcheck="false" @input=${e=>{this.updateSpeechInputDraft({baseUrl:bN(e)})}}>
|
|
4957
4957
|
</label>
|
|
4958
4958
|
<label class="field">
|
|
4959
4959
|
<span class="field-heading"><span>Cloud model</span></span>
|
|
4960
|
-
<input .value=${this.speechInputDraft.model} ?disabled=${t} autocomplete="off" spellcheck="false" @input=${e=>{this.updateSpeechInputDraft({model:
|
|
4960
|
+
<input .value=${this.speechInputDraft.model} ?disabled=${t} autocomplete="off" spellcheck="false" @input=${e=>{this.updateSpeechInputDraft({model:bN(e)})}}>
|
|
4961
4961
|
</label>
|
|
4962
4962
|
<label class="field">
|
|
4963
4963
|
<span class="field-heading"><span>API key source</span></span>
|
|
@@ -4989,7 +4989,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4989
4989
|
<span class="field-heading">
|
|
4990
4990
|
<span>External filesystem roots</span>
|
|
4991
4991
|
</span>
|
|
4992
|
-
<textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs /opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:
|
|
4992
|
+
<textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs /opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:SN(e)})}}></textarea>
|
|
4993
4993
|
<small>Allowlist for absolute <code>@</code> completions and file explorer reads outside a workspace on ${this.targetLabel}. Enter one absolute path, Windows absolute path, or <code>~</code>-prefixed path per line. Leave empty to deny external paths by default.</small>
|
|
4994
4994
|
</label>
|
|
4995
4995
|
|
|
@@ -4997,7 +4997,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
4997
4997
|
<span class="field-heading">
|
|
4998
4998
|
<span>Default upload folder</span>
|
|
4999
4999
|
</span>
|
|
5000
|
-
<input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${xc} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:
|
|
5000
|
+
<input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${xc} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:bN(e)})}}>
|
|
5001
5001
|
<small>Workspace-relative folder for manual file uploads on ${this.targetLabel}. Leave empty to use PI WEBUI's default <code>${xc}</code>.</small>
|
|
5002
5002
|
</label>
|
|
5003
5003
|
|
|
@@ -5009,7 +5009,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5009
5009
|
</form>
|
|
5010
5010
|
`}
|
|
5011
5011
|
</section>
|
|
5012
|
-
`}renderHostSpeechSettings(){let e=this.hostSpeechStatus,t=e?.available===!0,n=this.configResponse===void 0,r=this.saving||this.hostSpeechStatusLoading||!t||this.loading||n,i=this.hostSpeechDraft.voice.trim(),a=
|
|
5012
|
+
`}renderHostSpeechSettings(){let e=this.hostSpeechStatus,t=e?.available===!0,n=this.configResponse===void 0,r=this.saving||this.hostSpeechStatusLoading||!t||this.loading||n,i=this.hostSpeechDraft.voice.trim(),a=_N(e?.voices??[],i,t),o=e?.voices.some(e=>e.name===i)===!0,s=t&&i!==``&&!o,c=e?.reason??(this.hostSpeechStatusLoading?`Checking OS speech availability.`:`Host speech is unavailable on this gateway host.`);return g`
|
|
5013
5013
|
<section class="settings-card" aria-label="Text to speech settings">
|
|
5014
5014
|
<div class="card-heading">
|
|
5015
5015
|
<h3>Text to speech</h3>
|
|
@@ -5023,7 +5023,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5023
5023
|
<select
|
|
5024
5024
|
.value=${i}
|
|
5025
5025
|
?disabled=${r}
|
|
5026
|
-
@change=${e=>{this.updateHostSpeechDraft({voice:
|
|
5026
|
+
@change=${e=>{this.updateHostSpeechDraft({voice:xN(e)})}}
|
|
5027
5027
|
>
|
|
5028
5028
|
<option value="">System default</option>
|
|
5029
5029
|
${a.map(e=>g`<option .value=${e.name}>${e.label}</option>`)}
|
|
@@ -5039,9 +5039,9 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5039
5039
|
min="-100"
|
|
5040
5040
|
max="100"
|
|
5041
5041
|
step="1"
|
|
5042
|
-
.value=${String(
|
|
5042
|
+
.value=${String(yN(this.hostSpeechDraft.rate))}
|
|
5043
5043
|
?disabled=${r}
|
|
5044
|
-
@input=${e=>{this.updateHostSpeechDraft({rate:
|
|
5044
|
+
@input=${e=>{this.updateHostSpeechDraft({rate:bN(e)})}}
|
|
5045
5045
|
>
|
|
5046
5046
|
<input
|
|
5047
5047
|
aria-label="Speech rate"
|
|
@@ -5052,7 +5052,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5052
5052
|
inputmode="numeric"
|
|
5053
5053
|
.value=${this.hostSpeechDraft.rate}
|
|
5054
5054
|
?disabled=${r}
|
|
5055
|
-
@input=${e=>{this.updateHostSpeechDraft({rate:
|
|
5055
|
+
@input=${e=>{this.updateHostSpeechDraft({rate:bN(e)})}}
|
|
5056
5056
|
>
|
|
5057
5057
|
</div>
|
|
5058
5058
|
<small>Set an integer from -100 to 100. Leave this at 0 for the system's normal rate.</small>
|
|
@@ -5062,24 +5062,24 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5062
5062
|
</footer>
|
|
5063
5063
|
</form>
|
|
5064
5064
|
</section>
|
|
5065
|
-
`}adoptSpeechInputProperties(){let e=this.speechInputSettings;if(e===void 0)return;if(this.speechInputAdoptionGeneration!==this.appliedSpeechInputAdoptionGeneration){this.appliedSpeechInputAdoptionGeneration=this.speechInputAdoptionGeneration,this.appliedSpeechInputCredentialClearGeneration=this.speechInputCredentialClearGeneration,this.adoptSpeechInputResponse(e,!0);return}if(this.speechInputCredentialClearGeneration!==this.appliedSpeechInputCredentialClearGeneration){this.appliedSpeechInputCredentialClearGeneration=this.speechInputCredentialClearGeneration,this.adoptSpeechInputCredentialClear(e);return}let t=this.speechInputSavedResponse;if(t===void 0||t.revision===e.revision){t===void 0?this.adoptSpeechInputResponse(e,!1):this.speechInputSavedResponse=e;return}if(this.speechInputDraftDirty||this.credentialEntryDirty){this.speechInputStale=!0,this.speechInputLocalError=`Speech input settings changed in another tab. Reload before saving.`;return}this.adoptSpeechInputResponse(e,!1)}adoptSpeechInputResponse(e,t){this.speechInputSavedResponse=e,this.speechInputDraft=
|
|
5065
|
+
`}adoptSpeechInputProperties(){let e=this.speechInputSettings;if(e===void 0)return;if(this.speechInputAdoptionGeneration!==this.appliedSpeechInputAdoptionGeneration){this.appliedSpeechInputAdoptionGeneration=this.speechInputAdoptionGeneration,this.appliedSpeechInputCredentialClearGeneration=this.speechInputCredentialClearGeneration,this.adoptSpeechInputResponse(e,!0);return}if(this.speechInputCredentialClearGeneration!==this.appliedSpeechInputCredentialClearGeneration){this.appliedSpeechInputCredentialClearGeneration=this.speechInputCredentialClearGeneration,this.adoptSpeechInputCredentialClear(e);return}let t=this.speechInputSavedResponse;if(t===void 0||t.revision===e.revision){t===void 0?this.adoptSpeechInputResponse(e,!1):this.speechInputSavedResponse=e;return}if(this.speechInputDraftDirty||this.credentialEntryDirty){this.speechInputStale=!0,this.speechInputLocalError=`Speech input settings changed in another tab. Reload before saving.`;return}this.adoptSpeechInputResponse(e,!1)}adoptSpeechInputResponse(e,t){this.speechInputSavedResponse=e,this.speechInputDraft=XM(e),this.speechInputDraftDirty=!1,this.credentialEntryDirty=!1,this.speechInputStale=!1,this.speechInputLocalError=``,t&&this.clearSpeechInputCredentialInput()}adoptSpeechInputCredentialClear(e){this.speechInputSavedResponse=e,this.speechInputDraftDirty||(this.speechInputDraft=XM(e)),this.credentialEntryDirty=!1,this.speechInputStale=!1,this.speechInputLocalError=``,this.clearSpeechInputCredentialInput()}async saveSpeechInputSettings(e){if(e.preventDefault(),!this.isSpeechInputSecureContext())return;let t=this.speechInputSavedResponse;if(t===void 0||this.speechInputStale||this.saving)return;this.speechInputLocalError=``;let n=this.speechInputApiKeyInput?.value??``,r=n===``?{action:`preserve`}:{action:`replace`,value:n};try{let e=await this.onSaveSpeechInput?.(ZM(this.speechInputDraft,t.revision,r));e!==void 0&&this.adoptSpeechInputResponse(e,!0)}catch(e){this.handleSpeechInputSaveError(e)}}async clearSpeechInputCredential(){if(!this.isSpeechInputSecureContext())return;let e=this.speechInputSavedResponse;if(!(e===void 0||this.speechInputStale||this.saving)&&!(typeof globalThis.confirm!=`function`||!globalThis.confirm(`Clear the saved speech input credential?`))){this.speechInputLocalError=``;try{let t=await this.onSaveSpeechInput?.({expectedRevision:e.revision,settings:e.settings,credential:{action:`clear`}});t!==void 0&&this.adoptSpeechInputCredentialClear(t)}catch(e){this.handleSpeechInputSaveError(e)}}}handleSpeechInputSaveError(e){if(e instanceof Jt&&e.status===409){this.speechInputStale=!0,this.speechInputLocalError=`Speech input settings changed in another tab. Reload before saving.`;return}if(e instanceof Jt&&e.status===400&&e.message===`Re-enter the API key source when changing the cloud base URL.`){this.speechInputLocalError=`Re-enter the API key source when changing the cloud base URL, or clear the saved credential first.`;return}this.speechInputLocalError=CN(e)}updateSpeechInputDraft(e){this.speechInputDraft={...this.speechInputDraft,...e},this.speechInputDraftDirty=!0,this.speechInputLocalError=``}markSpeechInputCredentialEntryDirty(){this.credentialEntryDirty=!0,this.speechInputLocalError=``}clearSpeechInputCredentialInput(){this.speechInputApiKeyInput!==void 0&&(this.speechInputApiKeyInput.value=``)}isSpeechInputSecureContext(){return this.speechInputSecureContext??globalThis.isSecureContext}panelNotices(){let e=[],t=this.gatewayLocalError||this.error;return t!==``&&e.push({type:`error`,title:`Gateway server`,content:t}),this.hostSpeechLocalError!==``&&e.push({type:`error`,title:`Text to speech`,content:this.hostSpeechLocalError}),this.speechInputLocalError!==``&&e.push({type:`error`,title:`Speech input`,content:this.speechInputLocalError}),this.savedMessage!==``&&e.push({type:`success`,content:this.savedMessage}),e}renderMachineMessages(){let e=this.machineLocalError||this.machineError;return e===``?null:g`<div class="message error-message">${e}</div>`}renderOverrideBadge(e){return this.configResponse?.envOverrides[e]===!0?g`<span class="override-badge">environment override</span>`:null}renderGatewayEffectiveConfig(){let e=this.configResponse?.effectiveConfig??{};return g`
|
|
5066
5066
|
<section class="effective-card" aria-label="Effective gateway configuration summary">
|
|
5067
5067
|
<h3>Effective gateway settings after environment overrides</h3>
|
|
5068
5068
|
<dl>
|
|
5069
5069
|
<div><dt>Host</dt><dd>${e.host??g`<span class="muted">127.0.0.1 default</span>`}</dd></div>
|
|
5070
5070
|
<div><dt>Port</dt><dd>${e.port??g`<span class="muted">8808 default</span>`}</dd></div>
|
|
5071
|
-
<div><dt>Allowed hosts</dt><dd>${
|
|
5071
|
+
<div><dt>Allowed hosts</dt><dd>${hN(e.allowedHosts)}</dd></div>
|
|
5072
5072
|
</dl>
|
|
5073
5073
|
</section>
|
|
5074
5074
|
`}renderMachineEffectiveConfig(){let e=this.machineConfigResponse?.effectiveConfig??{};return g`
|
|
5075
5075
|
<section class="effective-card" aria-label="Effective selected machine file access and upload summary">
|
|
5076
5076
|
<h3>Effective selected-machine settings</h3>
|
|
5077
5077
|
<dl>
|
|
5078
|
-
<div><dt>External roots</dt><dd>${
|
|
5078
|
+
<div><dt>External roots</dt><dd>${gN(e.pathAccess?.allowedPaths)}</dd></div>
|
|
5079
5079
|
<div><dt>Upload folder</dt><dd>${e.uploads?.defaultFolder??g`<span class="muted">${`.pi-webui/uploads`} default</span>`}</dd></div>
|
|
5080
5080
|
</dl>
|
|
5081
5081
|
</section>
|
|
5082
|
-
`}reloadAll(){this.onReload?.(),this.onReloadMachine?.(),this.showHostSpeechSettings&&this.onReloadHostSpeech?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(
|
|
5082
|
+
`}reloadAll(){this.onReload?.(),this.onReloadMachine?.(),this.showHostSpeechSettings&&this.onReloadHostSpeech?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(nN(this.gatewayDraft,this.configResponse?.config??{}))}catch(e){this.gatewayLocalError=CN(e)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError=``;try{await this.onSaveMachineConfig?.(rN(this.machineDraft))}catch(e){this.machineLocalError=CN(e)}}async saveHostSpeechConfig(e){e.preventDefault(),this.hostSpeechLocalError=``;let t=this.configResponse;if(t===void 0){this.hostSpeechLocalError=`Reload gateway configuration before saving text to speech settings.`;return}try{await this.onSave?.(eN(this.hostSpeechDraft,t.config))}catch(e){this.hostSpeechLocalError=CN(e)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=``}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=``}updateHostSpeechDraft(e){this.hostSpeechDraft={...this.hostSpeechDraft,...e},this.hostSpeechDraftDirty=!0,this.hostSpeechLocalError=``}static{this.styles=h`
|
|
5083
5083
|
:host { display: block; }
|
|
5084
5084
|
.card-heading { display: grid; gap: 6px; min-width: 0; }
|
|
5085
5085
|
h3, p { margin: 0; }
|
|
@@ -5125,10 +5125,10 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5125
5125
|
@media (max-width: 760px) {
|
|
5126
5126
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
5127
5127
|
}
|
|
5128
|
-
`}};H([x({attribute:!1})],J.prototype,`configResponse`,void 0),H([x({attribute:!1})],J.prototype,`machineConfigResponse`,void 0),H([x({type:Boolean})],J.prototype,`loading`,void 0),H([x({type:Boolean})],J.prototype,`machineLoading`,void 0),H([x({type:Boolean})],J.prototype,`saving`,void 0),H([x()],J.prototype,`error`,void 0),H([x()],J.prototype,`machineError`,void 0),H([x()],J.prototype,`savedMessage`,void 0),H([x()],J.prototype,`targetLabel`,void 0),H([x({type:Boolean})],J.prototype,`showHostSpeechSettings`,void 0),H([x({attribute:!1})],J.prototype,`hostSpeechStatus`,void 0),H([x({type:Boolean})],J.prototype,`hostSpeechStatusLoading`,void 0),H([x({attribute:!1})],J.prototype,`speechInputSettings`,void 0),H([x({attribute:!1})],J.prototype,`speechInputSecureContext`,void 0),H([x({type:Number})],J.prototype,`speechInputAdoptionGeneration`,void 0),H([x({type:Number})],J.prototype,`speechInputCredentialClearGeneration`,void 0),H([x({attribute:!1})],J.prototype,`onReload`,void 0),H([x({attribute:!1})],J.prototype,`onReloadMachine`,void 0),H([x({attribute:!1})],J.prototype,`onReloadHostSpeech`,void 0),H([x({attribute:!1})],J.prototype,`onSave`,void 0),H([x({attribute:!1})],J.prototype,`onSaveSpeechInput`,void 0),H([x({attribute:!1})],J.prototype,`onSaveMachineConfig`,void 0),H([C(`.speech-input-api-key`)],J.prototype,`speechInputApiKeyInput`,void 0),H([S()],J.prototype,`gatewayDraft`,void 0),H([S()],J.prototype,`hostSpeechDraft`,void 0),H([S()],J.prototype,`machineDraft`,void 0),H([S()],J.prototype,`speechInputDraft`,void 0),H([S()],J.prototype,`speechInputSavedResponse`,void 0),H([S()],J.prototype,`speechInputDraftDirty`,void 0),H([S()],J.prototype,`credentialEntryDirty`,void 0),H([S()],J.prototype,`speechInputStale`,void 0),H([S()],J.prototype,`speechInputLocalError`,void 0),H([S()],J.prototype,`gatewayLocalError`,void 0),H([S()],J.prototype,`hostSpeechDraftDirty`,void 0),H([S()],J.prototype,`hostSpeechLocalError`,void 0),H([S()],J.prototype,`machineLocalError`,void 0),J=H([b(`settings-general-panel`)],J);function
|
|
5128
|
+
`}};H([x({attribute:!1})],J.prototype,`configResponse`,void 0),H([x({attribute:!1})],J.prototype,`machineConfigResponse`,void 0),H([x({type:Boolean})],J.prototype,`loading`,void 0),H([x({type:Boolean})],J.prototype,`machineLoading`,void 0),H([x({type:Boolean})],J.prototype,`saving`,void 0),H([x()],J.prototype,`error`,void 0),H([x()],J.prototype,`machineError`,void 0),H([x()],J.prototype,`savedMessage`,void 0),H([x()],J.prototype,`targetLabel`,void 0),H([x({type:Boolean})],J.prototype,`showHostSpeechSettings`,void 0),H([x({attribute:!1})],J.prototype,`hostSpeechStatus`,void 0),H([x({type:Boolean})],J.prototype,`hostSpeechStatusLoading`,void 0),H([x({attribute:!1})],J.prototype,`speechInputSettings`,void 0),H([x({attribute:!1})],J.prototype,`speechInputSecureContext`,void 0),H([x({type:Number})],J.prototype,`speechInputAdoptionGeneration`,void 0),H([x({type:Number})],J.prototype,`speechInputCredentialClearGeneration`,void 0),H([x({attribute:!1})],J.prototype,`onReload`,void 0),H([x({attribute:!1})],J.prototype,`onReloadMachine`,void 0),H([x({attribute:!1})],J.prototype,`onReloadHostSpeech`,void 0),H([x({attribute:!1})],J.prototype,`onSave`,void 0),H([x({attribute:!1})],J.prototype,`onSaveSpeechInput`,void 0),H([x({attribute:!1})],J.prototype,`onSaveMachineConfig`,void 0),H([C(`.speech-input-api-key`)],J.prototype,`speechInputApiKeyInput`,void 0),H([S()],J.prototype,`gatewayDraft`,void 0),H([S()],J.prototype,`hostSpeechDraft`,void 0),H([S()],J.prototype,`machineDraft`,void 0),H([S()],J.prototype,`speechInputDraft`,void 0),H([S()],J.prototype,`speechInputSavedResponse`,void 0),H([S()],J.prototype,`speechInputDraftDirty`,void 0),H([S()],J.prototype,`credentialEntryDirty`,void 0),H([S()],J.prototype,`speechInputStale`,void 0),H([S()],J.prototype,`speechInputLocalError`,void 0),H([S()],J.prototype,`gatewayLocalError`,void 0),H([S()],J.prototype,`hostSpeechDraftDirty`,void 0),H([S()],J.prototype,`hostSpeechLocalError`,void 0),H([S()],J.prototype,`machineLocalError`,void 0),J=H([b(`settings-general-panel`)],J);function fN(){return{provider:`auto`,language:``,baseUrl:``,model:``}}function pN(e){return e?.credential.configured??!1}function mN(e){return e.configured?e.source===`literal`?`A literal API key source is configured.`:e.source===`environment`?e.resolution===`resolved`?`An environment API key source is configured and resolves for this gateway.`:`An environment API key source is configured but is not currently resolved for this gateway.`:`A command API key source is configured and is checked when transcription starts.`:`No API key source is configured.`}function hN(e){return e===!0?`Any host`:Array.isArray(e)?e.length===0?g`<span class="muted">None listed</span>`:e.join(`, `):g`<span class="muted">Unset</span>`}function gN(e){return e===void 0||e.length===0?g`<span class="muted">External paths denied</span>`:e.join(`, `)}function _N(e,t,n){let r=new Map;for(let t of e)r.has(t.name)||r.set(t.name,{name:t.name,label:vN(t)});let i=t.trim();return i!==``&&!r.has(i)&&r.set(i,{name:i,label:n?`${i} (no longer available)`:`${i} (configured)`}),[...r.values()]}function vN(e){return`${e.name} (${e.language}${e.variant===void 0?``:`, ${e.variant}`})`}function yN(e){let t=Number(e.trim());return Number.isInteger(t)&&t>=-100&&t<=100?t:0}function bN(e){return e.target instanceof HTMLInputElement?e.target.value:``}function xN(e){return e.target instanceof HTMLSelectElement?e.target.value:``}function SN(e){return e.target instanceof HTMLTextAreaElement?e.target.value:``}function CN(e){return e instanceof Error?e.message:String(e)}function wN(e){return{spawnSessions:e}}function TN(e){return{subsessions:e}}function EN(e,t){let n=e?.effectiveConfig.agent;if(n?.command===void 0||n.dir===void 0||t===void 0)return`unavailable`;let r=[`PI_WEBUI_AGENT_SESSION_DIR`,...Qt(n.command)?[`PI_CODING_AGENT_SESSION_DIR`]:[]];return n.command===t.command&&n.dir===t.dir&&kN(t.sessionDirEnvKeys,r)?`active`:`restart-required`}function DN(e,t){return e?.agentDirSource===`pi-webui`?!0:e?.agentDirSource===`pi-compatibility`?Qt(t.trim()||`pi`):e?.agentDir===!0}function ON(e,t){let n={...e.envOverrides,spawnSessions:t.envOverrides.spawnSessions,subsessions:t.envOverrides.subsessions,agentCommand:t.envOverrides.agentCommand,agentDir:t.envOverrides.agentDir,agentSessionDir:t.envOverrides.agentSessionDir};return t.envOverrides.agentDirSource===void 0?delete n.agentDirSource:n.agentDirSource=t.envOverrides.agentDirSource,{...e,config:{...e.config,...t.config},effectiveConfig:{...e.effectiveConfig,...t.effectiveConfig},envOverrides:n}}function kN(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var AN=class extends y{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`,this.agentProfileSupport={state:`supported`},this.agentDraft=WM(),this.agentDraftDirty=!1,this.agentLocalError=``}willUpdate(e){if(e.has(`configResponse`)){if(this.configResponse===void 0){this.agentDraft=WM(),this.agentDraftDirty=!1,this.agentLocalError=``;return}(!this.agentDraftDirty||$M(this.agentDraft,this.configResponse.config))&&(this.agentDraft=JM(this.configResponse.config),this.agentDraftDirty=!1,this.agentLocalError=``)}}render(){let e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,n=e?.effectiveConfig.spawnSessions!==!1,r=e?.envOverrides.subsessions===!0,i=e?.effectiveConfig.subsessions===!0&&n,a=e?.envOverrides.agentCommand===!0,o=this.agentProfileSupport.state===`supported`,s=a?e.effectiveConfig.agent?.command??this.agentDraft.command:this.agentDraft.command,c=DN(e?.envOverrides,s),l=e?.envOverrides.agentDir===!0,u=e?.effectiveConfig.agent,d=EN(e,this.activeAgentProfile);return g`
|
|
5129
5129
|
<settings-panel-frame
|
|
5130
5130
|
heading="Session daemon"
|
|
5131
|
-
.description=${
|
|
5131
|
+
.description=${PN(this.targetLabel)}
|
|
5132
5132
|
actionLabel="Reload"
|
|
5133
5133
|
.actionDisabled=${this.loading}
|
|
5134
5134
|
.notices=${this.panelNotices(e)}
|
|
@@ -5154,7 +5154,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5154
5154
|
.value=${this.agentDraft.command}
|
|
5155
5155
|
placeholder="pi"
|
|
5156
5156
|
?disabled=${this.loading||this.saving||!o||a}
|
|
5157
|
-
@input=${e=>{this.updateAgentDraft({command:
|
|
5157
|
+
@input=${e=>{this.updateAgentDraft({command:MN(e)})}}
|
|
5158
5158
|
>
|
|
5159
5159
|
<small>Set the Pi-compatible companion CLI used for doctor and update checks. The embedded session runtime remains PI WEBUI's bundled Pi SDK.</small>
|
|
5160
5160
|
</label>
|
|
@@ -5171,7 +5171,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5171
5171
|
.value=${this.agentDraft.dir}
|
|
5172
5172
|
placeholder="~/.pi/agent or ~/agent-profiles/work"
|
|
5173
5173
|
?disabled=${this.loading||this.saving||!o||c}
|
|
5174
|
-
@input=${e=>{this.updateAgentDraft({dir:
|
|
5174
|
+
@input=${e=>{this.updateAgentDraft({dir:MN(e)})}}
|
|
5175
5175
|
>
|
|
5176
5176
|
<small>Choose the Pi-compatible auth, models, settings, and sessions PI WEBUI reads. An alternate command and its required state directory are saved together.</small>
|
|
5177
5177
|
</label>
|
|
@@ -5219,14 +5219,14 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5219
5219
|
<div><dt>Desired state</dt><dd>${u?.dir??g`<span class="muted">Unavailable</span>`}</dd></div>
|
|
5220
5220
|
<div><dt>Active command</dt><dd>${this.activeAgentProfile?.command??g`<span class="muted">Unavailable</span>`}</dd></div>
|
|
5221
5221
|
<div><dt>Active state</dt><dd>${this.activeAgentProfile?.dir??g`<span class="muted">Unavailable</span>`}</dd></div>
|
|
5222
|
-
<div><dt>Profile status</dt><dd>${
|
|
5222
|
+
<div><dt>Profile status</dt><dd>${jN(d)}</dd></div>
|
|
5223
5223
|
<div><dt>Spawn sessions</dt><dd>${n?`Enabled`:g`<span class="muted">Disabled</span>`}</dd></div>
|
|
5224
5224
|
<div><dt>Subsessions</dt><dd>${i?`Enabled`:g`<span class="muted">Disabled</span>`}</dd></div>
|
|
5225
5225
|
</dl>
|
|
5226
5226
|
</section>
|
|
5227
5227
|
`}
|
|
5228
5228
|
</settings-panel-frame>
|
|
5229
|
-
`}panelNotices(e){return
|
|
5229
|
+
`}panelNotices(e){return FN(e,{error:this.agentLocalError||this.error,savedMessage:this.savedMessage,activeProfile:this.activeAgentProfile,targetLabel:this.targetLabel,profileEditingSupported:this.agentProfileSupport.state===`supported`})}renderUnavailableConfigState(){return g`<div class="loading-card">${this.loading?`Loading configuration…`:`Configuration is unavailable. Reload to try again.`}</div>`}async saveAgentProfile(e){e.preventDefault(),this.agentLocalError=``;try{await this.onSave?.(QM(this.agentDraft))}catch(e){this.agentLocalError=NN(e)}}updateAgentDraft(e){this.agentDraft={...this.agentDraft,...e},this.agentDraftDirty=!0,this.agentLocalError=``}async toggleSpawnSessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(wN(t))}async toggleSubsessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(TN(t))}static{this.styles=h`
|
|
5230
5230
|
:host { display: block; }
|
|
5231
5231
|
h3 { margin: 0; font-size: 13px; line-height: 1.3; }
|
|
5232
5232
|
button, input { font: inherit; }
|
|
@@ -5272,10 +5272,10 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5272
5272
|
@media (max-width: 760px) {
|
|
5273
5273
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
5274
5274
|
}
|
|
5275
|
-
`}};H([x({attribute:!1})],
|
|
5275
|
+
`}};H([x({attribute:!1})],AN.prototype,`configResponse`,void 0),H([x({type:Boolean})],AN.prototype,`loading`,void 0),H([x({type:Boolean})],AN.prototype,`saving`,void 0),H([x()],AN.prototype,`error`,void 0),H([x()],AN.prototype,`savedMessage`,void 0),H([x()],AN.prototype,`targetLabel`,void 0),H([x({attribute:!1})],AN.prototype,`activeAgentProfile`,void 0),H([x({attribute:!1})],AN.prototype,`agentProfileSupport`,void 0),H([x({attribute:!1})],AN.prototype,`onReload`,void 0),H([x({attribute:!1})],AN.prototype,`onSave`,void 0),H([S()],AN.prototype,`agentDraft`,void 0),H([S()],AN.prototype,`agentDraftDirty`,void 0),H([S()],AN.prototype,`agentLocalError`,void 0),AN=H([b(`settings-sessiond-panel`)],AN);function jN(e){return e===`active`?`Active`:e===`restart-required`?`Restart required`:g`<span class="muted">Unavailable</span>`}function MN(e){return e.target instanceof HTMLInputElement?e.target.value:``}function NN(e){return e instanceof Error?e.message:String(e)}function PN(e){return`Select the Pi-compatible agent profile and companion CLI for ${e}. Changes are saved immediately but only take effect after the session daemon on that machine restarts.`}function FN(e,t){let n=[];t.error!==``&&n.push({type:`error`,content:t.error}),t.savedMessage!==``&&n.push({type:`success`,content:t.savedMessage});let r=EN(e,t.activeProfile);return r===`restart-required`?n.push({type:`warning`,title:`Pi-compatible agent profile restart required on ${t.targetLabel}`,content:g`The desired profile differs from the active session-daemon profile. Run <code>pi-webui restart</code> on that machine (or restart its session daemon service) to apply the command and state directory together.`}):e!==void 0&&r===`unavailable`&&t.profileEditingSupported&&n.push({type:`info`,title:`Active Pi-compatible agent profile unavailable on ${t.targetLabel}`,content:`PI WEBUI cannot compare the desired profile with the running session daemon. Reload after the daemon is available.`}),n}function IN(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function LN(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function RN(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?E(t,w.piPackagesManage)?{state:`supported`}:{state:`unsupported`,message:VN(e)}:{state:`unknown`}}function zN(e){return`${e.state}:${e.message??``}`}function BN(e){return e?.state===`unsupported`}function VN(e){return`Pi package management is not available on ${e.name}. Update and restart Pi-Web on that machine, then try again.`}function HN(e){return e.kind===`local`}function UN(e){return e.trim()}function WN(e){if(UN(e)===``)return`Enter a Pi package source accepted by Pi, such as npm:@scope/package, a git/URL source, or a local path.`}function GN(e){return e.scope===`project`?`Project scope`:`User scope`}function KN(e){return e.filtered?`Filtered by current Pi package settings`:`Available in this PI WEBUI process`}function qN(e){return e.installedPath??`Installed path not reported by Pi`}function JN(e){return e.scope===`user`}function YN(e){if(!JN(e))return`Project-scope Pi packages are listed for visibility, but PI WEBUI only updates user-scope Pi packages safely from this view.`}function XN(e){return e.length>0&&e.every(JN)}function ZN(e){if(e.length===0)return`No Pi packages are configured yet.`;if(!XN(e))return`Update all is disabled while project-scope Pi packages are listed; update user-scope packages individually.`}function QN(e,t,n){return e?.kind===t?n===void 0||e.source===n:!1}function $N(e,t=IN(void 0)){return`Pi package ${e===`install`?`installed`:e===`remove`?`removed`:`updated`}${t.kind===`local`?``:` on ${t.name}`}. Type /reload in ${t.kind===`local`?`each idle PI WEBUI session`:`each idle PI WEBUI session on ${t.name}`} to rediscover Pi runtime resources: extensions, skills, prompt templates, themes, and context/system prompt files. Reload the browser page separately for ${t.kind===`local`?`PI WEBUI browser plugin changes`:`PI WEBUI browser plugin changes served by ${t.name}`}.`}function eP(e,t){let n=e.trim();return t.kind===`remote`?tP(n)?VN(t):n===`Remote machine timeout`?`Timed out while contacting ${t.name} for Pi package management. The package operation may still be running remotely; reload the package list before retrying.`:n===`Remote machine unavailable`?`Could not reach ${t.name} for Pi package management. Check the machine connection and try again.`:n:n}function tP(e){return e===`Not Found`||/route\s+(GET|POST):?\/api\/pi-packages\b.*not found/iu.test(e)||/cannot\s+(GET|POST)\s+.*\/api\/pi-packages\b/iu.test(e)}var nP=class extends y{constructor(...e){super(...e),this.loading=!1,this.error=``,this.operationMessage=``,this.installSource=``,this.validationMessage=``}render(){let e=this.packagesResponse?.packages??[],t=this.packageTarget,n=LN(t),r=this.packageManagementUnavailable,i=this.packagesResponse!==void 0&&!r;return g`
|
|
5276
5276
|
<settings-panel-frame
|
|
5277
5277
|
heading="Pi packages"
|
|
5278
|
-
.description=${
|
|
5278
|
+
.description=${rP(n)}
|
|
5279
5279
|
actionLabel="Reload"
|
|
5280
5280
|
actionTitle=${r?this.packageManagementUnavailableMessage(n):`Reload Pi packages from ${n}`}
|
|
5281
5281
|
.actionDisabled=${this.loading||this.isOperating||r}
|
|
@@ -5292,12 +5292,12 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5292
5292
|
<label for="package-source">Pi package source</label>
|
|
5293
5293
|
<div class="install-row">
|
|
5294
5294
|
<input id="package-source" .value=${this.installSource} ?disabled=${this.isOperating} placeholder="npm:@scope/package, git URL, or local path" @input=${e=>{this.updateInstallSource(e)}}>
|
|
5295
|
-
<button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${
|
|
5295
|
+
<button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${QN(this.operation,`install`)?`Installing…`:`Install`}</button>
|
|
5296
5296
|
</div>
|
|
5297
5297
|
${this.validationMessage===``?null:g`<div class="field-error">${this.validationMessage}</div>`}
|
|
5298
5298
|
<small>Installs run on ${e} and use Pi's default package location, equivalent to <code>pi install <source></code>. PI WEBUI does not ask you to choose an install location.</small>
|
|
5299
5299
|
</form>
|
|
5300
|
-
`}renderPackageList(e,t){let n=
|
|
5300
|
+
`}renderPackageList(e,t){let n=LN(t),r=this.packageManagementUnavailable?this.packageManagementUnavailableMessage(n):ZN(e),i=r!==void 0&&e.length>0;return g`
|
|
5301
5301
|
<section class="package-section" aria-label="Configured Pi packages">
|
|
5302
5302
|
<div class="package-toolbar">
|
|
5303
5303
|
<div>
|
|
@@ -5305,7 +5305,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5305
5305
|
<p>This list comes from Pi's package manager settings on ${n}.</p>
|
|
5306
5306
|
</div>
|
|
5307
5307
|
<button class="secondary" title=${r??`Update all user-scope Pi packages`} ?disabled=${this.isOperating||r!==void 0} @click=${()=>{this.updatePackage()}}>
|
|
5308
|
-
${
|
|
5308
|
+
${QN(this.operation,`update-all`)?`Updating…`:`Update all`}
|
|
5309
5309
|
</button>
|
|
5310
5310
|
</div>
|
|
5311
5311
|
${i?g`<div class="action-note">${r}</div>`:null}
|
|
@@ -5316,12 +5316,12 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5316
5316
|
<div class="package-list">
|
|
5317
5317
|
${e.map(e=>this.renderPackage(e))}
|
|
5318
5318
|
</div>
|
|
5319
|
-
`}renderPackage(e){let t=
|
|
5319
|
+
`}renderPackage(e){let t=LN(this.packageTarget),n=this.packageManagementUnavailable,r=n?this.packageManagementUnavailableMessage(t):YN(e),i=n?this.packageManagementUnavailableMessage(t):`Remove this Pi package`,a=QN(this.operation,`update`,e.source),o=QN(this.operation,`remove`,e.source);return g`
|
|
5320
5320
|
<article class=${`package-card${e.filtered?` filtered`:``}`}>
|
|
5321
5321
|
<div class="package-main">
|
|
5322
5322
|
<strong>${e.source}</strong>
|
|
5323
|
-
<small>${
|
|
5324
|
-
<small>Installed path: <code>${
|
|
5323
|
+
<small>${GN(e)} · ${KN(e)}</small>
|
|
5324
|
+
<small>Installed path: <code>${qN(e)}</code></small>
|
|
5325
5325
|
${r===void 0?null:g`<small class="action-note">${r}</small>`}
|
|
5326
5326
|
</div>
|
|
5327
5327
|
<div class="package-actions">
|
|
@@ -5329,7 +5329,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5329
5329
|
<button class="danger" title=${i} ?disabled=${this.isOperating||n} @click=${()=>{this.removePackage(e)}}>${o?`Removing…`:`Remove`}</button>
|
|
5330
5330
|
</div>
|
|
5331
5331
|
</article>
|
|
5332
|
-
`}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=
|
|
5332
|
+
`}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=WN(this.installSource);if(t!==void 0){this.validationMessage=t;return}let n=UN(this.installSource);try{await this.onInstallPackage?.(n),this.installSource=``,this.validationMessage=``}catch{}}async removePackage(e){try{await this.onRemovePackage?.(e.source,e.scope)}catch{}}async updatePackage(e){try{await this.onUpdatePackage?.(e)}catch{}}get packageTarget(){return this.targetMachine??IN(void 0)}get packageManagementUnavailable(){return BN(this.managementSupport)}packageManagementUnavailableMessage(e){return this.managementSupport?.message??`Pi package management is not available on ${e}.`}get isOperating(){return this.operation!==void 0}static{this.styles=h`
|
|
5333
5333
|
:host { display: block; }
|
|
5334
5334
|
.package-toolbar { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
5335
5335
|
.package-toolbar > div, .package-main { display: grid; gap: 6px; min-width: 0; }
|
|
@@ -5364,10 +5364,10 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5364
5364
|
.package-actions { justify-self: start; flex-wrap: wrap; }
|
|
5365
5365
|
.package-main strong, .package-main small { white-space: normal; }
|
|
5366
5366
|
}
|
|
5367
|
-
`}};H([x({attribute:!1})],
|
|
5367
|
+
`}};H([x({attribute:!1})],nP.prototype,`packagesResponse`,void 0),H([x({type:Boolean})],nP.prototype,`loading`,void 0),H([x({attribute:!1})],nP.prototype,`operation`,void 0),H([x({attribute:!1})],nP.prototype,`targetMachine`,void 0),H([x({attribute:!1})],nP.prototype,`managementSupport`,void 0),H([x()],nP.prototype,`error`,void 0),H([x()],nP.prototype,`operationMessage`,void 0),H([x({attribute:!1})],nP.prototype,`onReload`,void 0),H([x({attribute:!1})],nP.prototype,`onInstallPackage`,void 0),H([x({attribute:!1})],nP.prototype,`onRemovePackage`,void 0),H([x({attribute:!1})],nP.prototype,`onUpdatePackage`,void 0),H([S()],nP.prototype,`installSource`,void 0),H([S()],nP.prototype,`validationMessage`,void 0),nP=H([b(`settings-packages-panel`)],nP);function rP(e){return g`Managing Pi packages on <strong>${e}</strong>. Install, remove, and update packages managed by Pi on the selected machine. Pi packages can provide extensions, skills, prompt templates, themes, context/system prompt files, and PI WEBUI browser plugins.`}var iP=class extends y{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`}render(){let e=this.pluginsResponse?.plugins??[],t=this.pluginsResponse!==void 0;return g`
|
|
5368
5368
|
<settings-panel-frame
|
|
5369
5369
|
heading="PI WEBUI plugins"
|
|
5370
|
-
.description=${
|
|
5370
|
+
.description=${aP(this.targetLabel)}
|
|
5371
5371
|
actionLabel="Reload"
|
|
5372
5372
|
actionTitle=${`Reload PI WEBUI plugins from ${this.targetLabel}`}
|
|
5373
5373
|
.actionDisabled=${this.loading}
|
|
@@ -5413,7 +5413,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5413
5413
|
.plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
5414
5414
|
.toggle { justify-self: start; }
|
|
5415
5415
|
}
|
|
5416
|
-
`}};H([x({attribute:!1})],
|
|
5416
|
+
`}};H([x({attribute:!1})],iP.prototype,`pluginsResponse`,void 0),H([x({attribute:!1})],iP.prototype,`configResponse`,void 0),H([x({type:Boolean})],iP.prototype,`loading`,void 0),H([x({type:Boolean})],iP.prototype,`saving`,void 0),H([x()],iP.prototype,`error`,void 0),H([x()],iP.prototype,`savedMessage`,void 0),H([x()],iP.prototype,`targetLabel`,void 0),H([x({attribute:!1})],iP.prototype,`onReload`,void 0),H([x({attribute:!1})],iP.prototype,`onTogglePlugin`,void 0),iP=H([b(`settings-plugins-panel`)],iP);function aP(e){return g`Enable or disable discovered PI WEBUI browser plugins on <strong>${e}</strong>. This is separate from installing Pi packages. Reload the browser tab to apply plugin runtime changes.`}function oP(e){return JSON.stringify([e.provider,e.id])}function sP(e){return`${e.provider}/${e.id}`}function cP(e,t){return e.find(e=>oP(e.model)===t)}function lP(e,t){let n=[...e].sort((e,t)=>e.model.provider===t.model.provider?e.model.id.localeCompare(t.model.id):e.model.provider.localeCompare(t.model.provider)).map(e=>({value:oP(e.model),label:e.model.id,...e.name===void 0||e.name===``||e.name===e.model.id?{}:{description:e.name},...e.model.provider===``?{}:{group:e.model.provider}}));return t===void 0?n:[{value:``,label:t.label},...n]}var uP=class extends y{constructor(...e){super(...e),this.triggerId=``,this.accessibleLabel=``,this.dialogTitle=`Select Model`,this.choices=[],this.inheritedLabel=``,this.placeholder=`Select a model…`,this.disabled=!1,this.invalid=!1,this.pickerOpen=!1}get isPickerOpen(){return this.pickerOpen}render(){let e=this.selected,t=e!==void 0&&this.choices.some(t=>dP(t.model,e)),n=e===void 0?this.emptyLabel():`${sP(e)}${t?``:` (unavailable)`}`;return g`
|
|
5417
5417
|
<button
|
|
5418
5418
|
type="button"
|
|
5419
5419
|
id=${this.triggerId}
|
|
@@ -5430,7 +5430,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5430
5430
|
<span class="model-chevron" aria-hidden="true">▾</span>
|
|
5431
5431
|
</button>
|
|
5432
5432
|
${this.pickerOpen?this.renderPicker():null}
|
|
5433
|
-
`}renderPicker(){let e=this.selected,t=
|
|
5433
|
+
`}renderPicker(){let e=this.selected,t=lP(this.choices,this.inheritedLabel===``?void 0:{label:this.inheritedLabel}),n=e===void 0?this.inheritedLabel===``?void 0:``:oP(e);return g`
|
|
5434
5434
|
<div
|
|
5435
5435
|
class="picker-host"
|
|
5436
5436
|
@keydown=${e=>{e.key===`Escape`&&e.stopPropagation()}}
|
|
@@ -5445,7 +5445,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5445
5445
|
.onCancel=${()=>{this.closePicker()}}
|
|
5446
5446
|
></command-picker>
|
|
5447
5447
|
</div>
|
|
5448
|
-
`}showPicker(){this.disabled||(this.pickerOpen=!0)}closePicker(){this.pickerOpen&&(this.pickerOpen=!1,this.updateComplete.then(()=>{this.isConnected&&this.renderRoot.querySelector(`.model-trigger`)?.focus()}))}pickModel(e){if(e===``){if(this.inheritedLabel===``)return;this.closePicker(),this.onSelect?.(void 0);return}let t=
|
|
5448
|
+
`}showPicker(){this.disabled||(this.pickerOpen=!0)}closePicker(){this.pickerOpen&&(this.pickerOpen=!1,this.updateComplete.then(()=>{this.isConnected&&this.renderRoot.querySelector(`.model-trigger`)?.focus()}))}pickModel(e){if(e===``){if(this.inheritedLabel===``)return;this.closePicker(),this.onSelect?.(void 0);return}let t=cP(this.choices,e);t!==void 0&&(this.closePicker(),this.onSelect?.({...t.model}))}emptyLabel(){return this.inheritedLabel===``?this.placeholder:this.inheritedLabel}triggerTitle(e,t){let n=this.selected;if(n===void 0||!t)return e;let r=this.choices.find(e=>dP(e.model,n))?.name;return r===void 0||r===``||r===n.id?e:`${r} (${e})`}static{this.styles=h`
|
|
5449
5449
|
:host { display: block; min-width: 0; }
|
|
5450
5450
|
.model-trigger { display: flex; align-items: center; justify-content: space-between; gap: 8px; width: 100%; min-width: 0; box-sizing: border-box; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 7px 10px; font: inherit; font-size: 13px; text-align: left; cursor: pointer; }
|
|
5451
5451
|
.model-trigger:hover:not(:disabled), .model-trigger:focus-visible { border-color: var(--pi-accent); }
|
|
@@ -5454,7 +5454,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5454
5454
|
.model-trigger.empty .model-summary { color: var(--pi-muted); }
|
|
5455
5455
|
.model-summary { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
5456
5456
|
.model-chevron { flex: 0 0 auto; color: var(--pi-muted); }
|
|
5457
|
-
`}};H([x()],
|
|
5457
|
+
`}};H([x()],uP.prototype,`triggerId`,void 0),H([x()],uP.prototype,`accessibleLabel`,void 0),H([x()],uP.prototype,`dialogTitle`,void 0),H([x({attribute:!1})],uP.prototype,`choices`,void 0),H([x({attribute:!1})],uP.prototype,`selected`,void 0),H([x()],uP.prototype,`inheritedLabel`,void 0),H([x()],uP.prototype,`placeholder`,void 0),H([x({type:Boolean})],uP.prototype,`disabled`,void 0),H([x({type:Boolean})],uP.prototype,`invalid`,void 0),H([x({attribute:!1})],uP.prototype,`onSelect`,void 0),H([S()],uP.prototype,`pickerOpen`,void 0),uP=H([b(`settings-model-picker-field`)],uP);function dP(e,t){return e.provider===t.provider&&e.id===t.id}function fP(){return{economy:vP(),fast:vP(),standard:vP(),advanced:vP(),capable:vP(),frontier:vP()}}function pP(e){return e.ladder===void 0?fP():{economy:yP(e.ladder.economy),fast:yP(e.ladder.fast),standard:yP(e.ladder.standard),advanced:yP(e.ladder.advanced),capable:yP(e.ladder.capable),frontier:yP(e.ladder.frontier)}}function mP(e,t,n){let r=e[t],i=r.thinkingLevel===``||n.thinkingLevels.includes(r.thinkingLevel)?r.thinkingLevel:``;return{...e,[t]:{model:{...n.model},thinkingLevel:i}}}function hP(e,t,n){return{...e,[t]:{...e[t],thinkingLevel:n}}}function gP(e,t){let n={economy:xP(`economy`,e.economy,t),fast:xP(`fast`,e.fast,t),standard:xP(`standard`,e.standard,t),advanced:xP(`advanced`,e.advanced,t),capable:xP(`capable`,e.capable,t),frontier:xP(`frontier`,e.frontier,t)};return{valid:Lt.every(e=>n[e].valid),rows:n}}function _P(e,t){if(gP(e,t).valid)return{economy:bP(e.economy),fast:bP(e.fast),standard:bP(e.standard),advanced:bP(e.advanced),capable:bP(e.capable),frontier:bP(e.frontier)}}function vP(){return{thinkingLevel:``}}function yP(e){return{model:{...e.model},thinkingLevel:e.thinkingLevel}}function bP(e){if(e.model===void 0)throw Error(`Cannot build a model-tier ladder from an incomplete draft`);return{model:{...e.model},thinkingLevel:e.thinkingLevel}}function xP(e,t,n){let r=t.model;if(r===void 0)return{valid:!1,reason:`tier ${e} has no model selected`};let i=n.find(e=>SP(e.model,r));return i===void 0?{valid:!1,reason:`tier ${e} names unavailable model ${CP(r)}`}:t.thinkingLevel===``?{valid:!1,reason:`tier ${e} has no thinking level selected`}:i.thinkingLevels.includes(t.thinkingLevel)?{valid:!0}:{valid:!1,reason:`tier ${e} names thinking level ${t.thinkingLevel}, unsupported by ${CP(r)}`}}function SP(e,t){return e.provider===t.provider&&e.id===t.id}function CP(e){return`${e.provider}/${e.id}`}var wP={economy:{label:`Economy`,step:`1`},fast:{label:`Fast`,step:`↓`},standard:{label:`Standard`,step:`↓`},advanced:{label:`Advanced`,step:`↓`},capable:{label:`Capable`,step:`↓`},frontier:{label:`Frontier`,step:`6`}},TP=class extends y{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`selected machine`,this.support={state:`supported`},this.draft=fP()}get canSave(){let e=this.response?.models??[];return gP(this.draft,e).valid&&!this.saving&&!this.loading&&this.support.state===`supported`}willUpdate(e){e.has(`response`)&&(this.response===void 0?this.draft=fP():this.draft=pP(this.response))}handleReload(){this.onReload?.()}handleSave(){if(!this.canSave)return;let e=this.response?.models??[],t=_P(this.draft,e);t&&this.onSave&&this.onSave(t)}handleModelChange(e,t){this.draft=mP(this.draft,e,t)}handleThinkingChange(e,t){this.draft=hP(this.draft,e,t)}onModelPicked(e,t){if(t===void 0)return;let n=(this.response?.models??[]).find(e=>EP(e.model,t));n!==void 0&&this.handleModelChange(e,n)}onThinkingSelectChange(e,t){t.target instanceof HTMLSelectElement&&this.handleThinkingChange(e,t.target.value)}panelNotices(){let e=[];return this.support.state===`unsupported`?e.push({type:`availability`,tone:`error`,content:this.support.message??`Model tier configuration is not available on ${this.targetLabel}. Update and restart Pi-Web on that machine, then try again.`}):this.support.state===`unknown`&&e.push({type:`availability`,tone:`warning`,content:this.support.message??`Model tier configuration support is unknown for ${this.targetLabel}.`}),this.error!==``&&e.push({type:`error`,content:this.error}),this.response?.configError!==void 0&&this.response.configError!==``&&e.push({type:`error`,title:`Configuration error`,content:this.response.configError}),this.savedMessage!==``&&e.push({type:`success`,content:this.savedMessage}),e}render(){let e=this.response?.models??[],t=gP(this.draft,e),n=Lt.filter(e=>t.rows[e].valid).length,r=this.loading||this.saving||this.support.state!==`supported`;return g`
|
|
5458
5458
|
<settings-panel-frame
|
|
5459
5459
|
heading="Model tiers"
|
|
5460
5460
|
description="Configure the six exact model/thinking bindings used by tiered sessions."
|
|
@@ -5488,7 +5488,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5488
5488
|
</footer>
|
|
5489
5489
|
`}
|
|
5490
5490
|
</settings-panel-frame>
|
|
5491
|
-
`}renderTierRow(e,t,n,r){let i=
|
|
5491
|
+
`}renderTierRow(e,t,n,r){let i=wP[e],a=this.draft[e],o=n.rows[e],s=a.model,c=s?t.find(e=>EP(e.model,s)):void 0;return g`
|
|
5492
5492
|
<div class="tier-row ${o.valid?``:`invalid`}" data-tier=${e}>
|
|
5493
5493
|
<div class="step-col" aria-hidden="true">${i.step}</div>
|
|
5494
5494
|
<div class="tier-col">
|
|
@@ -5700,10 +5700,10 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5700
5700
|
width: 100%;
|
|
5701
5701
|
}
|
|
5702
5702
|
}
|
|
5703
|
-
`}};H([x({attribute:!1})],
|
|
5703
|
+
`}};H([x({attribute:!1})],TP.prototype,`response`,void 0),H([x({type:Boolean})],TP.prototype,`loading`,void 0),H([x({type:Boolean})],TP.prototype,`saving`,void 0),H([x()],TP.prototype,`error`,void 0),H([x()],TP.prototype,`savedMessage`,void 0),H([x()],TP.prototype,`targetLabel`,void 0),H([x({attribute:!1})],TP.prototype,`support`,void 0),H([x({attribute:!1})],TP.prototype,`onReload`,void 0),H([x({attribute:!1})],TP.prototype,`onSave`,void 0),H([S()],TP.prototype,`draft`,void 0),TP=H([b(`settings-model-tiers-panel`)],TP);function EP(e,t){return e.provider===t.provider&&e.id===t.id}var DP={capture:!0},OP=[{value:`auto`,label:`Auto/default`,description:`Desktop-like Enter sends; mobile, coarse pointer, or narrow screens insert a new line.`},{value:`send`,label:`Enter sends message`,description:`Enter sends the chat message; Shift+Enter adds a new line when supported.`},{value:`newline`,label:`Enter inserts new line`,description:`Enter adds a line break; Shift+Enter sends the chat message when supported.`}];function kP(){return g`Edit app shortcuts by action. Type a shortcut such as <code>mod+k</code> or <code>mod+g p</code>, record one from the keyboard, disable it with None, or reset it to the default. When shortcuts conflict, custom shortcuts win before defaults; ties are resolved by action id, and shorter shortcuts shadow longer sequences with the same prefix.`}var AP=class extends y{constructor(...e){super(...e),this.actions=[],this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.drafts={},this.localError=``,this.promptEnterPreference=FO(),this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{let t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key===`Escape`){this.stopRecording();return}let n=tv(e);if(n===void 0){this.localError=`Press a letter, number, punctuation, function, or navigation key. Press Esc to cancel recording.`;return}if(t.tokens.length===0&&!nv(n)){this.localError=`Start shortcuts with Ctrl/⌘ or Alt so normal typing is not captured.`;return}let r=[...t.tokens,n];this.localError=``,this.drafts={[t.actionId]:r.join(` `)},this.recording={actionId:t.actionId,tokens:r},this.armRecordingTimer()}}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.drafts={},this.localError=``,this.stopRecording())}disconnectedCallback(){this.stopRecording(),super.disconnectedCallback()}render(){let e=PP(this.actions),t=this.shortcutResolutions();return g`
|
|
5704
5704
|
<settings-panel-frame
|
|
5705
5705
|
heading="Keyboard shortcuts"
|
|
5706
|
-
.description=${
|
|
5706
|
+
.description=${kP()}
|
|
5707
5707
|
actionLabel="Reload"
|
|
5708
5708
|
.actionDisabled=${this.loading}
|
|
5709
5709
|
.notices=${this.panelNotices()}
|
|
@@ -5734,7 +5734,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5734
5734
|
<p>Choose what Enter does in this browser. Shift+Enter does the opposite when supported; automatic touch-keyboard capitalization is ignored to avoid accidental sends.</p>
|
|
5735
5735
|
</div>
|
|
5736
5736
|
<div class="prompt-enter-options" role="radiogroup" aria-label="Enter and Shift Enter behavior in the chat composer">
|
|
5737
|
-
${
|
|
5737
|
+
${OP.map(e=>g`
|
|
5738
5738
|
<label class="prompt-enter-option">
|
|
5739
5739
|
<input
|
|
5740
5740
|
type="radio"
|
|
@@ -5751,8 +5751,8 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5751
5751
|
`)}
|
|
5752
5752
|
</div>
|
|
5753
5753
|
</section>
|
|
5754
|
-
`}updatePromptEnterPreference(e){this.promptEnterPreference=e,IO(e)}renderShortcutRow(e,t){let n=this.configResponse?.config.shortcuts,r=
|
|
5755
|
-
<article class=${
|
|
5754
|
+
`}updatePromptEnterPreference(e){this.promptEnterPreference=e,IO(e)}renderShortcutRow(e,t){let n=this.configResponse?.config.shortcuts,r=IP(e.id,n),i=zP(e,n),a=this.shortcutInputText(e),o=a.trim()===``?void 0:Q_(a),s=o?.ok===!0?o.shortcut:RP(e,n),c=r!==void 0,l=this.drafts[e.id]!==void 0,u=l&&a.trim()!==``?`custom`:i,d=this.recordingHint(e.id),f=NP(t);return g`
|
|
5755
|
+
<article class=${jP(t)}>
|
|
5756
5756
|
<div class="shortcut-main">
|
|
5757
5757
|
<strong>${e.title}</strong>
|
|
5758
5758
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
@@ -5762,8 +5762,8 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5762
5762
|
<div class="shortcut-editor">
|
|
5763
5763
|
<div class="shortcut-status">
|
|
5764
5764
|
${s!==void 0&&s!==``?g`<kbd>${ev(s)}</kbd>`:g`<span class="unassigned">${i===`disabled`?`Disabled`:`Unassigned`}</span>`}
|
|
5765
|
-
<small class=${u}>${
|
|
5766
|
-
${f===void 0?null:g`<small class=${
|
|
5765
|
+
<small class=${u}>${BP(u)}${l?` · Unsaved`:``}</small>
|
|
5766
|
+
${f===void 0?null:g`<small class=${MP(t)}>${f}</small>`}
|
|
5767
5767
|
</div>
|
|
5768
5768
|
<label class="shortcut-input-label">
|
|
5769
5769
|
<span>Shortcut</span>
|
|
@@ -5776,7 +5776,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5776
5776
|
autocapitalize="off"
|
|
5777
5777
|
spellcheck="false"
|
|
5778
5778
|
?disabled=${this.saving}
|
|
5779
|
-
@input=${t=>{this.updateDraft(e.id,
|
|
5779
|
+
@input=${t=>{this.updateDraft(e.id,VP(t))}}
|
|
5780
5780
|
>
|
|
5781
5781
|
</label>
|
|
5782
5782
|
${d===``?null:g`<small class="recording-hint">${d}</small>`}
|
|
@@ -5788,7 +5788,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5788
5788
|
</div>
|
|
5789
5789
|
</div>
|
|
5790
5790
|
</article>
|
|
5791
|
-
`}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=
|
|
5791
|
+
`}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=IP(e.id,this.configResponse?.config.shortcuts);return n===null?``:n??e.shortcut??``}recordingHint(e){let t=this.recording;return t?.actionId===e?t.tokens.length===0?`Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.`:`Recording: ${ev(t.tokens.join(` `))}. Press another key to add a sequence, or wait to finish.`:``}updateDraft(e,t){this.drafts={[e]:t},this.localError=``}async saveShortcut(e){this.stopRecording();let t=Q_(this.shortcutInputText(e).trim());if(!t.ok){this.localError=t.message;return}this.localError=``,await this.saveShortcutPreference(e.id,t.shortcut)}async setShortcutNone(e){this.stopRecording(),this.localError=``,await this.saveShortcutPreference(e,null)}async resetShortcut(e){this.stopRecording(),this.localError=``,await this.saveShortcutPreference(e,void 0)}async saveShortcutPreference(e,t){let n={...this.configResponse?.config??{}},r=n.shortcuts??{},i=t===void 0?LP(r,e):{...r,[e]:t};Object.keys(i).length===0?delete n.shortcuts:n.shortcuts=i,await this.onSave?.(n)}shortcutResolutions(){return new Map(Z_(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){let e={...this.configResponse?.config.shortcuts??{}};for(let[t,n]of Object.entries(this.drafts)){let r=n.trim();if(r===``)continue;let i=Q_(r);i.ok&&(e[t]=i.shortcut)}return Object.keys(e).length===0?void 0:e}async toggleRecording(e){if(this.recording?.actionId===e){this.stopRecording();return}this.stopRecording(),this.localError=``,this.recording={actionId:e,tokens:[]},this.ensureRecordingListener(),await this.updateComplete,this.focusShortcutInput(e)}focusShortcutInput(e){for(let t of this.renderRoot.querySelectorAll(`.shortcut-input`))if(t.dataset.actionId===e){t.focus(),t.select();return}}armRecordingTimer(){this.clearRecordingTimer(),this.recordingTimer=window.setTimeout(()=>{this.recordingTimer=void 0,this.stopRecording()},J_)}stopRecording(){this.clearRecordingTimer(),this.removeRecordingListener(),this.recording=void 0}clearRecordingTimer(){this.recordingTimer!==void 0&&(window.clearTimeout(this.recordingTimer),this.recordingTimer=void 0)}ensureRecordingListener(){this.recordingListenerActive||=(window.addEventListener(`keydown`,this.onRecordKeyDown,DP),!0)}removeRecordingListener(){this.recordingListenerActive&&=(window.removeEventListener(`keydown`,this.onRecordKeyDown,DP),!1)}static{this.styles=h`
|
|
5792
5792
|
:host { display: block; }
|
|
5793
5793
|
h3, p { margin: 0; }
|
|
5794
5794
|
h3 { font-size: 13px; line-height: 1.3; }
|
|
@@ -5844,7 +5844,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5844
5844
|
.shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
5845
5845
|
.shortcut-status, .shortcut-actions { justify-content: flex-start; }
|
|
5846
5846
|
}
|
|
5847
|
-
`}};H([x({attribute:!1})],
|
|
5847
|
+
`}};H([x({attribute:!1})],AP.prototype,`actions`,void 0),H([x({attribute:!1})],AP.prototype,`configResponse`,void 0),H([x({type:Boolean})],AP.prototype,`loading`,void 0),H([x({type:Boolean})],AP.prototype,`saving`,void 0),H([x()],AP.prototype,`error`,void 0),H([x()],AP.prototype,`savedMessage`,void 0),H([x({attribute:!1})],AP.prototype,`onReload`,void 0),H([x({attribute:!1})],AP.prototype,`onSave`,void 0),H([S()],AP.prototype,`drafts`,void 0),H([S()],AP.prototype,`localError`,void 0),H([S()],AP.prototype,`promptEnterPreference`,void 0),H([S()],AP.prototype,`recording`,void 0),AP=H([b(`settings-shortcuts-panel`)],AP);function jP(e){return e?.active===!1?`shortcut-row shadowed`:e?.active===!0&&e.shadows.length>0?`shortcut-row shadowing`:`shortcut-row`}function MP(e){return e?.active===!1?`conflict shadowed`:`conflict shadowing`}function NP(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??`another action`}`;let t=e.shadows.length;if(t===0)return;let n=e.shadows.slice(0,2).map(e=>e.action.title).join(`, `),r=t>2?`, +${String(t-2)} more`:``;return`Shadows ${String(t)} ${t===1?`action`:`actions`}: ${n}${r}`}function PP(e){let t=new Map;for(let n of[...e].sort(FP)){let e=n.group??`Other`;t.set(e,[...t.get(e)??[],n])}return[...t.entries()].map(([e,t])=>({name:e,actions:t}))}function FP(e,t){return(e.group??`Other`).localeCompare(t.group??`Other`)||e.title.localeCompare(t.title)}function IP(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function LP(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function RP(e,t){let n=IP(e.id,t);if(n!==null)return n??e.shortcut}function zP(e,t){let n=IP(e.id,t);return n===null?`disabled`:n===void 0?e.shortcut===void 0||e.shortcut===``?`unassigned`:`default`:`custom`}function BP(e){switch(e){case`default`:return`Default`;case`custom`:return`Custom`;case`disabled`:return`Disabled`;case`unassigned`:return`No default`}}function VP(e){return e.target instanceof HTMLInputElement?e.target.value:``}var HP=`auto`;function UP(e){return XP(e.settings)}function WP(e,t,n){return ZP(e,t,n===void 0?void 0:n.model)}function GP(e,t,n){let r=e[t];return r===void 0||n!==`auto`&&!Cn(n)?XP(e):ZP(e,t,n===`auto`?{provider:r.provider,id:r.id}:{provider:r.provider,id:r.id,thinkingLevel:n})}function KP(e,t){let n=YP();if(e.contractVersion!==2||t===void 0)return[n];let r=e.models.find(e=>nF(e.model,t));if(r===void 0)return[n];let i=new Set(r.thinkingLevels),a=Sn.filter(e=>i.has(e)),o=[n];return t.thinkingLevel!==void 0&&!i.has(t.thinkingLevel)&&o.push({value:t.thinkingLevel,label:`${t.thinkingLevel} (unavailable)`,disabled:!0}),o.push(...a.map(e=>({value:e,label:e,disabled:!1}))),o}function qP(e,t){let n={lightweight:eF(`lightweight`,e.lightweight,t),context:eF(`context`,e.context,t)};return{valid:n.lightweight.valid&&n.context.valid,slots:n}}function JP(e,t){if(qP(e,t).valid)return{lightweight:e.lightweight===void 0?null:$P(e.lightweight),context:e.context===void 0?null:$P(e.context)}}function YP(){return{value:HP,label:HP,disabled:!1}}function XP(e){return QP(e.lightweight,e.context)}function ZP(e,t,n){return QP(t===`lightweight`?n:e.lightweight,t===`context`?n:e.context)}function QP(e,t){return{...e===void 0?{}:{lightweight:$P(e)},...t===void 0?{}:{context:$P(t)}}}function $P(e){return{provider:e.provider,id:e.id,...e.thinkingLevel===void 0?{}:{thinkingLevel:e.thinkingLevel}}}function eF(e,t,n){if(t===void 0)return{valid:!0};let r=n.models.find(e=>nF(e.model,t));return r===void 0?{valid:!1,reason:`utility slot ${e} names unavailable model ${rF(t)}`}:t.thinkingLevel===void 0?{valid:!0}:n.contractVersion===2?!Cn(t.thinkingLevel)||!tF(r,t.thinkingLevel)?{valid:!1,reason:`utility slot ${e} names thinking level ${t.thinkingLevel}, unsupported by ${rF(t)}`}:{valid:!0}:{valid:!1,reason:`utility slot ${e} names thinking level ${t.thinkingLevel}, unavailable in this runtime`}}function tF(e,t){return`thinkingLevels`in e&&e.thinkingLevels.includes(t)}function nF(e,t){return e.provider===t.provider&&e.id===t.id}function rF(e){return`${e.provider}/${e.id}`}var iF={lightweight:{label:`Lightweight`,description:`Titles and branch summaries`,emptyLabel:`Use active session model`},context:{label:`Context`,description:`Compaction and context summaries`,emptyLabel:`Use lightweight, then active session model`}},aF=class extends y{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`selected machine`,this.support={state:`supported`},this.draft={}}get editingDisabled(){return this.loading||this.saving||this.support.state!==`supported`}get canSave(){return this.response!==void 0&&qP(this.draft,this.response).valid&&!this.editingDisabled}willUpdate(e){e.has(`response`)&&(this.draft=this.response===void 0?{}:UP(this.response))}handleReload(){this.onReload?.()}handleSave(){let e=this.response;if(!this.canSave||e===void 0)return;let t=JP(this.draft,e);t!==void 0&&this.onSave!==void 0&&this.onSave(t)}handleModelChange(e,t){this.draft=WP(this.draft,e,t)}handleThinkingChange(e,t){this.draft=GP(this.draft,e,t)}panelNotices(){let e=[];return this.support.state===`unsupported`?e.push({type:`availability`,tone:`error`,content:this.support.message??`Utility model settings are not available on ${this.targetLabel}. Update and restart PI WEBUI on that machine, then try again.`}):this.support.state===`unknown`&&e.push({type:`availability`,tone:`warning`,content:this.support.message??`Utility model settings support is unknown for ${this.targetLabel}.`}),this.response?.contractVersion===1&&e.push({type:`info`,content:`Explicit thinking levels require a newer PI WEBUI runtime on ${this.targetLabel}. Model routing remains available.`}),this.error!==``&&e.push({type:`error`,content:this.error}),this.response?.configError!==void 0&&this.response.configError!==``&&e.push({type:`error`,title:`Configuration error`,content:this.response.configError}),this.savedMessage!==``&&e.push({type:`success`,content:this.savedMessage}),e}render(){return g`
|
|
5848
5848
|
<settings-panel-frame
|
|
5849
5849
|
heading="Utility models"
|
|
5850
5850
|
description="Choose machine-global models for utility operations outside active sessions."
|
|
@@ -5875,7 +5875,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5875
5875
|
</footer>
|
|
5876
5876
|
`}
|
|
5877
5877
|
</settings-panel-frame>
|
|
5878
|
-
`}renderFieldRow(e){let t=this.response;if(t===void 0)return g``;let n=
|
|
5878
|
+
`}renderFieldRow(e){let t=this.response;if(t===void 0)return g``;let n=iF[e],r=this.draft[e],i=r===void 0?void 0:t.models.find(e=>oF(e.model,r)),a=qP(this.draft,t).slots[e],o=`select-utility-model-${e}`,s=`select-utility-thinking-${e}`,c=KP(t,r),l=t.contractVersion===2&&i!==void 0?r?.thinkingLevel??`auto`:HP,u=this.editingDisabled||t.contractVersion===1||r===void 0||i===void 0;return g`
|
|
5879
5879
|
<div class="field-row ${a.valid?``:`invalid`}" data-slot=${e}>
|
|
5880
5880
|
<div class="field-copy">
|
|
5881
5881
|
<span class="slot-label">${n.label}</span>
|
|
@@ -5917,7 +5917,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5917
5917
|
</div>
|
|
5918
5918
|
${!a.valid&&a.reason!==void 0&&a.reason!==``?g`<div class="row-error" role="alert">${a.reason}</div>`:null}
|
|
5919
5919
|
</div>
|
|
5920
|
-
`}onModelLabelClick(e){if(!(e.currentTarget instanceof HTMLElement))return;let t=e.currentTarget.nextElementSibling;t instanceof
|
|
5920
|
+
`}onModelLabelClick(e){if(!(e.currentTarget instanceof HTMLElement))return;let t=e.currentTarget.nextElementSibling;t instanceof uP&&t.showPicker()}onModelPicked(e,t){if(t===void 0){this.handleModelChange(e,void 0);return}let n=this.response?.models.find(e=>oF(e.model,t));n!==void 0&&this.handleModelChange(e,n)}onThinkingSelectChange(e,t){if(!(t.target instanceof HTMLSelectElement))return;let n=t.target.value;n!==`auto`&&!Cn(n)||this.handleThinkingChange(e,n)}static{this.styles=h`
|
|
5921
5921
|
:host { display: block; }
|
|
5922
5922
|
.loading-message { color: var(--pi-muted); }
|
|
5923
5923
|
.field-list { display: grid; gap: 14px; }
|
|
@@ -5943,7 +5943,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
5943
5943
|
.panel-footer { display: block; }
|
|
5944
5944
|
button.primary { width: 100%; }
|
|
5945
5945
|
}
|
|
5946
|
-
`}};H([x({attribute:!1})],
|
|
5946
|
+
`}};H([x({attribute:!1})],aF.prototype,`response`,void 0),H([x({type:Boolean})],aF.prototype,`loading`,void 0),H([x({type:Boolean})],aF.prototype,`saving`,void 0),H([x()],aF.prototype,`error`,void 0),H([x()],aF.prototype,`savedMessage`,void 0),H([x()],aF.prototype,`targetLabel`,void 0),H([x({attribute:!1})],aF.prototype,`support`,void 0),H([x({attribute:!1})],aF.prototype,`onReload`,void 0),H([x({attribute:!1})],aF.prototype,`onSave`,void 0),H([S()],aF.prototype,`draft`,void 0),aF=H([b(`settings-utility-models-panel`)],aF);function oF(e,t){return e.provider===t.provider&&e.id===t.id}async function sF(e){let[t,n,r]=await Promise.allSettled([e.loadConfig(),e.loadPlugins(),e.loadSpeechInputSettings()]),i={error:``},a=[];return t.status===`fulfilled`?i.config=t.value:a.push(`config: ${lF(t.reason)}`),n.status===`fulfilled`?i.plugins=n.value:a.push(`PI WEBUI plugins: ${lF(n.reason)}`),r.status===`fulfilled`?i.speechInputSettings=r.value:a.push(`speech input: ${lF(r.reason)}`),a.length>0&&(i.error=`Failed to load settings: ${a.join(`; `)}`),i}async function cF(e,t,n){if(BN(n))return{error:n.message??`Pi package management is not available on ${LN(e)}.`,skipped:!0};try{return{packagesResponse:await t(e.id),error:``}}catch(t){return{error:`Failed to load Pi packages from ${LN(e)}: ${eP(lF(t),e)}`}}}function lF(e){return e instanceof Error?e.message:String(e)}function uF(e,t){return{...e,config:dF(e.config,t.config),effectiveConfig:dF(e.effectiveConfig,t.effectiveConfig)}}function dF(e,t){return{...e,...t.pathAccess===void 0?{}:{pathAccess:t.pathAccess},...t.uploads===void 0?{}:{uploads:t.uploads},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes}}}function fF(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function Y(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function pF(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?E(t,w.selectedMachineSettings)?{state:`supported`}:{state:`unsupported`,message:bF(e)}:{state:`unknown`}}function mF(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?E(t,w.agentProfileConfig)?{state:`supported`}:{state:`unsupported`,message:`Pi-compatible agent profile settings are not available on ${e.name}. Update and restart PI WEBUI on that machine, then try again.`}:{state:`unknown`,message:`Pi-compatible agent profile support could not be verified on ${e.name}. Reload machine status before changing the profile.`}}function hF(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?E(t,w.modelTierSettings)?{state:`supported`}:{state:`unsupported`,message:bF(e)}:{state:`unknown`}}function gF(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?E(t,w.utilityModelSettings)?{state:`supported`}:{state:`unsupported`,message:bF(e)}:{state:`unknown`}}function _F(e){return`${e.state}:${e.message??``}`}function vF(e){return e?.state===`unsupported`}function yF(e){return e?.state===`supported`}function bF(e){return`Selected-machine settings are not available on ${e.name}. Update and restart PI WEBUI on that machine, then try again.`}function xF(e,t){let n=e.trim();return t.kind===`remote`?SF(n)?bF(t):n===`Remote machine timeout`?`Timed out while contacting ${t.name} for selected-machine settings. The operation may still be running remotely; reload before retrying.`:n===`Remote machine unavailable`?`Could not reach ${t.name} for selected-machine settings. Check the machine connection and try again.`:n:n}function SF(e){return e===`Not Found`||/route\s+(GET|PUT):?\/api\/(config|plugins)\b.*not found/iu.test(e)||/cannot\s+(GET|PUT)\s+.*\/api\/(config|plugins)\b/iu.test(e)}function CF(e,t,n){let r=e.plugins??{},i=r[t]??{};return{plugins:{...r,[t]:{...i,enabled:n}}}}function wF(e,t){return{...e,config:TF(e.config,t.config),effectiveConfig:TF(e.effectiveConfig,t.effectiveConfig)}}function TF(e,t){return t.plugins===void 0?e:{...e,plugins:t.plugins}}var X=class extends y{constructor(...e){super(...e),this.section=`general`,this.actions=[],this.showHostSpeechSettings=!1,this.hostSpeechStatusLoading=!1,this.speechInputSettingsRequestSeq=0,this.loading=!0,this.accessLoading=!0,this.sessiondLoading=!0,this.pluginLoading=!0,this.packageLoading=!0,this.modelTiersLoading=!0,this.utilityModelsLoading=!0,this.saving=!1,this.error=``,this.accessError=``,this.sessiondError=``,this.pluginError=``,this.packageError=``,this.modelTiersError=``,this.utilityModelsError=``,this.speechInputAdoptionGeneration=0,this.speechInputCredentialClearGeneration=0,this.savedMessage=``,this.packageMessage=``,this.loadRequestSeq=0,this.accessLoadRequestSeq=0,this.sessiondLoadRequestSeq=0,this.pluginLoadRequestSeq=0,this.packageLoadRequestSeq=0,this.packageMutationSeq=0,this.modelTiersLoadRequestSeq=0,this.utilityModelsLoadRequestSeq=0}connectedCallback(){super.connectedCallback(),this.loadConfig(),this.loadAccessConfigForTarget(),this.reloadSessiondState(),this.loadPluginsForTarget(),this.loadPackagesForTarget(),this.loadModelTiersForTarget(),this.loadUtilityModelsForTarget()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}updated(e){e.has(`speechInputSettings`)&&this.adoptPendingSpeechInputForceAdoption();let t=this.settingsTarget();if(e.has(`machine`)&&fF(e.get(`machine`)).id!==t.id){this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t),this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t),this.resetModelTiersStateForTargetChange(),this.isConnected&&this.loadModelTiersForTarget(t),this.resetUtilityModelsStateForTargetChange(),this.isConnected&&this.loadUtilityModelsForTarget(t);return}e.has(`machineRuntime`)&&(this.selectedMachineSettingsSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t),this.resetModelTiersStateForTargetChange(),this.isConnected&&this.loadModelTiersForTarget(t)),this.utilityModelSettingsSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetUtilityModelsStateForTargetChange(),this.isConnected&&this.loadUtilityModelsForTarget(t)),this.packageManagementSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t)))}render(){return g`
|
|
5947
5947
|
<div class="backdrop" @mousedown=${()=>this.onClose?.()}>
|
|
5948
5948
|
<section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEBUI settings" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
5949
5949
|
<header class="settings-header">
|
|
@@ -6072,7 +6072,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6072
6072
|
<strong>${t}</strong>
|
|
6073
6073
|
<small>${n}</small>
|
|
6074
6074
|
</button>
|
|
6075
|
-
`}navigate(e){this.onNavigate?.(e)}async loadConfig(e=!1){let t=++this.loadRequestSeq;this.pendingSpeechInputForceAdoption?.loadRequestSeq!==t&&(this.pendingSpeechInputForceAdoption=void 0);let n=this.speechInputSettings,r=this.speechInputSettingsRequestSeq;this.loading=!0,this.error=``;try{let i=await oF({loadConfig:()=>Vs.config(),loadPlugins:()=>Hs.plugins(),loadSpeechInputSettings:()=>Ns.settings()});if(!this.isCurrentLoad(t))return;i.config!==void 0&&(this.configResponse=i.config),i.plugins!==void 0&&(this.pluginsResponse=i.plugins);let a=i.speechInputSettings;a!==void 0&&this.speechInputSettings===n&&(this.isSpeechInputSettingsRequestCurrent?.(r)??!0)?(this.speechInputSettings=a,e&&(this.pendingSpeechInputForceAdoption=void 0,this.speechInputAdoptionGeneration+=1),this.onSpeechInputSettingsLoaded?.(a)):e&&a!==void 0&&this.requestSpeechInputForceAdoption(t,n),this.error=i.error}finally{this.isCurrentLoad(t)&&(this.loading=!1)}}async loadAccessConfigForTarget(e=this.settingsTarget()){let t=++this.accessLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(_F(n)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.accessLoading=!0,this.accessError=``;try{let n=await Vs.config(e.id);if(!this.isCurrentAccessLoad(t,e))return;this.accessConfigResponse=n}catch(n){this.isCurrentAccessLoad(t,e)&&(this.accessError=`Failed to load file access/upload config from ${Y(e)}: ${bF(TF(n),e)}`)}finally{this.isCurrentAccessLoad(t,e)&&(this.accessLoading=!1)}}async reloadSessiondState(e=this.settingsTarget()){await Promise.all([this.loadSessiondConfigForTarget(e),this.onRefreshMachineRuntime?.(e.id)])}async loadSessiondConfigForTarget(e=this.settingsTarget()){let t=++this.sessiondLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(_F(n)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.sessiondLoading=!0,this.sessiondError=``;try{let n=await Vs.config(e.id);if(!this.isCurrentSessiondLoad(t,e))return;this.sessiondConfigResponse=n}catch(n){this.isCurrentSessiondLoad(t,e)&&(this.sessiondError=`Failed to load session-daemon config from ${Y(e)}: ${bF(TF(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(_F(n)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.pluginLoading=!0,this.pluginError=``;try{let[n,r]=await Promise.allSettled([Vs.config(e.id),Hs.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let i=[];n.status===`fulfilled`?this.selectedPluginConfigResponse=n.value:i.push(`config: ${bF(TF(n.reason),e)}`),r.status===`fulfilled`?this.selectedPluginsResponse=r.value:i.push(`PI WEBUI plugins: ${bF(TF(r.reason),e)}`),this.pluginError=i.length===0?``:`Failed to load PI WEBUI plugin settings from ${Y(e)}: ${i.join(`; `)}`}finally{this.isCurrentPluginLoad(t,e)&&(this.pluginLoading=!1)}}async loadPackagesForTarget(e=this.packageTarget()){let t=++this.packageLoadRequestSeq;this.packageLoading=!0,this.packageError=``,this.packageMessage=``;try{let n=await sF(e,e=>ec.packages(e),this.packageManagementSupport(e));if(!this.isCurrentPackageLoad(t,e))return;this.packagesResponse=n.packagesResponse,this.packageError=n.error}finally{this.isCurrentPackageLoad(t,e)&&(this.packageLoading=!1)}}async loadModelTiersForTarget(e=this.settingsTarget()){let t=++this.modelTiersLoadRequestSeq,n=this.modelTierSettingsSupport(e);if(_F(n)){this.modelTiersConfigResponse=void 0,this.modelTiersLoading=!1,this.modelTiersError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.modelTiersLoading=!0,this.modelTiersError=``;try{let n=await Ks.settings(e.id);if(!this.isCurrentModelTiersLoad(t,e))return;this.modelTiersConfigResponse=n}catch(n){this.isCurrentModelTiersLoad(t,e)&&(this.modelTiersError=`Failed to load model tier settings from ${Y(e)}: ${bF(TF(n),e)}`)}finally{this.isCurrentModelTiersLoad(t,e)&&(this.modelTiersLoading=!1)}}async loadUtilityModelsForTarget(e=this.settingsTarget()){let t=++this.utilityModelsLoadRequestSeq,n=this.utilityModelSettingsSupport(e);if(_F(n)){this.utilityModelsConfigResponse=void 0,this.utilityModelsLoading=!1,this.utilityModelsError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.utilityModelsLoading=!0,this.utilityModelsError=``;try{let n=await Ys.settings(e.id);if(!this.isCurrentUtilityModelsLoad(t,e))return;this.utilityModelsConfigResponse=n}catch(n){this.isCurrentUtilityModelsLoad(t,e)&&(this.utilityModelsError=`Failed to load utility model settings from ${Y(e)}: ${bF(TF(n),e)}`)}finally{this.isCurrentUtilityModelsLoad(t,e)&&(this.utilityModelsLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;let n=this.settingsTarget(),r=this.selectedMachineSettingsSupport(n);if(_F(r)){this.pluginError=r.message??`Selected-machine settings are not available on ${Y(n)}.`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${Y(n)}. Reload before changing plugin enablement.`;return}let i=SF(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await Vs.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=CF(this.configResponse,e),this.onConfigSaved?.(this.configResponse.effectiveConfig));let t=await this.refreshPluginsForTarget(n);if(!this.isCurrentSettingsTarget(n))return;t!==void 0&&(this.pluginError=t),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(n)&&(this.pluginError=`Failed to save PI WEBUI plugin config on ${Y(n)}: ${bF(TF(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await Vs.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`Failed to save config: ${TF(e)}`}finally{this.saving=!1}}}async saveSpeechInputSettings(e){if(this.saving)throw Error(`A settings operation is already running.`);this.saving=!0,this.savedMessage=``;try{let t=await Ns.saveSettings(e);return this.speechInputSettings=t,e.credential.action===`clear`?this.speechInputCredentialClearGeneration+=1:this.speechInputAdoptionGeneration+=1,this.onSpeechInputSettingsSaved?.(t),this.showSavedMessage(),t}finally{this.saving=!1}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(_F(n)){this.accessError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await Vs.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=lF(this.configResponse,n),this.onConfigSaved?.(this.configResponse.effectiveConfig)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.accessError=`Failed to save file access/upload config on ${Y(t)}: ${bF(TF(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(_F(n)){this.sessiondError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}if(e.agent!==void 0){let e=this.agentProfileSettingsSupport(t);if(!vF(e)){this.sessiondError=e.message??`Pi-compatible agent profile settings are not available on ${Y(t)}.`;return}}this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await Vs.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=DN(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${Y(t)}: ${bF(TF(e),t)}`)}finally{this.saving=!1}}async saveModelTiers(e){if(this.saving)return;let t=this.settingsTarget(),n=this.modelTierSettingsSupport(t);if(_F(n)){this.modelTiersError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.modelTiersError=``,this.savedMessage=``;try{let n=await Ks.save(e,t.id);if(!this.isCurrentSettingsTarget(t))return;if(this.modelTiersConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&n.ladder!==void 0){let e=n.ladder;this.configResponse={...this.configResponse,config:{...this.configResponse.config,modelTiers:e},effectiveConfig:{...this.configResponse.effectiveConfig,modelTiers:e}},this.onConfigSaved?.(this.configResponse.effectiveConfig)}this.onModelTiersSaved?.(t.id,n),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.modelTiersError=`Failed to save model tier settings on ${Y(t)}: ${bF(TF(e),t)}`)}finally{this.saving=!1}}async saveUtilityModels(e){if(this.saving)return;let t=this.settingsTarget(),n=this.utilityModelsConfigResponse;if(n===void 0){this.utilityModelsError=`Utility model settings must be loaded before saving.`;return}let r=this.utilityModelSettingsSupport(t);if(_F(r)){this.utilityModelsError=r.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.utilityModelsError=``,this.savedMessage=``;try{let r=await Ys.save(e,n.contractVersion,t.id);if(!this.isCurrentSettingsTarget(t))return;if(this.utilityModelsConfigResponse=r,t.kind===`local`&&this.configResponse!==void 0){let e=r.settings;this.configResponse={...this.configResponse,config:{...this.configResponse.config,utilityModels:e},effectiveConfig:{...this.configResponse.effectiveConfig,utilityModels:e}},this.onConfigSaved?.(this.configResponse.effectiveConfig)}this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.utilityModelsError=`Failed to save utility model settings on ${Y(t)}: ${bF(TF(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`install Pi package`,t,()=>ec.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`remove Pi package`,n,()=>ec.remove(e,t,n.id))}async updatePiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation(e===void 0?{kind:`update-all`}:{kind:`update`,source:e},`update Pi packages`,t,()=>ec.update(e,t.id))}async runPiPackageMutation(e,t,n,r){let i=this.packageManagementSupport(n);if(zN(i))throw this.packageError=i.message??`Pi package management is not available on ${IN(n)}.`,Error(this.packageError);if(this.saving)throw Error(`A settings operation is already running.`);let a=++this.packageMutationSeq;this.packageLoadRequestSeq+=1,this.packageLoading=!1,this.saving=!0,this.packageOperation=e,this.packageError=``,this.packageMessage=``;try{let e=await r();if(!this.isCurrentPackageMutation(a,n))return;this.packagesResponse={packages:e.packages};let t=VN(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(a,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=QN(e.action,n)}catch(e){throw this.isCurrentPackageMutation(a,n)&&(this.packageError=`Failed to ${t} on ${IN(n)}: ${$N(TF(e),n)}`),e}finally{this.packageMutationSeq===a&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await Hs.plugins();return}catch(e){return`Failed to refresh gateway PI WEBUI plugins: ${TF(e)}`}}async refreshPluginsForTarget(e){try{let t=await Hs.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`Config saved, but failed to refresh PI WEBUI plugins from ${Y(e)}: ${bF(TF(t),e)}`}}settingsTarget(){return dF(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return fF(e,this.machineRuntime)}agentProfileSettingsSupport(e=this.settingsTarget()){return pF(e,this.machineRuntime)}modelTierSettingsSupport(e=this.settingsTarget()){return mF(e,this.machineRuntime)}utilityModelSettingsSupport(e=this.settingsTarget()){return hF(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){let n=fF(t,e),r=this.selectedMachineSettingsSupport(t);return gF(n)!==gF(r)}utilityModelSettingsSupportNeedsReload(e,t){let n=hF(t,e),r=this.utilityModelSettingsSupport(t);return gF(n)!==gF(r)}packageManagementSupport(e=this.packageTarget()){return LN(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){let n=LN(t,e),r=this.packageManagementSupport(t);return RN(n)===RN(r)?!1:n.state===`unsupported`||r.state===`unsupported`}isCurrentLoad(e){return e===this.loadRequestSeq}requestSpeechInputForceAdoption(e,t){if(this.isCurrentLoad(e)){if(this.speechInputSettings!==t){this.speechInputAdoptionGeneration+=1;return}this.pendingSpeechInputForceAdoption={loadRequestSeq:e,startingSnapshot:t}}}adoptPendingSpeechInputForceAdoption(){let e=this.pendingSpeechInputForceAdoption;e===void 0||!this.isCurrentLoad(e.loadRequestSeq)||this.speechInputSettings!==e.startingSnapshot&&(this.pendingSpeechInputForceAdoption=void 0,this.speechInputAdoptionGeneration+=1)}isCurrentAccessLoad(e,t){return e===this.accessLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentSessiondLoad(e,t){return e===this.sessiondLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPluginLoad(e,t){return e===this.pluginLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentModelTiersLoad(e,t){return e===this.modelTiersLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentUtilityModelsLoad(e,t){return e===this.utilityModelsLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPackageLoad(e,t){return e===this.packageLoadRequestSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageMutation(e,t){return e===this.packageMutationSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageTarget(e){return this.packageTarget().id===e.id}isCurrentSettingsTarget(e){return this.settingsTarget().id===e.id}resetAccessStateForTargetChange(){this.accessLoadRequestSeq+=1,this.accessLoading=!1,this.accessError=``,this.accessConfigResponse=void 0,this.savedMessage=``}resetSessiondStateForTargetChange(){this.sessiondLoadRequestSeq+=1,this.sessiondLoading=!1,this.sessiondError=``,this.sessiondConfigResponse=void 0,this.savedMessage=``}resetPluginStateForTargetChange(){this.pluginLoadRequestSeq+=1,this.pluginLoading=!1,this.pluginError=``,this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.savedMessage=``}resetPackageStateForTargetChange(){let e=this.packageOperation!==void 0;this.packageLoadRequestSeq+=1,this.packageMutationSeq+=1,this.packageLoading=!1,this.packageOperation=void 0,this.packageMessage=``,this.packageError=``,this.packagesResponse=void 0,e&&(this.saving=!1)}resetModelTiersStateForTargetChange(){this.modelTiersLoadRequestSeq+=1,this.modelTiersLoading=!1,this.modelTiersError=``,this.modelTiersConfigResponse=void 0,this.savedMessage=``}resetUtilityModelsStateForTargetChange(){this.utilityModelsLoadRequestSeq+=1,this.utilityModelsLoading=!1,this.utilityModelsError=``,this.utilityModelsConfigResponse=void 0,this.savedMessage=``}showSavedMessage(){this.savedMessage=`Config saved.`,this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage===`Config saved.`&&(this.savedMessage=``),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}static{this.styles=h`
|
|
6075
|
+
`}navigate(e){this.onNavigate?.(e)}async loadConfig(e=!1){let t=++this.loadRequestSeq;this.pendingSpeechInputForceAdoption?.loadRequestSeq!==t&&(this.pendingSpeechInputForceAdoption=void 0);let n=this.speechInputSettings,r=this.speechInputSettingsRequestSeq;this.loading=!0,this.error=``;try{let i=await sF({loadConfig:()=>Vs.config(),loadPlugins:()=>Hs.plugins(),loadSpeechInputSettings:()=>Ns.settings()});if(!this.isCurrentLoad(t))return;i.config!==void 0&&(this.configResponse=i.config),i.plugins!==void 0&&(this.pluginsResponse=i.plugins);let a=i.speechInputSettings;a!==void 0&&this.speechInputSettings===n&&(this.isSpeechInputSettingsRequestCurrent?.(r)??!0)?(this.speechInputSettings=a,e&&(this.pendingSpeechInputForceAdoption=void 0,this.speechInputAdoptionGeneration+=1),this.onSpeechInputSettingsLoaded?.(a)):e&&a!==void 0&&this.requestSpeechInputForceAdoption(t,n),this.error=i.error}finally{this.isCurrentLoad(t)&&(this.loading=!1)}}async loadAccessConfigForTarget(e=this.settingsTarget()){let t=++this.accessLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(vF(n)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.accessLoading=!0,this.accessError=``;try{let n=await Vs.config(e.id);if(!this.isCurrentAccessLoad(t,e))return;this.accessConfigResponse=n}catch(n){this.isCurrentAccessLoad(t,e)&&(this.accessError=`Failed to load file access/upload config from ${Y(e)}: ${xF(EF(n),e)}`)}finally{this.isCurrentAccessLoad(t,e)&&(this.accessLoading=!1)}}async reloadSessiondState(e=this.settingsTarget()){await Promise.all([this.loadSessiondConfigForTarget(e),this.onRefreshMachineRuntime?.(e.id)])}async loadSessiondConfigForTarget(e=this.settingsTarget()){let t=++this.sessiondLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(vF(n)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.sessiondLoading=!0,this.sessiondError=``;try{let n=await Vs.config(e.id);if(!this.isCurrentSessiondLoad(t,e))return;this.sessiondConfigResponse=n}catch(n){this.isCurrentSessiondLoad(t,e)&&(this.sessiondError=`Failed to load session-daemon config from ${Y(e)}: ${xF(EF(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(vF(n)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.pluginLoading=!0,this.pluginError=``;try{let[n,r]=await Promise.allSettled([Vs.config(e.id),Hs.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let i=[];n.status===`fulfilled`?this.selectedPluginConfigResponse=n.value:i.push(`config: ${xF(EF(n.reason),e)}`),r.status===`fulfilled`?this.selectedPluginsResponse=r.value:i.push(`PI WEBUI plugins: ${xF(EF(r.reason),e)}`),this.pluginError=i.length===0?``:`Failed to load PI WEBUI plugin settings from ${Y(e)}: ${i.join(`; `)}`}finally{this.isCurrentPluginLoad(t,e)&&(this.pluginLoading=!1)}}async loadPackagesForTarget(e=this.packageTarget()){let t=++this.packageLoadRequestSeq;this.packageLoading=!0,this.packageError=``,this.packageMessage=``;try{let n=await cF(e,e=>ec.packages(e),this.packageManagementSupport(e));if(!this.isCurrentPackageLoad(t,e))return;this.packagesResponse=n.packagesResponse,this.packageError=n.error}finally{this.isCurrentPackageLoad(t,e)&&(this.packageLoading=!1)}}async loadModelTiersForTarget(e=this.settingsTarget()){let t=++this.modelTiersLoadRequestSeq,n=this.modelTierSettingsSupport(e);if(vF(n)){this.modelTiersConfigResponse=void 0,this.modelTiersLoading=!1,this.modelTiersError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.modelTiersLoading=!0,this.modelTiersError=``;try{let n=await Ks.settings(e.id);if(!this.isCurrentModelTiersLoad(t,e))return;this.modelTiersConfigResponse=n}catch(n){this.isCurrentModelTiersLoad(t,e)&&(this.modelTiersError=`Failed to load model tier settings from ${Y(e)}: ${xF(EF(n),e)}`)}finally{this.isCurrentModelTiersLoad(t,e)&&(this.modelTiersLoading=!1)}}async loadUtilityModelsForTarget(e=this.settingsTarget()){let t=++this.utilityModelsLoadRequestSeq,n=this.utilityModelSettingsSupport(e);if(vF(n)){this.utilityModelsConfigResponse=void 0,this.utilityModelsLoading=!1,this.utilityModelsError=n.message??`Selected-machine settings are not available on ${Y(e)}.`;return}this.utilityModelsLoading=!0,this.utilityModelsError=``;try{let n=await Ys.settings(e.id);if(!this.isCurrentUtilityModelsLoad(t,e))return;this.utilityModelsConfigResponse=n}catch(n){this.isCurrentUtilityModelsLoad(t,e)&&(this.utilityModelsError=`Failed to load utility model settings from ${Y(e)}: ${xF(EF(n),e)}`)}finally{this.isCurrentUtilityModelsLoad(t,e)&&(this.utilityModelsLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;let n=this.settingsTarget(),r=this.selectedMachineSettingsSupport(n);if(vF(r)){this.pluginError=r.message??`Selected-machine settings are not available on ${Y(n)}.`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${Y(n)}. Reload before changing plugin enablement.`;return}let i=CF(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await Vs.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=wF(this.configResponse,e),this.onConfigSaved?.(this.configResponse.effectiveConfig));let t=await this.refreshPluginsForTarget(n);if(!this.isCurrentSettingsTarget(n))return;t!==void 0&&(this.pluginError=t),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(n)&&(this.pluginError=`Failed to save PI WEBUI plugin config on ${Y(n)}: ${xF(EF(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await Vs.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`Failed to save config: ${EF(e)}`}finally{this.saving=!1}}}async saveSpeechInputSettings(e){if(this.saving)throw Error(`A settings operation is already running.`);this.saving=!0,this.savedMessage=``;try{let t=await Ns.saveSettings(e);return this.speechInputSettings=t,e.credential.action===`clear`?this.speechInputCredentialClearGeneration+=1:this.speechInputAdoptionGeneration+=1,this.onSpeechInputSettingsSaved?.(t),this.showSavedMessage(),t}finally{this.saving=!1}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(vF(n)){this.accessError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await Vs.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=uF(this.configResponse,n),this.onConfigSaved?.(this.configResponse.effectiveConfig)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.accessError=`Failed to save file access/upload config on ${Y(t)}: ${xF(EF(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(vF(n)){this.sessiondError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}if(e.agent!==void 0){let e=this.agentProfileSettingsSupport(t);if(!yF(e)){this.sessiondError=e.message??`Pi-compatible agent profile settings are not available on ${Y(t)}.`;return}}this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await Vs.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=ON(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${Y(t)}: ${xF(EF(e),t)}`)}finally{this.saving=!1}}async saveModelTiers(e){if(this.saving)return;let t=this.settingsTarget(),n=this.modelTierSettingsSupport(t);if(vF(n)){this.modelTiersError=n.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.modelTiersError=``,this.savedMessage=``;try{let n=await Ks.save(e,t.id);if(!this.isCurrentSettingsTarget(t))return;if(this.modelTiersConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&n.ladder!==void 0){let e=n.ladder;this.configResponse={...this.configResponse,config:{...this.configResponse.config,modelTiers:e},effectiveConfig:{...this.configResponse.effectiveConfig,modelTiers:e}},this.onConfigSaved?.(this.configResponse.effectiveConfig)}this.onModelTiersSaved?.(t.id,n),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.modelTiersError=`Failed to save model tier settings on ${Y(t)}: ${xF(EF(e),t)}`)}finally{this.saving=!1}}async saveUtilityModels(e){if(this.saving)return;let t=this.settingsTarget(),n=this.utilityModelsConfigResponse;if(n===void 0){this.utilityModelsError=`Utility model settings must be loaded before saving.`;return}let r=this.utilityModelSettingsSupport(t);if(vF(r)){this.utilityModelsError=r.message??`Selected-machine settings are not available on ${Y(t)}.`;return}this.saving=!0,this.utilityModelsError=``,this.savedMessage=``;try{let r=await Ys.save(e,n.contractVersion,t.id);if(!this.isCurrentSettingsTarget(t))return;if(this.utilityModelsConfigResponse=r,t.kind===`local`&&this.configResponse!==void 0){let e=r.settings;this.configResponse={...this.configResponse,config:{...this.configResponse.config,utilityModels:e},effectiveConfig:{...this.configResponse.effectiveConfig,utilityModels:e}},this.onConfigSaved?.(this.configResponse.effectiveConfig)}this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.utilityModelsError=`Failed to save utility model settings on ${Y(t)}: ${xF(EF(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`install Pi package`,t,()=>ec.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`remove Pi package`,n,()=>ec.remove(e,t,n.id))}async updatePiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation(e===void 0?{kind:`update-all`}:{kind:`update`,source:e},`update Pi packages`,t,()=>ec.update(e,t.id))}async runPiPackageMutation(e,t,n,r){let i=this.packageManagementSupport(n);if(BN(i))throw this.packageError=i.message??`Pi package management is not available on ${LN(n)}.`,Error(this.packageError);if(this.saving)throw Error(`A settings operation is already running.`);let a=++this.packageMutationSeq;this.packageLoadRequestSeq+=1,this.packageLoading=!1,this.saving=!0,this.packageOperation=e,this.packageError=``,this.packageMessage=``;try{let e=await r();if(!this.isCurrentPackageMutation(a,n))return;this.packagesResponse={packages:e.packages};let t=HN(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(a,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=$N(e.action,n)}catch(e){throw this.isCurrentPackageMutation(a,n)&&(this.packageError=`Failed to ${t} on ${LN(n)}: ${eP(EF(e),n)}`),e}finally{this.packageMutationSeq===a&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await Hs.plugins();return}catch(e){return`Failed to refresh gateway PI WEBUI plugins: ${EF(e)}`}}async refreshPluginsForTarget(e){try{let t=await Hs.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`Config saved, but failed to refresh PI WEBUI plugins from ${Y(e)}: ${xF(EF(t),e)}`}}settingsTarget(){return fF(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return pF(e,this.machineRuntime)}agentProfileSettingsSupport(e=this.settingsTarget()){return mF(e,this.machineRuntime)}modelTierSettingsSupport(e=this.settingsTarget()){return hF(e,this.machineRuntime)}utilityModelSettingsSupport(e=this.settingsTarget()){return gF(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){let n=pF(t,e),r=this.selectedMachineSettingsSupport(t);return _F(n)!==_F(r)}utilityModelSettingsSupportNeedsReload(e,t){let n=gF(t,e),r=this.utilityModelSettingsSupport(t);return _F(n)!==_F(r)}packageManagementSupport(e=this.packageTarget()){return RN(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){let n=RN(t,e),r=this.packageManagementSupport(t);return zN(n)===zN(r)?!1:n.state===`unsupported`||r.state===`unsupported`}isCurrentLoad(e){return e===this.loadRequestSeq}requestSpeechInputForceAdoption(e,t){if(this.isCurrentLoad(e)){if(this.speechInputSettings!==t){this.speechInputAdoptionGeneration+=1;return}this.pendingSpeechInputForceAdoption={loadRequestSeq:e,startingSnapshot:t}}}adoptPendingSpeechInputForceAdoption(){let e=this.pendingSpeechInputForceAdoption;e===void 0||!this.isCurrentLoad(e.loadRequestSeq)||this.speechInputSettings!==e.startingSnapshot&&(this.pendingSpeechInputForceAdoption=void 0,this.speechInputAdoptionGeneration+=1)}isCurrentAccessLoad(e,t){return e===this.accessLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentSessiondLoad(e,t){return e===this.sessiondLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPluginLoad(e,t){return e===this.pluginLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentModelTiersLoad(e,t){return e===this.modelTiersLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentUtilityModelsLoad(e,t){return e===this.utilityModelsLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPackageLoad(e,t){return e===this.packageLoadRequestSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageMutation(e,t){return e===this.packageMutationSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageTarget(e){return this.packageTarget().id===e.id}isCurrentSettingsTarget(e){return this.settingsTarget().id===e.id}resetAccessStateForTargetChange(){this.accessLoadRequestSeq+=1,this.accessLoading=!1,this.accessError=``,this.accessConfigResponse=void 0,this.savedMessage=``}resetSessiondStateForTargetChange(){this.sessiondLoadRequestSeq+=1,this.sessiondLoading=!1,this.sessiondError=``,this.sessiondConfigResponse=void 0,this.savedMessage=``}resetPluginStateForTargetChange(){this.pluginLoadRequestSeq+=1,this.pluginLoading=!1,this.pluginError=``,this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.savedMessage=``}resetPackageStateForTargetChange(){let e=this.packageOperation!==void 0;this.packageLoadRequestSeq+=1,this.packageMutationSeq+=1,this.packageLoading=!1,this.packageOperation=void 0,this.packageMessage=``,this.packageError=``,this.packagesResponse=void 0,e&&(this.saving=!1)}resetModelTiersStateForTargetChange(){this.modelTiersLoadRequestSeq+=1,this.modelTiersLoading=!1,this.modelTiersError=``,this.modelTiersConfigResponse=void 0,this.savedMessage=``}resetUtilityModelsStateForTargetChange(){this.utilityModelsLoadRequestSeq+=1,this.utilityModelsLoading=!1,this.utilityModelsError=``,this.utilityModelsConfigResponse=void 0,this.savedMessage=``}showSavedMessage(){this.savedMessage=`Config saved.`,this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage===`Config saved.`&&(this.savedMessage=``),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}static{this.styles=h`
|
|
6076
6076
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
6077
6077
|
.backdrop { box-sizing: border-box; width: 100%; height: 100dvh; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-overlay); overflow: hidden; }
|
|
6078
6078
|
.settings-shell { width: min(980px, 100%); max-height: min(760px, 100%); min-height: min(620px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr); border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
|
|
@@ -6099,7 +6099,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6099
6099
|
.settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
|
|
6100
6100
|
.settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
|
|
6101
6101
|
}
|
|
6102
|
-
`}};H([x({attribute:!1})],X.prototype,`section`,void 0),H([x({attribute:!1})],X.prototype,`actions`,void 0),H([x({attribute:!1})],X.prototype,`machine`,void 0),H([x({attribute:!1})],X.prototype,`machineRuntime`,void 0),H([x({attribute:!1})],X.prototype,`onNavigate`,void 0),H([x({attribute:!1})],X.prototype,`onClose`,void 0),H([x({attribute:!1})],X.prototype,`onConfigSaved`,void 0),H([x({attribute:!1})],X.prototype,`onRefreshMachineRuntime`,void 0),H([x({attribute:!1})],X.prototype,`onModelTiersSaved`,void 0),H([x({type:Boolean})],X.prototype,`showHostSpeechSettings`,void 0),H([x({attribute:!1})],X.prototype,`hostSpeechStatus`,void 0),H([x({type:Boolean})],X.prototype,`hostSpeechStatusLoading`,void 0),H([x({attribute:!1})],X.prototype,`onReloadHostSpeech`,void 0),H([x({attribute:!1})],X.prototype,`speechInputSettings`,void 0),H([x({attribute:!1})],X.prototype,`speechInputSettingsRequestSeq`,void 0),H([x({attribute:!1})],X.prototype,`isSpeechInputSettingsRequestCurrent`,void 0),H([x({attribute:!1})],X.prototype,`onSpeechInputSettingsLoaded`,void 0),H([x({attribute:!1})],X.prototype,`onSpeechInputSettingsSaved`,void 0),H([S()],X.prototype,`configResponse`,void 0),H([S()],X.prototype,`accessConfigResponse`,void 0),H([S()],X.prototype,`sessiondConfigResponse`,void 0),H([S()],X.prototype,`pluginsResponse`,void 0),H([S()],X.prototype,`selectedPluginConfigResponse`,void 0),H([S()],X.prototype,`selectedPluginsResponse`,void 0),H([S()],X.prototype,`packagesResponse`,void 0),H([S()],X.prototype,`modelTiersConfigResponse`,void 0),H([S()],X.prototype,`utilityModelsConfigResponse`,void 0),H([S()],X.prototype,`loading`,void 0),H([S()],X.prototype,`accessLoading`,void 0),H([S()],X.prototype,`sessiondLoading`,void 0),H([S()],X.prototype,`pluginLoading`,void 0),H([S()],X.prototype,`packageLoading`,void 0),H([S()],X.prototype,`modelTiersLoading`,void 0),H([S()],X.prototype,`utilityModelsLoading`,void 0),H([S()],X.prototype,`saving`,void 0),H([S()],X.prototype,`packageOperation`,void 0),H([S()],X.prototype,`error`,void 0),H([S()],X.prototype,`accessError`,void 0),H([S()],X.prototype,`sessiondError`,void 0),H([S()],X.prototype,`pluginError`,void 0),H([S()],X.prototype,`packageError`,void 0),H([S()],X.prototype,`modelTiersError`,void 0),H([S()],X.prototype,`utilityModelsError`,void 0),H([S()],X.prototype,`speechInputAdoptionGeneration`,void 0),H([S()],X.prototype,`speechInputCredentialClearGeneration`,void 0),H([S()],X.prototype,`savedMessage`,void 0),H([S()],X.prototype,`packageMessage`,void 0),X=H([b(`settings-dialog`)],X);function
|
|
6102
|
+
`}};H([x({attribute:!1})],X.prototype,`section`,void 0),H([x({attribute:!1})],X.prototype,`actions`,void 0),H([x({attribute:!1})],X.prototype,`machine`,void 0),H([x({attribute:!1})],X.prototype,`machineRuntime`,void 0),H([x({attribute:!1})],X.prototype,`onNavigate`,void 0),H([x({attribute:!1})],X.prototype,`onClose`,void 0),H([x({attribute:!1})],X.prototype,`onConfigSaved`,void 0),H([x({attribute:!1})],X.prototype,`onRefreshMachineRuntime`,void 0),H([x({attribute:!1})],X.prototype,`onModelTiersSaved`,void 0),H([x({type:Boolean})],X.prototype,`showHostSpeechSettings`,void 0),H([x({attribute:!1})],X.prototype,`hostSpeechStatus`,void 0),H([x({type:Boolean})],X.prototype,`hostSpeechStatusLoading`,void 0),H([x({attribute:!1})],X.prototype,`onReloadHostSpeech`,void 0),H([x({attribute:!1})],X.prototype,`speechInputSettings`,void 0),H([x({attribute:!1})],X.prototype,`speechInputSettingsRequestSeq`,void 0),H([x({attribute:!1})],X.prototype,`isSpeechInputSettingsRequestCurrent`,void 0),H([x({attribute:!1})],X.prototype,`onSpeechInputSettingsLoaded`,void 0),H([x({attribute:!1})],X.prototype,`onSpeechInputSettingsSaved`,void 0),H([S()],X.prototype,`configResponse`,void 0),H([S()],X.prototype,`accessConfigResponse`,void 0),H([S()],X.prototype,`sessiondConfigResponse`,void 0),H([S()],X.prototype,`pluginsResponse`,void 0),H([S()],X.prototype,`selectedPluginConfigResponse`,void 0),H([S()],X.prototype,`selectedPluginsResponse`,void 0),H([S()],X.prototype,`packagesResponse`,void 0),H([S()],X.prototype,`modelTiersConfigResponse`,void 0),H([S()],X.prototype,`utilityModelsConfigResponse`,void 0),H([S()],X.prototype,`loading`,void 0),H([S()],X.prototype,`accessLoading`,void 0),H([S()],X.prototype,`sessiondLoading`,void 0),H([S()],X.prototype,`pluginLoading`,void 0),H([S()],X.prototype,`packageLoading`,void 0),H([S()],X.prototype,`modelTiersLoading`,void 0),H([S()],X.prototype,`utilityModelsLoading`,void 0),H([S()],X.prototype,`saving`,void 0),H([S()],X.prototype,`packageOperation`,void 0),H([S()],X.prototype,`error`,void 0),H([S()],X.prototype,`accessError`,void 0),H([S()],X.prototype,`sessiondError`,void 0),H([S()],X.prototype,`pluginError`,void 0),H([S()],X.prototype,`packageError`,void 0),H([S()],X.prototype,`modelTiersError`,void 0),H([S()],X.prototype,`utilityModelsError`,void 0),H([S()],X.prototype,`speechInputAdoptionGeneration`,void 0),H([S()],X.prototype,`speechInputCredentialClearGeneration`,void 0),H([S()],X.prototype,`savedMessage`,void 0),H([S()],X.prototype,`packageMessage`,void 0),X=H([b(`settings-dialog`)],X);function EF(e){return e instanceof Error?e.message:String(e)}var DF=class extends y{constructor(...e){super(...e),this.sessionsApi=cc,this.loading=!0,this.error=``,this.loadRequestSequence=0}connectedCallback(){super.connectedCallback(),this.loadSystemPrompt()}updated(e){let t=e.has(`session`)&&kF(e.get(`session`))!==kF(this.session),n=e.has(`machine`)&&OF(e.get(`machine`))!==OF(this.machine);(t||n)&&this.isConnected&&this.loadSystemPrompt()}render(){return g`
|
|
6103
6103
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
6104
6104
|
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="system-prompt-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
6105
6105
|
<header>
|
|
@@ -6108,7 +6108,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6108
6108
|
<h1 id="system-prompt-dialog-title">System prompt</h1>
|
|
6109
6109
|
</div>
|
|
6110
6110
|
<button class="icon-button" type="button" title="Close system prompt" aria-label="Close system prompt" @click=${()=>{this.close()}}>
|
|
6111
|
-
${
|
|
6111
|
+
${NF()}
|
|
6112
6112
|
</button>
|
|
6113
6113
|
</header>
|
|
6114
6114
|
<div class="prompt-body" aria-live="polite">
|
|
@@ -6119,7 +6119,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6119
6119
|
</footer>
|
|
6120
6120
|
</section>
|
|
6121
6121
|
</div>
|
|
6122
|
-
`}renderPrompt(){return this.loading?g`<p class="prompt-state">Loading system prompt…</p>`:this.error===``?this.systemPrompt===void 0?g`<p class="prompt-state">Send a message to load the system prompt</p>`:this.systemPrompt===``?g`<p class="prompt-state">System prompt is empty (tools are disabled)</p>`:g`<pre class="system-prompt">${this.systemPrompt}</pre>`:g`<p class="prompt-state error">${this.error}</p>`}async loadSystemPrompt(){let e=this.session,t=e===void 0?void 0:
|
|
6122
|
+
`}renderPrompt(){return this.loading?g`<p class="prompt-state">Loading system prompt…</p>`:this.error===``?this.systemPrompt===void 0?g`<p class="prompt-state">Send a message to load the system prompt</p>`:this.systemPrompt===``?g`<p class="prompt-state">System prompt is empty (tools are disabled)</p>`:g`<pre class="system-prompt">${this.systemPrompt}</pre>`:g`<p class="prompt-state error">${this.error}</p>`}async loadSystemPrompt(){let e=this.session,t=e===void 0?void 0:jF(OF(this.machine),e),n=++this.loadRequestSequence;if(this.loading=!0,this.error=``,this.systemPrompt=void 0,e===void 0||t===void 0){this.loading=!1;return}try{let r=await this.sessionsApi.systemPrompt(e,OF(this.machine));if(!this.isCurrentLoad(n,t))return;this.systemPrompt=r.systemPrompt}catch(e){if(!this.isCurrentLoad(n,t))return;this.error=`Failed to load system prompt: ${MF(e)}`}finally{this.isCurrentLoad(n,t)&&(this.loading=!1)}}isCurrentLoad(e,t){let n=this.session;return e===this.loadRequestSequence&&n!==void 0&&jF(OF(this.machine),n)===t}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}close(){this.onClose?.()}static{this.styles=h`
|
|
6123
6123
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
6124
6124
|
* { box-sizing: border-box; }
|
|
6125
6125
|
.backdrop { box-sizing: border-box; width: 100%; height: 100dvh; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-overlay); overflow: hidden; }
|
|
@@ -6145,11 +6145,11 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6145
6145
|
header, footer { padding: 12px; }
|
|
6146
6146
|
.system-prompt, .prompt-state { padding: 12px; }
|
|
6147
6147
|
}
|
|
6148
|
-
`}};H([x({attribute:!1})],
|
|
6148
|
+
`}};H([x({attribute:!1})],DF.prototype,`machine`,void 0),H([x({attribute:!1})],DF.prototype,`session`,void 0),H([x({attribute:!1})],DF.prototype,`sessionsApi`,void 0),H([x({attribute:!1})],DF.prototype,`onClose`,void 0),H([S()],DF.prototype,`systemPrompt`,void 0),H([S()],DF.prototype,`loading`,void 0),H([S()],DF.prototype,`error`,void 0),DF=H([b(`system-prompt-dialog`)],DF);function OF(e){return e?.id??`local`}function kF(e){return e===void 0?void 0:AF(e)}function AF(e){return JSON.stringify([e.id,e.cwd])}function jF(e,t){return JSON.stringify([e,t.id,t.cwd])}function MF(e){return e instanceof Error?e.message:String(e)}function NF(){return _`
|
|
6149
6149
|
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
6150
6150
|
<path d="M6 6l12 12M18 6 6 18"></path>
|
|
6151
6151
|
</svg>
|
|
6152
|
-
`}var
|
|
6152
|
+
`}var PF=class extends y{constructor(...e){super(...e),this.tabs=[],this.tool=`core:workspace.files`,this.hiddenTools=[],this.hideToolTabs=!1,this.onSelectTool=()=>void 0,this.workspaceHeaderCanScrollLeft=!1,this.workspaceHeaderCanScrollRight=!1,this.onWorkspaceHeaderScroll=()=>{this.updateWorkspaceHeaderScrollState()}}firstUpdated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}updated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}disconnectedCallback(){this.workspaceHeaderResizeObserver?.disconnect(),this.workspaceHeaderResizeObserver=void 0,this.observedWorkspaceHeaderStrip=void 0,super.disconnectedCallback()}render(){let e=this.tabs;if(e.length===0)return this.renderEmptyState(this.emptyState??{title:`Select a workspace`,body:`Choose a workspace to inspect files, Git, or terminals.`});let t=e.filter(e=>!this.hiddenTools.includes(e.id)),n=e.find(e=>e.id===this.tool)??t[0]??e[0];return g`
|
|
6153
6153
|
${this.hideToolTabs?null:g`
|
|
6154
6154
|
<header>
|
|
6155
6155
|
<div class=${this.workspaceHeaderFrameClass()}>
|
|
@@ -6179,16 +6179,16 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6179
6179
|
<h2>${e.title}</h2>
|
|
6180
6180
|
${e.body===void 0?null:g`<p>${e.body}</p>`}
|
|
6181
6181
|
</section>
|
|
6182
|
-
`}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?` can-scroll-left`:``}${this.workspaceHeaderCanScrollRight?` can-scroll-right`:``}`}observeWorkspaceHeaderStrip(){let e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>`u`)&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){let e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=e!==void 0&&e.scrollLeft>1,r=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==n&&(this.workspaceHeaderCanScrollLeft=n),this.workspaceHeaderCanScrollRight!==r&&(this.workspaceHeaderCanScrollRight=r)}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=Xy}};H([x({attribute:!1})],
|
|
6182
|
+
`}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?` can-scroll-left`:``}${this.workspaceHeaderCanScrollRight?` can-scroll-right`:``}`}observeWorkspaceHeaderStrip(){let e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>`u`)&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){let e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=e!==void 0&&e.scrollLeft>1,r=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==n&&(this.workspaceHeaderCanScrollLeft=n),this.workspaceHeaderCanScrollRight!==r&&(this.workspaceHeaderCanScrollRight=r)}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=Xy}};H([x({attribute:!1})],PF.prototype,`tabs`,void 0),H([x({attribute:!1})],PF.prototype,`emptyState`,void 0),H([x()],PF.prototype,`tool`,void 0),H([x({attribute:!1})],PF.prototype,`hiddenTools`,void 0),H([x({type:Boolean})],PF.prototype,`hideToolTabs`,void 0),H([x({attribute:!1})],PF.prototype,`onSelectTool`,void 0),H([C(`.workspace-header-strip`)],PF.prototype,`workspaceHeaderStrip`,void 0),H([S()],PF.prototype,`workspaceHeaderCanScrollLeft`,void 0),H([S()],PF.prototype,`workspaceHeaderCanScrollRight`,void 0),PF=H([b(`workspace-panel`)],PF);function FF(e,t){return t.find(t=>t.path===e.path)}function IF(e,t,n,r){let i=[],a=[];for(let o of e){let e=FF(o,t);e!==void 0&&Gu(e,n[e.id]??[],r)!==void 0?i.push(o):a.push(o)}return[...i,...a]}var LF=class extends y{constructor(...e){super(...e),this.state={kind:`loading`},this.projects=[],this.workspacesByProjectId={},this.activities={}}render(){return this.state.kind===`loading`?g`<p class="muted" role="status">Loading recent projects…</p>`:this.state.kind===`failed`?this.renderFailure(this.state.message):this.state.entries.length===0?g`<p class="muted recent-projects-empty" role="status" tabindex="-1">No recent projects</p>`:g`
|
|
6183
6183
|
<div class="list-body recent-projects-list">
|
|
6184
|
-
${KC(
|
|
6184
|
+
${KC(IF(this.state.entries,this.projects,this.workspacesByProjectId,this.activities),e=>e.id,(e,t)=>this.renderEntry(e,t))}
|
|
6185
6185
|
</div>
|
|
6186
6186
|
`}renderFailure(e){return g`
|
|
6187
6187
|
<div class="recent-projects-failure" role="status">
|
|
6188
6188
|
<p class="muted">Recent projects could not be loaded: ${e}</p>
|
|
6189
6189
|
<button class="recent-projects-retry" type="button" @click=${()=>{this.onRetry?.()}}>Retry</button>
|
|
6190
6190
|
</div>
|
|
6191
|
-
`}renderEntry(e,t){let n=
|
|
6191
|
+
`}renderEntry(e,t){let n=FF(e,this.projects),r=n!==void 0&&n.id===this.selectedProjectId,i=`Remove ${e.name} from Recent Projects`;return g`
|
|
6192
6192
|
<div class=${`action-row recent-project-row ${r?`selected`:``}`} data-recent-project-id=${e.id}>
|
|
6193
6193
|
<button
|
|
6194
6194
|
class="action-main recent-project-open"
|
|
@@ -6251,7 +6251,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6251
6251
|
@media (hover: none) {
|
|
6252
6252
|
.recent-project-remove { opacity: 1; pointer-events: auto; }
|
|
6253
6253
|
}
|
|
6254
|
-
`]}};H([x({attribute:!1})],
|
|
6254
|
+
`]}};H([x({attribute:!1})],LF.prototype,`state`,void 0),H([x({attribute:!1})],LF.prototype,`projects`,void 0),H([x({attribute:!1})],LF.prototype,`workspacesByProjectId`,void 0),H([x({attribute:!1})],LF.prototype,`activities`,void 0),H([x({attribute:!1})],LF.prototype,`selectedProjectId`,void 0),H([x({attribute:!1})],LF.prototype,`onOpenRegistered`,void 0),H([x({attribute:!1})],LF.prototype,`onOpenClosed`,void 0),H([x({attribute:!1})],LF.prototype,`onRemoveRequested`,void 0),H([x({attribute:!1})],LF.prototype,`onRetry`,void 0),LF=H([b(`recent-projects-panel`)],LF);var RF=class extends y{constructor(...e){super(...e),this.initialView=`closed-actions`,this.view=`closed-actions`,this.busy=!1,this.requestRemoval=()=>{this.view=`removal-confirmation`,this.failure=void 0,this.updateComplete.then(()=>{this.cancelButton?.focus()})},this.handleCancel=e=>{e.preventDefault(),!this.busy&&this.onClose()},this.handleBackdropClick=e=>{e.target===e.currentTarget&&(this.busy||this.onClose())}}willUpdate(e){(e.has(`entry`)||e.has(`initialView`))&&(this.view=this.initialView,this.failure=void 0)}firstUpdated(){let e=this.nativeDialog;e?.isConnected===!0&&(e.showModal(),this.view===`removal-confirmation`?this.cancelButton?.focus():this.reopenButton?.focus())}disconnectedCallback(){this.close(),super.disconnectedCallback()}close(){let e=this.nativeDialog;e?.open===!0&&e.close()}render(){return g`
|
|
6255
6255
|
<dialog
|
|
6256
6256
|
class="recent-project-backdrop"
|
|
6257
6257
|
aria-modal="true"
|
|
@@ -6300,10 +6300,10 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6300
6300
|
button:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; }
|
|
6301
6301
|
.recent-project-confirm-remove { border-color: color-mix(in srgb, var(--pi-danger) 45%, transparent); background: color-mix(in srgb, var(--pi-danger) 14%, transparent); color: var(--pi-danger); }
|
|
6302
6302
|
.recent-project-confirm-remove:hover:not(:disabled) { border-color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 24%, transparent); }
|
|
6303
|
-
`}};H([x({attribute:!1})],
|
|
6304
|
-
`),lines:p,physicalLineCount:f.length,viewportLine:Math.min(d,Math.max(0,e.viewportY))}}function
|
|
6303
|
+
`}};H([x({attribute:!1})],RF.prototype,`entry`,void 0),H([x({attribute:!1})],RF.prototype,`initialView`,void 0),H([x({attribute:!1})],RF.prototype,`onReopen`,void 0),H([x({attribute:!1})],RF.prototype,`onRemove`,void 0),H([x({attribute:!1})],RF.prototype,`onClose`,void 0),H([C(`dialog`)],RF.prototype,`nativeDialog`,void 0),H([C(`.recent-project-reopen`)],RF.prototype,`reopenButton`,void 0),H([C(`.recent-project-cancel`)],RF.prototype,`cancelButton`,void 0),H([S()],RF.prototype,`view`,void 0),H([S()],RF.prototype,`busy`,void 0),H([S()],RF.prototype,`failure`,void 0),RF=H([b(`recent-project-dialog`)],RF);var zF=`important`,BF=` !important`,VF=St(class extends Ct{constructor(e){if(super(e),e.type!==xt.ATTRIBUTE||e.name!==`style`||e.strings?.length>2)throw Error("The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.")}render(e){return Object.keys(e).reduce((t,n)=>{let r=e[n];return r==null?t:t+`${n=n.includes(`-`)?n:n.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,`-$&`).toLowerCase()}:${r};`},``)}update(e,[t]){let{style:n}=e.element;if(this.ft===void 0)return this.ft=new Set(Object.keys(t)),this.render(t);for(let e of this.ft)t[e]??(this.ft.delete(e),e.includes(`-`)?n.removeProperty(e):n[e]=null);for(let e in t){let r=t[e];if(r!=null){this.ft.add(e);let t=typeof r==`string`&&r.endsWith(BF);e.includes(`-`)||t?n.setProperty(e,t?r.slice(0,-11):r,t?zF:``):n[e]=r}}return nt}}),HF=`#ffffff`,UF=`#000000`,WF=[`#2e3436`,`#cc0000`,`#4e9a06`,`#c4a000`,`#3465a4`,`#75507b`,`#06989a`,`#d3d7cf`,`#555753`,`#ef2929`,`#8ae234`,`#fce94f`,`#729fcf`,`#ad7fa8`,`#34e2e2`,`#eeeeec`],GF=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightBlack`,`brightRed`,`brightGreen`,`brightYellow`,`brightBlue`,`brightMagenta`,`brightCyan`,`brightWhite`],KF={black:WF[0],red:WF[1],green:WF[2],yellow:WF[3],blue:WF[4],magenta:WF[5],cyan:WF[6],white:WF[7],brightBlack:WF[8],brightRed:WF[9],brightGreen:WF[10],brightYellow:WF[11],brightBlue:WF[12],brightMagenta:WF[13],brightCyan:WF[14],brightWhite:WF[15]};function qF(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=tI(n.theme),a=n.theme?.foreground??HF,o=n.theme?.background??UF,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=JF(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,QF(t.runs,e.runs);continue}p.push({text:e.text,runs:e.runs.map(e=>({text:e.text,style:e.style}))})}return{text:p.map(e=>e.text).join(`
|
|
6304
|
+
`),lines:p,physicalLineCount:f.length,viewportLine:Math.min(d,Math.max(0,e.viewportY))}}function JF(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:ZF(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:YF(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,$F(s,{text:t.text,style:t.style}))}return{text:c,runs:s,wrapped:e.isWrapped}}function YF(e,t){let n=e.isInverse()!==0,r=XF(e,`foreground`,t),i=XF(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 XF(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?nI(a):i?n.palette[a]??(t===`foreground`?n.foreground:n.background):t===`foreground`?n.foreground:n.background}function ZF(e){return{foreground:e.foreground,background:e.background,bold:!1,italic:!1,dim:!1,underline:!1,invisible:!1,strikethrough:!1,overline:!1}}function QF(e,t){for(let n of t)$F(e,n)}function $F(e,t){if(t.text===``)return;let n=e.at(-1);if(n!==void 0&&eI(n.style,t.style)){n.text+=t.text;return}e.push({text:t.text,style:t.style})}function eI(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 tI(e){let t=[...WF];for(let n=0;n<GF.length;n+=1){let r=GF[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(rI(r,i,a))}for(let e=0;e<24;e+=1){let n=8+e*10;t.push(rI(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 nI(e){return`#${(e&16777215).toString(16).padStart(6,`0`)}`}function rI(e,t,n){return`#${e.toString(16).padStart(2,`0`)}${t.toString(16).padStart(2,`0`)}${n.toString(16).padStart(2,`0`)}`}var iI=`pi-webui.terminal.softKeys`,aI=`(pointer: coarse), (max-width: 760px)`;function oI(e,t){return e??t}function sI(e){if(e===`true`)return!0;if(e===`false`)return!1}function cI(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(aI):void 0}function lI(e){return e?.matches===!0}function uI(e=cI()){return oI(fI(),lI(e))}function dI(){return fI()!==void 0}function fI(e=mI()){if(e!==void 0)try{return sI(e.getItem(iI))}catch{return}}function pI(e,t=mI()){if(t!==void 0)try{t.setItem(iI,String(e))}catch{}}function mI(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var hI=[{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`}],gI=`\x1B`,_I=``;function vI(e,t){switch(e){case`escape`:return gI;case`tab`:return` `;case`ctrl-c`:return yI(`c`);case`ctrl-d`:return yI(`d`);case`ctrl-z`:return yI(`z`);case`ctrl-l`:return yI(`l`);case`ctrl-r`:return yI(`r`);case`ctrl-u`:return yI(`u`);case`ctrl-w`:return yI(`w`);case`arrow-left`:return bI(`D`,t);case`arrow-up`:return bI(`A`,t);case`arrow-down`:return bI(`B`,t);case`arrow-right`:return bI(`C`,t);case`home`:return xI(`H`,t);case`end`:return xI(`F`,t);case`page-up`:return`${gI}[5~`;case`page-down`:return`${gI}[6~`;case`delete`:return`${gI}[3~`;case`backspace`:return _I;case`meta-backward-word`:return`${gI}b`;case`meta-forward-word`:return`${gI}f`}}function yI(e){return String.fromCharCode(e.toUpperCase().charCodeAt(0)-64)}function bI(e,t){return t?.applicationCursorKeysMode===!0?`${gI}O${e}`:`${gI}[${e}`}function xI(e,t){return t?.applicationCursorKeysMode===!0?`${gI}O${e}`:`${gI}[${e}`}var SI=8,CI=500,wI=class extends y{constructor(...e){super(...e),this.refocusOnClick=!0,this.onInput=()=>void 0,this.lastPointerFinishedAt=0}sendSoftKey(e,t){this.onInput(vI(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&&TI(t,e)&&this.finishSoftKeyPointer()}onSoftKeyPointerUp(e,t){let n=this.pointerStart;n?.pointerId===e.pointerId&&(e.preventDefault(),this.finishSoftKeyPointer(),!(n.key.id!==t.id||TI(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<CI){e.preventDefault();return}this.sendSoftKey(t,{refocus:this.refocusOnClick})}render(){return g`
|
|
6305
6305
|
<div class="terminal-soft-keys" role="toolbar" aria-label="Terminal soft keys">
|
|
6306
|
-
${
|
|
6306
|
+
${hI.map(e=>g`
|
|
6307
6307
|
<button
|
|
6308
6308
|
type="button"
|
|
6309
6309
|
class="soft-key"
|
|
@@ -6323,7 +6323,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6323
6323
|
.terminal-soft-keys::-webkit-scrollbar { display: none; }
|
|
6324
6324
|
button { display: inline-flex; align-items: center; gap: 6px; flex: 0 0 auto; max-width: none; min-height: 34px; border: 1px solid var(--pi-border); border-radius: 7px; background: var(--pi-surface); color: var(--pi-text); padding: 6px 9px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; cursor: pointer; touch-action: pan-x; -webkit-touch-callout: none; user-select: none; }
|
|
6325
6325
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
6326
|
-
`}};H([x({attribute:!1})],CI.prototype,`modes`,void 0),H([x({type:Boolean})],CI.prototype,`refocusOnClick`,void 0),H([x({attribute:!1})],CI.prototype,`onInput`,void 0),CI=H([b(`terminal-soft-keys`)],CI);function wI(e,t){return Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)>xI}var TI=ue({TerminalPanel:()=>Z,filterTerminalInput:()=>BI,terminalBackgroundWithOpacity:()=>KI}),EI={allowTransparency:!0,cursorBlink:!0,convertEol:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,fontSize:13},DI={cols:100,rows:30},OI=1e3,kI=500,AI=5e3,jI=1.6,MI=`--pi-terminal-effective-bg`,NI=`--pi-terminal-ui-opacity`,Z=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.autoStart=!1,this.fontSize=13,this.bgOpacity=100,this.onSelectTerminal=()=>void 0,this.terminals=[],this.commandRuns=[],this.loading=!1,this.visible=!1,this.cancellingRunIds=[],this.continuingTerminalIds=[],this.defaultSoftKeysEnvironment=!1,this.softKeysEnabled=lI(),this.suppressTerminalInput=!1,this.terminalReconnectDelay=kI,this.softKeysDefaultEnvironmentMedia=sI(),this.softKeysPreferenceStored=uI(),this.onSoftKeysDefaultEnvironmentChange=()=>{this.syncDefaultSoftKeysEnvironment()}}connectedCallback(){super.connectedCallback(),this.syncTerminalBackground(),this.syncDefaultSoftKeysEnvironment(),this.softKeysDefaultEnvironmentMedia?.addEventListener(`change`,this.onSoftKeysDefaultEnvironmentChange),this.themeObserver=new MutationObserver(()=>{this.applyTerminalTheme()}),this.themeObserver.observe(document.documentElement,{attributes:!0,attributeFilter:[`class`,`style`,`data-theme`]})}firstUpdated(){this.intersectionObserver=new IntersectionObserver(e=>{this.visible=e[0]?.isIntersecting===!0}),this.intersectionObserver.observe(this)}disconnectedCallback(){this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.themeObserver?.disconnect(),this.themeObserver=void 0,this.softKeysDefaultEnvironmentMedia?.removeEventListener(`change`,this.onSoftKeysDefaultEnvironmentChange),this.updateCommandRunPolling(!1),this.disposeTerminalView(),super.disconnectedCallback()}syncDefaultSoftKeysEnvironment(){let e=cI(this.softKeysDefaultEnvironmentMedia),t=this.softKeysEnabled;this.defaultSoftKeysEnvironment=e,this.softKeysPreferenceStored||(this.softKeysEnabled=e),this.softKeysEnabled!==t&&this.scheduleFitAndNotify()}scheduleFitAndNotify(){this.updateComplete.then(()=>{this.fitAndNotify()})}willUpdate(e){e.has(`bgOpacity`)&&this.syncTerminalBackground();let t=this.workspace===void 0?void 0:JSON.stringify([this.machineId,this.workspace.path]);if(t!==this.observedWorkspaceScope){this.observedWorkspaceScope=t,this.loadedCwd=void 0,this.autoStartConsumedCwd=void 0,this.terminals=[],this.commandRuns=[],this.selectedId=void 0,this.cancellingRunIds=[],this.continuingTerminalIds=[],this.updateCommandRunPolling(!1),this.disposeTerminalView();return}if(e.has(`selectedTerminalId`)){if(e.get(`selectedTerminalId`)!==void 0&&this.selectedTerminalId===void 0){this.loadedCwd=void 0,this.selectTerminalIdInView(void 0);return}this.applyRequestedTerminalSelection()}}updated(e){this.visible?this.hasPendingCommandRuns()&&this.updateCommandRunPolling(!0):this.updateCommandRunPolling(!1),this.loadVisibleWorkspaceTerminals(),e.has(`selectedTerminalId`)&&this.shouldReloadForRequestedTerminal()&&this.loadTerminals(),e.has(`fontSize`)&&this.terminal!==void 0&&(this.terminal.options.fontSize=this.fontSize,this.fitAndNotify()),e.has(`bgOpacity`)&&this.applyTerminalTheme(),this.ensureTerminalView()}loadVisibleWorkspaceTerminals(){let e=this.workspace?.path;!this.visible||e===void 0||e===this.loadedCwd||(this.loadedCwd=e,this.loadTerminals())}async loadTerminals(){this.loading=!0,this.error=void 0;try{let e=this.workspace;if(e===void 0)return;let t=this.consumeAutoStart(),[n,r]=await Promise.all([lc.terminals(e.projectId,e.id,this.machineId),lc.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId)]);this.terminals=n,this.commandRuns=r,this.selectPreferredLoadedTerminal({replaceUrl:!0}),this.updateCommandRunPolling(this.hasPendingCommandRuns(r)),n.length===0&&t&&await this.startTerminal()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.loading=!1}}applyRequestedTerminalSelection(){this.selectedTerminalId!==void 0&&!this.terminals.some(e=>e.id===this.selectedTerminalId)||this.selectPreferredLoadedTerminal({replaceUrl:!0})}consumeAutoStart(){let e=this.workspace?.path;return!this.autoStart||e===void 0||this.autoStartConsumedCwd===e?!1:(this.autoStartConsumedCwd=e,!0)}shouldReloadForRequestedTerminal(){let e=this.workspace?.path;return this.visible&&e!==void 0&&e===this.loadedCwd&&this.selectedTerminalId!==void 0&&!this.loading&&!this.terminals.some(e=>e.id===this.selectedTerminalId)}selectPreferredLoadedTerminal(e){let t=K_(this.terminals,{targetTerminalId:this.selectedTerminalId});t===void 0&&this.selectedTerminalId!==void 0&&(t=q_(this.terminals)),this.selectTerminalIdInView(t?.id),(t?.id!==this.selectedTerminalId||t===void 0&&this.selectedTerminalId!==void 0)&&this.onSelectTerminal(t?.id,{replace:e?.replaceUrl===!0})}selectTerminalIdInView(e){this.selectedId!==e&&(this.selectedId=e,this.disposeTerminalView())}async startTerminal(){let e=this.workspace;if(e===void 0)return;let t=this.machineId,n=this.onStarted;this.error=void 0;try{let r=this.measureTerminalSize()??DI,i=await lc.startTerminal(e.projectId,e.id,r,t);this.terminals=[...this.terminals,i],this.selectTerminal(i.id),n?.()}catch(e){this.error=e instanceof Error?e.message:String(e)}}async closeTerminal(e,t){t.stopPropagation();try{if(this.workspace===void 0)return;await lc.closeTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);let t=this.terminals.filter(t=>t.id!==e);if(this.terminals=t,this.selectedId===e||this.selectedTerminalId===e){let e=q_(t)?.id;this.selectTerminalIdInView(e),this.onSelectTerminal(e,{replace:!0})}}catch(e){this.error=e instanceof Error?e.message:String(e)}}selectTerminal(e){this.selectedId!==e&&this.selectTerminalIdInView(e),this.onSelectTerminal(e)}selectedTerminalInfo(){return this.terminals.find(e=>e.id===this.selectedId)}selectedCommandRun(){let e=this.selectedTerminalInfo()?.commandRunId;if(e!==void 0)return this.commandRuns.find(t=>t.id===e)}async loadCommandRuns(){let e=this.workspace;if(e!==void 0)try{let t=await lc.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId);this.commandRuns=t,this.cancellingRunIds=this.cancellingRunIds.filter(e=>t.some(t=>t.id===e&&LI(t))),this.updateCommandRunPolling(this.hasPendingCommandRuns(t))}catch(e){this.error=e instanceof Error?e.message:String(e)}}updateCommandRunPolling(e){if(e&&this.commandRunPollTimer===void 0){this.commandRunPollTimer=window.setInterval(()=>{this.loadCommandRuns()},OI);return}!e&&this.commandRunPollTimer!==void 0&&(window.clearInterval(this.commandRunPollTimer),this.commandRunPollTimer=void 0)}hasPendingCommandRuns(e=this.commandRuns){return e.some(LI)}async cancelCommandRun(e){if(!(!LI(e)||this.cancellingRunIds.includes(e.id))){this.error=void 0,this.cancellingRunIds=[...this.cancellingRunIds,e.id];try{await lc.cancelCommandRun(e.id,this.machineId),await this.loadCommandRuns()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.cancellingRunIds=this.cancellingRunIds.filter(t=>t!==e.id)}}}async continueTerminal(e){if(!(this.workspace===void 0||this.continuingTerminalIds.includes(e))){this.error=void 0,this.continuingTerminalIds=[...this.continuingTerminalIds,e];try{let t=await lc.continueTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);this.terminals=this.terminals.map(n=>n.id===e?t:n),this.socket===void 0&&this.disposeTerminalView(),this.fitAndNotify(),this.terminal?.focus()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.continuingTerminalIds=this.continuingTerminalIds.filter(t=>t!==e)}}}ensureTerminalView(){let e=this.workspace,t=this.terminalHostElement();if(!this.visible||this.terminal!==void 0||this.selectedId===void 0||t===void 0||e===void 0)return;let n=new se(HI(this)),r=new ce;n.loadAddon(r),n.open(t),this.terminal=n,this.fitAddon=r,this.resizeObserver=new ResizeObserver(()=>{this.fitAndNotify()}),this.resizeObserver.observe(t),n.onData(e=>{this.suppressTerminalInput||this.copySnapshot!==void 0||this.sendTerminalInput(e)});let i=this.fitTerminal();this.connectSocket(e.projectId,e.id,this.selectedId,n,i),requestAnimationFrame(()=>{this.fitAndNotify()}),n.focus()}connectSocket(e,t,n,r,i){let a=vc(e,t,n,i,this.machineId);a.binaryType=`arraybuffer`,this.socket=a,a.addEventListener(`open`,()=>{this.socket===a&&(this.terminalReconnectDelay=kI,this.fitAndNotify())}),a.addEventListener(`message`,e=>{this.handleSocketMessage(e.data,n,r)}),a.addEventListener(`close`,()=>{if(this.socket!==a||(this.socket=void 0,this.terminals.some(e=>e.id===n&&e.exited)))return;this.terminalReconnectTimer!==void 0&&window.clearTimeout(this.terminalReconnectTimer);let o=this.terminalReconnectDelay;this.terminalReconnectDelay=Math.min(this.terminalReconnectDelay*jI,AI),this.terminalReconnectTimer=window.setTimeout(()=>{this.terminalReconnectTimer=void 0,!(this.socket!==void 0||this.terminals.some(e=>e.id===n&&e.exited))&&this.connectSocket(e,t,n,r,i)},o)})}async handleSocketMessage(e,t,n){try{let r=zI(await VI(e));r.type===`output`&&this.writeTerminalOutput(n,r.data,r.replay===!0),r.type===`exit`&&(n.writeln(`\r\n[process exited${r.exitCode===void 0?``:` with code ${String(r.exitCode)}`}]`),this.terminals=this.terminals.map(e=>e.id===t?{...e,exited:!0,...r.exitCode===void 0?{}:{exitCode:r.exitCode}}:e),this.loadCommandRuns()),r.type===`error`&&n.writeln(`\r\n[terminal error: ${r.message}]`)}catch(e){n.writeln(`\r\n[terminal error: ${e instanceof Error?e.message:String(e)}]`)}}writeTerminalOutput(e,t,n){if(!n){e.write(t);return}this.suppressTerminalInput=!0,e.reset(),e.write(`\x1Bc`+t,()=>{this.suppressTerminalInput=!1})}fitAndNotify(){let e=this.fitTerminal();e!==void 0&&this.send({type:`resize`,...e})}fitTerminal(){if(this.fitAddon===void 0||this.terminal===void 0)return;let e=qI(this.fitAddon.proposeDimensions());if(e!==void 0)return this.fitAddon.fit(),e}measureTerminalSize(){let e=this.fitTerminal();if(e!==void 0)return e;let t=this.terminalHostElement();if(this.terminal!==void 0||t===void 0)return;let n=new se(HI(this)),r=new ce;n.loadAddon(r),n.open(t);let i=qI(r.proposeDimensions());return n.dispose(),i}terminalHostElement(){let e=this.terminalHost;return e instanceof HTMLDivElement?e:void 0}applyTerminalTheme(){this.syncTerminalBackground(),this.terminal!==void 0&&(this.terminal.options.theme=UI(this))}syncTerminalBackground(){let e=GI(this.bgOpacity),t=KI(WI(this,`--pi-terminal-bg`,`#05070a`),e);this.style.setProperty(MI,t),this.style.setProperty(NI,`${String(e)}%`)}sendTerminalInput(e){let t=BI(e);t!==``&&this.send({type:`input`,data:t})}sendSoftKeyInput(e,t){this.copySnapshot===void 0&&(this.sendTerminalInput(e),t.refocus&&this.focusTerminal())}focusTerminal(){let e=this.terminal;e!==void 0&&(e.focus(),requestAnimationFrame(()=>{e.focus()}))}send(e){this.socket?.readyState===WebSocket.OPEN&&(this.socket.send(JSON.stringify(e)),e.type===`input`&&this.onInput?.())}disposeTerminalView(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.terminalReconnectTimer!==void 0&&(window.clearTimeout(this.terminalReconnectTimer),this.terminalReconnectTimer=void 0),this.terminalReconnectDelay=kI;let e=this.socket;this.socket=void 0,e?.close(),this.terminal?.dispose(),this.terminal=void 0,this.fitAddon=void 0,this.copySnapshot=void 0,this.copyStatus=void 0}renderCommandRunNotice(){let e=this.selectedCommandRun();if(e===void 0)return null;let t=this.selectedTerminalInfo();if(LI(e)){let t=this.cancellingRunIds.includes(e.id);return g`
|
|
6326
|
+
`}};H([x({attribute:!1})],wI.prototype,`modes`,void 0),H([x({type:Boolean})],wI.prototype,`refocusOnClick`,void 0),H([x({attribute:!1})],wI.prototype,`onInput`,void 0),wI=H([b(`terminal-soft-keys`)],wI);function TI(e,t){return Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)>SI}var EI=ue({TerminalPanel:()=>Z,filterTerminalInput:()=>VI,terminalBackgroundWithOpacity:()=>qI}),DI={allowTransparency:!0,cursorBlink:!0,convertEol:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,fontSize:13},OI={cols:100,rows:30},kI=1e3,AI=500,jI=5e3,MI=1.6,NI=`--pi-terminal-effective-bg`,PI=`--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=uI(),this.suppressTerminalInput=!1,this.terminalReconnectDelay=AI,this.softKeysDefaultEnvironmentMedia=cI(),this.softKeysPreferenceStored=dI(),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=lI(this.softKeysDefaultEnvironmentMedia),t=this.softKeysEnabled;this.defaultSoftKeysEnvironment=e,this.softKeysPreferenceStored||(this.softKeysEnabled=e),this.softKeysEnabled!==t&&this.scheduleFitAndNotify()}scheduleFitAndNotify(){this.updateComplete.then(()=>{this.fitAndNotify()})}willUpdate(e){e.has(`bgOpacity`)&&this.syncTerminalBackground();let t=this.workspace===void 0?void 0:JSON.stringify([this.machineId,this.workspace.path]);if(t!==this.observedWorkspaceScope){this.observedWorkspaceScope=t,this.loadedCwd=void 0,this.autoStartConsumedCwd=void 0,this.terminals=[],this.commandRuns=[],this.selectedId=void 0,this.cancellingRunIds=[],this.continuingTerminalIds=[],this.updateCommandRunPolling(!1),this.disposeTerminalView();return}if(e.has(`selectedTerminalId`)){if(e.get(`selectedTerminalId`)!==void 0&&this.selectedTerminalId===void 0){this.loadedCwd=void 0,this.selectTerminalIdInView(void 0);return}this.applyRequestedTerminalSelection()}}updated(e){this.visible?this.hasPendingCommandRuns()&&this.updateCommandRunPolling(!0):this.updateCommandRunPolling(!1),this.loadVisibleWorkspaceTerminals(),e.has(`selectedTerminalId`)&&this.shouldReloadForRequestedTerminal()&&this.loadTerminals(),e.has(`fontSize`)&&this.terminal!==void 0&&(this.terminal.options.fontSize=this.fontSize,this.fitAndNotify()),e.has(`bgOpacity`)&&this.applyTerminalTheme(),this.ensureTerminalView()}loadVisibleWorkspaceTerminals(){let e=this.workspace?.path;!this.visible||e===void 0||e===this.loadedCwd||(this.loadedCwd=e,this.loadTerminals())}async loadTerminals(){this.loading=!0,this.error=void 0;try{let e=this.workspace;if(e===void 0)return;let t=this.consumeAutoStart(),[n,r]=await Promise.all([lc.terminals(e.projectId,e.id,this.machineId),lc.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId)]);this.terminals=n,this.commandRuns=r,this.selectPreferredLoadedTerminal({replaceUrl:!0}),this.updateCommandRunPolling(this.hasPendingCommandRuns(r)),n.length===0&&t&&await this.startTerminal()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.loading=!1}}applyRequestedTerminalSelection(){this.selectedTerminalId!==void 0&&!this.terminals.some(e=>e.id===this.selectedTerminalId)||this.selectPreferredLoadedTerminal({replaceUrl:!0})}consumeAutoStart(){let e=this.workspace?.path;return!this.autoStart||e===void 0||this.autoStartConsumedCwd===e?!1:(this.autoStartConsumedCwd=e,!0)}shouldReloadForRequestedTerminal(){let e=this.workspace?.path;return this.visible&&e!==void 0&&e===this.loadedCwd&&this.selectedTerminalId!==void 0&&!this.loading&&!this.terminals.some(e=>e.id===this.selectedTerminalId)}selectPreferredLoadedTerminal(e){let t=K_(this.terminals,{targetTerminalId:this.selectedTerminalId});t===void 0&&this.selectedTerminalId!==void 0&&(t=q_(this.terminals)),this.selectTerminalIdInView(t?.id),(t?.id!==this.selectedTerminalId||t===void 0&&this.selectedTerminalId!==void 0)&&this.onSelectTerminal(t?.id,{replace:e?.replaceUrl===!0})}selectTerminalIdInView(e){this.selectedId!==e&&(this.selectedId=e,this.disposeTerminalView())}async startTerminal(){let e=this.workspace;if(e===void 0)return;let t=this.machineId,n=this.onStarted;this.error=void 0;try{let r=this.measureTerminalSize()??OI,i=await lc.startTerminal(e.projectId,e.id,r,t);this.terminals=[...this.terminals,i],this.selectTerminal(i.id),n?.()}catch(e){this.error=e instanceof Error?e.message:String(e)}}async closeTerminal(e,t){t.stopPropagation();try{if(this.workspace===void 0)return;await lc.closeTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);let t=this.terminals.filter(t=>t.id!==e);if(this.terminals=t,this.selectedId===e||this.selectedTerminalId===e){let e=q_(t)?.id;this.selectTerminalIdInView(e),this.onSelectTerminal(e,{replace:!0})}}catch(e){this.error=e instanceof Error?e.message:String(e)}}selectTerminal(e){this.selectedId!==e&&this.selectTerminalIdInView(e),this.onSelectTerminal(e)}selectedTerminalInfo(){return this.terminals.find(e=>e.id===this.selectedId)}selectedCommandRun(){let e=this.selectedTerminalInfo()?.commandRunId;if(e!==void 0)return this.commandRuns.find(t=>t.id===e)}async loadCommandRuns(){let e=this.workspace;if(e!==void 0)try{let t=await lc.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId);this.commandRuns=t,this.cancellingRunIds=this.cancellingRunIds.filter(e=>t.some(t=>t.id===e&&RI(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()},kI);return}!e&&this.commandRunPollTimer!==void 0&&(window.clearInterval(this.commandRunPollTimer),this.commandRunPollTimer=void 0)}hasPendingCommandRuns(e=this.commandRuns){return e.some(RI)}async cancelCommandRun(e){if(!(!RI(e)||this.cancellingRunIds.includes(e.id))){this.error=void 0,this.cancellingRunIds=[...this.cancellingRunIds,e.id];try{await lc.cancelCommandRun(e.id,this.machineId),await this.loadCommandRuns()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.cancellingRunIds=this.cancellingRunIds.filter(t=>t!==e.id)}}}async continueTerminal(e){if(!(this.workspace===void 0||this.continuingTerminalIds.includes(e))){this.error=void 0,this.continuingTerminalIds=[...this.continuingTerminalIds,e];try{let t=await lc.continueTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);this.terminals=this.terminals.map(n=>n.id===e?t:n),this.socket===void 0&&this.disposeTerminalView(),this.fitAndNotify(),this.terminal?.focus()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.continuingTerminalIds=this.continuingTerminalIds.filter(t=>t!==e)}}}ensureTerminalView(){let e=this.workspace,t=this.terminalHostElement();if(!this.visible||this.terminal!==void 0||this.selectedId===void 0||t===void 0||e===void 0)return;let n=new se(UI(this)),r=new ce;n.loadAddon(r),n.open(t),this.terminal=n,this.fitAddon=r,this.resizeObserver=new ResizeObserver(()=>{this.fitAndNotify()}),this.resizeObserver.observe(t),n.onData(e=>{this.suppressTerminalInput||this.copySnapshot!==void 0||this.sendTerminalInput(e)});let i=this.fitTerminal();this.connectSocket(e.projectId,e.id,this.selectedId,n,i),requestAnimationFrame(()=>{this.fitAndNotify()}),n.focus()}connectSocket(e,t,n,r,i){let a=vc(e,t,n,i,this.machineId);a.binaryType=`arraybuffer`,this.socket=a,a.addEventListener(`open`,()=>{this.socket===a&&(this.terminalReconnectDelay=AI,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*MI,jI),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=BI(await HI(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=JI(this.fitAddon.proposeDimensions());if(e!==void 0)return this.fitAddon.fit(),e}measureTerminalSize(){let e=this.fitTerminal();if(e!==void 0)return e;let t=this.terminalHostElement();if(this.terminal!==void 0||t===void 0)return;let n=new se(UI(this)),r=new ce;n.loadAddon(r),n.open(t);let i=JI(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=WI(this))}syncTerminalBackground(){let e=KI(this.bgOpacity),t=qI(GI(this,`--pi-terminal-bg`,`#05070a`),e);this.style.setProperty(NI,t),this.style.setProperty(PI,`${String(e)}%`)}sendTerminalInput(e){let t=VI(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=AI;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(RI(e)){let t=this.cancellingRunIds.includes(e.id);return g`
|
|
6327
6327
|
<section class="command-run-notice running">
|
|
6328
6328
|
<div>
|
|
6329
6329
|
<strong>${e.title}</strong>
|
|
@@ -6335,13 +6335,13 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6335
6335
|
`}if(t?.exited===!0){let n=this.continuingTerminalIds.includes(t.id);return g`
|
|
6336
6336
|
<section class=${`command-run-notice ${e.status}`}>
|
|
6337
6337
|
<div>
|
|
6338
|
-
<strong>${
|
|
6338
|
+
<strong>${zI(e)}</strong>
|
|
6339
6339
|
<p>Output is preserved. Continue in a shell to inspect or run follow-up commands.</p>
|
|
6340
6340
|
<code>${e.command}</code>
|
|
6341
6341
|
</div>
|
|
6342
6342
|
<button ?disabled=${n} @click=${()=>{this.continueTerminal(t.id)}}>${n?`Starting shell…`:`Continue in shell`}</button>
|
|
6343
6343
|
</section>
|
|
6344
|
-
`}return null}enterCopyMode(){this.copySnapshot===void 0&&this.captureCopySnapshot()}refreshCopyMode(){this.copySnapshot!==void 0&&this.captureCopySnapshot()}captureCopySnapshot(){let e=this.terminal;if(e===void 0)return;let t=
|
|
6344
|
+
`}return null}enterCopyMode(){this.copySnapshot===void 0&&this.captureCopySnapshot()}refreshCopyMode(){this.copySnapshot!==void 0&&this.captureCopySnapshot()}captureCopySnapshot(){let e=this.terminal;if(e===void 0)return;let t=qF(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=FI(e.scrollTop,n,r),t.scrollLeft=FI(e.scrollLeft,i,a)}async copyAllSnapshotText(){let e=this.copySnapshot?.text??``;if(e===``){this.copyStatus=`No terminal output to copy.`;return}this.copyStatus=await pE(e)?`Copied all terminal output.`:`Unable to copy terminal output.`}renderCopyModeToggle(){if(this.selectedId===void 0)return null;let e=this.copySnapshot!==void 0;return g`
|
|
6345
6345
|
<button
|
|
6346
6346
|
type="button"
|
|
6347
6347
|
class=${e?`copy-mode-toggle selected`:`copy-mode-toggle`}
|
|
@@ -6364,7 +6364,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6364
6364
|
${this.copyToolbarReplacesSoftKeys()?null:this.renderCopyModeToolbar()}
|
|
6365
6365
|
<div class="terminal-copy-layers">
|
|
6366
6366
|
<pre class="terminal-copy-content" aria-hidden="true">${e.lines.map((e,t)=>g`${t===0?null:`
|
|
6367
|
-
`}${e.runs.map(e=>g`<span style=${
|
|
6367
|
+
`}${e.runs.map(e=>g`<span style=${VF(LI(e.style))}>${e.text}</span>`)}`)}</pre>
|
|
6368
6368
|
<textarea
|
|
6369
6369
|
class="terminal-copy-selector"
|
|
6370
6370
|
readonly
|
|
@@ -6379,7 +6379,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6379
6379
|
></textarea>
|
|
6380
6380
|
</div>
|
|
6381
6381
|
</section>
|
|
6382
|
-
`}selectedTerminalAcceptsInput(){let e=this.selectedTerminalInfo();return e!==void 0&&!e.exited}copyToolbarReplacesSoftKeys(){return this.copySnapshot!==void 0&&this.selectedTerminalAcceptsInput()&&this.softKeysEnabled}renderTerminalAccessoryBar(){return this.copySnapshot===void 0?this.shouldShowSoftKeys()?this.renderSoftKeys():null:this.copyToolbarReplacesSoftKeys()?this.renderCopyModeToolbar():null}shouldShowSoftKeys(){return this.selectedTerminalAcceptsInput()&&this.softKeysEnabled}shouldShowSoftKeysToggle(){return this.copySnapshot===void 0&&this.selectedTerminalAcceptsInput()}toggleSoftKeys(){this.copySnapshot===void 0&&(this.softKeysEnabled=!this.softKeysEnabled,this.softKeysPreferenceStored=!0,
|
|
6382
|
+
`}selectedTerminalAcceptsInput(){let e=this.selectedTerminalInfo();return e!==void 0&&!e.exited}copyToolbarReplacesSoftKeys(){return this.copySnapshot!==void 0&&this.selectedTerminalAcceptsInput()&&this.softKeysEnabled}renderTerminalAccessoryBar(){return this.copySnapshot===void 0?this.shouldShowSoftKeys()?this.renderSoftKeys():null:this.copyToolbarReplacesSoftKeys()?this.renderCopyModeToolbar():null}shouldShowSoftKeys(){return this.selectedTerminalAcceptsInput()&&this.softKeysEnabled}shouldShowSoftKeysToggle(){return this.copySnapshot===void 0&&this.selectedTerminalAcceptsInput()}toggleSoftKeys(){this.copySnapshot===void 0&&(this.softKeysEnabled=!this.softKeysEnabled,this.softKeysPreferenceStored=!0,pI(this.softKeysEnabled),this.scheduleFitAndNotify())}renderSoftKeysToggle(){return this.shouldShowSoftKeysToggle()?g`
|
|
6383
6383
|
<button
|
|
6384
6384
|
type="button"
|
|
6385
6385
|
class=${this.softKeysEnabled?`soft-keys-toggle selected`:`soft-keys-toggle`}
|
|
@@ -6500,32 +6500,32 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6500
6500
|
.error { flex: 0 0 auto; margin: 0; padding: 8px; color: var(--pi-danger); border-bottom: 1px solid var(--pi-border); background: color-mix(in srgb, var(--pi-surface) var(--pi-terminal-ui-opacity, 100%), transparent); }
|
|
6501
6501
|
.muted { margin: 10px; color: var(--pi-muted); }
|
|
6502
6502
|
.xterm { height: 100%; }
|
|
6503
|
-
`}};H([x({attribute:!1})],Z.prototype,`workspace`,void 0),H([x()],Z.prototype,`machineId`,void 0),H([x({attribute:!1})],Z.prototype,`selectedTerminalId`,void 0),H([x({type:Boolean})],Z.prototype,`autoStart`,void 0),H([x({type:Number})],Z.prototype,`fontSize`,void 0),H([x({type:Number})],Z.prototype,`bgOpacity`,void 0),H([x({attribute:!1})],Z.prototype,`onSelectTerminal`,void 0),H([x({attribute:!1})],Z.prototype,`onStarted`,void 0),H([x({attribute:!1})],Z.prototype,`onInput`,void 0),H([C(`.terminal-host`)],Z.prototype,`terminalHost`,void 0),H([C(`.terminal-copy-content`)],Z.prototype,`terminalCopyContent`,void 0),H([C(`.terminal-copy-selector`)],Z.prototype,`terminalCopySelector`,void 0),H([S()],Z.prototype,`terminals`,void 0),H([S()],Z.prototype,`commandRuns`,void 0),H([S()],Z.prototype,`selectedId`,void 0),H([S()],Z.prototype,`loading`,void 0),H([S()],Z.prototype,`error`,void 0),H([S()],Z.prototype,`visible`,void 0),H([S()],Z.prototype,`cancellingRunIds`,void 0),H([S()],Z.prototype,`continuingTerminalIds`,void 0),H([S()],Z.prototype,`defaultSoftKeysEnvironment`,void 0),H([S()],Z.prototype,`softKeysEnabled`,void 0),H([S()],Z.prototype,`copySnapshot`,void 0),H([S()],Z.prototype,`copyStatus`,void 0),Z=H([b(`terminal-panel`)],Z);function
|
|
6503
|
+
`}};H([x({attribute:!1})],Z.prototype,`workspace`,void 0),H([x()],Z.prototype,`machineId`,void 0),H([x({attribute:!1})],Z.prototype,`selectedTerminalId`,void 0),H([x({type:Boolean})],Z.prototype,`autoStart`,void 0),H([x({type:Number})],Z.prototype,`fontSize`,void 0),H([x({type:Number})],Z.prototype,`bgOpacity`,void 0),H([x({attribute:!1})],Z.prototype,`onSelectTerminal`,void 0),H([x({attribute:!1})],Z.prototype,`onStarted`,void 0),H([x({attribute:!1})],Z.prototype,`onInput`,void 0),H([C(`.terminal-host`)],Z.prototype,`terminalHost`,void 0),H([C(`.terminal-copy-content`)],Z.prototype,`terminalCopyContent`,void 0),H([C(`.terminal-copy-selector`)],Z.prototype,`terminalCopySelector`,void 0),H([S()],Z.prototype,`terminals`,void 0),H([S()],Z.prototype,`commandRuns`,void 0),H([S()],Z.prototype,`selectedId`,void 0),H([S()],Z.prototype,`loading`,void 0),H([S()],Z.prototype,`error`,void 0),H([S()],Z.prototype,`visible`,void 0),H([S()],Z.prototype,`cancellingRunIds`,void 0),H([S()],Z.prototype,`continuingTerminalIds`,void 0),H([S()],Z.prototype,`defaultSoftKeysEnvironment`,void 0),H([S()],Z.prototype,`softKeysEnabled`,void 0),H([S()],Z.prototype,`copySnapshot`,void 0),H([S()],Z.prototype,`copyStatus`,void 0),Z=H([b(`terminal-panel`)],Z);function FI(e,t,n){return t<=0||n<=0?0:Math.min(1,Math.max(0,e/t))*n}function II(e){return/^#[\da-f]{6}$/i.test(e)?`${e}80`:`color-mix(in srgb, ${e} 50%, transparent)`}function LI(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?II(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 RI(e){return e.status===`queued`||e.status===`running`}function zI(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 BI(e){let t=JSON.parse(e);if(!XI(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 VI(e){return e.replaceAll(`\x1B[I`,``).replaceAll(`\x1B[O`,``)}async function HI(e){return typeof e==`string`?e:e instanceof ArrayBuffer?new TextDecoder().decode(e):e instanceof Blob?await e.text():String(e)}function UI(e){let t=DI;return e instanceof Z?{...t,fontSize:e.fontSize,theme:WI(e)}:{...t,theme:WI(e)}}function WI(e){let t=qI(GI(e,`--pi-terminal-bg`,`#05070a`),e instanceof Z?e.bgOpacity:100);return{...KF,background:t,foreground:GI(e,`--pi-terminal-text`,`#e6edf3`),cursor:GI(e,`--pi-accent`,`#58a6ff`),selectionBackground:GI(e,`--pi-terminal-selection`,`#264f78`)}}function GI(e,t,n){let r=getComputedStyle(e).getPropertyValue(t).trim();return r===``?n:r}function KI(e){return Math.max(0,Math.min(100,e))}function qI(e,t){let n=KI(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 JI(e){if(!(e===void 0||!YI(e.cols,e.rows)))return{cols:Math.floor(e.cols),rows:Math.floor(e.rows)}}function YI(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&e>0&&t>0}function XI(e){return typeof e==`object`&&!!e}var ZI=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=QI(this.machines),t=$I(this.machine),n=tL(this.project),r=rL(this.workspace),i=aL(this.session);return g`
|
|
6504
6504
|
<nav class=${this.contextBarClass()} aria-label="Current location">
|
|
6505
6505
|
<span class="context-bar-label">Location</span>
|
|
6506
6506
|
<ol class="context-items" @scroll=${this.onContextScroll}>
|
|
6507
6507
|
${e?g`
|
|
6508
6508
|
<li class="context-item">
|
|
6509
|
-
<button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${
|
|
6509
|
+
<button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${eL(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.(`machines`)}}>
|
|
6510
6510
|
<span class="context-kind">Machine</span>
|
|
6511
6511
|
<span class="context-value">${t}</span>
|
|
6512
6512
|
</button>
|
|
6513
6513
|
</li>
|
|
6514
6514
|
`:null}
|
|
6515
6515
|
<li class="context-item">
|
|
6516
|
-
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${
|
|
6516
|
+
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${nL(this.project)} aria-label=${`Project: ${n}. Open project selection.`} @click=${()=>{this.onOpenSection?.(`projects`)}}>
|
|
6517
6517
|
<span class="context-kind">Project</span>
|
|
6518
6518
|
<span class="context-value">${n}</span>
|
|
6519
6519
|
</button>
|
|
6520
6520
|
</li>
|
|
6521
6521
|
<li class="context-item">
|
|
6522
|
-
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${
|
|
6522
|
+
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${iL(this.workspace)} aria-label=${`Workspace: ${r}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
|
|
6523
6523
|
<span class="context-kind">Workspace</span>
|
|
6524
6524
|
<span class="context-value">${r}</span>
|
|
6525
6525
|
</button>
|
|
6526
6526
|
</li>
|
|
6527
6527
|
<li class="context-item">
|
|
6528
|
-
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${
|
|
6528
|
+
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${oL(this.session)} aria-label=${`Session: ${i}. Open session selection.`} @click=${()=>{this.onOpenSection?.(`sessions`)}}>
|
|
6529
6529
|
<span class="context-kind">Session</span>
|
|
6530
6530
|
<span class="context-value">${i}</span>
|
|
6531
6531
|
</button>
|
|
@@ -6573,7 +6573,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6573
6573
|
.context-kind { display: none; }
|
|
6574
6574
|
.context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
|
|
6575
6575
|
button { cursor: pointer; }
|
|
6576
|
-
`}};H([x({attribute:!1})],
|
|
6576
|
+
`}};H([x({attribute:!1})],ZI.prototype,`machines`,void 0),H([x({attribute:!1})],ZI.prototype,`machine`,void 0),H([x({attribute:!1})],ZI.prototype,`project`,void 0),H([x({attribute:!1})],ZI.prototype,`workspace`,void 0),H([x({attribute:!1})],ZI.prototype,`session`,void 0),H([x({attribute:!1})],ZI.prototype,`refreshControl`,void 0),H([x({attribute:!1})],ZI.prototype,`onOpenSection`,void 0),H([x({attribute:!1})],ZI.prototype,`onShowActions`,void 0),H([x({type:Boolean})],ZI.prototype,`activityRailOpen`,void 0),H([x({attribute:!1})],ZI.prototype,`onToggleActivityRail`,void 0),H([C(`.context-items`)],ZI.prototype,`contextItems`,void 0),H([S()],ZI.prototype,`canScrollLeft`,void 0),H([S()],ZI.prototype,`canScrollRight`,void 0),ZI=H([b(`app-context-bar`)],ZI);function QI(e){return e.length>1}function $I(e){return e===void 0?`No machine`:`${e.name}${e.kind===`remote`?` · remote`:``}`}function eL(e){return e===void 0?`No machine selected`:e.baseUrl??e.name}function tL(e){return e?.name??`No project`}function nL(e){return e===void 0?`No project selected`:`${e.name} — ${e.path}`}function rL(e){return e===void 0?`No workspace`:`${e.label}${e.isMain?` · main`:``} · ${e.path}`}function iL(e){return e===void 0?`No workspace selected`:`${e.label}${e.isMain?` · main`:``} — ${e.path}`}function aL(e){let t=e?.name?.trim(),n=e?.firstMessage.trim();return t!==void 0&&t!==``?t:n!==void 0&&n!==``?n:e===void 0?`No session`:Aw(e.id)}function oL(e){return e===void 0?`No session selected`:e.path}var sL=class extends y{constructor(...e){super(...e),this.tabs=[],this.selectedView=`chat`,this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.mobileTabsResizeObserver?.disconnect(),this.mobileTabsResizeObserver=void 0,this.observedMobileTabs=void 0,super.disconnectedCallback()}firstUpdated(){this.observeMobileTabs(),this.updateScrollState()}updated(){this.observeMobileTabs(),this.updateScrollState()}render(){let e=this.fallbackLabels();return g`
|
|
6577
6577
|
<div class=${this.frameClass()}>
|
|
6578
6578
|
<div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
|
|
6579
6579
|
${this.tabs.map(t=>{let n=this.selectedView===t.id;return g`
|
|
@@ -6612,12 +6612,12 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6612
6612
|
.tab-label { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; }
|
|
6613
6613
|
.tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
|
|
6614
6614
|
}
|
|
6615
|
-
`}};H([x({attribute:!1})],
|
|
6615
|
+
`}};H([x({attribute:!1})],sL.prototype,`tabs`,void 0),H([x({attribute:!1})],sL.prototype,`selectedView`,void 0),H([x({attribute:!1})],sL.prototype,`onSelect`,void 0),H([C(`.mobile-tabs`)],sL.prototype,`mobileTabs`,void 0),H([S()],sL.prototype,`canScrollLeft`,void 0),H([S()],sL.prototype,`canScrollRight`,void 0),sL=H([b(`app-mobile-main-tabs`)],sL);var cL=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=lL(e,this.statuses),n=e.name;return g`
|
|
6616
6616
|
<div class="machine-switcher">
|
|
6617
6617
|
<button
|
|
6618
6618
|
type="button"
|
|
6619
6619
|
class="machine-switcher-button"
|
|
6620
|
-
title=${
|
|
6620
|
+
title=${dL(e)}
|
|
6621
6621
|
aria-label=${this.machineSwitcherAriaLabel(e)}
|
|
6622
6622
|
aria-expanded=${String(this.open)}
|
|
6623
6623
|
@click=${e=>{this.toggleMenu(e.currentTarget)}}
|
|
@@ -6628,7 +6628,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6628
6628
|
<span class="machine-switcher-kicker">Machine</span>
|
|
6629
6629
|
<span class="machine-switcher-label">${n}</span>
|
|
6630
6630
|
</span>
|
|
6631
|
-
<span class=${`machine-status ${t}`}>${
|
|
6631
|
+
<span class=${`machine-status ${t}`}>${uL(t)}</span>
|
|
6632
6632
|
<span class="machine-chevron" aria-hidden="true">▾</span>
|
|
6633
6633
|
</button>
|
|
6634
6634
|
${this.open?g`
|
|
@@ -6637,18 +6637,18 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6637
6637
|
</div>
|
|
6638
6638
|
`:null}
|
|
6639
6639
|
</div>
|
|
6640
|
-
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=
|
|
6640
|
+
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=lL(e,this.statuses),r=UC(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return g`
|
|
6641
6641
|
<div class=${`machine-option ${t?`selected`:``} ${r?``:`no-actions`}`}>
|
|
6642
6642
|
<button
|
|
6643
6643
|
type="button"
|
|
6644
6644
|
class="machine-option-main"
|
|
6645
|
-
title=${
|
|
6645
|
+
title=${dL(e)}
|
|
6646
6646
|
data-machine-id=${e.id}
|
|
6647
6647
|
@click=${()=>{this.select(e)}}
|
|
6648
6648
|
@keydown=${e=>{this.handleMachineOptionKeydown(e)}}
|
|
6649
6649
|
>
|
|
6650
6650
|
<span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
|
|
6651
|
-
<small>${e.kind===`local`?`Local Pi WebUI`:e.baseUrl??`Remote Pi WebUI`} · ${
|
|
6651
|
+
<small>${e.kind===`local`?`Local Pi WebUI`:e.baseUrl??`Remote Pi WebUI`} · ${uL(n)}</small>
|
|
6652
6652
|
</button>
|
|
6653
6653
|
${r?g`
|
|
6654
6654
|
<div class="machine-option-actions">
|
|
@@ -6668,7 +6668,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6668
6668
|
</div>
|
|
6669
6669
|
`:null}
|
|
6670
6670
|
</div>
|
|
6671
|
-
`}renderActivity(e){let t=
|
|
6671
|
+
`}renderActivity(e){let t=lL(e,this.statuses);if(t===`offline`||t===`error`)return;let n=qu(this.activities[e.id]);return EC(n,n===`terminal`?`Machine terminal active`:`Machine active`)}selectedMachine(){return this.selected??this.machines.find(e=>e.id===`local`)??this.machines[0]}machineSwitcherAriaLabel(e){return`Machine: ${e.name}. Switch machine.`}switcherButton(){return this.renderRoot.querySelector(`.machine-switcher-button`)}handleSwitcherButtonKeydown(e){if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget);return}if(e.key===`ArrowRight`&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.onFocusNextSection();return}e.key===`Escape`&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){if(e.key===`ArrowUp`){this.focusRelativeMachineOption(e.currentTarget,-1,e);return}if(e.key===`ArrowDown`){this.focusRelativeMachineOption(e.currentTarget,1,e);return}if(e.key===`Home`){this.focusIndexedMachineOption(0,e);return}if(e.key===`End`){this.focusIndexedMachineOption(-1,e);return}if(e.key===`ArrowRight`&&this.onFocusNextSection!==void 0){e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection();return}(e.key===`ArrowLeft`||e.key===`Escape`)&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()}))}toggleMenu(e){this.menuStyle=fL(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=fL(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){let e=this.renderRoot.querySelector(`.machine-option.selected .machine-option-main`),t=this.machineOptionButtons()[0],n=e??t;return n===void 0?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}focusRelativeMachineOption(e,t,n){n.preventDefault(),n.stopPropagation();let r=this.machineOptionButtons();if(r.length===0||!(e instanceof HTMLElement))return;let i=r.indexOf(e);i<0||this.focusMachineOptionAt(i+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){let t=this.machineOptionButtons(),n=t[Math.min(Math.max(e,0),t.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(`.machine-option-main`))}toggleActionsMenu(e,t){if(this.openActionsMachineId===e){this.openActionsMachineId=void 0;return}this.actionMenuStyle=SC(t,{constrainTo:`viewport`}),this.openActionsMachineId=e}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}static{this.styles=h`
|
|
6672
6672
|
:host { min-width: 0; display: block; }
|
|
6673
6673
|
.machine-switcher { min-width: 0; }
|
|
6674
6674
|
.machine-switcher-button { box-sizing: border-box; width: 100%; min-width: 0; display: flex; align-items: center; gap: 6px; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 8px; cursor: pointer; text-align: left; }
|
|
@@ -6701,10 +6701,10 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6701
6701
|
.machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
|
|
6702
6702
|
.machine-option-actions-panel button.danger:hover, .machine-option-actions-panel button.danger:focus-visible { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
|
|
6703
6703
|
@keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
|
|
6704
|
-
`}};H([x({attribute:!1})],
|
|
6704
|
+
`}};H([x({attribute:!1})],cL.prototype,`machines`,void 0),H([x({attribute:!1})],cL.prototype,`selected`,void 0),H([x({attribute:!1})],cL.prototype,`statuses`,void 0),H([x({attribute:!1})],cL.prototype,`activities`,void 0),H([x({attribute:!1})],cL.prototype,`onSelect`,void 0),H([x({attribute:!1})],cL.prototype,`onRemove`,void 0),H([x({attribute:!1})],cL.prototype,`onFocusNextSection`,void 0),H([x({attribute:!1})],cL.prototype,`onCancelKeyboardNavigation`,void 0),H([S()],cL.prototype,`open`,void 0),H([S()],cL.prototype,`menuStyle`,void 0),H([S()],cL.prototype,`openActionsMachineId`,void 0),H([S()],cL.prototype,`actionMenuStyle`,void 0),cL=H([b(`machine-switcher`)],cL);function lL(e,t){return t[e.id]?.status??e.status??`unknown`}function uL(e){return e===`online`?`online`:e===`offline`?`offline`:e===`error`?`error`:`unknown`}function dL(e){return e.baseUrl??e.name}function fL(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: ${pL(t.bottom)};`,`left: ${pL(r)};`,`width: ${pL(n)};`,`max-height: ${pL(i)};`].join(` `)}function pL(e){return`${String(Math.round(e))}px`}var mL=[{id:`models`,label:`Models`},{id:`skills`,label:`Skills`},{id:`plugins`,label:`Plugins`}],Q=class extends y{constructor(...e){super(...e),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.projectSessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.unreadSessionIds=new Set,this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.startingSessionCount=0,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.canReorderSessions=!1,this.canCleanupSessions=!1,this.authoritativeSessionPersistence=!1,this.archivedDeleteUnavailableMessage=`Update and restart Pi-Web on this machine to delete archived sessions.`,this.cleanupUnavailableMessage=`Update and restart Pi-Web on this machine to clean up sessions.`,this.skillsEnabled=!1,this.pluginsEnabled=!1,this.projectStatisticsAvailable=!1}async focusSection(e){switch(await this.updateComplete,e){case`machines`:return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case`projects`:return await this.focusNavigableSection(this.projectList);case`workspaces`:return await this.focusNavigableSection(this.workspaceList);case`sessions`:return await this.focusNavigableSection(this.sessionList)}}render(){let e=this.version;return g`
|
|
6705
6705
|
<header>
|
|
6706
6706
|
<strong class="brand" aria-label=${e===void 0?`Pi WebUI`:`Pi WebUI version ${e}`}><span class="brand-symbol" aria-hidden="true">π</span><span>WebUI</span>${e===void 0?null:g`<span class="brand-version">v${e}</span>`}</strong>
|
|
6707
|
-
${
|
|
6707
|
+
${vL(this.machines)?g`
|
|
6708
6708
|
<machine-switcher
|
|
6709
6709
|
.machines=${this.machines}
|
|
6710
6710
|
.selected=${this.selectedMachine}
|
|
@@ -6721,7 +6721,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6721
6721
|
<button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.onShowActions?.()}}>Actions</button>
|
|
6722
6722
|
</div>
|
|
6723
6723
|
</header>
|
|
6724
|
-
${this.compact&&
|
|
6724
|
+
${this.compact&&vL(this.machines)?g`
|
|
6725
6725
|
<machine-list
|
|
6726
6726
|
.machines=${this.machines}
|
|
6727
6727
|
.selected=${this.selectedMachine}
|
|
@@ -6818,9 +6818,9 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6818
6818
|
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
6819
6819
|
></session-list>
|
|
6820
6820
|
<footer class="resource-underbar" aria-label="Resources">
|
|
6821
|
-
${
|
|
6821
|
+
${mL.map(e=>hL(e,e.id===`models`?()=>{this.onOpenModels?.()}:e.id===`skills`?()=>{this.onOpenSkills?.()}:()=>{this.onOpenPlugins?.()},this.skillsEnabled,this.pluginsEnabled))}
|
|
6822
6822
|
</footer>
|
|
6823
|
-
`}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=
|
|
6823
|
+
`}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=yL(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(bL(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
|
|
6824
6824
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
|
|
6825
6825
|
:host([compact]) { flex: 1 1 auto; }
|
|
6826
6826
|
header { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
|
|
@@ -6852,12 +6852,12 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6852
6852
|
:host([compact]) workspace-list[collapsed],
|
|
6853
6853
|
:host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
6854
6854
|
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
6855
|
-
`}};H([x({attribute:!1})],Q.prototype,`machines`,void 0),H([x({attribute:!1})],Q.prototype,`selectedMachine`,void 0),H([x({attribute:!1})],Q.prototype,`machineStatuses`,void 0),H([x({attribute:!1})],Q.prototype,`machineActivities`,void 0),H([x({attribute:!1})],Q.prototype,`projects`,void 0),H([x({attribute:!1})],Q.prototype,`selectedProject`,void 0),H([x({attribute:!1})],Q.prototype,`workspaces`,void 0),H([x({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),H([x({attribute:!1})],Q.prototype,`sessions`,void 0),H([x({attribute:!1})],Q.prototype,`projectSessions`,void 0),H([x({attribute:!1})],Q.prototype,`selectedSession`,void 0),H([x({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),H([x({attribute:!1})],Q.prototype,`sessionActivities`,void 0),H([x({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),H([x({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),H([x({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),H([x({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),H([x({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),H([x({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),H([x({type:String})],Q.prototype,`version`,void 0),H([x({attribute:!1})],Q.prototype,`refreshControl`,void 0),H([x({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),H([x({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),H([x({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),H([x({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),H([x({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),H([x({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),H([x({type:Number})],Q.prototype,`startingSessionCount`,void 0),H([x({type:Boolean})],Q.prototype,`canStartSession`,void 0),H([x({type:Boolean})],Q.prototype,`canDeleteArchivedSessions`,void 0),H([x({type:Boolean})],Q.prototype,`canReloadSessions`,void 0),H([x({type:Boolean})],Q.prototype,`canReorderSessions`,void 0),H([x({type:Boolean})],Q.prototype,`canCleanupSessions`,void 0),H([x({type:Boolean})],Q.prototype,`authoritativeSessionPersistence`,void 0),H([x({type:String})],Q.prototype,`archivedDeleteUnavailableMessage`,void 0),H([x({type:String})],Q.prototype,`cleanupUnavailableMessage`,void 0),H([x({attribute:!1})],Q.prototype,`onShowActions`,void 0),H([x({type:Boolean})],Q.prototype,`skillsEnabled`,void 0),H([x({type:Boolean})],Q.prototype,`pluginsEnabled`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenModels`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenSkills`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenPlugins`,void 0),H([x({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),H([x({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),H([x({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),H([x({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),H([x({attribute:!1})],Q.prototype,`onAddProject`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenProjectBrowser`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenSessionBrowser`,void 0),H([x({attribute:!1})],Q.prototype,`onSelectProject`,void 0),H([x({attribute:!1})],Q.prototype,`onCloseProject`,void 0),H([x({attribute:!1})],Q.prototype,`onCloseProjectTree`,void 0),H([x({attribute:!1})],Q.prototype,`onPinProject`,void 0),H([x({attribute:!1})],Q.prototype,`onUnpinProject`,void 0),H([x({attribute:!1})],Q.prototype,`onShowProjectStatistics`,void 0),H([x({type:Boolean})],Q.prototype,`projectStatisticsAvailable`,void 0),H([x({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),H([x({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),H([x({attribute:!1})],Q.prototype,`onStartSession`,void 0),H([x({attribute:!1})],Q.prototype,`onSelectSession`,void 0),H([x({attribute:!1})],Q.prototype,`onRenameSessionStart`,void 0),H([x({attribute:!1})],Q.prototype,`onRenameSession`,void 0),H([x({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),H([x({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),H([x({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),H([x({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),H([x({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),H([x({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),H([x({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),H([x({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),H([x({attribute:!1})],Q.prototype,`onReloadSession`,void 0),H([x({attribute:!1})],Q.prototype,`onReorderSession`,void 0),H([x({attribute:!1})],Q.prototype,`onPinSession`,void 0),H([x({attribute:!1})],Q.prototype,`onUnpinSession`,void 0),H([x({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),H([x({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),H([x({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),H([x({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),H([x({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),H([x({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),H([C(`machine-list`)],Q.prototype,`machineList`,void 0),H([C(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),H([C(`project-list`)],Q.prototype,`projectList`,void 0),H([C(`workspace-list`)],Q.prototype,`workspaceList`,void 0),H([C(`session-list`)],Q.prototype,`sessionList`,void 0),Q=H([b(`app-navigation-panel`)],Q);function
|
|
6856
|
-
<button type="button" ?disabled=${!
|
|
6857
|
-
${
|
|
6855
|
+
`}};H([x({attribute:!1})],Q.prototype,`machines`,void 0),H([x({attribute:!1})],Q.prototype,`selectedMachine`,void 0),H([x({attribute:!1})],Q.prototype,`machineStatuses`,void 0),H([x({attribute:!1})],Q.prototype,`machineActivities`,void 0),H([x({attribute:!1})],Q.prototype,`projects`,void 0),H([x({attribute:!1})],Q.prototype,`selectedProject`,void 0),H([x({attribute:!1})],Q.prototype,`workspaces`,void 0),H([x({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),H([x({attribute:!1})],Q.prototype,`sessions`,void 0),H([x({attribute:!1})],Q.prototype,`projectSessions`,void 0),H([x({attribute:!1})],Q.prototype,`selectedSession`,void 0),H([x({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),H([x({attribute:!1})],Q.prototype,`sessionActivities`,void 0),H([x({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),H([x({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),H([x({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),H([x({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),H([x({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),H([x({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),H([x({type:String})],Q.prototype,`version`,void 0),H([x({attribute:!1})],Q.prototype,`refreshControl`,void 0),H([x({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),H([x({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),H([x({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),H([x({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),H([x({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),H([x({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),H([x({type:Number})],Q.prototype,`startingSessionCount`,void 0),H([x({type:Boolean})],Q.prototype,`canStartSession`,void 0),H([x({type:Boolean})],Q.prototype,`canDeleteArchivedSessions`,void 0),H([x({type:Boolean})],Q.prototype,`canReloadSessions`,void 0),H([x({type:Boolean})],Q.prototype,`canReorderSessions`,void 0),H([x({type:Boolean})],Q.prototype,`canCleanupSessions`,void 0),H([x({type:Boolean})],Q.prototype,`authoritativeSessionPersistence`,void 0),H([x({type:String})],Q.prototype,`archivedDeleteUnavailableMessage`,void 0),H([x({type:String})],Q.prototype,`cleanupUnavailableMessage`,void 0),H([x({attribute:!1})],Q.prototype,`onShowActions`,void 0),H([x({type:Boolean})],Q.prototype,`skillsEnabled`,void 0),H([x({type:Boolean})],Q.prototype,`pluginsEnabled`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenModels`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenSkills`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenPlugins`,void 0),H([x({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),H([x({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),H([x({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),H([x({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),H([x({attribute:!1})],Q.prototype,`onAddProject`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenProjectBrowser`,void 0),H([x({attribute:!1})],Q.prototype,`onOpenSessionBrowser`,void 0),H([x({attribute:!1})],Q.prototype,`onSelectProject`,void 0),H([x({attribute:!1})],Q.prototype,`onCloseProject`,void 0),H([x({attribute:!1})],Q.prototype,`onCloseProjectTree`,void 0),H([x({attribute:!1})],Q.prototype,`onPinProject`,void 0),H([x({attribute:!1})],Q.prototype,`onUnpinProject`,void 0),H([x({attribute:!1})],Q.prototype,`onShowProjectStatistics`,void 0),H([x({type:Boolean})],Q.prototype,`projectStatisticsAvailable`,void 0),H([x({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),H([x({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),H([x({attribute:!1})],Q.prototype,`onStartSession`,void 0),H([x({attribute:!1})],Q.prototype,`onSelectSession`,void 0),H([x({attribute:!1})],Q.prototype,`onRenameSessionStart`,void 0),H([x({attribute:!1})],Q.prototype,`onRenameSession`,void 0),H([x({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),H([x({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),H([x({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),H([x({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),H([x({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),H([x({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),H([x({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),H([x({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),H([x({attribute:!1})],Q.prototype,`onReloadSession`,void 0),H([x({attribute:!1})],Q.prototype,`onReorderSession`,void 0),H([x({attribute:!1})],Q.prototype,`onPinSession`,void 0),H([x({attribute:!1})],Q.prototype,`onUnpinSession`,void 0),H([x({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),H([x({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),H([x({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),H([x({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),H([x({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),H([x({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),H([C(`machine-list`)],Q.prototype,`machineList`,void 0),H([C(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),H([C(`project-list`)],Q.prototype,`projectList`,void 0),H([C(`workspace-list`)],Q.prototype,`workspaceList`,void 0),H([C(`session-list`)],Q.prototype,`sessionList`,void 0),Q=H([b(`app-navigation-panel`)],Q);function hL(e,t,n,r){return g`
|
|
6856
|
+
<button type="button" ?disabled=${!gL(e.id,n,r)} title=${e.label} aria-label=${e.label} @click=${t}>
|
|
6857
|
+
${_L(e.id)}
|
|
6858
6858
|
<span>${e.label}</span>
|
|
6859
6859
|
</button>
|
|
6860
|
-
`}function
|
|
6860
|
+
`}function gL(e,t=!1,n=t){return e===`models`||e===`skills`&&t||e===`plugins`&&n}function _L(e){switch(e){case`models`:return _`
|
|
6861
6861
|
<svg class="resource-underbar-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
6862
6862
|
<rect x="4" y="4" width="16" height="16" rx="2"></rect>
|
|
6863
6863
|
<rect x="9" y="9" width="6" height="6"></rect>
|
|
@@ -6875,7 +6875,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6875
6875
|
<path d="M6 13V8a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v5a6 6 0 0 1-12 0Z"></path>
|
|
6876
6876
|
<path d="M12 19v3"></path>
|
|
6877
6877
|
</svg>
|
|
6878
|
-
`}}function
|
|
6878
|
+
`}}function vL(e){return e.length>1}function yL(e,t){let n=xL(t);return n[n.indexOf(e)-1]}function bL(e,t){let n=xL(t);return n[n.indexOf(e)+1]??`chat`}function xL(e){return Zx.filter(t=>t!==`machines`||vL(e))}var SL=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),CL=420,wL=4,TL=class extends y{constructor(...e){super(...e),this.side=`navigation`,this.collapsed=!1,this.resizable=!1,this.controls=``,this.resizeLabel=`Resize panel`,this.expandLabel=`Expand panel`,this.collapseLabel=`Collapse panel`,this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){let e=this.collapsed?this.expandLabel:this.collapseLabel;return g`
|
|
6879
6879
|
${this.renderResizeHandle()}
|
|
6880
6880
|
<button
|
|
6881
6881
|
type="button"
|
|
@@ -6905,7 +6905,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6905
6905
|
@dblclick=${e=>{this.onResizeDoubleClick(e)}}
|
|
6906
6906
|
@keydown=${e=>{this.onResizeKeyDown(e)}}
|
|
6907
6907
|
></div>
|
|
6908
|
-
`}resizeAriaValueNow(){return this.panelWidth===void 0?v:String(Math.round(this.panelWidth))}renderIcon(){return g`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${this.iconDirection()===`left`?`M15 18l-6-6 6-6`:`M9 18l6-6-6-6`}/></svg>`}iconDirection(){return this.side===`navigation`?this.collapsed?`right`:`left`:this.collapsed?`left`:`right`}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;let t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=this.resizeStartWidth();n!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:n,handle:t,moved:!1},this.toggleAttribute(`resizing`,!0))}onResizePointerMove(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=
|
|
6908
|
+
`}resizeAriaValueNow(){return this.panelWidth===void 0?v:String(Math.round(this.panelWidth))}renderIcon(){return g`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${this.iconDirection()===`left`?`M15 18l-6-6 6-6`:`M9 18l6-6-6-6`}/></svg>`}iconDirection(){return this.side===`navigation`?this.collapsed?`right`:`left`:this.collapsed?`left`:`right`}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;let t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=this.resizeStartWidth();n!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:n,handle:t,moved:!1},this.toggleAttribute(`resizing`,!0))}onResizePointerMove(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=wL)&&(t.moved=!0,this.commitPanelWidth(hS(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),this.finishActiveResize(),t.moved||this.registerTapForReset())}onResizePointerCancel(e){this.activeResize?.pointerId===e.pointerId&&this.finishActiveResize()}onResizeDoubleClick(e){e.preventDefault(),e.stopPropagation(),this.resetPanelSize()}onResizeKeyDown(e){if(!this.resizable||!SL.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=gS(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});n!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(n),this.onResizeEnd?.())}registerTapForReset(){let e=Date.now();if(e-this.lastTapAt<=CL){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){let e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return _S(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(_S(this.side,e,this.resizeConstraints()))}finishActiveResize(){let e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute(`resizing`,!1),this.onResizeEnd?.()}}resizeConstraints(){let e=pS(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=h`
|
|
6909
6909
|
:host { position: relative; min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: visible; background: var(--pi-border-muted); z-index: 2; }
|
|
6910
6910
|
:host([side="navigation"]) { grid-column: 2; }
|
|
6911
6911
|
:host([side="workspace"]) { grid-column: 4; }
|
|
@@ -6924,7 +6924,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6924
6924
|
@media (max-width: 760px) {
|
|
6925
6925
|
:host([side="navigation"]) { display: none; }
|
|
6926
6926
|
}
|
|
6927
|
-
`}};H([x({reflect:!0})],
|
|
6927
|
+
`}};H([x({reflect:!0})],TL.prototype,`side`,void 0),H([x({type:Boolean,reflect:!0})],TL.prototype,`collapsed`,void 0),H([x({type:Boolean})],TL.prototype,`resizable`,void 0),H([x({type:Number})],TL.prototype,`panelWidth`,void 0),H([x({type:Number})],TL.prototype,`minWidth`,void 0),H([x({type:Number})],TL.prototype,`maxWidth`,void 0),H([x()],TL.prototype,`controls`,void 0),H([x()],TL.prototype,`resizeLabel`,void 0),H([x()],TL.prototype,`expandLabel`,void 0),H([x()],TL.prototype,`collapseLabel`,void 0),H([x({attribute:!1})],TL.prototype,`onToggle`,void 0),H([x({attribute:!1})],TL.prototype,`onResizeStart`,void 0),H([x({attribute:!1})],TL.prototype,`onResize`,void 0),H([x({attribute:!1})],TL.prototype,`onResizeEnd`,void 0),H([x({attribute:!1})],TL.prototype,`onReset`,void 0),TL=H([b(`app-panel-edge-control`)],TL);var EL=class extends y{constructor(...e){super(...e),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){let e=`Full page reload`;return g`
|
|
6928
6928
|
<button
|
|
6929
6929
|
class="app-refresh-button"
|
|
6930
6930
|
title=${e}
|
|
@@ -6943,7 +6943,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
6943
6943
|
:host, :host * { -webkit-user-select: none; user-select: none; }
|
|
6944
6944
|
.app-refresh-button { box-sizing: border-box; width: 36px; height: 36px; display: grid; place-items: center; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 0; line-height: 1; cursor: pointer; touch-action: manipulation; -webkit-touch-callout: none; }
|
|
6945
6945
|
.app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
6946
|
-
`}};H([x({attribute:!1})],
|
|
6946
|
+
`}};H([x({attribute:!1})],EL.prototype,`onReload`,void 0),EL=H([b(`app-refresh-control`)],EL);var DL=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`],OL=`file-manager`,kL=`browser`,AL=[...DL],jL=new Set(DL),ML=`pi-webui:activity-rail-order`;function NL(){return typeof localStorage>`u`?void 0:localStorage}function PL(e){return jL.has(e)}function FL(e){if(!Array.isArray(e))return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`)return;let e=r===OL?`git-update-manager`:r;if(e!==kL){if(!PL(e)||n.has(e))return;n.add(e),t.push(e)}}if(t.length===DL.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===DL.length?r:void 0}function IL(){try{let e=NL();if(e===void 0)return;let t=e.getItem(ML);return t===null?void 0:FL(JSON.parse(t))}catch{return}}function LL(e){try{let t=NL();if(t===void 0)return;t.setItem(ML,JSON.stringify(e))}catch{}}var RL=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`];function zL(e){return RL.includes(e)}function BL(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}var VL=class extends y{constructor(){super(),this.terminalCount=0,this.gitUpdateManagerCount=0,this.systemPromptEnabled=!1,this.historyEnabled=!1,this.railOrder=[...AL],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(),BL(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||!zL(n)){this.dragItem=void 0;return}let r=[...this.railOrder],i=r.indexOf(this.dragItem),a=r.indexOf(n);if(i===-1||a===-1){this.dragItem=void 0;return}r.splice(i,1),r.splice(a,0,this.dragItem),this.railOrder=r,this.onRailOrderChange?.(r),this.dragItem=void 0},typeof window<`u`&&`matchMedia`in window&&(this.desktopMedia=window.matchMedia(Ix))}connectedCallback(){super.connectedCallback(),this.desktopMedia?.addEventListener(`change`,this.onDesktopMediaChange)}disconnectedCallback(){super.disconnectedCallback(),this.desktopMedia?.removeEventListener(`change`,this.onDesktopMediaChange)}updated(e){!e.has(`compactOpen`)||!this.compactOpen||this.isDesktopRailLayout()||this.renderRoot.querySelector(`.compact-rail-close`)?.focus()}isDesktopRailLayout(){return this.desktopMedia?.matches??!0}closeCompactBeforeAction(){this.isDesktopRailLayout()||this.onCloseCompact?.()}invokeCoreAction(e){this.closeCompactBeforeAction(),e?.()}resolveDragTarget(e){if(e===null||!(e instanceof HTMLElement))return null;let t=e.closest(`[data-rail-item]`);return t instanceof HTMLElement?t:null}dndProps(e){return{draggable:`true`,"data-rail-item":e}}renderReorderableButton(e){switch(e){case`terminal`:return this.renderTerminalButton();case`git-update-manager`:return this.renderGitUpdateManagerButton();case`theme`:return this.renderThemeButton();case`system-prompt`:return this.renderSystemPromptButton();case`history`:return this.renderHistoryButton();case`info`:return this.renderInfoButton()}}renderTerminalButton(){let e=this.dndProps(`terminal`),t=this.terminalCount>0?this.terminalCount:void 0,n=t===void 0?``:`${String(t)} active terminal${t===1?``:`s`}`;return g`
|
|
6947
6947
|
<button
|
|
6948
6948
|
type="button"
|
|
6949
6949
|
class="icon-button terminal-button"
|
|
@@ -7095,7 +7095,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7095
7095
|
${e.badge===void 0?v:g`<span class="rail-badge" aria-hidden="true">${e.badge}</span>`}
|
|
7096
7096
|
</button>
|
|
7097
7097
|
`}renderRailContents(){return g`
|
|
7098
|
-
${(this.railOrder.length===0?[...
|
|
7098
|
+
${(this.railOrder.length===0?[...AL]:this.railOrder).map(e=>this.renderReorderableButton(e))}
|
|
7099
7099
|
${this.pluginItems.length===0?v:g`
|
|
7100
7100
|
<div class="rail-plugin-separator" role="separator"></div>
|
|
7101
7101
|
${this.pluginItems.map(e=>this.renderPluginButton(e))}
|
|
@@ -7210,7 +7210,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7210
7210
|
.compact-rail-dialog { height: 100%; }
|
|
7211
7211
|
.compact-rail-dialog .rail { box-shadow: 8px 0 24px var(--pi-shadow); }
|
|
7212
7212
|
.compact-rail-close { margin-bottom: 2px; }
|
|
7213
|
-
`}};H([x({attribute:!1})],
|
|
7213
|
+
`}};H([x({attribute:!1})],VL.prototype,`onOpenTerminal`,void 0),H([x({attribute:!1})],VL.prototype,`onOpenGitUpdateManager`,void 0),H([x({attribute:!1})],VL.prototype,`onOpenTheme`,void 0),H([x({attribute:!1})],VL.prototype,`onOpenSystemPrompt`,void 0),H([x({attribute:!1})],VL.prototype,`onOpenHistory`,void 0),H([x({attribute:!1})],VL.prototype,`onOpenInfo`,void 0),H([x({attribute:!1})],VL.prototype,`onOpenSettings`,void 0),H([x({type:Number})],VL.prototype,`terminalCount`,void 0),H([x({type:Number})],VL.prototype,`gitUpdateManagerCount`,void 0),H([x({type:Boolean})],VL.prototype,`systemPromptEnabled`,void 0),H([x({type:Boolean})],VL.prototype,`historyEnabled`,void 0),H([x({attribute:!1})],VL.prototype,`railOrder`,void 0),H([x({attribute:!1})],VL.prototype,`onRailOrderChange`,void 0),H([x({attribute:!1})],VL.prototype,`pluginItems`,void 0),H([x({attribute:!1})],VL.prototype,`onOpenPluginActivity`,void 0),H([x({type:Boolean})],VL.prototype,`compactOpen`,void 0),H([x({attribute:!1})],VL.prototype,`onCloseCompact`,void 0),VL=H([b(`activity-rail`)],VL);var HL=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},UL=class extends y{constructor(...e){super(...e),this.close=()=>{this.onClose?.()},this.handleCancel=e=>{e.preventDefault(),this.close()},this.handleBackdropClick=e=>{e.target===e.currentTarget&&this.close()}}firstUpdated(){let e=this.nativeDialog;e?.isConnected===!0&&(e.showModal(),this.closeButton?.focus())}disconnectedCallback(){let e=this.nativeDialog;e?.open===!0&&e.close(),super.disconnectedCallback()}render(){let e=uy(this.activity,this.context,this.onReportError??HL);return g`
|
|
7214
7214
|
<dialog
|
|
7215
7215
|
class="plugin-activity-backdrop"
|
|
7216
7216
|
role="dialog"
|
|
@@ -7272,7 +7272,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7272
7272
|
header { padding-top: max(12px, env(safe-area-inset-top)); }
|
|
7273
7273
|
.plugin-activity-body { padding-bottom: max(12px, env(safe-area-inset-bottom)); }
|
|
7274
7274
|
}
|
|
7275
|
-
`}};H([x({attribute:!1})],
|
|
7275
|
+
`}};H([x({attribute:!1})],UL.prototype,`activity`,void 0),H([x({attribute:!1})],UL.prototype,`context`,void 0),H([x({attribute:!1})],UL.prototype,`onClose`,void 0),H([x({attribute:!1})],UL.prototype,`onReportError`,void 0),H([C(`dialog.plugin-activity-backdrop`)],UL.prototype,`nativeDialog`,void 0),H([C(`.plugin-activity-close`)],UL.prototype,`closeButton`,void 0),UL=H([b(`plugin-activity-dialog`)],UL);var WL=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.api=hc,this.loadingStatus=!1,this.loadingDiff=!1,this.error=``,this.statusRequest=0,this.diffRequest=0,this.refresh=async()=>{let e=this.workspace;if(e===void 0)return;let t=this.machineId,n=this.selectedChange?.id,r=++this.statusRequest;this.diffRequest+=1,this.status=void 0,this.selectedDiff=void 0,this.loadingStatus=!0,this.loadingDiff=!1,this.error=``;try{let i=await this.api.gitStatus(e.projectId,e.id,t);if(r!==this.statusRequest||!this.isCurrentWorkspace(e,t))return;this.status=i,this.loadingStatus=!1,this.onStatusChange?.(i);let a=n===void 0?void 0:KL(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=YL(n)}},this.selectChange=e=>{let t=this.workspace;if(t===void 0)return;let n=this.machineId;this.selectedChange=e,this.selectedDiff=void 0,this.error=``,this.loadDiff(e,t,n)},this.onViewportResize=()=>{this.bounds!==void 0&&(this.bounds=XS(this.bounds,this.viewport()))},this.handleMovePointerDown=e=>{this.startPointerInteraction(`move`,e)},this.handleResizePointerDown=e=>{this.startPointerInteraction(`resize`,e)},this.handlePointerMove=e=>{let t=this.pointerInteraction;if(t?.pointerId!==e.pointerId)return;e.preventDefault();let n={x:e.clientX-t.startClientX,y:e.clientY-t.startClientY};this.bounds=t.operation===`move`?JS(t.bounds,n,this.viewport()):YS(t.bounds,n,this.viewport())},this.handlePointerUp=e=>{this.pointerInteraction?.pointerId===e.pointerId&&(e.preventDefault(),this.finishPointerInteraction())},this.handlePointerCancel=e=>{this.pointerInteraction?.pointerId===e.pointerId&&this.finishPointerInteraction()},this.close=()=>{this.finishPointerInteraction(),this.onClose?.()}}connectedCallback(){super.connectedCallback(),window.addEventListener(`resize`,this.onViewportResize),this.ensureWorkspaceScope()}willUpdate(){this.ensureWorkspaceScope()}disconnectedCallback(){this.finishPointerInteraction(),this.statusRequest+=1,this.diffRequest+=1,window.removeEventListener(`resize`,this.onViewportResize),super.disconnectedCallback()}render(){return g`
|
|
7276
7276
|
<div class="git-update-manager-backdrop" role="dialog" aria-modal="true" aria-label="Git Update Manager">
|
|
7277
7277
|
<section class=${this.bounds===void 0?`git-update-manager-frame`:`git-update-manager-frame git-update-manager-frame-positioned`} style=${this.frameStyle()}>
|
|
7278
7278
|
<header class="git-update-manager-header">
|
|
@@ -7306,15 +7306,15 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7306
7306
|
></div>
|
|
7307
7307
|
</section>
|
|
7308
7308
|
</div>
|
|
7309
|
-
`}ensureWorkspaceScope(){let e=
|
|
7309
|
+
`}ensureWorkspaceScope(){let e=JL(this.workspace,this.machineId);e!==this.workspaceScope&&(this.workspaceScope=e,this.statusRequest+=1,this.diffRequest+=1,this.status=void 0,this.selectedChange=void 0,this.selectedDiff=void 0,this.loadingStatus=!1,this.loadingDiff=!1,this.error=``,e!==void 0&&this.isConnected&&this.refresh())}renderChangeList(){if(this.loadingStatus)return g`<p class="git-update-manager-empty">Loading changes…</p>`;let e=this.status;if(e===void 0)return g`<p class="git-update-manager-empty">Refresh to load Git changes.</p>`;if(!e.isGitRepo)return g`<p class="git-update-manager-empty">This workspace is not a Git repository.</p>`;let t=Cu(e.files);return t.staged.length===0&&t.unstaged.length===0?g`<p class="git-update-manager-empty">No Git changes.</p>`:g`
|
|
7310
7310
|
${this.renderChangeGroup(`staged`,t.staged)}
|
|
7311
7311
|
${this.renderChangeGroup(`unstaged`,t.unstaged)}
|
|
7312
|
-
`}renderChangeGroup(e,t){if(t.length===0)return null;let n=
|
|
7312
|
+
`}renderChangeGroup(e,t){if(t.length===0)return null;let n=qL(e);return g`
|
|
7313
7313
|
<section class="git-update-manager-change-group" aria-label=${`${n} changes`}>
|
|
7314
7314
|
<h2>${n} (${String(t.length)})</h2>
|
|
7315
7315
|
${t.map(e=>this.renderChange(e))}
|
|
7316
7316
|
</section>
|
|
7317
|
-
`}renderChange(e){let t=this.selectedChange?.id===e.id,n=Du(e),r=Eu(e.state),i=
|
|
7317
|
+
`}renderChange(e){let t=this.selectedChange?.id===e.id,n=Du(e),r=Eu(e.state),i=qL(e.scope);return g`
|
|
7318
7318
|
<button
|
|
7319
7319
|
type="button"
|
|
7320
7320
|
class=${`git-update-manager-entry ${t?`selected`:``}`}
|
|
@@ -7326,13 +7326,13 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7326
7326
|
<span class="git-update-manager-path">${n}</span>
|
|
7327
7327
|
<span class="git-update-manager-scope">${i}</span>
|
|
7328
7328
|
</button>
|
|
7329
|
-
`}renderDiffPreview(){let e=this.selectedChange;if(e===void 0)return g`<p class="git-update-manager-empty">Select a Git change to review.</p>`;if(this.error!==``)return g`<p class="git-update-manager-empty">Could not load ${Du(e)}.</p>`;if(this.loadingDiff||this.selectedDiff===void 0)return g`<p class="git-update-manager-empty">Loading ${Du(e)}…</p>`;let t=this.selectedDiff;return
|
|
7329
|
+
`}renderDiffPreview(){let e=this.selectedChange;if(e===void 0)return g`<p class="git-update-manager-empty">Select a Git change to review.</p>`;if(this.error!==``)return g`<p class="git-update-manager-empty">Could not load ${Du(e)}.</p>`;if(this.loadingDiff||this.selectedDiff===void 0)return g`<p class="git-update-manager-empty">Loading ${Du(e)}…</p>`;let t=this.selectedDiff;return GL(),g`
|
|
7330
7330
|
<header class="git-update-manager-diff-header">
|
|
7331
7331
|
<strong>${Du(e)}</strong>
|
|
7332
|
-
<small>${
|
|
7332
|
+
<small>${qL(e.scope)} · ${Eu(e.state)}${t.truncated?` · truncated`:``}</small>
|
|
7333
7333
|
</header>
|
|
7334
7334
|
<unified-diff-viewer .diff=${t.diff}></unified-diff-viewer>
|
|
7335
|
-
`}async loadDiff(e,t,n){let r=++this.diffRequest;this.loadingDiff=!0;try{let i=await this.api.gitDiff(t.projectId,t.id,{path:e.path,staged:e.scope===`staged`},n);if(r!==this.diffRequest||!this.isCurrentWorkspace(t,n)||this.selectedChange?.id!==e.id)return;this.selectedDiff=i,this.loadingDiff=!1,this.error=``}catch(i){if(r!==this.diffRequest||!this.isCurrentWorkspace(t,n)||this.selectedChange?.id!==e.id)return;this.selectedDiff=void 0,this.loadingDiff=!1,this.error=
|
|
7335
|
+
`}async loadDiff(e,t,n){let r=++this.diffRequest;this.loadingDiff=!0;try{let i=await this.api.gitDiff(t.projectId,t.id,{path:e.path,staged:e.scope===`staged`},n);if(r!==this.diffRequest||!this.isCurrentWorkspace(t,n)||this.selectedChange?.id!==e.id)return;this.selectedDiff=i,this.loadingDiff=!1,this.error=``}catch(i){if(r!==this.diffRequest||!this.isCurrentWorkspace(t,n)||this.selectedChange?.id!==e.id)return;this.selectedDiff=void 0,this.loadingDiff=!1,this.error=YL(i)}}startPointerInteraction(e,t){if(t.button!==0)return;let n=t.currentTarget;if(!(n instanceof HTMLElement))return;let r=n.closest(`.git-update-manager-frame`);if(!(r instanceof HTMLElement))return;t.preventDefault(),t.stopPropagation();let i=XS(this.boundsFromFrame(r),this.viewport());n.setPointerCapture(t.pointerId),this.bounds=i,this.pointerInteraction={operation:e,pointerId:t.pointerId,target:n,startClientX:t.clientX,startClientY:t.clientY,bounds:i}}boundsFromFrame(e){let{left:t,top:n,width:r,height:i}=e.getBoundingClientRect();return{left:t,top:n,width:r,height:i}}viewport(){return typeof window>`u`?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight}}frameStyle(){let e=this.bounds;return e===void 0?``:`left: ${String(e.left)}px; top: ${String(e.top)}px; width: ${String(e.width)}px; height: ${String(e.height)}px;`}finishPointerInteraction(){let e=this.pointerInteraction;if(e!==void 0){try{e.target.releasePointerCapture(e.pointerId)}catch{}this.pointerInteraction=void 0}}isCurrentWorkspace(e,t){return this.workspace?.id===e.id&&this.workspace.projectId===e.projectId&&this.machineId===t}static{this.styles=h`
|
|
7336
7336
|
:host { position: fixed; inset: 0; z-index: 80; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
7337
7337
|
.git-update-manager-backdrop { width: 100%; height: 100dvh; display: grid; place-items: center; padding: 16px; background: rgba(0, 0, 0, .48); }
|
|
7338
7338
|
.git-update-manager-frame { position: relative; display: flex; flex-direction: column; width: min(calc(100vw - 32px), 1280px); height: min(calc(100vh - 32px), 880px); overflow: hidden; border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 64px var(--pi-shadow-strong); }
|
|
@@ -7371,7 +7371,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7371
7371
|
.git-update-manager-workspace { grid-template-columns: 1fr; grid-template-rows: minmax(190px, 40%) minmax(0, 1fr); }
|
|
7372
7372
|
.git-update-manager-entries { border-right: 0; border-bottom: 1px solid var(--pi-border); }
|
|
7373
7373
|
}
|
|
7374
|
-
`}};H([x({attribute:!1})],UL.prototype,`onClose`,void 0),H([x({attribute:!1})],UL.prototype,`onStatusChange`,void 0),H([x({attribute:!1})],UL.prototype,`workspace`,void 0),H([x()],UL.prototype,`machineId`,void 0),H([x({attribute:!1})],UL.prototype,`api`,void 0),H([S()],UL.prototype,`status`,void 0),H([S()],UL.prototype,`selectedChange`,void 0),H([S()],UL.prototype,`selectedDiff`,void 0),H([S()],UL.prototype,`loadingStatus`,void 0),H([S()],UL.prototype,`loadingDiff`,void 0),H([S()],UL.prototype,`error`,void 0),H([S()],UL.prototype,`bounds`,void 0),UL=H([b(`git-update-manager-panel`)],UL);function WL(){sb(()=>import(`./UnifiedDiffViewer-I9Fc0TRx.js`),[],import.meta.url)}function GL(e,t){let n=Cu(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function KL(e){return e===`staged`?`Staged`:`Unstaged`}function qL(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function JL(e){return e instanceof Error?e.message:String(e)}var YL=900*1e3,XL=750,ZL=[1e3,3e3,8e3,15e3,3e4],QL={capture:!0},$L=`auto:on`,eR=`auto:off`,tR=`theme:`,nR=Yl(`core:workspace.files`),rR=Yl(`core:workspace.git`),iR=Yl(`core:workspace.terminal`),aR=`workspace-memory`,oR=`workspace.memory`,sR=`workspace-memory:workspace.memory`,cR=`workspace-learned-skills`,lR=`workspace.learned-skills`,uR=`workspace-learned-skills:workspace.learned-skills`,dR=320,fR=2,pR=`(min-width: 1181px)`,mR=75,hR=`Could not remember this model policy; this session still uses it.`,$=class extends y{constructor(e={}){super(),this.state=Il(),this.sessionUnread=new Jv({onChange:e=>{R(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new hh(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.hostSpeech=new xh({onStateChange:()=>{this.hostSpeechSurfaceVisible()&&this.requestUpdate()}}),this.sessions=new gm(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Qp,{refreshProjectSessionCatalog:()=>this.projectCatalog.refresh(),notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(R(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)},onStarterModelPolicyConfirmed:e=>{this.handleStarterModelPolicyConfirmed(e)}}),this.workspaces=new b_(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new v_,{onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new zu(()=>this.state,{workspaces:sc.workspaces,applySnapshot:async e=>{await this.workspaces.reconcileProjectCatalog(e)},captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectActivityOwnership=new Xu(()=>this.state,e=>{this.setState(e)},{api:sc,captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onProjectTopology:async e=>{let t=this.state.projects.find(t=>t.id===e.projectId&&t.path===e.projectPath);t!==void 0&&await this.workspaces.reconcileProjectCatalog({machineId:e.machineId,project:t,workspaces:e.workspaces,...e.topologyRequest===void 0?{}:{topologyRequest:e.topologyRequest}})},onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Hl(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new Kl(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.projects=new Fu(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e),this.recentProjects.load()}}),this.machines=new ju(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new Qu(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new cu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new mu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new xu(()=>this.state,e=>{this.setState(e)}),this.learnedSkills=new _u(()=>this.state,e=>{this.setState(e)}),this.recentProjects=new Vu({machineId:()=>R(this.state),onChange:()=>{this.requestUpdate()},onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.keyboard=new X_,this.realtime=new gp,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new M_,this.terminalSelection=new G_,this.appShell=new Lx(this),this.browserResume=new Bx({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.speechInputSettingsConnected=!1,this.speechInputSettingsRequestSeq=0,this.isSpeechInputSettingsRequestCurrent=e=>this.speechInputSettingsConnected&&e===this.speechInputSettingsRequestSeq,this.speechInputSettingsChannelDispatchQueued=!1,this.speechInputSettingsChannelRefreshInFlight=!1,this.panelCollapse=new cS(this),this.panelResize=new fS(this),this.navigationSections=new aS(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=gR(),this.reportActivityRailError=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=gy()??fy,this.activeThemeId=dy,this.isRefreshingApp=!1,this.recentProjectDialogInitialView=`closed-actions`,this.recentProjectDialogGeneration=0,this.starterSessionDefaultsSeq=0,this.starterModelPolicyPreferenceReadError=``,this.starterModelPolicyPreferenceWriter=new Sv({save:async(e,t)=>{let n=await cc.updateSessionDefaults(e.cwd,{starterModelPolicyPreference:t},e.machineId),r=this.starterModelPolicyPreferenceScope();return r?.machineId===e.machineId&&r.cwd===e.cwd&&(this.starterModelPolicyPreferenceReadError=``),n},onStateChange:()=>{this.requestUpdate()}}),this.confirmedStarterModelPolicyPreferenceWriter=new Dv({remember:(e,t)=>cc.rememberCurrentModelPolicy(t,e.machineId),onStateChange:(e,t)=>{this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(e)&&this.confirmedStarterModelPolicyUiGeneration===this.starterModelPolicySelectionGeneration&&(!t.saving&&t.error===void 0&&(this.starterModelPolicyPreferenceReadError=``),this.requestUpdate())}}),this.starterModelPolicySelectionGeneration=0,this.modelTierCatalogLoading=!1,this.modelTierCatalogError=``,this.activeModelPolicyApplyGeneration=0,this.modelTierCatalogSeq=0,this.modelsConfigDialogOpen=!1,this.projectBrowserOpen=!1,this.statisticsLoading=!1,this.statisticsRequestGeneration=0,this.sessionBrowserOpen=!1,this.skillsConfigDialogOpen=!1,this.pluginsConfigDialogOpen=!1,this.systemPromptDialogOpen=!1,this.gitUpdateManagerPanelOpen=!1,this.terminalModalOpen=!1,this.terminalModalMaximized=!1,this.initialTerminalModalPreferences=rC(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.initialWorkspaceTabVisibility=dC(),this.terminalTabHidden=this.initialWorkspaceTabVisibility.terminalHidden,this.infoTabHidden=this.initialWorkspaceTabVisibility.infoHidden,this.railOrder=FL()??[...kL],this.compactRailOpen=!1,this.activeActivityRailGeneration=0,this.settingsSection=NS(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=wc(void 0),this.sessionWarningVisibility=ny(),this.onPopState=()=>void this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)}),this.onPageShow=()=>{this.renegotiateUnreadMachines(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onTerminalModalViewportResize=()=>{this.terminalModalBounds!==void 0&&(this.terminalModalBounds=XS(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{if(e.key===`Escape`&&this.promptEditor?.cancelSpeechInput()===!0){e.preventDefault(),e.stopPropagation();return}this.compactRailOpen||this.activeActivityRailId!==void 0||this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.state.actionPaletteOpen||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.closeCompactActivityRail=()=>{if(!this.compactRailOpen)return;this.compactRailOpen=!1;let e=this.compactActivityRailLauncher;this.updateComplete.then(()=>{!this.compactRailOpen&&this.activeActivityRailId===void 0&&(e===void 0?this.currentCompactActivityRailLauncher()?.focus():this.restoreActivityRailFocus(e))})},this.toggleCompactActivityRail=e=>{this.appShell.isDesktopActivityRailLayout||(!this.compactRailOpen&&e!==void 0&&(this.compactActivityRailLauncher=e),this.compactRailOpen=!this.compactRailOpen)},this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStartSessionPrompt=(e,t,n,r)=>{if(!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e))return;if(this.starterModelPolicyBlocksStart()){let e=this.starterNoticeScope();e!==void 0&&this.publishStarterNotice(wl(e));return}this.starterNotice=void 0;let i=this.state.selectedWorkspace?.id,a=R(this.state),o=this.selectedProjectWorkTarget(a),s=this.starterModelPolicy,c=this.starterPlusModelPolicyInitializer();this.starterModelPolicySelectionSupported(a)&&c===void 0||((c===void 0?this.sessions.startSessionWithPrompt(e,t,n,r,this.starterModelPolicyStartSnapshot(),e=>{this.clearStarterModelPolicyAfterSuccessfulStart(e,i,s)}):this.sessions.startPlusSessionWithPrompt(e,t,n,r??`inline`,c,()=>void 0)).then(e=>{e&&this.recordProjectWork(o)}).catch(e=>{i!==void 0&&this.publishStarterNotice(Tl(`start-failed`,`Could not start the session. ${WR(e)}`,{machineId:a,workspaceId:i}))}),this.focusChatComposer())},this.handleSelectStarterModel=()=>{this.openStarterModelDialog()},this.handleSelectStarterThinking=()=>{this.openStarterThinkingDialog()},this.handleSelectStarterPolicyMode=async e=>{let t=this.starterModelPolicy;if(t===void 0||t.mode===e)return;if(this.starterModelPolicySelectionSupported()){let n=e===`exact`?$c(t):t.tier===void 0?{...t,mode:`tiered`}:Qc(t,t.tier);this.setStarterModelPolicyDraft(n),this.ensureModelTierCatalog(R(this.state));return}if(e===`exact`){let e=$c(t);this.setStarterModelPolicyDraft(e);let n=this.starterSessionDefaults,r=n===void 0?void 0:qc(n);r!==void 0&&Zc(e.exact,r)&&this.persistStarterModelPolicyPreference(e);return}let n=t.tier===void 0?{...t,mode:`tiered`}:Qc(t,t.tier),r=this.setStarterModelPolicyDraft(n);if(n.tier===void 0){this.ensureModelTierCatalog(R(this.state));return}let i=await this.ensureStarterModelPolicyCatalog();this.starterModelPolicy!==r||i===void 0||nl(r,i)!==void 0&&this.persistStarterModelPolicyPreference(r)},this.handleSelectStarterPolicyTier=async e=>{let t=this.starterModelPolicy,n=await this.ensureStarterModelPolicyCatalog();if(t===void 0||t!==this.starterModelPolicy||n===void 0)return;let r=Qc(t,e);if(this.starterModelPolicySelectionSupported()){this.setStarterModelPolicyDraft(r);return}nl(r,n)!==void 0&&(this.setStarterModelPolicyDraft(r),this.persistStarterModelPolicyPreference(r))},this.handleSelectStarterPolicyThinking=async e=>{await this.pickStarterThinking(e)},this.handleSelectActivePolicyMode=async e=>{let t=await this.prepareActiveModelPolicyDraft();if(!(t===void 0||t!==this.activeModelPolicyDraftForState(this.state)||t.mode===e)){if(this.cancelActiveModelPolicyApply(),e===`exact`){this.setActiveModelPolicyDraft($c(t)),this.scheduleActiveExactModelPolicyApply();return}if(t.tier===void 0){this.setActiveModelPolicyDraft({...t,mode:`tiered`});return}this.setActiveModelPolicyDraft(Qc(t,t.tier)),await this.applyActiveModelPolicyDraft()}},this.handleSelectActivePolicyTier=async e=>{let t=await this.prepareActiveModelPolicyDraft();if(t===void 0||t!==this.activeModelPolicyDraftForState(this.state))return;this.cancelActiveModelPolicyApply();let n=Qc(t,e);this.setActiveModelPolicyDraft(n),await this.applyActiveModelPolicyDraft()},this.handleSelectActivePolicyThinking=async e=>{await this.pickThinking(e)},this.handleOpenTerminalFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.terminalModalOpen=!0)},this.handleOpenGitUpdateManagerFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.gitUpdateManagerPanelOpen=!0)},this.handleCloseGitUpdateManagerPanel=()=>{this.gitUpdateManagerPanelOpen=!1},this.handleOpenThemeFromRail=()=>{this.closeCompactActivityRail(),this.openThemeDialog()},this.handleRailOrderChange=e=>{this.railOrder=e,IL(e)},this.handleCloseTerminalModal=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalOpen=!1},this.toggleTerminalModalMaximized=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalMaximized=!this.terminalModalMaximized},this.handleTerminalModalMovePointerDown=e=>{this.startTerminalModalPointerInteraction(`move`,e)},this.handleTerminalModalResizePointerDown=e=>{this.startTerminalModalPointerInteraction(`resize`,e)},this.handleTerminalModalPointerMove=e=>{let t=this.terminalModalPointerInteraction;if(t?.pointerId!==e.pointerId)return;e.preventDefault();let n={x:e.clientX-t.startClientX,y:e.clientY-t.startClientY},r=this.terminalModalViewport();this.terminalModalBounds=t.operation===`move`?JS(t.bounds,n,r):YS(t.bounds,n,r)},this.handleTerminalModalPointerUp=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&(e.preventDefault(),this.finishTerminalModalPointerInteraction())},this.handleTerminalModalPointerCancel=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&this.finishTerminalModalPointerInteraction()},this.adjustTerminalFontSize=e=>{let t=tC(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=nC(this.terminalModalOpacity+e);t!==this.terminalModalOpacity&&(this.terminalModalOpacity=t,this.persistTerminalModalPreferences())},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleCompact=()=>{this.sessions.runCommand(`/compact`)},this.handleToggleHostSpeech=e=>{let t=this.state.selectedSession;if(t===void 0||R(this.state)!==`local`)return;let n=this.hostSpeech.snapshot.active;if(n?.sessionId===t.id&&n.messageKey===e.messageKey){this.hostSpeech.stop();return}this.hostSpeech.startManual({machineId:`local`,sessionId:t.id,messageKey:e.messageKey,text:e.text})},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleEditFromHere=async(e,t)=>{let n=R(this.state),r=this.state.selectedSession?.id;try{!(await this.sessions.editFromHere(e,t)).cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer()}catch{}},this.handleForkFromHere=async e=>{await this.sessions.forkFromHere(e)},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=sy(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()},this.speechInputSettingsApi=e.speechInputApi??Ns,this.createSpeechInputSettingsChannel=e.createSpeechInputSettingsChannel??(e=>new Kx(e))}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility(),this.syncStarterNotice()}updated(){this.committedChatIdentity=yR(this.state),this.syncSelectedSessionReadState(),this.compactRailOpen&&this.appShell.isDesktopActivityRailLayout&&this.closeCompactActivityRail();let e=this.activeActivityRailId;e!==void 0&&this.activeActivityRailItem()===void 0&&this.closeActivityRailItem(e,this.activeActivityRailGeneration)}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=iy(this.sessionWarningVisibility,e===void 0?void 0:Bl(R(this.state),e.id),this.state.status===void 0?void 0:this.state.status.warnings??[])}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=R(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}async commitReadyChatAfterRender(e,t){let n=vR(e,t);await this.updateComplete,!(!this.unreadConnected||yR(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);RR(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=_C(this.state.selectedProject?.name);this.windowTitleCleanup=vC(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=vR(e,t);return yR(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isChatObscured()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isChatObscured(){return this.compactRailOpen||this.activeActivityRailId!==void 0||this.settingsSection!==void 0||this.sessionCleanupDialog!==void 0||this.historyWindow!==void 0||this.modelsConfigDialogOpen||this.skillsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.pluginsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.systemPromptDialogOpen&&this.state.selectedSession!==void 0||this.state.actionPaletteOpen||this.projectBrowserOpen||this.statisticsProject!==void 0||this.sessionBrowserOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.treeDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.state.authDialog!==void 0||this.gitUpdateManagerPanelOpen||this.terminalModalOpen||this.recentProjectDialogEntry!==void 0}hostSpeechSurfaceVisible(){return R(this.state)===`local`?this.settingsSection===`general`||this.state.selectedSession!==void 0&&!this.isChatObscured():!1}abandonHostSpeechIfSourceInvalid(e){let t=this.hostSpeech.snapshot.active;if(t===void 0)return;let n=e.selectedSession;if(n?.id!==t.sessionId)return;if(n.archived===!0){this.hostSpeech.stop();return}let r=h_({messages:e.messages,messagePageStart:e.messagePageStart},t.messageKey);(r===``||!this.hostSpeech.matchesActiveSource({sessionId:t.sessionId,messageKey:t.messageKey,text:r}))&&this.hostSpeech.stop()}connectedCallback(){super.connectedCallback(),this.connectSpeechInputSettings(),this.hostSpeech.select(bR(this.state)),this.hostSpeech.refreshStatus(),this.synchronizeProjectCatalogPolling(),this.unreadConnected=!0,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),window.addEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,QL),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},YL),this.refreshWorkspaceActivity(),this.recentProjects.load(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebUiStatusRefresh()}),this.syncWindowTitle()}disconnectedCallback(){this.disconnectSpeechInputSettings(),this.finishTerminalModalPointerInteraction(),this.hostSpeech.dispose(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.unreadRuntimeRefreshes.clear(),this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),window.removeEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,QL),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.resetActiveModelPolicyDraft(),this.sessions.dispose(),this.projectCatalog.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.memory.dispose(),this.learnedSkills.dispose(),this.piWebUiStatusTimer!==void 0&&window.clearInterval(this.piWebUiStatusTimer),this.piWebUiStatusTimer=void 0,this.clearScheduledPiWebUiStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),this.disconnectWindowTitle(),super.disconnectedCallback()}setState(e){if(!LR(this.state,e))return;let t=this.state,n={...t,...e},r=bR(t),i=bR(n);xR(r,i)?t.status?.isCompacting!==!0&&n.status?.isCompacting===!0?this.hostSpeech.stop():this.abandonHostSpeechIfSourceInvalid(n):this.hostSpeech.select(i);let a=SR(t),o=wR(t),s=CR(t);this.state=n,s!==CR(this.state)&&(this.starterModelPolicySelectionGeneration+=1),a!==SR(this.state)&&this.resetActiveModelPolicyDraft(),yR(t)!==yR(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),NR(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),!this.shouldShowSessionStartScreen(t)&&this.shouldShowSessionStartScreen(this.state)&&this.state.selectedWorkspace!==void 0&&this.loadStarterSessionDefaults(this.state.selectedWorkspace),this.handleMachineChange(t,this.state),this.handleStarterModelPolicyCapabilityChange(t,this.state),PR(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle(),this.synchronizeProjectCatalogPolling();let c=wR(this.state);c!==void 0&&c!==o&&this.preloadActiveModelPolicyInputs()}synchronizeProjectCatalogPolling(){this.projectCatalog.updatePolling(!!this.isConnected)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=OS();await this.machines.loadMachines(e.machineId);let t=this.routeForSelectedMachine(e),n=this.state.machineStatuses[t.machineId??`local`];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,n)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}connectSpeechInputSettings(){if(!this.speechInputSettingsConnected){this.speechInputSettingsConnected=!0;try{this.speechInputSettingsChannel=this.createSpeechInputSettingsChannel(e=>{this.handleSpeechInputSettingsChannelRevision(e)})}catch{this.speechInputSettingsChannel=void 0}this.refreshSpeechInputSettings()}}disconnectSpeechInputSettings(){!this.speechInputSettingsConnected&&this.speechInputSettingsChannel===void 0||(this.speechInputSettingsConnected=!1,this.speechInputSettingsRequestSeq+=1,this.speechInputSettingsChannelDispatchQueued=!1,this.speechInputSettingsChannelRefreshInFlight=!1,this.pendingSpeechInputSettingsChannelRevision=void 0,this.speechInputSettingsChannel?.close(),this.speechInputSettingsChannel=void 0)}async refreshSpeechInputSettings(){if(!this.speechInputSettingsConnected)return;let e=++this.speechInputSettingsRequestSeq;try{let t=await this.speechInputSettingsApi.settings();if(e!==this.speechInputSettingsRequestSeq)return;this.speechInputSettings=t}catch{}}handleSpeechInputSettingsLoaded(e){this.adoptSpeechInputSettings(e,!1)}handleSpeechInputSettingsSaved(e){this.adoptSpeechInputSettings(e,!0)}adoptSpeechInputSettings(e,t){this.speechInputSettingsConnected&&(this.speechInputSettingsRequestSeq+=1,this.speechInputSettings=e,this.pendingSpeechInputSettingsChannelRevision===e.revision&&(this.pendingSpeechInputSettingsChannelRevision=void 0),t&&this.speechInputSettingsChannel?.publish(e.revision))}handleSpeechInputSettingsChannelRevision(e){!this.speechInputSettingsConnected||e===this.speechInputSettings?.revision||(this.pendingSpeechInputSettingsChannelRevision=e,!(this.speechInputSettingsChannelRefreshInFlight||this.speechInputSettingsChannelDispatchQueued)&&(this.speechInputSettingsChannelDispatchQueued=!0,queueMicrotask(()=>{this.speechInputSettingsChannelDispatchQueued=!1,!(!this.speechInputSettingsConnected||this.speechInputSettingsChannelRefreshInFlight)&&this.refreshSpeechInputSettingsFromChannel()})))}async refreshSpeechInputSettingsFromChannel(){if(!(!this.speechInputSettingsConnected||this.speechInputSettingsChannelRefreshInFlight)&&this.pendingSpeechInputSettingsChannelRevision!==void 0){this.pendingSpeechInputSettingsChannelRevision=void 0,this.speechInputSettingsChannelRefreshInFlight=!0;try{await this.refreshSpeechInputSettings()}finally{this.speechInputSettingsChannelRefreshInFlight=!1,this.shouldRunSpeechInputSettingsChannelTrailingRefresh()&&this.refreshSpeechInputSettingsFromChannel()}}}shouldRunSpeechInputSettingsChannelTrailingRefresh(){return this.speechInputSettingsConnected&&this.pendingSpeechInputSettingsChannelRevision!==void 0}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebUiStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){this.projectCatalog.refresh(),await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.refreshSpeechInputSettings()])}schedulePiWebUiStatusRefresh(e=XL){this.clearScheduledPiWebUiStatusRefresh(),this.piWebUiStatusDeferredTimer=window.setTimeout(()=>{this.piWebUiStatusDeferredTimer=void 0,this.piWebUiStatusController.refresh()},e)}clearScheduledPiWebUiStatusRefresh(){this.piWebUiStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebUiStatusDeferredTimer),this.piWebUiStatusDeferredTimer=void 0)}async refreshWorkspaceActivity(e=R(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){let e=this.state.machines.length===0?[R(this.state)]:this.state.machines.filter(e=>IR(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}async loadClientConfig(){try{this.applyClientConfig((await Vs.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=wc(e),this.hostSpeech.configure(e.tts)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebUiStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let e=this.state.selectedWorkspace,t=this.state.mainView!==`chat`&&this.state.mainView!==`navigation`?this.state.mainView:this.state.workspaceTool;t===`core:workspace.files`?await this.files.refreshFiles():t===`core:workspace.git`?await this.git.refreshGit():t===`core:workspace.terminal`&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(OS(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?VR():n,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=a.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);let n=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith(`machine.`)===!0&&await n,!this.isCurrentRouteRestore(o))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:r??e.view??this.defaultRouteView(),selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),e.projectId===void 0||e.projectId===``){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}let i=this.state.projects.find(t=>t.id===e.projectId);if(!i){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(i,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),R(this.state)!==i&&this.schedulePiWebUiStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?VR():{selectedFilePath:Zl(nR,`file`),selectedDiffPath:Zl(rR,`diff`),selectedTerminalId:Zl(iR,`terminal`)}}routeForSelectedMachine(e){let t=this.state.selectedMachine?.id??`local`;return(e.machineId??`local`)===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){kS(e,{replace:!0}),Ql(nR,`file`,void 0,{replace:!0}),Ql(rR,`diff`,void 0,{replace:!0}),Ql(iR,`terminal`,void 0,{replace:!0})}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??`local`]){let n=e.machineId??`local`,r=this.state.selectedMachine;return n===`local`||r?.id!==n||r.kind!==`remote`||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===``?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=UR(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;let e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e)){this.clearPendingRemoteRouteRestore();return}this.remoteRouteRestoreInProgress=!0;try{let t=e.machineId??`local`,n=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(n?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e)||(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e)))return;if(this.state.error!==``){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}scheduleNextRemoteRouteRestoreAttempt(e){if(this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=ZL.length){this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore();return}this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}setRemoteRouteRestoreMessage(e,t={}){let n=e.machineId??`local`,r=this.state.machines.find(e=>e.id===n)?.name??this.state.selectedMachine?.name??`Remote machine`,i=this.state.machineStatuses[n]?.error??(this.state.error===``?void 0:this.state.error),a=t.exhausted===!0?`${r} is still unavailable.`:`${r} is unavailable; reconnecting…`;this.setState({error:`${a}${i===void 0?``:` ${i}`}`})}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){let n=e.machineId??`local`;if(this.state.selectedMachine?.id===n)return;let r=this.state.machines.find(e=>e.id===n);r!==void 0&&await this.machines.selectMachine(r,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??`local`)===(this.state.selectedMachine?.id??`local`)&&e.workspaceId!==void 0&&e.workspaceId!==``&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e===`core:workspace.files`&&await this.files.refreshFiles(),e===`core:workspace.files`&&t!==void 0&&await this.files.restoreFile(t),e===`core:workspace.git`&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await qR(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),kS({machineId:this.state.selectedMachine?.id,projectId:this.state.selectedProject?.id,workspaceId:this.state.selectedWorkspace?.id,sessionId:this.state.selectedSession?.id,tool:this.state.workspaceTool,view:this.state.mainView===`navigation`?void 0:this.state.mainView},e),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(P_(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(P_(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){kS(F_(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){Ql(nR,`file`,e.selectedFilePath,{replace:!0}),Ql(rR,`diff`,e.selectedDiffPath,{replace:!0}),Ql(iR,`terminal`,e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();let n=++this.machineNavigationRestoreSeq,r=this.machineNavigation.latest(e.id)??N_(e.id);if(await this.restoreRouteFor(F_(r),!1,r.surface,r.view),!(n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(r)){this.machineNavigation.remember(r),this.writeMachineNavigationSnapshotToUrl(r);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==``}openWorkspaceTool(e){e===`core:workspace.terminal`&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool(`core:workspace.terminal`)}terminalCommandRunsForOrigin(e,t=R(this.state)){let n=HR(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=BS(e,{api:{runTerminalCommand:(e,n)=>lc.runTerminalCommand(e,n,t),listCommandRuns:e=>lc.listCommandRuns(e,t),getCommandRun:e=>lc.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}}),a={...i,runCommand:async e=>{let n=await i.runCommand(e);return this.recordProjectWork({machineId:t,projectId:e.workspace.projectId}),n}};return this.terminalCommandRunRuntimes.set(n,a),a}async openRuntimeTerminal(e,t,n){return(R(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:`core:workspace.terminal`,view:`core:workspace.terminal`},!1,{selectedTerminalId:n?.terminalId},`core:workspace.terminal`),R(this.state)!==e)?(this.setState({error:`Machine not found for terminal command run`}),!1):(this.openTerminal(n),!0)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){let t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){Ql(iR,`terminal`,e,t)}terminalWorkspaceKey(e){return`${R(this.state)}:${e.path}`}selectMainView(e){if(e!==`navigation`&&e!==`chat`){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e=`general`){this.settingsSection=e,PS(e)}closeSettings(){this.settingsSection=void 0,PS(void 0)}navigateSettings(e){this.settingsSection=e,PS(e)}restoreSettingsRoute(){this.settingsSection=NS()}handleWorkspaceChange(e,t){let n=MR(e,t);if(e.selectedWorkspace?.id===t.selectedWorkspace?.id){n&&(this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace());return}this.starterSessionDefaults=void 0,this.resetStarterModelPolicyForScopeChange(),this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let r=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));if(this.setState({activeTerminalCount:0,selectedTerminalId:r}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(r,{replace:!0})),t.selectedWorkspace===void 0){this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace();return}this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling(),this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace()}async loadStarterSessionDefaults(e,t={}){let n=R(this.state),r=++this.starterSessionDefaultsSeq,i=this.starterModelPolicySelectionSupported(n),a=()=>r===this.starterSessionDefaultsSeq&&R(this.state)===n&&this.state.selectedWorkspace?.id===e.id&&this.state.selectedWorkspace.path===e.path&&(t.expectedSelectionGeneration===void 0||this.starterModelPolicySelectionGeneration===t.expectedSelectionGeneration);try{let r=i?await cc.sessionDefaultsV2(e.path,n):await cc.sessionDefaults(e.path,n);if(!a())return;let o=this.starterSessionDefaults;this.starterSessionDefaults=r,this.starterNotice=void 0,this.starterModelPolicyPreferenceReadError=r.starterModelPolicyPreferenceError??``;let s=this.starterModelPolicy;s===void 0||i&&!OR(o)?this.starterModelPolicy=Jc(r):i?this.starterModelPolicy=s:this.starterModelPolicy=Yc(s,r),this.completeStarterModelPolicyFromActiveTier();let c=this.starterModelPolicy;if(this.selectedMachineModelTierCatalog()===void 0&&(i||c.mode===`tiered`&&!this.modelTierCatalogLoading)){let e=this.ensureModelTierCatalog(n);t.awaitModelTierCatalog===!0&&await e}}catch(t){a()&&(console.warn(`Failed to load Pi session defaults`,t),this.publishStarterNotice(Tl(`defaults-failed`,`Could not load this workspace's model defaults. ${WR(t)}`,{machineId:n,workspaceId:e.id})))}}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));this.sessionUnread.retainMachines(e);for(let t of e){let e=this.state.machineRuntimes[t];if(e===void 0)continue;let n=this.unreadRuntimeRefreshes.has(t)||!e.ok?`unknown`:E(e,w.sessionsUnread)?`supported`:`unsupported`;this.sessionUnread.setCapability(t,n)&&this.sessionUnread.refresh(t)}}async renegotiateUnreadMachines(){if(!this.unreadConnected)return;let e=new Set(this.state.machines.map(e=>e.id));e.add(R(this.state)),await Promise.all([...e].map(async e=>{await this.renegotiateUnreadMachine(e)}))}renegotiateUnreadMachine(e){let t=this.unreadRuntimeRefreshes.get(e);if(t!==void 0)return t;this.sessionUnread.setCapability(e,`unknown`);let n=!1,r=Promise.resolve().then(async()=>{n=await this.machines.refreshMachineRuntime(e)!==void 0});this.unreadRuntimeRefreshes.set(e,r);let i=()=>{this.unreadRuntimeRefreshes.get(e)===r&&(this.unreadRuntimeRefreshes.delete(e),this.unreadConnected&&(n?this.syncSessionUnreadMachines():this.sessionUnread.setCapability(e,`unknown`)))};return r.then(i,i),r}connectRealtime(){let e=R(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.renegotiateUnreadMachine(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t),this.refreshWorkspaceActivity(e),this.projectCatalog.refresh()},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new gp;e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=R(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>FR(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity):BR(t)?(this.applyTerminalEvent(t),t.type===`terminal.exited`&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(t)}applyTerminalEvent(e){let t=this.state.selectedWorkspace;t!==void 0&&(e.type===`terminal.closed`?e.cwd:e.terminal.cwd)===t.path&&(e.type===`terminal.created`&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type===`terminal.closed`?e.terminalId:e.terminal.id),e.type===`terminal.closed`&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){let t=R(this.state);try{let n=await lc.terminals(e.projectId,e.id,t);if(R(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(let e of n)e.exited||this.activeTerminalIds.add(e.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(e){this.setState({error:String(e)})}}handleActivityTransition(e,t){let n=zR(e),r=zR(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??`local`)===(t.selectedMachine?.id??`local`))return;this.closeRecentProjectDialogForMachineChange(),this.closeProjectStatistics(),this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.starterSessionDefaults=void 0,this.resetStarterModelPolicyForScopeChange(),this.resetModelTierCatalogForMachineChange(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebUiStatus:void 0}),this.git.updatePolling(),this.recentProjects.load(),this.loadPluginsForSelectedMachine();let n=t.selectedWorkspace;n!==void 0&&this.shouldShowSessionStartScreen(t)&&this.loadStarterSessionDefaults(n)}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){return g`
|
|
7374
|
+
`}};H([x({attribute:!1})],WL.prototype,`onClose`,void 0),H([x({attribute:!1})],WL.prototype,`onStatusChange`,void 0),H([x({attribute:!1})],WL.prototype,`workspace`,void 0),H([x()],WL.prototype,`machineId`,void 0),H([x({attribute:!1})],WL.prototype,`api`,void 0),H([S()],WL.prototype,`status`,void 0),H([S()],WL.prototype,`selectedChange`,void 0),H([S()],WL.prototype,`selectedDiff`,void 0),H([S()],WL.prototype,`loadingStatus`,void 0),H([S()],WL.prototype,`loadingDiff`,void 0),H([S()],WL.prototype,`error`,void 0),H([S()],WL.prototype,`bounds`,void 0),WL=H([b(`git-update-manager-panel`)],WL);function GL(){sb(()=>import(`./UnifiedDiffViewer-j1-AFZ8f.js`),[],import.meta.url)}function KL(e,t){let n=Cu(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function qL(e){return e===`staged`?`Staged`:`Unstaged`}function JL(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function YL(e){return e instanceof Error?e.message:String(e)}var XL=900*1e3,ZL=750,QL=[1e3,3e3,8e3,15e3,3e4],$L={capture:!0},eR=`auto:on`,tR=`auto:off`,nR=`theme:`,rR=Yl(`core:workspace.files`),iR=Yl(`core:workspace.git`),aR=Yl(`core:workspace.terminal`),oR=`workspace-memory`,sR=`workspace.memory`,cR=`workspace-memory:workspace.memory`,lR=`workspace-learned-skills`,uR=`workspace.learned-skills`,dR=`workspace-learned-skills:workspace.learned-skills`,fR=320,pR=2,mR=`(min-width: 1181px)`,hR=75,gR=`Could not remember this model policy; this session still uses it.`,$=class extends y{constructor(e={}){super(),this.state=Il(),this.sessionUnread=new Jv({onChange:e=>{R(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new hh(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.hostSpeech=new xh({onStateChange:()=>{this.hostSpeechSurfaceVisible()&&this.requestUpdate()}}),this.sessions=new gm(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Qp,{refreshProjectSessionCatalog:()=>this.projectCatalog.refresh(),notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(R(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)},onStarterModelPolicyConfirmed:e=>{this.handleStarterModelPolicyConfirmed(e)}}),this.workspaces=new b_(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new v_,{onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectCatalog=new zu(()=>this.state,{workspaces:sc.workspaces,applySnapshot:async e=>{await this.workspaces.reconcileProjectCatalog(e)},captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.projectActivityOwnership=new Xu(()=>this.state,e=>{this.setState(e)},{api:sc,captureTopologyRequest:e=>this.workspaces.captureProjectCatalogTopologyRequest(e),onProjectTopology:async e=>{let t=this.state.projects.find(t=>t.id===e.projectId&&t.path===e.projectPath);t!==void 0&&await this.workspaces.reconcileProjectCatalog({machineId:e.machineId,project:t,workspaces:e.workspaces,...e.topologyRequest===void 0?{}:{topologyRequest:e.topologyRequest}})},onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Hl(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new Kl(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.projects=new Fu(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e),this.recentProjects.load()}}),this.machines=new ju(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new Qu(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new cu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new mu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.memory=new xu(()=>this.state,e=>{this.setState(e)}),this.learnedSkills=new _u(()=>this.state,e=>{this.setState(e)}),this.recentProjects=new Vu({machineId:()=>R(this.state),onChange:()=>{this.requestUpdate()},onBackgroundError:(e,t)=>{console.warn(`Failed to ${e}`,t)}}),this.keyboard=new X_,this.realtime=new gp,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new M_,this.terminalSelection=new G_,this.appShell=new Lx(this),this.browserResume=new Bx({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.speechInputSettingsConnected=!1,this.speechInputSettingsRequestSeq=0,this.isSpeechInputSettingsRequestCurrent=e=>this.speechInputSettingsConnected&&e===this.speechInputSettingsRequestSeq,this.speechInputSettingsChannelDispatchQueued=!1,this.speechInputSettingsChannelRefreshInFlight=!1,this.panelCollapse=new cS(this),this.panelResize=new fS(this),this.navigationSections=new aS(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=_R(),this.reportActivityRailError=(e,t,n)=>{console.warn(`Plugin activity rail contribution failed`,e,t,n)},this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=gy()??fy,this.activeThemeId=dy,this.isRefreshingApp=!1,this.recentProjectDialogInitialView=`closed-actions`,this.recentProjectDialogGeneration=0,this.starterSessionDefaultsSeq=0,this.starterModelPolicyPreferenceReadError=``,this.starterModelPolicyPreferenceWriter=new Sv({save:async(e,t)=>{let n=await cc.updateSessionDefaults(e.cwd,{starterModelPolicyPreference:t},e.machineId),r=this.starterModelPolicyPreferenceScope();return r?.machineId===e.machineId&&r.cwd===e.cwd&&(this.starterModelPolicyPreferenceReadError=``),n},onStateChange:()=>{this.requestUpdate()}}),this.confirmedStarterModelPolicyPreferenceWriter=new Dv({remember:(e,t)=>cc.rememberCurrentModelPolicy(t,e.machineId),onStateChange:(e,t)=>{this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(e)&&this.confirmedStarterModelPolicyUiGeneration===this.starterModelPolicySelectionGeneration&&(!t.saving&&t.error===void 0&&(this.starterModelPolicyPreferenceReadError=``),this.requestUpdate())}}),this.starterModelPolicySelectionGeneration=0,this.modelTierCatalogLoading=!1,this.modelTierCatalogError=``,this.activeModelPolicyApplyGeneration=0,this.modelTierCatalogSeq=0,this.modelsConfigDialogOpen=!1,this.projectBrowserOpen=!1,this.statisticsLoading=!1,this.statisticsRequestGeneration=0,this.sessionBrowserOpen=!1,this.skillsConfigDialogOpen=!1,this.pluginsConfigDialogOpen=!1,this.systemPromptDialogOpen=!1,this.gitUpdateManagerPanelOpen=!1,this.terminalModalOpen=!1,this.terminalModalMaximized=!1,this.initialTerminalModalPreferences=rC(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.initialWorkspaceTabVisibility=dC(),this.terminalTabHidden=this.initialWorkspaceTabVisibility.terminalHidden,this.infoTabHidden=this.initialWorkspaceTabVisibility.infoHidden,this.railOrder=IL()??[...AL],this.compactRailOpen=!1,this.activeActivityRailGeneration=0,this.settingsSection=NS(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=wc(void 0),this.sessionWarningVisibility=ny(),this.onPopState=()=>void this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)}),this.onPageShow=()=>{this.renegotiateUnreadMachines(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onTerminalModalViewportResize=()=>{this.terminalModalBounds!==void 0&&(this.terminalModalBounds=XS(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{if(e.key===`Escape`&&this.promptEditor?.cancelSpeechInput()===!0){e.preventDefault(),e.stopPropagation();return}this.compactRailOpen||this.activeActivityRailId!==void 0||this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.state.actionPaletteOpen||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.closeCompactActivityRail=()=>{if(!this.compactRailOpen)return;this.compactRailOpen=!1;let e=this.compactActivityRailLauncher;this.updateComplete.then(()=>{!this.compactRailOpen&&this.activeActivityRailId===void 0&&(e===void 0?this.currentCompactActivityRailLauncher()?.focus():this.restoreActivityRailFocus(e))})},this.toggleCompactActivityRail=e=>{this.appShell.isDesktopActivityRailLayout||(!this.compactRailOpen&&e!==void 0&&(this.compactActivityRailLauncher=e),this.compactRailOpen=!this.compactRailOpen)},this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStartSessionPrompt=(e,t,n,r)=>{if(!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e))return;if(this.starterModelPolicyBlocksStart()){let e=this.starterNoticeScope();e!==void 0&&this.publishStarterNotice(wl(e));return}this.starterNotice=void 0;let i=this.state.selectedWorkspace?.id,a=R(this.state),o=this.selectedProjectWorkTarget(a),s=this.starterModelPolicy,c=this.starterPlusModelPolicyInitializer();this.starterModelPolicySelectionSupported(a)&&c===void 0||((c===void 0?this.sessions.startSessionWithPrompt(e,t,n,r,this.starterModelPolicyStartSnapshot(),e=>{this.clearStarterModelPolicyAfterSuccessfulStart(e,i,s)}):this.sessions.startPlusSessionWithPrompt(e,t,n,r??`inline`,c,()=>void 0)).then(e=>{e&&this.recordProjectWork(o)}).catch(e=>{i!==void 0&&this.publishStarterNotice(Tl(`start-failed`,`Could not start the session. ${GR(e)}`,{machineId:a,workspaceId:i}))}),this.focusChatComposer())},this.handleSelectStarterModel=()=>{this.openStarterModelDialog()},this.handleSelectStarterThinking=()=>{this.openStarterThinkingDialog()},this.handleSelectStarterPolicyMode=async e=>{let t=this.starterModelPolicy;if(t===void 0||t.mode===e)return;if(this.starterModelPolicySelectionSupported()){let n=e===`exact`?$c(t):t.tier===void 0?{...t,mode:`tiered`}:Qc(t,t.tier);this.setStarterModelPolicyDraft(n),this.ensureModelTierCatalog(R(this.state));return}if(e===`exact`){let e=$c(t);this.setStarterModelPolicyDraft(e);let n=this.starterSessionDefaults,r=n===void 0?void 0:qc(n);r!==void 0&&Zc(e.exact,r)&&this.persistStarterModelPolicyPreference(e);return}let n=t.tier===void 0?{...t,mode:`tiered`}:Qc(t,t.tier),r=this.setStarterModelPolicyDraft(n);if(n.tier===void 0){this.ensureModelTierCatalog(R(this.state));return}let i=await this.ensureStarterModelPolicyCatalog();this.starterModelPolicy!==r||i===void 0||nl(r,i)!==void 0&&this.persistStarterModelPolicyPreference(r)},this.handleSelectStarterPolicyTier=async e=>{let t=this.starterModelPolicy,n=await this.ensureStarterModelPolicyCatalog();if(t===void 0||t!==this.starterModelPolicy||n===void 0)return;let r=Qc(t,e);if(this.starterModelPolicySelectionSupported()){this.setStarterModelPolicyDraft(r);return}nl(r,n)!==void 0&&(this.setStarterModelPolicyDraft(r),this.persistStarterModelPolicyPreference(r))},this.handleSelectStarterPolicyThinking=async e=>{await this.pickStarterThinking(e)},this.handleSelectActivePolicyMode=async e=>{let t=await this.prepareActiveModelPolicyDraft();if(!(t===void 0||t!==this.activeModelPolicyDraftForState(this.state)||t.mode===e)){if(this.cancelActiveModelPolicyApply(),e===`exact`){this.setActiveModelPolicyDraft($c(t)),this.scheduleActiveExactModelPolicyApply();return}if(t.tier===void 0){this.setActiveModelPolicyDraft({...t,mode:`tiered`});return}this.setActiveModelPolicyDraft(Qc(t,t.tier)),await this.applyActiveModelPolicyDraft()}},this.handleSelectActivePolicyTier=async e=>{let t=await this.prepareActiveModelPolicyDraft();if(t===void 0||t!==this.activeModelPolicyDraftForState(this.state))return;this.cancelActiveModelPolicyApply();let n=Qc(t,e);this.setActiveModelPolicyDraft(n),await this.applyActiveModelPolicyDraft()},this.handleSelectActivePolicyThinking=async e=>{await this.pickThinking(e)},this.handleOpenTerminalFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.terminalModalOpen=!0)},this.handleOpenGitUpdateManagerFromRail=()=>{this.closeCompactActivityRail(),this.state.selectedWorkspace!==void 0&&(this.gitUpdateManagerPanelOpen=!0)},this.handleCloseGitUpdateManagerPanel=()=>{this.gitUpdateManagerPanelOpen=!1},this.handleOpenThemeFromRail=()=>{this.closeCompactActivityRail(),this.openThemeDialog()},this.handleRailOrderChange=e=>{this.railOrder=e,LL(e)},this.handleCloseTerminalModal=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalOpen=!1},this.toggleTerminalModalMaximized=()=>{this.finishTerminalModalPointerInteraction(),this.terminalModalMaximized=!this.terminalModalMaximized},this.handleTerminalModalMovePointerDown=e=>{this.startTerminalModalPointerInteraction(`move`,e)},this.handleTerminalModalResizePointerDown=e=>{this.startTerminalModalPointerInteraction(`resize`,e)},this.handleTerminalModalPointerMove=e=>{let t=this.terminalModalPointerInteraction;if(t?.pointerId!==e.pointerId)return;e.preventDefault();let n={x:e.clientX-t.startClientX,y:e.clientY-t.startClientY},r=this.terminalModalViewport();this.terminalModalBounds=t.operation===`move`?JS(t.bounds,n,r):YS(t.bounds,n,r)},this.handleTerminalModalPointerUp=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&(e.preventDefault(),this.finishTerminalModalPointerInteraction())},this.handleTerminalModalPointerCancel=e=>{this.terminalModalPointerInteraction?.pointerId===e.pointerId&&this.finishTerminalModalPointerInteraction()},this.adjustTerminalFontSize=e=>{let t=tC(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=nC(this.terminalModalOpacity+e);t!==this.terminalModalOpacity&&(this.terminalModalOpacity=t,this.persistTerminalModalPreferences())},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleCompact=()=>{this.sessions.runCommand(`/compact`)},this.handleToggleHostSpeech=e=>{let t=this.state.selectedSession;if(t===void 0||R(this.state)!==`local`)return;let n=this.hostSpeech.snapshot.active;if(n?.sessionId===t.id&&n.messageKey===e.messageKey){this.hostSpeech.stop();return}this.hostSpeech.startManual({machineId:`local`,sessionId:t.id,messageKey:e.messageKey,text:e.text})},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleEditFromHere=async(e,t)=>{let n=R(this.state),r=this.state.selectedSession?.id;try{!(await this.sessions.editFromHere(e,t)).cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer()}catch{}},this.handleForkFromHere=async e=>{await this.sessions.forkFromHere(e)},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=sy(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()},this.speechInputSettingsApi=e.speechInputApi??Ns,this.createSpeechInputSettingsChannel=e.createSpeechInputSettingsChannel??(e=>new Kx(e))}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility(),this.syncStarterNotice()}updated(){this.committedChatIdentity=bR(this.state),this.syncSelectedSessionReadState(),this.compactRailOpen&&this.appShell.isDesktopActivityRailLayout&&this.closeCompactActivityRail();let e=this.activeActivityRailId;e!==void 0&&this.activeActivityRailItem()===void 0&&this.closeActivityRailItem(e,this.activeActivityRailGeneration)}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=iy(this.sessionWarningVisibility,e===void 0?void 0:Bl(R(this.state),e.id),this.state.status===void 0?void 0:this.state.status.warnings??[])}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=R(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}async commitReadyChatAfterRender(e,t){let n=yR(e,t);await this.updateComplete,!(!this.unreadConnected||bR(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);zR(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=_C(this.state.selectedProject?.name);this.windowTitleCleanup=vC(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=yR(e,t);return bR(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isChatObscured()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isChatObscured(){return this.compactRailOpen||this.activeActivityRailId!==void 0||this.settingsSection!==void 0||this.sessionCleanupDialog!==void 0||this.historyWindow!==void 0||this.modelsConfigDialogOpen||this.skillsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.pluginsConfigDialogOpen&&this.state.selectedWorkspace!==void 0||this.systemPromptDialogOpen&&this.state.selectedSession!==void 0||this.state.actionPaletteOpen||this.projectBrowserOpen||this.statisticsProject!==void 0||this.sessionBrowserOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.treeDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.state.authDialog!==void 0||this.gitUpdateManagerPanelOpen||this.terminalModalOpen||this.recentProjectDialogEntry!==void 0}hostSpeechSurfaceVisible(){return R(this.state)===`local`?this.settingsSection===`general`||this.state.selectedSession!==void 0&&!this.isChatObscured():!1}abandonHostSpeechIfSourceInvalid(e){let t=this.hostSpeech.snapshot.active;if(t===void 0)return;let n=e.selectedSession;if(n?.id!==t.sessionId)return;if(n.archived===!0){this.hostSpeech.stop();return}let r=h_({messages:e.messages,messagePageStart:e.messagePageStart},t.messageKey);(r===``||!this.hostSpeech.matchesActiveSource({sessionId:t.sessionId,messageKey:t.messageKey,text:r}))&&this.hostSpeech.stop()}connectedCallback(){super.connectedCallback(),this.connectSpeechInputSettings(),this.hostSpeech.select(xR(this.state)),this.hostSpeech.refreshStatus(),this.synchronizeProjectCatalogPolling(),this.unreadConnected=!0,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),window.addEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,$L),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},XL),this.refreshWorkspaceActivity(),this.recentProjects.load(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebUiStatusRefresh()}),this.syncWindowTitle()}disconnectedCallback(){this.disconnectSpeechInputSettings(),this.finishTerminalModalPointerInteraction(),this.hostSpeech.dispose(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.unreadRuntimeRefreshes.clear(),this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),window.removeEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,$L),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(!RR(this.state,e))return;let t=this.state,n={...t,...e},r=xR(t),i=xR(n);SR(r,i)?t.status?.isCompacting!==!0&&n.status?.isCompacting===!0?this.hostSpeech.stop():this.abandonHostSpeechIfSourceInvalid(n):this.hostSpeech.select(i);let a=CR(t),o=TR(t),s=wR(t);this.state=n,s!==wR(this.state)&&(this.starterModelPolicySelectionGeneration+=1),a!==CR(this.state)&&this.resetActiveModelPolicyDraft(),bR(t)!==bR(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),PR(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),FR(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle(),this.synchronizeProjectCatalogPolling();let c=TR(this.state);c!==void 0&&c!==o&&this.preloadActiveModelPolicyInputs()}synchronizeProjectCatalogPolling(){this.projectCatalog.updatePolling(!!this.isConnected)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=OS();await this.machines.loadMachines(e.machineId);let t=this.routeForSelectedMachine(e),n=this.state.machineStatuses[t.machineId??`local`];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,n)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}connectSpeechInputSettings(){if(!this.speechInputSettingsConnected){this.speechInputSettingsConnected=!0;try{this.speechInputSettingsChannel=this.createSpeechInputSettingsChannel(e=>{this.handleSpeechInputSettingsChannelRevision(e)})}catch{this.speechInputSettingsChannel=void 0}this.refreshSpeechInputSettings()}}disconnectSpeechInputSettings(){!this.speechInputSettingsConnected&&this.speechInputSettingsChannel===void 0||(this.speechInputSettingsConnected=!1,this.speechInputSettingsRequestSeq+=1,this.speechInputSettingsChannelDispatchQueued=!1,this.speechInputSettingsChannelRefreshInFlight=!1,this.pendingSpeechInputSettingsChannelRevision=void 0,this.speechInputSettingsChannel?.close(),this.speechInputSettingsChannel=void 0)}async refreshSpeechInputSettings(){if(!this.speechInputSettingsConnected)return;let e=++this.speechInputSettingsRequestSeq;try{let t=await this.speechInputSettingsApi.settings();if(e!==this.speechInputSettingsRequestSeq)return;this.speechInputSettings=t}catch{}}handleSpeechInputSettingsLoaded(e){this.adoptSpeechInputSettings(e,!1)}handleSpeechInputSettingsSaved(e){this.adoptSpeechInputSettings(e,!0)}adoptSpeechInputSettings(e,t){this.speechInputSettingsConnected&&(this.speechInputSettingsRequestSeq+=1,this.speechInputSettings=e,this.pendingSpeechInputSettingsChannelRevision===e.revision&&(this.pendingSpeechInputSettingsChannelRevision=void 0),t&&this.speechInputSettingsChannel?.publish(e.revision))}handleSpeechInputSettingsChannelRevision(e){!this.speechInputSettingsConnected||e===this.speechInputSettings?.revision||(this.pendingSpeechInputSettingsChannelRevision=e,!(this.speechInputSettingsChannelRefreshInFlight||this.speechInputSettingsChannelDispatchQueued)&&(this.speechInputSettingsChannelDispatchQueued=!0,queueMicrotask(()=>{this.speechInputSettingsChannelDispatchQueued=!1,!(!this.speechInputSettingsConnected||this.speechInputSettingsChannelRefreshInFlight)&&this.refreshSpeechInputSettingsFromChannel()})))}async refreshSpeechInputSettingsFromChannel(){if(!(!this.speechInputSettingsConnected||this.speechInputSettingsChannelRefreshInFlight)&&this.pendingSpeechInputSettingsChannelRevision!==void 0){this.pendingSpeechInputSettingsChannelRevision=void 0,this.speechInputSettingsChannelRefreshInFlight=!0;try{await this.refreshSpeechInputSettings()}finally{this.speechInputSettingsChannelRefreshInFlight=!1,this.shouldRunSpeechInputSettingsChannelTrailingRefresh()&&this.refreshSpeechInputSettingsFromChannel()}}}shouldRunSpeechInputSettingsChannelTrailingRefresh(){return this.speechInputSettingsConnected&&this.pendingSpeechInputSettingsChannelRevision!==void 0}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebUiStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){this.projectCatalog.refresh(),await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.refreshSpeechInputSettings()])}schedulePiWebUiStatusRefresh(e=ZL){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=>LR(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}async loadClientConfig(){try{this.applyClientConfig((await Vs.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=wc(e),this.hostSpeech.configure(e.tts)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebUiStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let e=this.state.selectedWorkspace,t=this.state.mainView!==`chat`&&this.state.mainView!==`navigation`?this.state.mainView:this.state.workspaceTool;t===`core:workspace.files`?await this.files.refreshFiles():t===`core:workspace.git`?await this.git.refreshGit():t===`core:workspace.terminal`&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(OS(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?HR():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===``?HR():{selectedFilePath:Zl(rR,`file`),selectedDiffPath:Zl(iR,`diff`),selectedTerminalId:Zl(aR,`terminal`)}}routeForSelectedMachine(e){let t=this.state.selectedMachine?.id??`local`;return(e.machineId??`local`)===t?e:{machineId:t,projectId:void 0,workspaceId:void 0,sessionId:void 0,tool:void 0,view:void 0}}replaceRouteAndClearWorkspaceQuery(e){kS(e,{replace:!0}),Ql(rR,`file`,void 0,{replace:!0}),Ql(iR,`diff`,void 0,{replace:!0}),Ql(aR,`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=WR(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>=QL.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 JR(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),kS({machineId:this.state.selectedMachine?.id,projectId:this.state.selectedProject?.id,workspaceId:this.state.selectedWorkspace?.id,sessionId:this.state.selectedSession?.id,tool:this.state.workspaceTool,view:this.state.mainView===`navigation`?void 0:this.state.mainView},e),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(P_(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(P_(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){kS(F_(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){Ql(rR,`file`,e.selectedFilePath,{replace:!0}),Ql(iR,`diff`,e.selectedDiffPath,{replace:!0}),Ql(aR,`terminal`,e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();let n=++this.machineNavigationRestoreSeq,r=this.machineNavigation.latest(e.id)??N_(e.id);if(await this.restoreRouteFor(F_(r),!1,r.surface,r.view),!(n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(r)){this.machineNavigation.remember(r),this.writeMachineNavigationSnapshotToUrl(r);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==``}openWorkspaceTool(e){e===`core:workspace.terminal`&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool(`core:workspace.terminal`)}terminalCommandRunsForOrigin(e,t=R(this.state)){let n=UR(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=BS(e,{api:{runTerminalCommand:(e,n)=>lc.runTerminalCommand(e,n,t),listCommandRuns:e=>lc.listCommandRuns(e,t),getCommandRun:e=>lc.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}}),a={...i,runCommand:async e=>{let n=await i.runCommand(e);return this.recordProjectWork({machineId:t,projectId:e.workspace.projectId}),n}};return this.terminalCommandRunRuntimes.set(n,a),a}async openRuntimeTerminal(e,t,n){return(R(this.state)!==e||t!==void 0&&(this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId))&&(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),await this.restoreRouteFor({machineId:e,projectId:t?.projectId,workspaceId:t?.id,sessionId:void 0,tool:`core:workspace.terminal`,view:`core:workspace.terminal`},!1,{selectedTerminalId:n?.terminalId},`core:workspace.terminal`),R(this.state)!==e)?(this.setState({error:`Machine not found for terminal command run`}),!1):(this.openTerminal(n),!0)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){let t=this.state.selectedWorkspace;t!==void 0&&(e===void 0?this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(t)):this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(t),e))}writeSelectedTerminalToUrl(e,t){Ql(aR,`terminal`,e,t)}terminalWorkspaceKey(e){return`${R(this.state)}:${e.path}`}selectMainView(e){if(e!==`navigation`&&e!==`chat`){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl(),this.git.updatePolling()}openSettings(e=`general`){this.settingsSection=e,PS(e)}closeSettings(){this.settingsSection=void 0,PS(void 0)}navigateSettings(e){this.settingsSection=e,PS(e)}restoreSettingsRoute(){this.settingsSection=NS()}handleWorkspaceChange(e,t){let n=NR(e,t);if(e.selectedWorkspace?.id===t.selectedWorkspace?.id){n&&(this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace());return}this.starterSessionDefaults=void 0,this.resetStarterModelPolicyForScopeChange(),this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let r=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));if(this.setState({activeTerminalCount:0,selectedTerminalId:r}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(r,{replace:!0})),t.selectedWorkspace===void 0){this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace();return}this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling(),this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace()}async loadStarterSessionDefaults(e,t={}){let n=R(this.state),r=++this.starterSessionDefaultsSeq,i=this.starterModelPolicySelectionSupported(n),a=()=>r===this.starterSessionDefaultsSeq&&R(this.state)===n&&this.state.selectedWorkspace?.id===e.id&&this.state.selectedWorkspace.path===e.path&&(t.expectedSelectionGeneration===void 0||this.starterModelPolicySelectionGeneration===t.expectedSelectionGeneration);try{let r=i?await cc.sessionDefaultsV2(e.path,n):await cc.sessionDefaults(e.path,n);if(!a())return;let o=this.starterSessionDefaults;this.starterSessionDefaults=r,this.starterNotice=void 0,this.starterModelPolicyPreferenceReadError=r.starterModelPolicyPreferenceError??``;let s=this.starterModelPolicy;s===void 0||i&&!kR(o)?this.starterModelPolicy=Jc(r):i?this.starterModelPolicy=s:this.starterModelPolicy=Yc(s,r),this.completeStarterModelPolicyFromActiveTier();let c=this.starterModelPolicy;if(this.selectedMachineModelTierCatalog()===void 0&&(i||c.mode===`tiered`&&!this.modelTierCatalogLoading)){let e=this.ensureModelTierCatalog(n);t.awaitModelTierCatalog===!0&&await e}}catch(t){a()&&(console.warn(`Failed to load Pi session defaults`,t),this.publishStarterNotice(Tl(`defaults-failed`,`Could not load this workspace's model defaults. ${GR(t)}`,{machineId:n,workspaceId:e.id})))}}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));this.sessionUnread.retainMachines(e);for(let t of e){let e=this.state.machineRuntimes[t];if(e===void 0)continue;let n=this.unreadRuntimeRefreshes.has(t)||!e.ok?`unknown`:E(e,w.sessionsUnread)?`supported`:`unsupported`;this.sessionUnread.setCapability(t,n)&&this.sessionUnread.refresh(t)}}async renegotiateUnreadMachines(){if(!this.unreadConnected)return;let e=new Set(this.state.machines.map(e=>e.id));e.add(R(this.state)),await Promise.all([...e].map(async e=>{await this.renegotiateUnreadMachine(e)}))}renegotiateUnreadMachine(e){let t=this.unreadRuntimeRefreshes.get(e);if(t!==void 0)return t;this.sessionUnread.setCapability(e,`unknown`);let n=!1,r=Promise.resolve().then(async()=>{n=await this.machines.refreshMachineRuntime(e)!==void 0});this.unreadRuntimeRefreshes.set(e,r);let i=()=>{this.unreadRuntimeRefreshes.get(e)===r&&(this.unreadRuntimeRefreshes.delete(e),this.unreadConnected&&(n?this.syncSessionUnreadMachines():this.sessionUnread.setCapability(e,`unknown`)))};return r.then(i,i),r}connectRealtime(){let e=R(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.renegotiateUnreadMachine(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t),this.refreshWorkspaceActivity(e),this.projectCatalog.refresh()},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new gp;e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=R(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>IR(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):VR(t)?(this.applyTerminalEvent(t),t.type===`terminal.exited`&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(t)}applyTerminalEvent(e){let t=this.state.selectedWorkspace;t!==void 0&&(e.type===`terminal.closed`?e.cwd:e.terminal.cwd)===t.path&&(e.type===`terminal.created`&&!e.terminal.exited?this.activeTerminalIds.add(e.terminal.id):this.activeTerminalIds.delete(e.type===`terminal.closed`?e.terminalId:e.terminal.id),e.type===`terminal.closed`&&(this.terminalSelection.forgetTerminal(e.terminalId),this.state.selectedTerminalId===e.terminalId&&this.selectTerminal(void 0,{replace:!0})),this.setState({activeTerminalCount:this.activeTerminalIds.size}))}async refreshActiveTerminals(e){let t=R(this.state);try{let n=await lc.terminals(e.projectId,e.id,t);if(R(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(let e of n)e.exited||this.activeTerminalIds.add(e.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(e){this.setState({error:String(e)})}}handleActivityTransition(e,t){let n=BR(e),r=BR(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){if((e.selectedMachine?.id??`local`)===(t.selectedMachine?.id??`local`))return;this.closeRecentProjectDialogForMachineChange(),this.closeProjectStatistics(),this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.starterSessionDefaults=void 0,this.resetStarterModelPolicyForScopeChange(),this.resetModelTierCatalogForMachineChange(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebUiStatus:void 0}),this.git.updatePolling(),this.recentProjects.load(),this.loadPluginsForSelectedMachine();let n=t.selectedWorkspace;n!==void 0&&this.shouldShowSessionStartScreen(t)&&this.loadStarterSessionDefaults(n)}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){return g`
|
|
7375
7375
|
<workspace-panel
|
|
7376
7376
|
id="workspace-panel"
|
|
7377
7377
|
.emptyState=${this.state.selectedWorkspace===void 0?this.workspacePanelEmptyState():void 0}
|
|
@@ -7428,7 +7428,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7428
7428
|
.onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
|
|
7429
7429
|
.onReset=${()=>{this.resetResizablePanel(`workspace`)}}
|
|
7430
7430
|
></app-panel-edge-control>
|
|
7431
|
-
`}startPanelResize(e){return e===`navigation`?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){let t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){let n=this.getBoundingClientRect().width||(typeof window>`u`?0:window.innerWidth);if(n<=0)return t.maxWidth;let r=this.oppositeResizablePanelWidth(e),i=Math.floor(n-r-fR-dR);return Math.max(t.minWidth,Math.min(t.maxWidth,i))}oppositeResizablePanelWidth(e){let t=e===`navigation`?`workspace`:`navigation`;return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e===`navigation`?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return typeof window>`u`||!(`matchMedia`in window)||window.matchMedia(pR).matches}measuredPanelWidth(e){let t=(e===`navigation`?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return t===void 0||t<=0?void 0:t}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){let e=this.selectedMachineRuntime();return e?.ok!==!0||E(e,w.sessionsDeleteArchived)}get projectStatisticsAvailable(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.projectUsageStatistics)}canReloadSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsReload)}canReorderSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsReorder)}canClearServerQueue(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsClearQueue)}canMessageActions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsMessageActions)}canViewSystemPrompt(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsSystemPrompt)}canCleanupSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsCleanup)}hasAuthoritativeSessionPersistence(){return zp(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=R(this.state)){if(e===`local`)return!0;let t=this.state.machineRuntimes[e];return t?.ok===!0&&E(t,w.workspaceFileSuggestions)}sessionModelPolicySupported(e=R(this.state)){return ER(this.state,e)}starterModelPolicySelectionSupported(e=R(this.state)){return DR(this.state,e)}handleStarterModelPolicyCapabilityChange(e,t){let n=R(t);if(R(e)!==n||DR(e,n)||!DR(t,n)||!this.shouldShowSessionStartScreen(t))return;let r=t.selectedWorkspace;r!==void 0&&this.loadStarterSessionDefaults(r)}starterModelPolicyPreferenceScope(){let e=this.state.selectedWorkspace;if(e!==void 0)return{machineId:R(this.state),cwd:e.path}}starterModelPolicyPreferenceScopeMatchesCurrentSelection(e){let t=this.starterModelPolicyPreferenceScope();return t?.machineId===e.machineId&&t.cwd===e.cwd}handleStarterModelPolicyConfirmed(e){let t={machineId:e.machineId,cwd:e.session.cwd},n=this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(t);n&&this.state.selectedSession?.id===e.session.id&&this.state.selectedSession.cwd===e.session.cwd?(this.starterModelPolicy=Wc(e.policy),this.starterModelPolicyPreferenceReadError=``,this.confirmedStarterModelPolicyUiScope=t,this.confirmedStarterModelPolicyUiGeneration=this.starterModelPolicySelectionGeneration):n&&(this.confirmedStarterModelPolicyUiScope!==void 0||this.confirmedStarterModelPolicyUiGeneration!==void 0)&&(this.confirmedStarterModelPolicyUiScope=void 0,this.confirmedStarterModelPolicyUiGeneration=void 0,this.requestUpdate()),this.confirmedStarterModelPolicyPreferenceWriter.write(t,e.session)}starterNoticeScope(){let e=this.state.selectedWorkspace;if(e!==void 0)return{machineId:R(this.state),workspaceId:e.id}}publishStarterNotice(e){let t=this.starterNoticeScope();t?.machineId!==e.scope.machineId||t.workspaceId!==e.scope.workspaceId||(this.starterNotice=e)}syncStarterNotice(){let e=this.starterNotice;e!==void 0&&(Dl(e,this.starterNoticeScope(),this.starterModelPolicyInputs()?.status.blockedReason)||(this.starterNotice=void 0))}starterModelPolicyPreferenceSupported(e){let t=this.state.machineRuntimes[e];return t?.ok===!0&&E(t,w.sessionsModelPolicyDefaults)}persistStarterModelPolicyPreference(e){let t=this.starterModelPolicyPreferenceScope(),n=Xc(e);t===void 0||n===void 0||!this.starterModelPolicyPreferenceSupported(t.machineId)||this.starterModelPolicyPreferenceWriter.write(t,n)}loadModelTierCatalog(e){let t=this.state.selectedWorkspace?.id,n=++this.modelTierCatalogSeq,r=this.performModelTierCatalogLoad(e,t,n);this.modelTierCatalogLoad={machineId:e,workspaceId:t,promise:r};let i=()=>{this.modelTierCatalogLoad?.promise===r&&(this.modelTierCatalogLoad=void 0)};return r.then(i,i),r}async performModelTierCatalogLoad(e,t,n){let r=()=>n===this.modelTierCatalogSeq&&R(this.state)===e&&this.state.selectedWorkspace?.id===t;this.modelTierCatalogLoading=!0,this.modelTierCatalogError=``;try{let t=await Ks.settings(e);if(!r())return;this.modelTierCatalogMachineId=e,this.modelTierCatalog=t,this.completeStarterModelPolicyFromActiveTier()}catch(e){if(!r())return;this.modelTierCatalogError=WR(e)}finally{n===this.modelTierCatalogSeq&&(this.modelTierCatalogLoading=!1)}}ensureModelTierCatalog(e){if(this.selectedMachineModelTierCatalog()!==void 0)return Promise.resolve();let t=this.state.selectedWorkspace?.id,n=this.modelTierCatalogLoad;return n?.machineId===e&&n.workspaceId===t?n.promise:this.loadModelTierCatalog(e)}resetStarterModelPolicyForScopeChange(){this.starterSessionDefaultsSeq+=1,this.starterModelPolicySelectionGeneration+=1,this.starterModelPolicy=void 0,this.starterModelPolicyPreferenceReadError=``,this.starterNotice=void 0,this.modelTierCatalogError=``}resetModelTierCatalogForMachineChange(){this.modelTierCatalogSeq+=1,this.modelTierCatalogLoad=void 0,this.modelTierCatalogMachineId=void 0,this.modelTierCatalog=void 0,this.modelTierCatalogLoading=!1,this.modelTierCatalogError=``}handleModelTiersSaved(e,t){R(this.state)===e&&(this.modelTierCatalogMachineId=e,this.modelTierCatalog=t,this.modelTierCatalogError=``,this.modelTierCatalogSeq+=1,this.modelTierCatalogLoad=void 0,this.modelTierCatalogLoading=!1,this.completeStarterModelPolicyFromActiveTier(),wR(this.state)!==void 0&&this.sessions.loadModelPolicy())}completeStarterModelPolicyFromActiveTier(){let e=this.starterSessionDefaults,t=this.starterModelPolicy,n=this.selectedMachineModelTierCatalog();if(e===void 0||t===void 0||n===void 0)return;let r=il(t,e,n);kR(t,r)||(this.starterModelPolicy=r)}selectedMachineModelTierCatalog(){if(this.modelTierCatalogMachineId===R(this.state))return this.modelTierCatalog}preloadActiveModelPolicyInputs(){this.sessions.loadModelPolicy(),this.ensureModelTierCatalog(R(this.state))}async prepareActiveModelPolicyDraft(){if(!this.sessionModelPolicySupported())return;let e=SR(this.state);if(e===void 0||TR(this.state)===void 0)return;let t=this.activeModelPolicyDraftForState(this.state);if(t!==void 0)return t;let n=[];if(this.state.modelPolicy===void 0&&n.push(this.sessions.loadModelPolicy()),this.selectedMachineModelTierCatalog()===void 0&&n.push(this.ensureModelTierCatalog(R(this.state))),await Promise.all(n),SR(this.state)!==e)return;let r=this.activeModelPolicyDraftForState(this.state);if(r!==void 0)return r;let i=this.selectedMachineModelTierCatalog(),a=TR(this.state);if(i===void 0||a===void 0)return;let o=this.state.modelPolicy?.policy,s;if(o!==void 0)s=Gc({policy:o,catalog:i});else if(a.mode===`exact`)s=Gc({liveResolved:a.resolved,catalog:i});else{let e=Gc({catalog:i});s=a.tier===void 0?{...e,mode:`tiered`}:Qc(e,a.tier)}return this.activeModelPolicyDraftScope=e,this.activeModelPolicyDraft=s,s}activeModelPolicyDraftForState(e){return this.activeModelPolicyDraftScope===SR(e)?this.activeModelPolicyDraft:void 0}setActiveModelPolicyDraft(e){let t=SR(this.state);t!==void 0&&(this.activeModelPolicyDraftScope=t,this.activeModelPolicyDraft=e)}resetActiveModelPolicyDraft(){this.cancelActiveModelPolicyApply(),this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0}cancelActiveModelPolicyApply(){this.activeModelPolicyApplyGeneration+=1,this.activeModelPolicyApplyTimer!==void 0&&window.clearTimeout(this.activeModelPolicyApplyTimer),this.activeModelPolicyApplyTimer=void 0}scheduleActiveExactModelPolicyApply(){this.cancelActiveModelPolicyApply();let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e?.mode!==`exact`||!rl(e,t))return;let n=this.activeModelPolicyApplyGeneration;this.activeModelPolicyApplyTimer=window.setTimeout(()=>{n===this.activeModelPolicyApplyGeneration&&(this.activeModelPolicyApplyTimer=void 0,this.applyActiveModelPolicyDraft())},mR)}async applyActiveModelPolicyDraft(){let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e===void 0||!rl(e,t)||t===void 0)return;let n=nl(e,t);if(n===void 0)return;let r=this.activeModelPolicyDraftScope,i=this.state.modelPolicy;if(await this.sessions.saveModelPolicy(n),r!==SR(this.state)||this.activeModelPolicyDraft!==e)return;if(this.state.modelPolicyError!==void 0){this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0;return}if(this.state.modelPolicy===i)return;let a=this.state.modelPolicy?.policy;if(a===void 0){this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0;return}this.setActiveModelPolicyDraft(Gc({policy:a,catalog:t}))}policyThinkingOptions(e,t){let n=this.selectedMachineModelTierCatalog(),r=n?.models.find(t=>t.model.provider===e.model.provider&&t.model.id===e.model.id);return Pl({supported:n===void 0?t:r?.thinkingLevels??[],all:e.thinkingLevel===``||t.includes(e.thinkingLevel)?t:[e.thinkingLevel,...t],selected:e.thinkingLevel})}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??`this machine`} to delete archived sessions.`}sessionCleanupUnavailableMessage(){return Vv(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[R(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:``}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}let t=R(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let n=await cc.cleanupPreview(e,t);if(R(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:n,previewRequest:e,result:void 0,loading:!1,error:``}}catch(e){R(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`Failed to preview cleanup: ${WR(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||Pv(t.previewRequest)!==Pv(e)){this.sessionCleanupDialog={...t??{},error:`Preview cleanup before running it.`};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}let n=R(this.state);this.sessionCleanupDialog={...t,running:!0,error:``};try{let t=await cc.cleanup(e,n);if(R(this.state)!==n)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:t,previewRequest:e,result:t,running:!1,error:``},await this.sessions.applySessionCleanupResult(t,n)}catch(e){R(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`Failed to run cleanup: ${WR(e)}`})}}async runForceSessionCleanup(){let e=this.sessionCleanupDialog;if(!this.canCleanupSessions()){this.sessionCleanupDialog={...e??{},error:this.sessionCleanupUnavailableMessage(),runningForce:!1};return}let t=R(this.state);this.sessionCleanupDialog={...e??{},runningForce:!0,error:``};try{let e=await cc.forceCleanup(t);if(R(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,forceCleanupResult:e,runningForce:!1,error:``},await this.sessions.applySessionCleanupResult(e,t)}catch(e){R(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,runningForce:!1,error:`Failed to force cleanup: ${WR(e)}`})}}renderNavigationPanel(){return g`
|
|
7431
|
+
`}startPanelResize(e){return e===`navigation`?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){let t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){let n=this.getBoundingClientRect().width||(typeof window>`u`?0:window.innerWidth);if(n<=0)return t.maxWidth;let r=this.oppositeResizablePanelWidth(e),i=Math.floor(n-r-pR-fR);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(mR).matches}measuredPanelWidth(e){let t=(e===`navigation`?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return t===void 0||t<=0?void 0:t}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){let e=this.selectedMachineRuntime();return e?.ok!==!0||E(e,w.sessionsDeleteArchived)}get projectStatisticsAvailable(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.projectUsageStatistics)}canReloadSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsReload)}canReorderSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsReorder)}canClearServerQueue(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsClearQueue)}canMessageActions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsMessageActions)}canViewSystemPrompt(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsSystemPrompt)}canCleanupSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&E(e,w.sessionsCleanup)}hasAuthoritativeSessionPersistence(){return zp(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=R(this.state)){if(e===`local`)return!0;let t=this.state.machineRuntimes[e];return t?.ok===!0&&E(t,w.workspaceFileSuggestions)}sessionModelPolicySupported(e=R(this.state)){return DR(this.state,e)}starterModelPolicySelectionSupported(e=R(this.state)){return OR(this.state,e)}handleStarterModelPolicyCapabilityChange(e,t){let n=R(t);if(R(e)!==n||OR(e,n)||!OR(t,n)||!this.shouldShowSessionStartScreen(t))return;let r=t.selectedWorkspace;r!==void 0&&this.loadStarterSessionDefaults(r)}starterModelPolicyPreferenceScope(){let e=this.state.selectedWorkspace;if(e!==void 0)return{machineId:R(this.state),cwd:e.path}}starterModelPolicyPreferenceScopeMatchesCurrentSelection(e){let t=this.starterModelPolicyPreferenceScope();return t?.machineId===e.machineId&&t.cwd===e.cwd}handleStarterModelPolicyConfirmed(e){let t={machineId:e.machineId,cwd:e.session.cwd},n=this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(t);n&&this.state.selectedSession?.id===e.session.id&&this.state.selectedSession.cwd===e.session.cwd?(this.starterModelPolicy=Wc(e.policy),this.starterModelPolicyPreferenceReadError=``,this.confirmedStarterModelPolicyUiScope=t,this.confirmedStarterModelPolicyUiGeneration=this.starterModelPolicySelectionGeneration):n&&(this.confirmedStarterModelPolicyUiScope!==void 0||this.confirmedStarterModelPolicyUiGeneration!==void 0)&&(this.confirmedStarterModelPolicyUiScope=void 0,this.confirmedStarterModelPolicyUiGeneration=void 0,this.requestUpdate()),this.confirmedStarterModelPolicyPreferenceWriter.write(t,e.session)}starterNoticeScope(){let e=this.state.selectedWorkspace;if(e!==void 0)return{machineId:R(this.state),workspaceId:e.id}}publishStarterNotice(e){let t=this.starterNoticeScope();t?.machineId!==e.scope.machineId||t.workspaceId!==e.scope.workspaceId||(this.starterNotice=e)}syncStarterNotice(){let e=this.starterNotice;e!==void 0&&(Dl(e,this.starterNoticeScope(),this.starterModelPolicyInputs()?.status.blockedReason)||(this.starterNotice=void 0))}starterModelPolicyPreferenceSupported(e){let t=this.state.machineRuntimes[e];return t?.ok===!0&&E(t,w.sessionsModelPolicyDefaults)}persistStarterModelPolicyPreference(e){let t=this.starterModelPolicyPreferenceScope(),n=Xc(e);t===void 0||n===void 0||!this.starterModelPolicyPreferenceSupported(t.machineId)||this.starterModelPolicyPreferenceWriter.write(t,n)}loadModelTierCatalog(e){let t=this.state.selectedWorkspace?.id,n=++this.modelTierCatalogSeq,r=this.performModelTierCatalogLoad(e,t,n);this.modelTierCatalogLoad={machineId:e,workspaceId:t,promise:r};let i=()=>{this.modelTierCatalogLoad?.promise===r&&(this.modelTierCatalogLoad=void 0)};return r.then(i,i),r}async performModelTierCatalogLoad(e,t,n){let r=()=>n===this.modelTierCatalogSeq&&R(this.state)===e&&this.state.selectedWorkspace?.id===t;this.modelTierCatalogLoading=!0,this.modelTierCatalogError=``;try{let t=await Ks.settings(e);if(!r())return;this.modelTierCatalogMachineId=e,this.modelTierCatalog=t,this.completeStarterModelPolicyFromActiveTier()}catch(e){if(!r())return;this.modelTierCatalogError=GR(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(),TR(this.state)!==void 0&&this.sessions.loadModelPolicy())}completeStarterModelPolicyFromActiveTier(){let e=this.starterSessionDefaults,t=this.starterModelPolicy,n=this.selectedMachineModelTierCatalog();if(e===void 0||t===void 0||n===void 0)return;let r=il(t,e,n);AR(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=CR(this.state);if(e===void 0||ER(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),CR(this.state)!==e)return;let r=this.activeModelPolicyDraftForState(this.state);if(r!==void 0)return r;let i=this.selectedMachineModelTierCatalog(),a=ER(this.state);if(i===void 0||a===void 0)return;let o=this.state.modelPolicy?.policy,s;if(o!==void 0)s=Gc({policy:o,catalog:i});else if(a.mode===`exact`)s=Gc({liveResolved:a.resolved,catalog:i});else{let e=Gc({catalog:i});s=a.tier===void 0?{...e,mode:`tiered`}:Qc(e,a.tier)}return this.activeModelPolicyDraftScope=e,this.activeModelPolicyDraft=s,s}activeModelPolicyDraftForState(e){return this.activeModelPolicyDraftScope===CR(e)?this.activeModelPolicyDraft:void 0}setActiveModelPolicyDraft(e){let t=CR(this.state);t!==void 0&&(this.activeModelPolicyDraftScope=t,this.activeModelPolicyDraft=e)}resetActiveModelPolicyDraft(){this.cancelActiveModelPolicyApply(),this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0}cancelActiveModelPolicyApply(){this.activeModelPolicyApplyGeneration+=1,this.activeModelPolicyApplyTimer!==void 0&&window.clearTimeout(this.activeModelPolicyApplyTimer),this.activeModelPolicyApplyTimer=void 0}scheduleActiveExactModelPolicyApply(){this.cancelActiveModelPolicyApply();let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e?.mode!==`exact`||!rl(e,t))return;let n=this.activeModelPolicyApplyGeneration;this.activeModelPolicyApplyTimer=window.setTimeout(()=>{n===this.activeModelPolicyApplyGeneration&&(this.activeModelPolicyApplyTimer=void 0,this.applyActiveModelPolicyDraft())},hR)}async applyActiveModelPolicyDraft(){let e=this.activeModelPolicyDraftForState(this.state),t=this.selectedMachineModelTierCatalog();if(e===void 0||!rl(e,t)||t===void 0)return;let n=nl(e,t);if(n===void 0)return;let r=this.activeModelPolicyDraftScope,i=this.state.modelPolicy;if(await this.sessions.saveModelPolicy(n),r!==CR(this.state)||this.activeModelPolicyDraft!==e)return;if(this.state.modelPolicyError!==void 0){this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0;return}if(this.state.modelPolicy===i)return;let a=this.state.modelPolicy?.policy;if(a===void 0){this.activeModelPolicyDraftScope=void 0,this.activeModelPolicyDraft=void 0;return}this.setActiveModelPolicyDraft(Gc({policy:a,catalog:t}))}policyThinkingOptions(e,t){let n=this.selectedMachineModelTierCatalog(),r=n?.models.find(t=>t.model.provider===e.model.provider&&t.model.id===e.model.id);return Pl({supported:n===void 0?t:r?.thinkingLevels??[],all:e.thinkingLevel===``||t.includes(e.thinkingLevel)?t:[e.thinkingLevel,...t],selected:e.thinkingLevel})}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??`this machine`} to delete archived sessions.`}sessionCleanupUnavailableMessage(){return Vv(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[R(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:``}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}let t=R(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let n=await cc.cleanupPreview(e,t);if(R(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:n,previewRequest:e,result:void 0,loading:!1,error:``}}catch(e){R(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`Failed to preview cleanup: ${GR(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||Pv(t.previewRequest)!==Pv(e)){this.sessionCleanupDialog={...t??{},error:`Preview cleanup before running it.`};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...t,error:this.sessionCleanupUnavailableMessage(),running:!1};return}let n=R(this.state);this.sessionCleanupDialog={...t,running:!0,error:``};try{let t=await cc.cleanup(e,n);if(R(this.state)!==n)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:t,previewRequest:e,result:t,running:!1,error:``},await this.sessions.applySessionCleanupResult(t,n)}catch(e){R(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`Failed to run cleanup: ${GR(e)}`})}}async runForceSessionCleanup(){let e=this.sessionCleanupDialog;if(!this.canCleanupSessions()){this.sessionCleanupDialog={...e??{},error:this.sessionCleanupUnavailableMessage(),runningForce:!1};return}let t=R(this.state);this.sessionCleanupDialog={...e??{},runningForce:!0,error:``};try{let e=await cc.forceCleanup(t);if(R(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,forceCleanupResult:e,runningForce:!1,error:``},await this.sessions.applySessionCleanupResult(e,t)}catch(e){R(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,runningForce:!1,error:`Failed to force cleanup: ${GR(e)}`})}}renderNavigationPanel(){return g`
|
|
7432
7432
|
<app-navigation-panel
|
|
7433
7433
|
.machines=${this.state.machines}
|
|
7434
7434
|
.selectedMachine=${this.state.selectedMachine}
|
|
@@ -7511,7 +7511,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7511
7511
|
.onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
|
|
7512
7512
|
.onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
|
|
7513
7513
|
></app-navigation-panel>
|
|
7514
|
-
`}canOpenSessionHistory(){let e=this.state.selectedSession;return e!==void 0&&e.persisted!==!1&&e.path!==``}openSessionHistory(){let e=this.state.selectedSession;e===void 0||!this.canOpenSessionHistory()||(this.historyWindow={machineId:R(this.state),session:e})}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}cancelPendingNavigationSelection(){this.navigationSelectionSeq+=1}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await n()},i),i()&&await this.focusNavigationTarget(t)}async selectSessionFromNavigation(e){if(this.state.selectedWorkspace?.path===e.cwd){await this.sessions.selectSession(e);return}let t=this.state.workspaces.find(t=>t.path===e.cwd);if(t===void 0){this.setState({error:`The session's workspace is no longer available.`});return}await this.workspaces.selectWorkspace(t,{sessionId:e.id})}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}async startSessionAndOpenChat(e=()=>!0){let t=this.state.selectedWorkspace;if(t===void 0)return;let n=R(this.state),r=this.starterModelPolicySelectionGeneration,i=this.starterModelPolicySelectionSupported(n),a=this.starterPlusModelPolicyInitializer();if(i&&a===void 0&&(this.starterModelPolicy===void 0||this.selectedMachineModelTierCatalog()===void 0)){if(await this.loadMissingStarterPlusModelPolicyInputs(t,n,r),!e()||this.starterModelPolicySelectionGeneration!==r)return;i=this.starterModelPolicySelectionSupported(n),a=this.starterPlusModelPolicyInitializer()}if(this.starterModelPolicyInputs()?.status.blockedReason!==void 0){let t=this.starterNoticeScope();e()&&t!==void 0&&this.publishStarterNotice(wl(t));return}if(i&&a===void 0)return;this.starterNotice=void 0;let o=t.id,s=this.starterModelPolicy;(a===void 0?this.sessions.startSession(this.starterModelPolicyStartSnapshot()):this.sessions.startPlusSession(a)).then(e=>{i||this.clearStarterModelPolicyAfterSuccessfulStart(e,o,s)}).catch(t=>{if(e()){let e={machineId:n,workspaceId:o};this.publishStarterNotice(Tl(`start-failed`,`Could not start the session. ${
|
|
7514
|
+
`}canOpenSessionHistory(){let e=this.state.selectedSession;return e!==void 0&&e.persisted!==!1&&e.path!==``}openSessionHistory(){let e=this.state.selectedSession;e===void 0||!this.canOpenSessionHistory()||(this.historyWindow={machineId:R(this.state),session:e})}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}cancelPendingNavigationSelection(){this.navigationSelectionSeq+=1}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await n()},i),i()&&await this.focusNavigationTarget(t)}async selectSessionFromNavigation(e){if(this.state.selectedWorkspace?.path===e.cwd){await this.sessions.selectSession(e);return}let t=this.state.workspaces.find(t=>t.path===e.cwd);if(t===void 0){this.setState({error:`The session's workspace is no longer available.`});return}await this.workspaces.selectWorkspace(t,{sessionId:e.id})}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}async startSessionAndOpenChat(e=()=>!0){let t=this.state.selectedWorkspace;if(t===void 0)return;let n=R(this.state),r=this.starterModelPolicySelectionGeneration,i=this.starterModelPolicySelectionSupported(n),a=this.starterPlusModelPolicyInitializer();if(i&&a===void 0&&(this.starterModelPolicy===void 0||this.selectedMachineModelTierCatalog()===void 0)){if(await this.loadMissingStarterPlusModelPolicyInputs(t,n,r),!e()||this.starterModelPolicySelectionGeneration!==r)return;i=this.starterModelPolicySelectionSupported(n),a=this.starterPlusModelPolicyInitializer()}if(this.starterModelPolicyInputs()?.status.blockedReason!==void 0){let t=this.starterNoticeScope();e()&&t!==void 0&&this.publishStarterNotice(wl(t));return}if(i&&a===void 0)return;this.starterNotice=void 0;let o=t.id,s=this.starterModelPolicy;(a===void 0?this.sessions.startSession(this.starterModelPolicyStartSnapshot()):this.sessions.startPlusSession(a)).then(e=>{i||this.clearStarterModelPolicyAfterSuccessfulStart(e,o,s)}).catch(t=>{if(e()){let e={machineId:n,workspaceId:o};this.publishStarterNotice(Tl(`start-failed`,`Could not start the session. ${GR(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`&&!vL(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 JR(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!==`chat`&&this.selectMainView(`chat`),await this.updateComplete,await JR(),this.promptEditor?.focusInput()}async navigateSessionTree(e,t){let n=R(this.state),r=this.state.selectedSession?.id,i=await this.sessions.navigateTree(e,t);return!i.cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer(),i}closeSessionTreeNavigator(){this.sessions.closeTreeDialog(),this.focusChatComposer()}renderSessionTreeNavigator(e){return e.treeDialog===void 0?null:g`
|
|
7515
7515
|
<session-tree-navigator
|
|
7516
7516
|
.tree=${e.treeDialog}
|
|
7517
7517
|
.onNavigate=${(e,t)=>this.navigateSessionTree(e,t)}
|
|
@@ -7526,7 +7526,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7526
7526
|
.onRemove=${async()=>{this.isCurrentRecentProjectDialog(t,e,n)&&(await this.recentProjects.removeEntry(e.id),this.isCurrentRecentProjectDialog(t,e,n)&&this.closeRecentProjectDialog(t,e,n,`removal`))}}
|
|
7527
7527
|
.onClose=${()=>{this.closeRecentProjectDialog(t,e,n,`cancel`)}}
|
|
7528
7528
|
></recent-project-dialog>
|
|
7529
|
-
`}openRecentProjectDialog(e,t,n,r){this.recentProjectDialogGeneration+=1,this.recentProjectDialogMachineId=R(this.state),this.recentProjectDialogInitialView=t,this.recentProjectDialogCancelFocus=n,this.recentProjectDialogRemovalFocus=r,this.recentProjectDialogEntry=e}closeRecentProjectDialogForMachineChange(){let e=this.recentProjectDialogMachineId,t=this.recentProjectDialogEntry;e===void 0||t===void 0||this.closeRecentProjectDialog(e,t,this.recentProjectDialogGeneration)}isCurrentRecentProjectDialog(e,t,n){return R(this.state)===e&&this.recentProjectDialogMachineId===e&&this.recentProjectDialogEntry===t&&this.recentProjectDialogGeneration===n}closeRecentProjectDialog(e,t,n,r){if(this.recentProjectDialogMachineId!==e||this.recentProjectDialogEntry!==t||this.recentProjectDialogGeneration!==n||r!==void 0&&R(this.state)!==e)return;let i=r===`cancel`?this.recentProjectDialogCancelFocus:r===`removal`?this.recentProjectDialogRemovalFocus:void 0,a=this.renderRoot.querySelector(`recent-project-dialog`);a?.isConnected===!0&&a.close(),this.recentProjectDialogCancelFocus=void 0,this.recentProjectDialogRemovalFocus=void 0,this.recentProjectDialogMachineId=void 0,this.recentProjectDialogInitialView=`closed-actions`,this.recentProjectDialogEntry=void 0,i!==void 0&&this.updateComplete.then(()=>{this.recentProjectDialogMachineId===void 0&&this.recentProjectDialogEntry===void 0&&this.recentProjectDialogGeneration===n&&R(this.state)===e&&i()})}workspacePanels(){let e=this.state.selectedWorkspace;if(e===void 0)return[];let t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(e=>e.visible?.(t)??!0)}synchronizeMemoryPollingForSelectedWorkspace(e=this.plugins.getActivityRailItems()){if(this.state.selectedWorkspace===void 0){this.memory.updatePolling(!1);return}this.synchronizeMemoryPolling(e)}synchronizeMemoryPolling(e){let t=e.some(e=>
|
|
7529
|
+
`}openRecentProjectDialog(e,t,n,r){this.recentProjectDialogGeneration+=1,this.recentProjectDialogMachineId=R(this.state),this.recentProjectDialogInitialView=t,this.recentProjectDialogCancelFocus=n,this.recentProjectDialogRemovalFocus=r,this.recentProjectDialogEntry=e}closeRecentProjectDialogForMachineChange(){let e=this.recentProjectDialogMachineId,t=this.recentProjectDialogEntry;e===void 0||t===void 0||this.closeRecentProjectDialog(e,t,this.recentProjectDialogGeneration)}isCurrentRecentProjectDialog(e,t,n){return R(this.state)===e&&this.recentProjectDialogMachineId===e&&this.recentProjectDialogEntry===t&&this.recentProjectDialogGeneration===n}closeRecentProjectDialog(e,t,n,r){if(this.recentProjectDialogMachineId!==e||this.recentProjectDialogEntry!==t||this.recentProjectDialogGeneration!==n||r!==void 0&&R(this.state)!==e)return;let i=r===`cancel`?this.recentProjectDialogCancelFocus:r===`removal`?this.recentProjectDialogRemovalFocus:void 0,a=this.renderRoot.querySelector(`recent-project-dialog`);a?.isConnected===!0&&a.close(),this.recentProjectDialogCancelFocus=void 0,this.recentProjectDialogRemovalFocus=void 0,this.recentProjectDialogMachineId=void 0,this.recentProjectDialogInitialView=`closed-actions`,this.recentProjectDialogEntry=void 0,i!==void 0&&this.updateComplete.then(()=>{this.recentProjectDialogMachineId===void 0&&this.recentProjectDialogEntry===void 0&&this.recentProjectDialogGeneration===n&&R(this.state)===e&&i()})}workspacePanels(){let e=this.state.selectedWorkspace;if(e===void 0)return[];let t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(e=>e.visible?.(t)??!0)}synchronizeMemoryPollingForSelectedWorkspace(e=this.plugins.getActivityRailItems()){if(this.state.selectedWorkspace===void 0){this.memory.updatePolling(!1);return}this.synchronizeMemoryPolling(e)}synchronizeMemoryPolling(e){let t=e.some(e=>jR(e)&&cy(e,this.createActivityRailContext(e.id),this.reportActivityRailError));this.memory.updatePolling(t)}synchronizeLearnedSkillsPollingForSelectedWorkspace(e=this.plugins.getActivityRailItems()){if(this.state.selectedWorkspace===void 0){this.learnedSkills.updatePolling(!1);return}this.synchronizeLearnedSkillsPolling(e)}synchronizeLearnedSkillsPolling(e){let t=e.some(e=>MR(e)&&cy(e,this.createActivityRailContext(e.id),this.reportActivityRailError));this.learnedSkills.updatePolling(t)}visibleWorkspacePanels(){let e=this.hiddenWorkspacePanelTools();return this.workspacePanels().filter(t=>!e.includes(t.id))}hiddenWorkspacePanelTools(){let e=[];return this.terminalTabHidden&&e.push(`core:workspace.terminal`),this.infoTabHidden&&e.push(`core:workspace.info`),e}workspacePanelEmptyState(){let e=this.state.selectedProject;return this.state.isLoadingProjects?{title:`Loading projects…`,body:`Looking for projects you have added to PI WEBUI.`}:e===void 0?this.state.projects.length===0?{title:`No projects yet`,body:`Use Actions → Add Project to add a folder. Workspace tools will appear here after you choose a workspace.`}:{title:`Select a project`,body:`Choose a project from the sidebar, then select a workspace to inspect files, Git, or terminals.`}:this.state.isLoadingWorkspaces?{title:`Loading workspaces…`,body:`Preparing workspace tools for ${e.name}.`}:this.state.workspaces.length===0?{title:`No workspaces found`,body:`${e.name} does not have any available workspaces. Try selecting the project again or re-adding it.`}:{title:`Select a workspace`,body:`Choose a workspace in ${e.name} to inspect files, Git, or terminals.`}}sessionEmptyMessage(){return this.state.isLoadingProjects?`Loading projects…`:this.state.isLoadingSessions?`Loading sessions…`:this.state.selectedWorkspace===void 0?this.state.selectedProject===void 0?this.state.projects.length===0?`Add a project to start a session.`:`Select a project and workspace to start a session.`:`Select a workspace to start a session.`:`Select or start a session.`}shouldShowSessionStartScreen(e){return e.selectedWorkspace!==void 0&&e.selectedSession===void 0&&!e.isLoadingSessions&&e.sessions.every(e=>e.archived===!0)&&e.error===``}renderStarterNotice(){let e=El(this.starterNotice,this.starterNoticeScope(),this.starterModelPolicyInputs()?.status.blockedReason)??this.confirmedStarterModelPolicyWarning();return e===void 0?null:g`<p class="starter-notice" role="alert">${e}</p>`}renderSessionStartScreen(e){let t=e.selectedWorkspace;if(t===void 0)return g``;let n=this.starterSessionDefaults,r=this.starterSessionConfiguration(),i=this.selectedMachineModelTierCatalog(),a=n!==void 0&&(this.starterModelPolicySelectionSupported()?(i?.models.length??0)>0:n.models.length>0),o=n!==void 0&&n.thinkingLevels.length>0,s=this.starterModelPolicyInputs(),c=s===void 0||n===void 0?[]:this.policyThinkingOptions(this.starterModelPolicy?.exact??s.status.resolved,n.thinkingLevels);return g`
|
|
7530
7530
|
<section class="session-start-screen" aria-labelledby="session-start-heading">
|
|
7531
7531
|
<div class="session-start-content">
|
|
7532
7532
|
<p class="session-start-eyebrow">PI WEBUI · ${t.label}</p>
|
|
@@ -7538,7 +7538,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7538
7538
|
<p class="session-start-hint">Describe a goal, paste a task, or attach a file to begin.</p>
|
|
7539
7539
|
</div>
|
|
7540
7540
|
</section>
|
|
7541
|
-
`}starterSessionConfiguration(){let e=this.starterSessionDefaults,t=this.starterModelPolicy;return e===void 0||t===void 0||!this.starterModelPolicySelectionSupported()?e:{...e,model:{provider:t.exact.model.provider,id:t.exact.model.id},thinkingLevel:t.exact.thinkingLevel}}starterModelPolicyInputs(){let e=this.starterSessionDefaults,t=this.starterModelPolicy;if(e===void 0||t===void 0||!this.sessionModelPolicySupported())return;let n=this.selectedMachineModelTierCatalog();if(this.starterModelPolicySelectionSupported()){let r=n===void 0?{kind:`blocked`,reason:this.modelTierCatalogError===``?`Loading model policy choices`:this.modelTierCatalogError}:al(t,n),i={mode:t.mode,...t.tier===void 0?{}:{tier:t.tier},resolved:r.kind===`ready`?r.resolved:t.exact,ladderValid:n?.valid??!0,...r.kind===`blocked`?{blockedReason:r.reason}:{}};return{status:i,response:{contractVersion:1,policy:t,session:{sessionId:`starter`,isStreaming:!1,isCompacting:!1,isBashRunning:!1,pendingMessageCount:0,queuedMessages:[],tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,...e.model===void 0?{}:{model:e.model},thinkingLevel:e.thinkingLevel,modelPolicy:i}}}}let r=t.tier,i=r===void 0?void 0:n?.rows[r],a=t.mode===`tiered`&&r!==void 0&&i?.valid===!0?n?.ladder?.[r]:void 0,o=qc(e),s=t.mode===`exact`&&o!==void 0&&!Zc(t.exact,o),c=t.mode===`tiered`&&a===void 0,l={mode:t.mode,...r===void 0?{}:{tier:r},resolved:a??t.exact,ladderValid:n===void 0||n.valid,...c?{blockedReason:n?.configError??(this.modelTierCatalogError===``?`Choose a valid model tier before starting`:this.modelTierCatalogError)}:s?{blockedReason:`Choose a model and thinking level before starting`}:{}};return{status:l,response:{contractVersion:1,policy:t,session:{sessionId:`starter`,isStreaming:!1,isCompacting:!1,isBashRunning:!1,pendingMessageCount:0,queuedMessages:[],tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,...e.model===void 0?{}:{model:e.model},thinkingLevel:e.thinkingLevel,modelPolicy:l}}}}starterModelPolicyBlocksStart(){return this.starterModelPolicyInputs()?.status.blockedReason!==void 0}starterModelPolicyError(){if(this.modelTierCatalogError!==``)return this.modelTierCatalogError;if(this.starterModelPolicySelectionSupported()){let e=this.currentConfirmedStarterModelPolicyWriterSnapshot()?.error;return e===void 0?this.starterModelPolicyPreferenceReadError:`${hR} ${e}`}let e=this.starterModelPolicyPreferenceScope(),t=e===void 0?void 0:this.starterModelPolicyPreferenceWriter.snapshot(e).error;return t===void 0?this.starterModelPolicyPreferenceReadError:`Could not remember this model policy; this session will still use it. ${t}`}currentConfirmedStarterModelPolicyWriterSnapshot(){let e=this.confirmedStarterModelPolicyUiScope;if(!(e===void 0||this.confirmedStarterModelPolicyUiGeneration!==this.starterModelPolicySelectionGeneration||!this.starterModelPolicyPreferenceScopeMatchesCurrentSelection(e)))return this.confirmedStarterModelPolicyPreferenceWriter.snapshot(e)}confirmedStarterModelPolicyWarning(){let e=this.currentConfirmedStarterModelPolicyWriterSnapshot()?.error;return e===void 0?void 0:`${hR} ${e}`}starterModelPolicyStartSnapshot(){let e=this.starterModelPolicy,t=this.starterSessionDefaults;if(e===void 0||t===void 0||!this.sessionModelPolicySupported())return;if(e.mode===`tiered`)return e.tier===void 0?void 0:{mode:`tiered`,tier:e.tier};let n=qc(t);if(!(n===void 0||Zc(n,e.exact)))return{mode:`exact`,exact:{model:{...e.exact.model},thinkingLevel:e.exact.thinkingLevel}}}starterPlusModelPolicyInitializer(){if(!this.starterModelPolicySelectionSupported())return;let e=this.starterModelPolicy,t=this.selectedMachineModelTierCatalog();if(e===void 0||t===void 0)return;let n=al(e,t);return n.kind===`ready`?n.initialModelPolicy:void 0}async loadMissingStarterPlusModelPolicyInputs(e,t,n){if(this.starterModelPolicy===void 0){await this.loadStarterSessionDefaults(e,{awaitModelTierCatalog:!0,expectedSelectionGeneration:n});return}this.selectedMachineModelTierCatalog()===void 0&&await this.ensureModelTierCatalog(t)}clearStarterModelPolicyAfterSuccessfulStart(e,t,n){!e||this.state.selectedWorkspace?.id!==t||this.starterModelPolicy!==n||(this.starterModelPolicy=void 0)}selectedProjectWorkTarget(e=R(this.state)){if(R(this.state)!==e)return;let t=this.state.selectedProject?.id;return t===void 0?void 0:{machineId:e,projectId:t}}recordProjectWork(e){e!==void 0&&this.recentProjects.recordWork(e.projectId,e.machineId)}mobilePanelBadge(e){let t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}mobilePanelIcon(e){switch(e.id){case`core:workspace.files`:return`files`;case`core:workspace.git`:return`git`;case`core:workspace.terminal`:return`terminal`;default:return}}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){let t=_R(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:n=>sc.workspaceFile(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await sc.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await sc.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await sc.moveWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelTerminal(e,t,n){let r=this.terminalCommandRunsForOrigin(n,t);return{open:n=>{this.openRuntimeTerminal(t,e,n)},runCommand:t=>r.runCommand({...t,workspace:e})}}createWorkspacePanelContext(e){let t=_R(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return Cx({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),prompt:this.createPromptEditor(),terminal:this.createWorkspacePanelTerminal(e,n,i),openTerminal:t=>{this.openRuntimeTerminal(n,e,t)},host:this.createWorkspaceHost(),piWebUiUnstable:{terminalCommandRuns:a},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:Tc(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:e=>{this.files.expandDir(e)},onSelectFile:e=>{this.files.selectFile(e)},onStartWorkspaceUpload:(e,t)=>this.files.startWorkspaceUpload(e,t),onCancelWorkspaceUpload:e=>{this.files.cancelWorkspaceUpload(e)},onClearWorkspaceUpload:e=>{this.files.clearWorkspaceUpload(e)},onRefreshGit:()=>{this.git.refreshGit()},onRefreshMemory:()=>{this.memory.refresh()},onSelectDiff:e=>{this.git.selectDiff(e)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(`core`)}getActions(){return LS(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}sessionActions(){return[{id:`app.sessions.cleanup`,title:`Clean Up Sessions`,description:`Preview and manually clean up idle or archived sessions on the selected machine`,group:`Sessions`,closesActionPalette:!0,...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.toggle-terminal-tab`,title:this.terminalTabHidden?`Show Terminal Tab`:`Hide Terminal Tab`,description:this.terminalTabHidden?`Show the terminal tab in the workspace panel`:`Hide the terminal tab from the workspace panel`,group:`View`,run:()=>{this.toggleTerminalTab()}},{id:`app.layout.toggle-info-tab`,title:this.infoTabHidden?`Show Info Tab`:`Hide Info Tab`,description:this.infoTabHidden?`Show the info tab in the workspace panel`:`Hide the info tab from the workspace panel`,group:`View`,run:()=>{this.toggleInfoTab()}},{id:`app.layout.reset-navigation-panel-size`,title:`Reset Navigation Panel Size`,description:`Restore the navigation panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`navigation`)}},{id:`app.layout.reset-workspace-panel-size`,title:`Reset Workspace Panel Size`,description:`Restore the workspace panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`workspace`)}},{id:`app.layout.reset-panel-sizes`,title:`Reset Panel Sizes`,description:`Restore all side panels to their default widths`,group:`View`,run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:`app.navigation.focus-machines`,title:`Focus Machines`,description:`Move keyboard focus to the machine selector`,shortcut:`mod+g m`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`machines`)},{id:`app.navigation.focus-projects`,title:`Focus Projects`,description:`Move keyboard focus to the projects list`,shortcut:`mod+g p`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`projects`)},{id:`app.navigation.focus-workspaces`,title:`Focus Workspaces`,description:`Move keyboard focus to the workspaces list`,shortcut:`mod+g w`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`workspaces`)},{id:`app.navigation.focus-sessions`,title:`Focus Sessions`,description:`Move keyboard focus to the sessions list`,shortcut:`mod+g s`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins(`PI WEBUI plugins`,()=>ix())}async loadPluginsForSelectedMachine(){let e=this.state.selectedMachine;e?.kind===`remote`&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){if(await this.ensureGatewayPluginsLoaded(),e.kind!==`remote`||this.loadedMachinePluginIds.has(e.id))return;let t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;let n=this.registerExternalPlugins(`PI WEBUI plugins from ${e.name}`,()=>ix(`api/machines/${encodeURIComponent(e.id)}/pi-webui-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.plugins.shouldLoadRemotePlugin(e.id,e.machineSpecific)})).then(t=>{t&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,n),await n}async registerExternalPlugins(e,t){try{let e=await t();for(let t of e)try{this.plugins.register(t)}catch(e){console.warn(`Failed to register PI WEBUI plugin ${t.id}`,e)}return this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(),this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(t){return console.warn(`Failed to load ${e}`,t),!1}}createPromptEditor(){return{insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){return this.createPluginRuntimeContextForOrigin(`core`,R(this.state))}createPluginRuntimeContextForOrigin(e,t){let n=e=>Sx({state:this.state,prompt:this.createPromptEditor(),piWebUiUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(e,t),openSettings:e=>{this.openSettings(e)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.openProjectDialog()},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:e=>{this.selectMainView(e)},selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),checkForPiWebUiUpdates:()=>this.piWebUiStatusController.checkForUpdates(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:e=>this.deleteWorkspace(e),startSession:()=>this.withChatScrollTransition(()=>this.startSessionAndOpenChat()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},n);return n(e)}createActivityRailContext(e){let t=_R(this.state),n=this.state.selectedWorkspace,r=this.activeActivityRailId===e?this.activeActivityRailGeneration:void 0,i=a=>wx({...this.createPluginRuntimeContextForOrigin(a,t.id),machine:t,...n===void 0?{}:{workspaceScope:{workspace:n,files:this.createWorkspaceFiles(n,t.id),terminal:this.createWorkspacePanelTerminal(n,t.id,a)}},host:{requestRender:()=>{this.requestUpdate()},close:()=>{r!==void 0&&this.closeActivityRailItem(e,r)}},onRefreshMemory:()=>{this.memory.refresh()},onRefreshLearnedSkills:()=>{this.learnedSkills.refresh()}},i);return i(`core`)}activityRailItems(){let e=this.plugins.getActivityRailItems();return this.synchronizeMemoryPollingForSelectedWorkspace(e),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(e),e.flatMap(e=>this.projectActivityRailItems([e],this.createActivityRailContext(e.id)))}projectActivityRailItems(e,t){return ly(e,t,this.reportActivityRailError)}activeActivityRailItem(){let e=this.activeActivityRailId;if(e===void 0)return;let t=this.resolveActivityRailItem(e);return t===void 0?void 0:{...t,generation:this.activeActivityRailGeneration}}openActivityRailItem(e,t){this.resolveActivityRailItem(e)!==void 0&&(this.closeCompactActivityRail(),this.activityRailRestoreFocus=t,this.activeActivityRailGeneration+=1,this.activeActivityRailId=e)}resolveActivityRailItem(e){let t=this.plugins.getActivityRailItems().find(t=>t.id===e);if(t===void 0)return;let n=this.createActivityRailContext(e);if(this.projectActivityRailItems([t],n).some(t=>t.id===e))return{activity:t,context:n}}closeActivityRailItem(e,t){if(this.activeActivityRailId!==e||this.activeActivityRailGeneration!==t)return;let n=this.activityRailRestoreFocus;this.activityRailRestoreFocus=void 0,this.activeActivityRailId=void 0,n!==void 0&&this.updateComplete.then(()=>{this.activeActivityRailId===void 0&&n()})}restoreActivityRailFocus(e){if(e.isConnected){e.focus();return}let t=this.compactActivityRailLauncher;if(t?.isConnected===!0){t.focus();return}this.currentCompactActivityRailLauncher()?.focus()}currentCompactActivityRailLauncher(){let e=this.renderRoot.querySelector(`app-context-bar`)?.shadowRoot?.querySelector(`.activity-rail-action-button`);return e?.isConnected===!0?e:void 0}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!x_(e)){this.setState({error:`Only secondary Git worktrees can be deleted`});return}if(My(this.state,e))return;let t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?\n\nThis will run git worktree remove and delete:\n${e.path}\n\nThe Git branch will not be deleted.`))return;let n=R(this.state);try{let t=await sc.deleteWorkspace(e.projectId,e.id,n);if(R(this.state)!==n)return;this.recordWorkspaceDeletionRun(t,n);let r=await this.workspaceForCommandRun(t);if(R(this.state)!==n)return;r!==void 0&&this.openRuntimeTerminal(n,r,{terminalId:t.terminalId})}catch(e){R(this.state)===n&&this.setState({error:`Failed to start workspace deletion: ${WR(e)}`})}}async workspaceForCommandRun(e){let t=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e.projectId)),t.find(t=>t.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(R(this.state)!==t)return;let n=Ny(e);n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;let e=R(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{let n=await this.terminalCommandRunsForOrigin(`core`,e).listCommandRuns(ky(t.id));if(R(this.state)!==e)return;let r=Ay(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))Py(t)||await this.handleCompletedWorkspaceDeletionRun(t,e)}catch(e){console.warn(`Failed to refresh workspace deletion runs`,e)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){let e=Object.values(this.state.workspaceDeletionRuns).some(Py);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=R(this.state)){if(R(this.state)!==t)return;let n=HR(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=Ny(e);if(r!==void 0){if(this.handledWorkspaceDeletionRunIds.add(n),e.status===`succeeded`){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,r),R(this.state)!==t)return;this.setState({workspaceDeletionRuns:KR(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&(this.setState({error:`Workspace deletion failed. See terminal output.`}),this.updateWorkspaceDeletionPolling())}}openProjectBrowser(e){this.projectBrowserRestoreFocus=e,this.projectBrowserOpen=!0}async showProjectStatistics(e){let t=++this.statisticsRequestGeneration,n=R(this.state),r=()=>t===this.statisticsRequestGeneration&&R(this.state)===n;this.statisticsProject=e,this.statisticsReport=void 0,this.statisticsSessionCount=void 0,this.statisticsError=void 0,this.statisticsLoading=!0;try{let t=await sc.workspaces(e.id,n);if(!r())return;let i={projectPath:e.path,liveCwds:t.map(e=>e.path)};ac.projectUsageCount(i,n).then(({sessionCount:e})=>{r()&&this.statisticsLoading&&(this.statisticsSessionCount=e)},()=>void 0);let a=await ac.projectUsage(i,n);if(!r())return;this.statisticsReport=a}catch(e){if(!r())return;this.statisticsError=e instanceof Error?e.message:String(e)}finally{r()&&(this.statisticsLoading=!1)}}closeProjectStatistics(){this.statisticsRequestGeneration+=1,this.statisticsProject=void 0,this.statisticsReport=void 0,this.statisticsSessionCount=void 0,this.statisticsError=void 0,this.statisticsLoading=!1}closeProjectBrowser(e={}){let t=e.restoreFocus===!0?this.projectBrowserRestoreFocus:void 0;this.projectBrowserRestoreFocus=void 0,this.projectBrowserOpen=!1,t!==void 0&&this.updateComplete.then(()=>{t()})}selectProjectFromBrowser(e){this.closeProjectBrowser(),this.selectNavigationItem(`projects`,`workspaces`,()=>this.workspaces.selectProject(e))}addProjectFromBrowser(){this.closeProjectBrowser(),this.openProjectDialog()}openSessionBrowser(e){this.state.selectedProject!==void 0&&(this.sessionBrowserRestoreFocus=e,this.sessionBrowserOpen=!0)}closeSessionBrowser(e={}){let t=e.restoreFocus===!0?this.sessionBrowserRestoreFocus:void 0;this.sessionBrowserRestoreFocus=void 0,this.sessionBrowserOpen=!1,t!==void 0&&this.updateComplete.then(()=>{t()})}selectSessionFromBrowser(e){this.closeSessionBrowser(),this.selectNavigationItem(`sessions`,`chat`,()=>this.selectSessionFromNavigation(e))}openProjectDialog(){this.setState({projectDialogOpen:!0})}openMachineDialog(){this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebUiStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(`Remove ${e.name}?\n\nThis only removes it from this PI WEBUI gateway.`))return;let t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();let n=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(t=>t.id===e.id)||this.machineNavigation.forget(e.id),t&&n!==void 0&&await this.selectMachineWithMemory(n,{rememberCurrent:!1})}openSelectedMachine(){let e=this.state.selectedMachine;e?.kind!==`remote`||e.baseUrl===void 0||window.open(e.baseUrl,`_blank`,`noopener,noreferrer`)}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{let n=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`Action failed: ${n}`})})}async openModelDialog(){let e=await this.sessions.listModels(),t=this.state.status?.model?.provider,n=this.state.status?.model?.id,r=[...e].sort((e,t)=>{let n=e.provider??``,r=t.provider??``;return n===r?(e.id??``).localeCompare(t.id??``):n.localeCompare(r)});this.setState({modelDialog:{title:`Select Model`,...t!==void 0&&n!==void 0?{selectedValue:`${t}/${n}`}:{},options:r.map(e=>{let r=e.provider??``,i=e.id??``,a=r===t&&i===n;return{value:`${r}/${i}`,label:i+(a?` ✓ current`:``),...r===``?{}:{group:r}}})}})}async pickModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+1);if(!this.sessionModelPolicySupported()){await this.sessions.setModel(n,r);return}let i=await this.prepareActiveModelPolicyDraft();if(i===void 0||i!==this.activeModelPolicyDraftForState(this.state)||i.mode!==`exact`)return;let a=this.selectedMachineModelTierCatalog(),o=a?.models.find(e=>e.model.provider===n&&e.model.id===r);if(o===void 0){a!==void 0&&(this.modelTierCatalogError=`Model ${n}/${r} is unavailable in the model policy catalog`);return}this.modelTierCatalogError=``,this.setActiveModelPolicyDraft(el(i,o)),this.scheduleActiveExactModelPolicyApply()}openStarterModelDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=this.starterModelPolicySelectionSupported(),n=t?this.starterModelPolicy?.exact:void 0,r=n?.model.provider??e.model?.provider,i=n?.model.id??e.model?.id,a=t?(this.selectedMachineModelTierCatalog()?.models??[]).map(e=>({provider:e.model.provider,id:e.model.id,...e.name===void 0?{}:{name:e.name}})):[...e.models],o=r!==void 0&&i!==void 0&&!a.some(e=>e.provider===r&&e.id===i),s=[...o?[...a,{provider:r,id:i}]:a].sort((e,t)=>{let n=e.provider??``,r=t.provider??``;return n===r?(e.id??``).localeCompare(t.id??``):n.localeCompare(r)});this.setState({modelDialog:{title:`Select Default Model`,source:`starter`,...r!==void 0&&i!==void 0?{selectedValue:`${r}/${i}`}:{},options:s.map(e=>{let t=e.provider??``,n=e.id??``,a=t===r&&n===i;return{value:`${t}/${n}`,label:n+(a?` ✓ current`:``)+(a&&o?` (unavailable)`:``),...t===``?{}:{group:t}}})}})}async pickStarterModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);if(!(t<=0)){if(this.starterModelPolicySelectionSupported()){let n=this.starterModelPolicy,r=e.slice(0,t),i=e.slice(t+1),a=this.selectedMachineModelTierCatalog()?.models.find(e=>e.model.provider===r&&e.model.id===i);if(n===void 0||a===void 0)return;this.setStarterModelPolicyDraft(el(n,a));return}await this.updateStarterSessionDefaults({model:{provider:e.slice(0,t),modelId:e.slice(t+1)}})}}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?eR:$L;this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${tR}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${tR}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===$L||e===eR){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===$L},this.applyPreferredTheme(!0);return}if(!e.startsWith(tR))return;let t=e.slice(6),n=this.plugins.getThemes().find(e=>e.id===t);n!==void 0&&(this.themePreference={themeId:n.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){let t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,vy(t),e&&_y(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return yy({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return xy(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?`Follow the system light/dark preference when the selected theme has a pair.`:e.selectedThemePair===void 0?`On, but the selected theme has no light/dark pair, so it will stay selected.`:`On · ${e.selectedThemePair.name} follows the system ${this.systemPrefersLight()?`light`:`dark`} preference.`}themeOptionLabel(e,t){let n=[...e.id===t?[`selected`]:[],...e.id===this.activeThemeId&&e.id!==t?[`active`]:[]];return n.length===0?e.name:`${e.name} ✓ ${n.join(` · `)}`}themeOptionDescription(e){let t=[e.colorScheme];return this.themePairForTheme(e.id)!==void 0&&t.push(`auto pair`),e.description!==void 0&&t.push(e.description),t.join(` · `)}async openThinkingDialog(){let e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??`off`;this.setState({thinkingDialog:{title:`Select Thinking Level`,selectedValue:t,options:e.map(e=>{let n=JR(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickThinking(e){if(this.setState({thinkingDialog:void 0}),e===``)return;if(!this.sessionModelPolicySupported()){await this.sessions.setThinkingLevel(e);return}let t=await this.prepareActiveModelPolicyDraft();if(t===void 0||t!==this.activeModelPolicyDraftForState(this.state)||t.mode!==`exact`)return;let n=tl(t,e);if(this.setActiveModelPolicyDraft(n),(this.selectedMachineModelTierCatalog()?.models.find(e=>e.model.provider===n.exact.model.provider&&e.model.id===n.exact.model.id))?.thinkingLevels.includes(e)!==!0){this.cancelActiveModelPolicyApply(),this.modelTierCatalogError=`Thinking level ${e} is unsupported by ${n.exact.model.provider}/${n.exact.model.id}`;return}this.modelTierCatalogError=``,this.scheduleActiveExactModelPolicyApply()}openStarterThinkingDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=this.starterModelPolicySelectionSupported()?this.starterModelPolicy?.exact.thinkingLevel??e.thinkingLevel:e.thinkingLevel,n=e.thinkingLevels.includes(t)?e.thinkingLevels:[t,...e.thinkingLevels];this.setState({thinkingDialog:{title:`Select Default Thinking Level`,source:`starter`,selectedValue:t,options:n.map(e=>{let n=JR(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickStarterThinking(e){if(this.setState({thinkingDialog:void 0}),e!==``){if(this.starterModelPolicySelectionSupported()){let t=this.starterModelPolicy;t!==void 0&&this.setStarterModelPolicyDraft(tl(t,e));return}await this.updateStarterSessionDefaults({thinkingLevel:e})}}async updateStarterSessionDefaults(e){let t=this.state.selectedWorkspace;if(t===void 0)return;let n=R(this.state);try{let r=await cc.updateSessionDefaults(t.path,e,n);if(R(this.state)!==n||this.state.selectedWorkspace?.id!==t.id)return;this.starterSessionDefaults=r,this.starterNotice=void 0,this.starterModelPolicyPreferenceReadError=r.starterModelPolicyPreferenceError??``;let i=this.starterModelPolicy,a=i===void 0?Jc(r):Yc(i,r);this.starterModelPolicy=a;let o=qc(r);a.mode===`exact`&&o!==void 0&&Zc(a.exact,o)&&this.persistStarterModelPolicyPreference(a)}catch(e){R(this.state)===n&&this.state.selectedWorkspace?.id===t.id&&this.publishStarterNotice(Tl(`defaults-failed`,`Could not save this workspace's model defaults. ${WR(e)}`,{machineId:n,workspaceId:t.id}))}}sendPrompt(e,t,n,r){if(!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e))return;let i=this.selectedProjectWorkTarget();this.sessions.send(e,t,n,r).then(e=>{e&&this.recordProjectWork(i)})}async ensureStarterModelPolicyCatalog(){let e=this.selectedMachineModelTierCatalog();return e===void 0?(await this.ensureModelTierCatalog(R(this.state)),this.selectedMachineModelTierCatalog()):e}setStarterModelPolicyDraft(e){this.starterNotice=void 0;let t={mode:e.mode,exact:{model:{...e.exact.model},thinkingLevel:e.exact.thinkingLevel},...e.tier===void 0?{}:{tier:e.tier}};return this.starterModelPolicy=t,t}applyGitUpdateManagerStatus(e,t,n){let r=this.state.selectedWorkspace;R(this.state)!==t||r?.id!==e.id||r.projectId!==e.projectId||this.setState({gitStatus:n,gitStale:!1})}startTerminalModalPointerInteraction(e,t){if(this.terminalModalMaximized||t.button!==0)return;let n=t.currentTarget;if(!(n instanceof HTMLElement))return;let r=n.closest(`.terminal-modal-frame`);if(!(r instanceof HTMLElement))return;t.preventDefault(),t.stopPropagation();let i=XS(this.terminalModalBoundsFromFrame(r),this.terminalModalViewport());n.setPointerCapture(t.pointerId),this.terminalModalBounds=i,this.terminalModalPointerInteraction={operation:e,pointerId:t.pointerId,target:n,startClientX:t.clientX,startClientY:t.clientY,bounds:i}}terminalModalBoundsFromFrame(e){let{left:t,top:n,width:r,height:i}=e.getBoundingClientRect();return{left:t,top:n,width:r,height:i}}terminalModalViewport(){return typeof window>`u`?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight}}terminalModalFrameStyle(){let e=this.terminalModalMaximized?void 0:this.terminalModalBounds,t=e===void 0?``:`; left: ${String(e.left)}px; top: ${String(e.top)}px; width: ${String(e.width)}px; height: ${String(e.height)}px`;return`--terminal-modal-opacity: ${String(this.terminalModalOpacity)}%${t};`}finishTerminalModalPointerInteraction(){let e=this.terminalModalPointerInteraction;if(e!==void 0){try{e.target.releasePointerCapture(e.pointerId)}catch{}this.terminalModalPointerInteraction=void 0}}persistTerminalModalPreferences(){iC({fontSize:this.terminalModalFontSize,opacity:this.terminalModalOpacity})}toggleTerminalTab(){this.terminalTabHidden=!this.terminalTabHidden,this.persistWorkspaceTabVisibility()}toggleInfoTab(){this.infoTabHidden=!this.infoTabHidden,this.persistWorkspaceTabVisibility()}persistWorkspaceTabVisibility(){fC({terminalHidden:this.terminalTabHidden,infoHidden:this.infoTabHidden})}activeModelPolicyInputs(e){let t=e.status?.modelPolicy;if(e.status===void 0||t===void 0||!this.sessionModelPolicySupported())return;let n=this.activeModelPolicyDraftForState(e);if(n===void 0)return{error:e.modelPolicyError??this.modelTierCatalogError,status:t,editorStatus:e.status,thinkingOptions:this.policyThinkingOptions(t.resolved,e.availableThinkingLevels)};let r=n.tier,i=r===void 0||this.selectedMachineModelTierCatalog()?.rows[r].valid!==!0?void 0:this.selectedMachineModelTierCatalog()?.ladder?.[r],a=n.mode===`exact`?n.exact:i??t.resolved,o={mode:n.mode,...r===void 0?{}:{tier:r},resolved:{model:{...a.model},thinkingLevel:a.thinkingLevel},ladderValid:t.ladderValid,...t.blockedReason===void 0?{}:{blockedReason:t.blockedReason}},s=n.exact.model.provider!==``&&n.exact.model.id!==``,c=n.mode===`exact`?{...e.status,...s?{model:{...n.exact.model}}:{},thinkingLevel:n.exact.thinkingLevel,modelPolicy:o}:{...e.status,modelPolicy:o};return{error:e.modelPolicyError??this.modelTierCatalogError,status:o,editorStatus:c,thinkingOptions:this.policyThinkingOptions(n.exact,e.availableThinkingLevels)}}renderChatView(e,t){let n=R(e)===`local`?this.hostSpeech.snapshot:void 0;return g`
|
|
7541
|
+
`}starterSessionConfiguration(){let e=this.starterSessionDefaults,t=this.starterModelPolicy;return e===void 0||t===void 0||!this.starterModelPolicySelectionSupported()?e:{...e,model:{provider:t.exact.model.provider,id:t.exact.model.id},thinkingLevel:t.exact.thinkingLevel}}starterModelPolicyInputs(){let e=this.starterSessionDefaults,t=this.starterModelPolicy;if(e===void 0||t===void 0||!this.sessionModelPolicySupported())return;let n=this.selectedMachineModelTierCatalog();if(this.starterModelPolicySelectionSupported()){let r=n===void 0?{kind:`blocked`,reason:this.modelTierCatalogError===``?`Loading model policy choices`:this.modelTierCatalogError}:al(t,n),i={mode:t.mode,...t.tier===void 0?{}:{tier:t.tier},resolved:r.kind===`ready`?r.resolved:t.exact,ladderValid:n?.valid??!0,...r.kind===`blocked`?{blockedReason:r.reason}:{}};return{status:i,response:{contractVersion:1,policy:t,session:{sessionId:`starter`,isStreaming:!1,isCompacting:!1,isBashRunning:!1,pendingMessageCount:0,queuedMessages:[],tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,...e.model===void 0?{}:{model:e.model},thinkingLevel:e.thinkingLevel,modelPolicy:i}}}}let r=t.tier,i=r===void 0?void 0:n?.rows[r],a=t.mode===`tiered`&&r!==void 0&&i?.valid===!0?n?.ladder?.[r]:void 0,o=qc(e),s=t.mode===`exact`&&o!==void 0&&!Zc(t.exact,o),c=t.mode===`tiered`&&a===void 0,l={mode:t.mode,...r===void 0?{}:{tier:r},resolved:a??t.exact,ladderValid:n===void 0||n.valid,...c?{blockedReason:n?.configError??(this.modelTierCatalogError===``?`Choose a valid model tier before starting`:this.modelTierCatalogError)}:s?{blockedReason:`Choose a model and thinking level before starting`}:{}};return{status:l,response:{contractVersion:1,policy:t,session:{sessionId:`starter`,isStreaming:!1,isCompacting:!1,isBashRunning:!1,pendingMessageCount:0,queuedMessages:[],tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,...e.model===void 0?{}:{model:e.model},thinkingLevel:e.thinkingLevel,modelPolicy:l}}}}starterModelPolicyBlocksStart(){return this.starterModelPolicyInputs()?.status.blockedReason!==void 0}starterModelPolicyError(){if(this.modelTierCatalogError!==``)return this.modelTierCatalogError;if(this.starterModelPolicySelectionSupported()){let e=this.currentConfirmedStarterModelPolicyWriterSnapshot()?.error;return e===void 0?this.starterModelPolicyPreferenceReadError:`${gR} ${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:`${gR} ${e}`}starterModelPolicyStartSnapshot(){let e=this.starterModelPolicy,t=this.starterSessionDefaults;if(e===void 0||t===void 0||!this.sessionModelPolicySupported())return;if(e.mode===`tiered`)return e.tier===void 0?void 0:{mode:`tiered`,tier:e.tier};let n=qc(t);if(!(n===void 0||Zc(n,e.exact)))return{mode:`exact`,exact:{model:{...e.exact.model},thinkingLevel:e.exact.thinkingLevel}}}starterPlusModelPolicyInitializer(){if(!this.starterModelPolicySelectionSupported())return;let e=this.starterModelPolicy,t=this.selectedMachineModelTierCatalog();if(e===void 0||t===void 0)return;let n=al(e,t);return n.kind===`ready`?n.initialModelPolicy:void 0}async loadMissingStarterPlusModelPolicyInputs(e,t,n){if(this.starterModelPolicy===void 0){await this.loadStarterSessionDefaults(e,{awaitModelTierCatalog:!0,expectedSelectionGeneration:n});return}this.selectedMachineModelTierCatalog()===void 0&&await this.ensureModelTierCatalog(t)}clearStarterModelPolicyAfterSuccessfulStart(e,t,n){!e||this.state.selectedWorkspace?.id!==t||this.starterModelPolicy!==n||(this.starterModelPolicy=void 0)}selectedProjectWorkTarget(e=R(this.state)){if(R(this.state)!==e)return;let t=this.state.selectedProject?.id;return t===void 0?void 0:{machineId:e,projectId:t}}recordProjectWork(e){e!==void 0&&this.recentProjects.recordWork(e.projectId,e.machineId)}mobilePanelBadge(e){let t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}mobilePanelIcon(e){switch(e.id){case`core:workspace.files`:return`files`;case`core:workspace.git`:return`git`;case`core:workspace.terminal`:return`terminal`;default:return}}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){let t=vR(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:n=>sc.workspaceFile(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await sc.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await sc.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await sc.moveWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelTerminal(e,t,n){let r=this.terminalCommandRunsForOrigin(n,t);return{open:n=>{this.openRuntimeTerminal(t,e,n)},runCommand:t=>r.runCommand({...t,workspace:e})}}createWorkspacePanelContext(e){let t=vR(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return Cx({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),prompt:this.createPromptEditor(),terminal:this.createWorkspacePanelTerminal(e,n,i),openTerminal:t=>{this.openRuntimeTerminal(n,e,t)},host:this.createWorkspaceHost(),piWebUiUnstable:{terminalCommandRuns:a},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:Tc(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onExpandDir:e=>{this.files.expandDir(e)},onSelectFile:e=>{this.files.selectFile(e)},onStartWorkspaceUpload:(e,t)=>this.files.startWorkspaceUpload(e,t),onCancelWorkspaceUpload:e=>{this.files.cancelWorkspaceUpload(e)},onClearWorkspaceUpload:e=>{this.files.clearWorkspaceUpload(e)},onRefreshGit:()=>{this.git.refreshGit()},onRefreshMemory:()=>{this.memory.refresh()},onSelectDiff:e=>{this.git.selectDiff(e)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(`core`)}getActions(){return LS(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}sessionActions(){return[{id:`app.sessions.cleanup`,title:`Clean Up Sessions`,description:`Preview and manually clean up idle or archived sessions on the selected machine`,group:`Sessions`,closesActionPalette:!0,...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.toggle-terminal-tab`,title:this.terminalTabHidden?`Show Terminal Tab`:`Hide Terminal Tab`,description:this.terminalTabHidden?`Show the terminal tab in the workspace panel`:`Hide the terminal tab from the workspace panel`,group:`View`,run:()=>{this.toggleTerminalTab()}},{id:`app.layout.toggle-info-tab`,title:this.infoTabHidden?`Show Info Tab`:`Hide Info Tab`,description:this.infoTabHidden?`Show the info tab in the workspace panel`:`Hide the info tab from the workspace panel`,group:`View`,run:()=>{this.toggleInfoTab()}},{id:`app.layout.reset-navigation-panel-size`,title:`Reset Navigation Panel Size`,description:`Restore the navigation panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`navigation`)}},{id:`app.layout.reset-workspace-panel-size`,title:`Reset Workspace Panel Size`,description:`Restore the workspace panel to its default width`,group:`View`,run:()=>{this.resetResizablePanel(`workspace`)}},{id:`app.layout.reset-panel-sizes`,title:`Reset Panel Sizes`,description:`Restore all side panels to their default widths`,group:`View`,run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:`app.navigation.focus-machines`,title:`Focus Machines`,description:`Move keyboard focus to the machine selector`,shortcut:`mod+g m`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`machines`)},{id:`app.navigation.focus-projects`,title:`Focus Projects`,description:`Move keyboard focus to the projects list`,shortcut:`mod+g p`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`projects`)},{id:`app.navigation.focus-workspaces`,title:`Focus Workspaces`,description:`Move keyboard focus to the workspaces list`,shortcut:`mod+g w`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`workspaces`)},{id:`app.navigation.focus-sessions`,title:`Focus Sessions`,description:`Move keyboard focus to the sessions list`,shortcut:`mod+g s`,group:`Navigation`,closesActionPalette:!0,run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins(`PI WEBUI plugins`,()=>ix())}async loadPluginsForSelectedMachine(){let e=this.state.selectedMachine;e?.kind===`remote`&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){if(await this.ensureGatewayPluginsLoaded(),e.kind!==`remote`||this.loadedMachinePluginIds.has(e.id))return;let t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;let n=this.registerExternalPlugins(`PI WEBUI plugins from ${e.name}`,()=>ix(`api/machines/${encodeURIComponent(e.id)}/pi-webui-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.plugins.shouldLoadRemotePlugin(e.id,e.machineSpecific)})).then(t=>{t&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,n),await n}async registerExternalPlugins(e,t){try{let e=await t();for(let t of e)try{this.plugins.register(t)}catch(e){console.warn(`Failed to register PI WEBUI plugin ${t.id}`,e)}return this.synchronizeMemoryPollingForSelectedWorkspace(),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(),this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(t){return console.warn(`Failed to load ${e}`,t),!1}}createPromptEditor(){return{insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){return this.createPluginRuntimeContextForOrigin(`core`,R(this.state))}createPluginRuntimeContextForOrigin(e,t){let n=e=>Sx({state:this.state,prompt:this.createPromptEditor(),piWebUiUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(e,t),openSettings:e=>{this.openSettings(e)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.openProjectDialog()},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:e=>{this.selectMainView(e)},selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),checkForPiWebUiUpdates:()=>this.piWebUiStatusController.checkForUpdates(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:e=>this.deleteWorkspace(e),startSession:()=>this.withChatScrollTransition(()=>this.startSessionAndOpenChat()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},n);return n(e)}createActivityRailContext(e){let t=vR(this.state),n=this.state.selectedWorkspace,r=this.activeActivityRailId===e?this.activeActivityRailGeneration:void 0,i=a=>wx({...this.createPluginRuntimeContextForOrigin(a,t.id),machine:t,...n===void 0?{}:{workspaceScope:{workspace:n,files:this.createWorkspaceFiles(n,t.id),terminal:this.createWorkspacePanelTerminal(n,t.id,a)}},host:{requestRender:()=>{this.requestUpdate()},close:()=>{r!==void 0&&this.closeActivityRailItem(e,r)}},onRefreshMemory:()=>{this.memory.refresh()},onRefreshLearnedSkills:()=>{this.learnedSkills.refresh()}},i);return i(`core`)}activityRailItems(){let e=this.plugins.getActivityRailItems();return this.synchronizeMemoryPollingForSelectedWorkspace(e),this.synchronizeLearnedSkillsPollingForSelectedWorkspace(e),e.flatMap(e=>this.projectActivityRailItems([e],this.createActivityRailContext(e.id)))}projectActivityRailItems(e,t){return ly(e,t,this.reportActivityRailError)}activeActivityRailItem(){let e=this.activeActivityRailId;if(e===void 0)return;let t=this.resolveActivityRailItem(e);return t===void 0?void 0:{...t,generation:this.activeActivityRailGeneration}}openActivityRailItem(e,t){this.resolveActivityRailItem(e)!==void 0&&(this.closeCompactActivityRail(),this.activityRailRestoreFocus=t,this.activeActivityRailGeneration+=1,this.activeActivityRailId=e)}resolveActivityRailItem(e){let t=this.plugins.getActivityRailItems().find(t=>t.id===e);if(t===void 0)return;let n=this.createActivityRailContext(e);if(this.projectActivityRailItems([t],n).some(t=>t.id===e))return{activity:t,context:n}}closeActivityRailItem(e,t){if(this.activeActivityRailId!==e||this.activeActivityRailGeneration!==t)return;let n=this.activityRailRestoreFocus;this.activityRailRestoreFocus=void 0,this.activeActivityRailId=void 0,n!==void 0&&this.updateComplete.then(()=>{this.activeActivityRailId===void 0&&n()})}restoreActivityRailFocus(e){if(e.isConnected){e.focus();return}let t=this.compactActivityRailLauncher;if(t?.isConnected===!0){t.focus();return}this.currentCompactActivityRailLauncher()?.focus()}currentCompactActivityRailLauncher(){let e=this.renderRoot.querySelector(`app-context-bar`)?.shadowRoot?.querySelector(`.activity-rail-action-button`);return e?.isConnected===!0?e:void 0}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!x_(e)){this.setState({error:`Only secondary Git worktrees can be deleted`});return}if(My(this.state,e))return;let t=e.branch??e.label;if(!confirm(`Delete workspace ${t}?\n\nThis will run git worktree remove and delete:\n${e.path}\n\nThe Git branch will not be deleted.`))return;let n=R(this.state);try{let t=await sc.deleteWorkspace(e.projectId,e.id,n);if(R(this.state)!==n)return;this.recordWorkspaceDeletionRun(t,n);let r=await this.workspaceForCommandRun(t);if(R(this.state)!==n)return;r!==void 0&&this.openRuntimeTerminal(n,r,{terminalId:t.terminalId})}catch(e){R(this.state)===n&&this.setState({error:`Failed to start workspace deletion: ${GR(e)}`})}}async workspaceForCommandRun(e){let t=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];return(t===void 0||t.length===0)&&(t=await this.workspaces.refreshProjectWorkspaces(e.projectId)),t.find(t=>t.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(R(this.state)!==t)return;let n=Ny(e);n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;let e=R(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{let n=await this.terminalCommandRunsForOrigin(`core`,e).listCommandRuns(ky(t.id));if(R(this.state)!==e)return;let r=Ay(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))Py(t)||await this.handleCompletedWorkspaceDeletionRun(t,e)}catch(e){console.warn(`Failed to refresh workspace deletion runs`,e)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){let e=Object.values(this.state.workspaceDeletionRuns).some(Py);if(e&&this.workspaceDeletionPollTimer===void 0){this.workspaceDeletionPollTimer=window.setInterval(()=>{this.refreshWorkspaceDeletionRuns()},1e3);return}!e&&this.workspaceDeletionPollTimer!==void 0&&(window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t=R(this.state)){if(R(this.state)!==t)return;let n=UR(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=Ny(e);if(r!==void 0){if(this.handledWorkspaceDeletionRunIds.add(n),e.status===`succeeded`){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,r),R(this.state)!==t)return;this.setState({workspaceDeletionRuns:qR(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&(this.setState({error:`Workspace deletion failed. See terminal output.`}),this.updateWorkspaceDeletionPolling())}}openProjectBrowser(e){this.projectBrowserRestoreFocus=e,this.projectBrowserOpen=!0}async showProjectStatistics(e){let t=++this.statisticsRequestGeneration,n=R(this.state),r=()=>t===this.statisticsRequestGeneration&&R(this.state)===n;this.statisticsProject=e,this.statisticsReport=void 0,this.statisticsSessionCount=void 0,this.statisticsError=void 0,this.statisticsLoading=!0;try{let t=await sc.workspaces(e.id,n);if(!r())return;let i={projectPath:e.path,liveCwds:t.map(e=>e.path)};ac.projectUsageCount(i,n).then(({sessionCount:e})=>{r()&&this.statisticsLoading&&(this.statisticsSessionCount=e)},()=>void 0);let a=await ac.projectUsage(i,n);if(!r())return;this.statisticsReport=a}catch(e){if(!r())return;this.statisticsError=e instanceof Error?e.message:String(e)}finally{r()&&(this.statisticsLoading=!1)}}closeProjectStatistics(){this.statisticsRequestGeneration+=1,this.statisticsProject=void 0,this.statisticsReport=void 0,this.statisticsSessionCount=void 0,this.statisticsError=void 0,this.statisticsLoading=!1}closeProjectBrowser(e={}){let t=e.restoreFocus===!0?this.projectBrowserRestoreFocus:void 0;this.projectBrowserRestoreFocus=void 0,this.projectBrowserOpen=!1,t!==void 0&&this.updateComplete.then(()=>{t()})}selectProjectFromBrowser(e){this.closeProjectBrowser(),this.selectNavigationItem(`projects`,`workspaces`,()=>this.workspaces.selectProject(e))}addProjectFromBrowser(){this.closeProjectBrowser(),this.openProjectDialog()}openSessionBrowser(e){this.state.selectedProject!==void 0&&(this.sessionBrowserRestoreFocus=e,this.sessionBrowserOpen=!0)}closeSessionBrowser(e={}){let t=e.restoreFocus===!0?this.sessionBrowserRestoreFocus:void 0;this.sessionBrowserRestoreFocus=void 0,this.sessionBrowserOpen=!1,t!==void 0&&this.updateComplete.then(()=>{t()})}selectSessionFromBrowser(e){this.closeSessionBrowser(),this.selectNavigationItem(`sessions`,`chat`,()=>this.selectSessionFromNavigation(e))}openProjectDialog(){this.setState({projectDialogOpen:!0})}openMachineDialog(){this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebUiStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(`Remove ${e.name}?\n\nThis only removes it from this PI WEBUI gateway.`))return;let t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();let n=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(t=>t.id===e.id)||this.machineNavigation.forget(e.id),t&&n!==void 0&&await this.selectMachineWithMemory(n,{rememberCurrent:!1})}openSelectedMachine(){let e=this.state.selectedMachine;e?.kind!==`remote`||e.baseUrl===void 0||window.open(e.baseUrl,`_blank`,`noopener,noreferrer`)}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{let n=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`Action failed: ${n}`})})}async openModelDialog(){let e=await this.sessions.listModels(),t=this.state.status?.model?.provider,n=this.state.status?.model?.id,r=[...e].sort((e,t)=>{let n=e.provider??``,r=t.provider??``;return n===r?(e.id??``).localeCompare(t.id??``):n.localeCompare(r)});this.setState({modelDialog:{title:`Select Model`,...t!==void 0&&n!==void 0?{selectedValue:`${t}/${n}`}:{},options:r.map(e=>{let r=e.provider??``,i=e.id??``,a=r===t&&i===n;return{value:`${r}/${i}`,label:i+(a?` ✓ current`:``),...r===``?{}:{group:r}}})}})}async pickModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);if(t<=0)return;let n=e.slice(0,t),r=e.slice(t+1);if(!this.sessionModelPolicySupported()){await this.sessions.setModel(n,r);return}let i=await this.prepareActiveModelPolicyDraft();if(i===void 0||i!==this.activeModelPolicyDraftForState(this.state)||i.mode!==`exact`)return;let a=this.selectedMachineModelTierCatalog(),o=a?.models.find(e=>e.model.provider===n&&e.model.id===r);if(o===void 0){a!==void 0&&(this.modelTierCatalogError=`Model ${n}/${r} is unavailable in the model policy catalog`);return}this.modelTierCatalogError=``,this.setActiveModelPolicyDraft(el(i,o)),this.scheduleActiveExactModelPolicyApply()}openStarterModelDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=this.starterModelPolicySelectionSupported(),n=t?this.starterModelPolicy?.exact:void 0,r=n?.model.provider??e.model?.provider,i=n?.model.id??e.model?.id,a=t?(this.selectedMachineModelTierCatalog()?.models??[]).map(e=>({provider:e.model.provider,id:e.model.id,...e.name===void 0?{}:{name:e.name}})):[...e.models],o=r!==void 0&&i!==void 0&&!a.some(e=>e.provider===r&&e.id===i),s=[...o?[...a,{provider:r,id:i}]:a].sort((e,t)=>{let n=e.provider??``,r=t.provider??``;return n===r?(e.id??``).localeCompare(t.id??``):n.localeCompare(r)});this.setState({modelDialog:{title:`Select Default Model`,source:`starter`,...r!==void 0&&i!==void 0?{selectedValue:`${r}/${i}`}:{},options:s.map(e=>{let t=e.provider??``,n=e.id??``,a=t===r&&n===i;return{value:`${t}/${n}`,label:n+(a?` ✓ current`:``)+(a&&o?` (unavailable)`:``),...t===``?{}:{group:t}}})}})}async pickStarterModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);if(!(t<=0)){if(this.starterModelPolicySelectionSupported()){let n=this.starterModelPolicy,r=e.slice(0,t),i=e.slice(t+1),a=this.selectedMachineModelTierCatalog()?.models.find(e=>e.model.provider===r&&e.model.id===i);if(n===void 0||a===void 0)return;this.setStarterModelPolicyDraft(el(n,a));return}await this.updateStarterSessionDefaults({model:{provider:e.slice(0,t),modelId:e.slice(t+1)}})}}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?tR:eR;this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${nR}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${nR}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===eR||e===tR){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===eR},this.applyPreferredTheme(!0);return}if(!e.startsWith(nR))return;let t=e.slice(6),n=this.plugins.getThemes().find(e=>e.id===t);n!==void 0&&(this.themePreference={themeId:n.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){let t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,vy(t),e&&_y(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return yy({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return xy(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?`Follow the system light/dark preference when the selected theme has a pair.`:e.selectedThemePair===void 0?`On, but the selected theme has no light/dark pair, so it will stay selected.`:`On · ${e.selectedThemePair.name} follows the system ${this.systemPrefersLight()?`light`:`dark`} preference.`}themeOptionLabel(e,t){let n=[...e.id===t?[`selected`]:[],...e.id===this.activeThemeId&&e.id!==t?[`active`]:[]];return n.length===0?e.name:`${e.name} ✓ ${n.join(` · `)}`}themeOptionDescription(e){let t=[e.colorScheme];return this.themePairForTheme(e.id)!==void 0&&t.push(`auto pair`),e.description!==void 0&&t.push(e.description),t.join(` · `)}async openThinkingDialog(){let e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??`off`;this.setState({thinkingDialog:{title:`Select Thinking Level`,selectedValue:t,options:e.map(e=>{let n=YR(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickThinking(e){if(this.setState({thinkingDialog:void 0}),e===``)return;if(!this.sessionModelPolicySupported()){await this.sessions.setThinkingLevel(e);return}let t=await this.prepareActiveModelPolicyDraft();if(t===void 0||t!==this.activeModelPolicyDraftForState(this.state)||t.mode!==`exact`)return;let n=tl(t,e);if(this.setActiveModelPolicyDraft(n),(this.selectedMachineModelTierCatalog()?.models.find(e=>e.model.provider===n.exact.model.provider&&e.model.id===n.exact.model.id))?.thinkingLevels.includes(e)!==!0){this.cancelActiveModelPolicyApply(),this.modelTierCatalogError=`Thinking level ${e} is unsupported by ${n.exact.model.provider}/${n.exact.model.id}`;return}this.modelTierCatalogError=``,this.scheduleActiveExactModelPolicyApply()}openStarterThinkingDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=this.starterModelPolicySelectionSupported()?this.starterModelPolicy?.exact.thinkingLevel??e.thinkingLevel:e.thinkingLevel,n=e.thinkingLevels.includes(t)?e.thinkingLevels:[t,...e.thinkingLevels];this.setState({thinkingDialog:{title:`Select Default Thinking Level`,source:`starter`,selectedValue:t,options:n.map(e=>{let n=YR(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickStarterThinking(e){if(this.setState({thinkingDialog:void 0}),e!==``){if(this.starterModelPolicySelectionSupported()){let t=this.starterModelPolicy;t!==void 0&&this.setStarterModelPolicyDraft(tl(t,e));return}await this.updateStarterSessionDefaults({thinkingLevel:e})}}async updateStarterSessionDefaults(e){let t=this.state.selectedWorkspace;if(t===void 0)return;let n=R(this.state);try{let r=await cc.updateSessionDefaults(t.path,e,n);if(R(this.state)!==n||this.state.selectedWorkspace?.id!==t.id)return;this.starterSessionDefaults=r,this.starterNotice=void 0,this.starterModelPolicyPreferenceReadError=r.starterModelPolicyPreferenceError??``;let i=this.starterModelPolicy,a=i===void 0?Jc(r):Yc(i,r);this.starterModelPolicy=a;let o=qc(r);a.mode===`exact`&&o!==void 0&&Zc(a.exact,o)&&this.persistStarterModelPolicyPreference(a)}catch(e){R(this.state)===n&&this.state.selectedWorkspace?.id===t.id&&this.publishStarterNotice(Tl(`defaults-failed`,`Could not save this workspace's model defaults. ${GR(e)}`,{machineId:n,workspaceId:t.id}))}}sendPrompt(e,t,n,r){if(!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e))return;let i=this.selectedProjectWorkTarget();this.sessions.send(e,t,n,r).then(e=>{e&&this.recordProjectWork(i)})}async ensureStarterModelPolicyCatalog(){let e=this.selectedMachineModelTierCatalog();return e===void 0?(await this.ensureModelTierCatalog(R(this.state)),this.selectedMachineModelTierCatalog()):e}setStarterModelPolicyDraft(e){this.starterNotice=void 0;let t={mode:e.mode,exact:{model:{...e.exact.model},thinkingLevel:e.exact.thinkingLevel},...e.tier===void 0?{}:{tier:e.tier}};return this.starterModelPolicy=t,t}applyGitUpdateManagerStatus(e,t,n){let r=this.state.selectedWorkspace;R(this.state)!==t||r?.id!==e.id||r.projectId!==e.projectId||this.setState({gitStatus:n,gitStale:!1})}startTerminalModalPointerInteraction(e,t){if(this.terminalModalMaximized||t.button!==0)return;let n=t.currentTarget;if(!(n instanceof HTMLElement))return;let r=n.closest(`.terminal-modal-frame`);if(!(r instanceof HTMLElement))return;t.preventDefault(),t.stopPropagation();let i=XS(this.terminalModalBoundsFromFrame(r),this.terminalModalViewport());n.setPointerCapture(t.pointerId),this.terminalModalBounds=i,this.terminalModalPointerInteraction={operation:e,pointerId:t.pointerId,target:n,startClientX:t.clientX,startClientY:t.clientY,bounds:i}}terminalModalBoundsFromFrame(e){let{left:t,top:n,width:r,height:i}=e.getBoundingClientRect();return{left:t,top:n,width:r,height:i}}terminalModalViewport(){return typeof window>`u`?{width:0,height:0}:{width:window.innerWidth,height:window.innerHeight}}terminalModalFrameStyle(){let e=this.terminalModalMaximized?void 0:this.terminalModalBounds,t=e===void 0?``:`; left: ${String(e.left)}px; top: ${String(e.top)}px; width: ${String(e.width)}px; height: ${String(e.height)}px`;return`--terminal-modal-opacity: ${String(this.terminalModalOpacity)}%${t};`}finishTerminalModalPointerInteraction(){let e=this.terminalModalPointerInteraction;if(e!==void 0){try{e.target.releasePointerCapture(e.pointerId)}catch{}this.terminalModalPointerInteraction=void 0}}persistTerminalModalPreferences(){iC({fontSize:this.terminalModalFontSize,opacity:this.terminalModalOpacity})}toggleTerminalTab(){this.terminalTabHidden=!this.terminalTabHidden,this.persistWorkspaceTabVisibility()}toggleInfoTab(){this.infoTabHidden=!this.infoTabHidden,this.persistWorkspaceTabVisibility()}persistWorkspaceTabVisibility(){fC({terminalHidden:this.terminalTabHidden,infoHidden:this.infoTabHidden})}activeModelPolicyInputs(e){let t=e.status?.modelPolicy;if(e.status===void 0||t===void 0||!this.sessionModelPolicySupported())return;let n=this.activeModelPolicyDraftForState(e);if(n===void 0)return{error:e.modelPolicyError??this.modelTierCatalogError,status:t,editorStatus:e.status,thinkingOptions:this.policyThinkingOptions(t.resolved,e.availableThinkingLevels)};let r=n.tier,i=r===void 0||this.selectedMachineModelTierCatalog()?.rows[r].valid!==!0?void 0:this.selectedMachineModelTierCatalog()?.ladder?.[r],a=n.mode===`exact`?n.exact:i??t.resolved,o={mode:n.mode,...r===void 0?{}:{tier:r},resolved:{model:{...a.model},thinkingLevel:a.thinkingLevel},ladderValid:t.ladderValid,...t.blockedReason===void 0?{}:{blockedReason:t.blockedReason}},s=n.exact.model.provider!==``&&n.exact.model.id!==``,c=n.mode===`exact`?{...e.status,...s?{model:{...n.exact.model}}:{},thinkingLevel:n.exact.thinkingLevel,modelPolicy:o}:{...e.status,modelPolicy:o};return{error:e.modelPolicyError??this.modelTierCatalogError,status:o,editorStatus:c,thinkingOptions:this.policyThinkingOptions(n.exact,e.availableThinkingLevels)}}renderChatView(e,t){let n=R(e)===`local`?this.hostSpeech.snapshot:void 0;return g`
|
|
7542
7542
|
<chat-view .sessionId=${t.id} .sessionInfo=${t} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isSendingPrompt=${e.sendingPrompts[t.id]===!0} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .clientQueuedMessages=${e.clientQueuedSessionMessages[t.id]??[]} .status=${e.status} .warningCount=${this.sessionWarningVisibility.warningCount} .warningsExpanded=${this.sessionWarningVisibility.warningCount>0&&!this.sessionWarningVisibility.collapsed} .onToggleWarnings=${this.handleToggleWarnings} .activity=${e.activity} .notificationInbox=${Xm(e.selectedNotificationInbox)} .canClearServerQueue=${this.canClearServerQueue()} .onClearServerQueue=${this.handleClearServerQueue} .canMessageActions=${this.canMessageActions()&&t.archived!==!0} .onEditFromHere=${this.handleEditFromHere} .onForkFromHere=${this.handleForkFromHere} .hostSpeechStatus=${n?.status} .activeHostSpeechMessageKey=${n?.active?.messageKey??``} .hostSpeechError=${n?.error??``} .onToggleHostSpeech=${n===void 0?void 0:this.handleToggleHostSpeech} .onDismissWarning=${this.handleDismissWarning} .onDismissNotification=${this.handleDismissNotification} .onDismissAllNotifications=${this.handleDismissAllNotifications} .warningsVisible=${!this.sessionWarningVisibility.collapsed} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
|
|
7543
7543
|
`}renderContextBar(){return this.appShell.isDesktopActivityRailLayout?null:g`
|
|
7544
7544
|
<app-context-bar
|
|
@@ -7670,7 +7670,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7670
7670
|
<div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
|
|
7671
7671
|
${e.selectedSession?g`
|
|
7672
7672
|
${this.renderChatView(e,e.selectedSession)}
|
|
7673
|
-
<prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${R(e)} .projectId=${e.selectedWorkspace?.projectId} .workspaceId=${e.selectedWorkspace?.id} .workspaceScopedFileSuggestions=${this.supportsWorkspaceFileSuggestions()} .speechInputSettings=${this.speechInputSettings} .disabled=${e.selectedSession.archived===!0} .canSteer=${e.status?.isStreaming===!0} .isCompacting=${e.status?.isCompacting===!0} .canStop=${e.status?.isStreaming===!0||e.status?.isBashRunning===!0||e.status?.isCompacting===!0||(e.status?.pendingMessageCount??0)>0} .status=${i===void 0?
|
|
7673
|
+
<prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${R(e)} .projectId=${e.selectedWorkspace?.projectId} .workspaceId=${e.selectedWorkspace?.id} .workspaceScopedFileSuggestions=${this.supportsWorkspaceFileSuggestions()} .speechInputSettings=${this.speechInputSettings} .disabled=${e.selectedSession.archived===!0} .canSteer=${e.status?.isStreaming===!0} .isCompacting=${e.status?.isCompacting===!0} .canStop=${e.status?.isStreaming===!0||e.status?.isBashRunning===!0||e.status?.isCompacting===!0||(e.status?.pendingMessageCount??0)>0} .status=${i===void 0?KR(e.status):i.editorStatus} .availableThinkingLevels=${e.availableThinkingLevels} .modelPolicyStatus=${i?.status} .modelTierCatalog=${i===void 0?void 0:this.selectedMachineModelTierCatalog()} .policyThinkingOptions=${i?.thinkingOptions??[]} .modelPolicyLoading=${i!==void 0&&(e.isLoadingModelPolicy||this.modelTierCatalogLoading)} .modelPolicySaving=${i!==void 0&&e.isSavingModelPolicy} .modelPolicyError=${i===void 0?``:i.error} .onSelectPolicyMode=${i===void 0?void 0:this.handleSelectActivePolicyMode} .onSelectPolicyTier=${i===void 0?void 0:this.handleSelectActivePolicyTier} .onSelectPolicyThinking=${i===void 0?void 0:this.handleSelectActivePolicyThinking} .sending=${e.sendingPrompts[e.selectedSession.id]===!0} .onSend=${this.handleSendPrompt} .onStop=${this.handleStopActiveWork} .onSelectModel=${this.handleSelectModel} .onSelectThinking=${this.handleSelectThinking} .onCompact=${t?this.handleCompact:void 0}></prompt-editor>
|
|
7674
7674
|
${e.commandDialog===void 0?null:g`<command-picker .title=${e.commandDialog.title} .options=${e.commandDialog.options} .onPick=${t=>this.sessions.respondToCommand(e.commandDialog?.requestId??``,t)} .onCancel=${()=>{this.sessions.cancelCommand()}}></command-picker>`}
|
|
7675
7675
|
`:this.shouldShowSessionStartScreen(e)?this.renderSessionStartScreen(e):g`<div class="empty">${this.sessionEmptyMessage()}</div>`}
|
|
7676
7676
|
${e.modelDialog===void 0?null:g`<command-picker title=${e.modelDialog.title} .searchable=${!0} .options=${e.modelDialog.options} .selectedValue=${e.modelDialog.selectedValue} .onPick=${t=>{e.modelDialog?.source===`starter`?this.pickStarterModel(t):this.pickModel(t)}} .onCancel=${()=>{this.setState({modelDialog:void 0})}}></command-picker>`}
|
|
@@ -7734,4 +7734,4 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
7734
7734
|
${Nt(this.recentProjectDialogGeneration,this.renderRecentProjectDialog())}
|
|
7735
7735
|
${this.settingsSection===void 0?null:g`<settings-dialog .section=${this.settingsSection} .machine=${e.selectedMachine} .machineRuntime=${this.selectedMachineRuntime()} .actions=${this.getDefaultActions()} .speechInputSettings=${this.speechInputSettings} .speechInputSettingsRequestSeq=${this.speechInputSettingsRequestSeq} .isSpeechInputSettingsRequestCurrent=${this.isSpeechInputSettingsRequestCurrent} .showHostSpeechSettings=${R(e)===`local`} .hostSpeechStatus=${R(e)===`local`?this.hostSpeech.snapshot.status:void 0} .hostSpeechStatusLoading=${R(e)===`local`&&this.hostSpeech.snapshot.loadingStatus} .onReloadHostSpeech=${R(e)===`local`?()=>this.hostSpeech.refreshStatus():void 0} .onNavigate=${e=>{this.navigateSettings(e)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${e=>{this.applyClientConfig(e)}} .onSpeechInputSettingsLoaded=${e=>{this.handleSpeechInputSettingsLoaded(e)}} .onSpeechInputSettingsSaved=${e=>{this.handleSpeechInputSettingsSaved(e)}} .onModelTiersSaved=${(e,t)=>{this.handleModelTiersSaved(e,t)}} .onRefreshMachineRuntime=${async e=>{await this.machines.refreshMachineRuntime(e)}}></settings-dialog>`}
|
|
7736
7736
|
</div>
|
|
7737
|
-
`}static{this.styles=Yy}};H([S()],$.prototype,`state`,void 0),H([C(`chat-view`)],$.prototype,`chatView`,void 0),H([C(`prompt-editor`)],$.prototype,`promptEditor`,void 0),H([C(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),H([C(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),H([C(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),H([S()],$.prototype,`unreadSessionIds`,void 0),H([S()],$.prototype,`speechInputSettings`,void 0),H([S()],$.prototype,`activeThemeId`,void 0),H([S()],$.prototype,`isRefreshingApp`,void 0),H([S()],$.prototype,`sessionCleanupDialog`,void 0),H([S()],$.prototype,`historyWindow`,void 0),H([S()],$.prototype,`recentProjectDialogEntry`,void 0),H([S()],$.prototype,`starterSessionDefaults`,void 0),H([S()],$.prototype,`starterModelPolicyPreferenceReadError`,void 0),H([S()],$.prototype,`starterNotice`,void 0),H([S()],$.prototype,`modelTierCatalog`,void 0),H([S()],$.prototype,`modelTierCatalogLoading`,void 0),H([S()],$.prototype,`modelTierCatalogError`,void 0),H([S()],$.prototype,`starterModelPolicy`,void 0),H([S()],$.prototype,`activeModelPolicyDraft`,void 0),H([S()],$.prototype,`modelsConfigDialogOpen`,void 0),H([S()],$.prototype,`projectBrowserOpen`,void 0),H([S()],$.prototype,`statisticsProject`,void 0),H([S()],$.prototype,`statisticsReport`,void 0),H([S()],$.prototype,`statisticsSessionCount`,void 0),H([S()],$.prototype,`statisticsLoading`,void 0),H([S()],$.prototype,`statisticsError`,void 0),H([S()],$.prototype,`sessionBrowserOpen`,void 0),H([S()],$.prototype,`skillsConfigDialogOpen`,void 0),H([S()],$.prototype,`pluginsConfigDialogOpen`,void 0),H([S()],$.prototype,`systemPromptDialogOpen`,void 0),H([S()],$.prototype,`gitUpdateManagerPanelOpen`,void 0),H([S()],$.prototype,`terminalModalOpen`,void 0),H([S()],$.prototype,`terminalModalBounds`,void 0),H([S()],$.prototype,`terminalModalMaximized`,void 0),H([S()],$.prototype,`terminalModalFontSize`,void 0),H([S()],$.prototype,`terminalModalOpacity`,void 0),H([S()],$.prototype,`terminalTabHidden`,void 0),H([S()],$.prototype,`infoTabHidden`,void 0),H([S()],$.prototype,`railOrder`,void 0),H([S()],$.prototype,`compactRailOpen`,void 0),H([S()],$.prototype,`activeActivityRailId`,void 0),H([S()],$.prototype,`settingsSection`,void 0),H([S()],$.prototype,`shortcutConfig`,void 0),H([S()],$.prototype,`workspaceUploadDefaultFolder`,void 0),$=H([b(`pi-webui-app`)],$);function
|
|
7737
|
+
`}static{this.styles=Yy}};H([S()],$.prototype,`state`,void 0),H([C(`chat-view`)],$.prototype,`chatView`,void 0),H([C(`prompt-editor`)],$.prototype,`promptEditor`,void 0),H([C(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),H([C(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),H([C(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),H([S()],$.prototype,`unreadSessionIds`,void 0),H([S()],$.prototype,`speechInputSettings`,void 0),H([S()],$.prototype,`activeThemeId`,void 0),H([S()],$.prototype,`isRefreshingApp`,void 0),H([S()],$.prototype,`sessionCleanupDialog`,void 0),H([S()],$.prototype,`historyWindow`,void 0),H([S()],$.prototype,`recentProjectDialogEntry`,void 0),H([S()],$.prototype,`starterSessionDefaults`,void 0),H([S()],$.prototype,`starterModelPolicyPreferenceReadError`,void 0),H([S()],$.prototype,`starterNotice`,void 0),H([S()],$.prototype,`modelTierCatalog`,void 0),H([S()],$.prototype,`modelTierCatalogLoading`,void 0),H([S()],$.prototype,`modelTierCatalogError`,void 0),H([S()],$.prototype,`starterModelPolicy`,void 0),H([S()],$.prototype,`activeModelPolicyDraft`,void 0),H([S()],$.prototype,`modelsConfigDialogOpen`,void 0),H([S()],$.prototype,`projectBrowserOpen`,void 0),H([S()],$.prototype,`statisticsProject`,void 0),H([S()],$.prototype,`statisticsReport`,void 0),H([S()],$.prototype,`statisticsSessionCount`,void 0),H([S()],$.prototype,`statisticsLoading`,void 0),H([S()],$.prototype,`statisticsError`,void 0),H([S()],$.prototype,`sessionBrowserOpen`,void 0),H([S()],$.prototype,`skillsConfigDialogOpen`,void 0),H([S()],$.prototype,`pluginsConfigDialogOpen`,void 0),H([S()],$.prototype,`systemPromptDialogOpen`,void 0),H([S()],$.prototype,`gitUpdateManagerPanelOpen`,void 0),H([S()],$.prototype,`terminalModalOpen`,void 0),H([S()],$.prototype,`terminalModalBounds`,void 0),H([S()],$.prototype,`terminalModalMaximized`,void 0),H([S()],$.prototype,`terminalModalFontSize`,void 0),H([S()],$.prototype,`terminalModalOpacity`,void 0),H([S()],$.prototype,`terminalTabHidden`,void 0),H([S()],$.prototype,`infoTabHidden`,void 0),H([S()],$.prototype,`railOrder`,void 0),H([S()],$.prototype,`compactRailOpen`,void 0),H([S()],$.prototype,`activeActivityRailId`,void 0),H([S()],$.prototype,`settingsSection`,void 0),H([S()],$.prototype,`shortcutConfig`,void 0),H([S()],$.prototype,`workspaceUploadDefaultFolder`,void 0),$=H([b(`pi-webui-app`)],$);function _R(){let e=new vx;return e.register({id:`core`,plugin:qb}),e.register({id:`themes`,plugin:Qb}),e}function vR(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 yR(e,t){return JSON.stringify([e,t.id,t.cwd])}function bR(e){let t=e.selectedSession;return t===void 0?void 0:yR(R(e),t)}function xR(e){let t=e.selectedSession;return t===void 0?void 0:{machineId:R(e),sessionId:t.id}}function SR(e,t){return e?.machineId===t?.machineId&&e?.sessionId===t?.sessionId}function CR(e){let t=e.selectedSession;return t===void 0?void 0:JSON.stringify([R(e),t.id,t.cwd])}function wR(e){return JSON.stringify([R(e),e.selectedWorkspace?.id,e.selectedWorkspace?.path,e.selectedSession?.id,e.selectedSession?.cwd])}function TR(e){if(ER(e)!==void 0&&DR(e,R(e)))return CR(e)}function ER(e){return e.status?.modelPolicy}function DR(e,t){if(t===`local`)return!0;let n=e.machineRuntimes[t];return n?.ok===!0&&E(n,w.sessionsModelPolicy)}function OR(e,t){let n=e.machineRuntimes[t];return n?.ok===!0&&E(n,w.sessionsModelPolicyStarterSelection)}function kR(e){return e!==void 0&&`starterModelPolicyContractVersion`in e}function AR(e,t){return e.mode===t.mode&&e.tier===t.tier&&Zc(e.exact,t.exact)}function jR(e){return e.id===cR||e.sourcePluginId===oR&&e.localId===sR}function MR(e){return e.id===dR||e.sourcePluginId===lR&&e.localId===uR}function NR(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 PR(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function FR(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function IR(e,t){return LR(e,t)}function LR(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function RR(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function zR(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function BR(e){return Ll(e.status,e.activity)}function VR(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function HR(){return{}}function UR(e,t){return JSON.stringify([e,t])}function WR(e){return QL[Math.min(e,QL.length-1)]??3e4}function GR(e){return e instanceof Error?e.message:String(e)}function KR(e){if(e?.modelPolicy===void 0)return e;let t={...e};return delete t.modelPolicy,t}function qR(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function JR(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function YR(e){switch(e){case`off`:return`No reasoning`;case`minimal`:return`Very brief reasoning (~1k tokens)`;case`low`:return`Light reasoning (~2k tokens)`;case`medium`:return`Moderate reasoning (~8k tokens)`;case`high`:return`Deep reasoning (~16k tokens)`;case`xhigh`:return`Maximum reasoning (~32k tokens)`;default:return}}export{y as a,b as i,C as n,g as o,x as r,h as s,H as t};
|