@hyperdreamer/pi-webui 1.9.0 → 1.9.1
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-Bpvsp0pk.js → CodeViewer-Cm2qJjkP.js} +1 -1
- package/dist/client/assets/{UnifiedDiffViewer-iSh_gYQc.js → UnifiedDiffViewer-XFd_Uipx.js} +1 -1
- package/dist/client/assets/{index-DCPkewJK.js → index-DtFX3SXN.js} +271 -271
- package/dist/client/index.html +1 -1
- package/dist/server/models/modelsConfigService.js +2 -1
- package/dist/server/models/modelsConfigService.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-Cm2qJjkP.js","./vendor-editor-core-vUi74DnD.js","./vendor-editor-languages-DoaXUodB.js","./vendor-editor-legacy-CYBnW6ZU.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j as u,l as d,p as f,q as p,u as m}from"./vendor-editor-core-vUi74DnD.js";import{a as ee,o as te,s as ne}from"./vendor-editor-languages-DoaXUodB.js";import{n as re,t as ie}from"./vendor-terminal-D8k4UKM2.js";var ae=Object.defineProperty,oe=(e,t)=>{let n={};for(var r in e)ae(n,r,{get:e[r],enumerable:!0});return t||ae(n,Symbol.toStringTag,{value:`Module`}),n};(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var se=globalThis,ce=se.ShadowRoot&&(se.ShadyCSS===void 0||se.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,le=Symbol(),ue=new WeakMap,de=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==le)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(ce&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=ue.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&ue.set(t,e))}return e}toString(){return this.cssText}},fe=e=>new de(typeof e==`string`?e:e+``,void 0,le),h=(e,...t)=>new de(e.length===1?e[0]:t.reduce((t,n,r)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if(typeof e==`number`)return e;throw Error(`Value passed to 'css' function must be a 'css' function result: `+e+`. Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.`)})(n)+e[r+1],e[0]),e,le),pe=(e,t)=>{if(ce)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=se.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},me=ce?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return fe(t)})(e):e,{is:he,defineProperty:ge,getOwnPropertyDescriptor:_e,getOwnPropertyNames:ve,getOwnPropertySymbols:ye,getPrototypeOf:be}=Object,xe=globalThis,Se=xe.trustedTypes,Ce=Se?Se.emptyScript:``,we=xe.reactiveElementPolyfillSupport,Te=(e,t)=>e,Ee={toAttribute(e,t){switch(t){case Boolean:e=e?Ce:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let n=e;switch(t){case Boolean:n=e!==null;break;case Number:n=e===null?null:Number(e);break;case Object:case Array:try{n=JSON.parse(e)}catch{n=null}}return n}},De=(e,t)=>!he(e,t),Oe={attribute:!0,type:String,converter:Ee,reflect:!1,useDefault:!1,hasChanged:De};Symbol.metadata??=Symbol(`metadata`),xe.litPropertyMetadata??=new WeakMap;var ke=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Oe){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),r=this.getPropertyDescriptor(e,n,t);r!==void 0&&ge(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=_e(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:r,set(t){let a=r?.call(this);i?.call(this,t),this.requestUpdate(e,a,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Oe}static _$Ei(){if(this.hasOwnProperty(Te(`elementProperties`)))return;let e=be(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Te(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Te(`properties`))){let e=this.properties,t=[...ve(e),...ye(e)];for(let n of t)this.createProperty(n,e[n])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[e,n]of t)this.elementProperties.set(e,n)}this._$Eh=new Map;for(let[e,t]of this.elementProperties){let n=this._$Eu(e,t);n!==void 0&&this._$Eh.set(n,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let e of n)t.unshift(me(e))}else e!==void 0&&t.push(me(e));return t}static _$Eu(e,t){let n=t.attribute;return!1===n?void 0:typeof n==`string`?n:typeof e==`string`?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return pe(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,n);if(r!==void 0&&!0===n.reflect){let i=(n.converter?.toAttribute===void 0?Ee:n.converter).toAttribute(t,n.type);this._$Em=e,i==null?this.removeAttribute(r):this.setAttribute(r,i),this._$Em=null}}_$AK(e,t){let n=this.constructor,r=n._$Eh.get(e);if(r!==void 0&&this._$Em!==r){let e=n.getPropertyOptions(r),i=typeof e.converter==`function`?{fromAttribute:e.converter}:e.converter?.fromAttribute===void 0?Ee:e.converter;this._$Em=r;let a=i.fromAttribute(t,e.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(e,t,n,r=!1,i){if(e!==void 0){let a=this.constructor;if(!1===r&&(i=this[e]),n??=a.getPropertyOptions(e),!((n.hasChanged??De)(i,t)||n.useDefault&&n.reflect&&i===this._$Ej?.get(e)&&!this.hasAttribute(a._$Eu(e,n))))return;this.C(e,t,n)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:r,wrapped:i},a){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,a??t??this[e]),!0!==i||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),!0===r&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}let e=this.constructor.elementProperties;if(e.size>0)for(let[t,n]of e){let{wrapped:e}=n,r=this[t];!0!==e||this._$AL.has(t)||r===void 0||this.C(t,void 0,n,r)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};ke.elementStyles=[],ke.shadowRootOptions={mode:`open`},ke[Te(`elementProperties`)]=new Map,ke[Te(`finalized`)]=new Map,we?.({ReactiveElement:ke}),(xe.reactiveElementVersions??=[]).push(`2.1.2`);var Ae=globalThis,je=e=>e,Me=Ae.trustedTypes,Ne=Me?Me.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,Pe=`$lit$`,Fe=`lit$${Math.random().toFixed(9).slice(2)}$`,Ie=`?`+Fe,Le=`<${Ie}>`,Re=document,ze=()=>Re.createComment(``),Be=e=>e===null||typeof e!=`object`&&typeof e!=`function`,Ve=Array.isArray,He=e=>Ve(e)||typeof e?.[Symbol.iterator]==`function`,Ue=`[
|
|
3
3
|
\f\r]`,We=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ge=/-->/g,Ke=/>/g,qe=RegExp(`>|${Ue}(?:([^\\s"'>=/]+)(${Ue}*=${Ue}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),Je=/'/g,Ye=/"/g,Xe=/^(?:script|style|textarea|title)$/i,Ze=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),g=Ze(1),_=Ze(2),Qe=Symbol.for(`lit-noChange`),v=Symbol.for(`lit-nothing`),$e=new WeakMap,et=Re.createTreeWalker(Re,129);function tt(e,t){if(!Ve(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return Ne===void 0?t:Ne.createHTML(t)}var nt=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=We;for(let t=0;t<n;t++){let n=e[t],s,c,l=-1,u=0;for(;u<n.length&&(o.lastIndex=u,c=o.exec(n),c!==null);)u=o.lastIndex,o===We?c[1]===`!--`?o=Ge:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=qe):(Xe.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=qe):o=Ke:o===qe?c[0]===`>`?(o=i??We,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?qe:c[3]===`"`?Ye:Je):o===Ye||o===Je?o=qe:o===Ge||o===Ke?o=We:(o=qe,i=void 0);let d=o===qe&&e[t+1].startsWith(`/>`)?` `:``;a+=o===We?n+Le:l>=0?(r.push(s),n.slice(0,l)+Pe+n.slice(l)+Fe+d):n+Fe+(l===-2?t:d)}return[tt(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},rt=class e{constructor({strings:t,_$litType$:n},r){let i;this.parts=[];let a=0,o=0,s=t.length-1,c=this.parts,[l,u]=nt(t,n);if(this.el=e.createElement(l,r),et.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=et.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(Pe)){let t=u[o++],n=i.getAttribute(e).split(Fe),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?ct:r[1]===`?`?lt:r[1]===`@`?ut:st}),i.removeAttribute(e)}else e.startsWith(Fe)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(Xe.test(i.tagName)){let e=i.textContent.split(Fe),t=e.length-1;if(t>0){i.textContent=Me?Me.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],ze()),et.nextNode(),c.push({type:2,index:++a});i.append(e[t],ze())}}}else if(i.nodeType===8)if(i.data===Ie)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(Fe,e+1))!==-1;)c.push({type:7,index:a}),e+=Fe.length-1}a++}}static createElement(e,t){let n=Re.createElement(`template`);return n.innerHTML=e,n}};function it(e,t,n=e,r){if(t===Qe)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=Be(t)?void 0:t._$litDirective$;return i?.constructor!==a&&(i?._$AO?.(!1),a===void 0?i=void 0:(i=new a(e),i._$AT(e,n,r)),r===void 0?n._$Cl=i:(n._$Co??=[])[r]=i),i!==void 0&&(t=it(e,i._$AS(e,t.values),i,r)),t}var at=class{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){let{el:{content:t},parts:n}=this._$AD,r=(e?.creationScope??Re).importNode(t,!0);et.currentNode=r;let i=et.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new ot(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new dt(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=et.nextNode(),a++)}return et.currentNode=Re,r}p(e){let t=0;for(let n of this._$AV)n!==void 0&&(n.strings===void 0?n._$AI(e[t]):(n._$AI(e,n,t),t+=n.strings.length-2)),t++}},ot=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=v,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=it(this,e,t),Be(e)?e===v||e==null||e===``?(this._$AH!==v&&this._$AR(),this._$AH=v):e!==this._$AH&&e!==Qe&&this._(e):e._$litType$===void 0?e.nodeType===void 0?He(e)?this.k(e):this._(e):this.T(e):this.$(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==v&&Be(this._$AH)?this._$AA.nextSibling.data=e:this.T(Re.createTextNode(e)),this._$AH=e}$(e){let{values:t,_$litType$:n}=e,r=typeof n==`number`?this._$AC(e):(n.el===void 0&&(n.el=rt.createElement(tt(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new at(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=$e.get(e.strings);return t===void 0&&$e.set(e.strings,t=new rt(e)),t}k(t){Ve(this._$AH)||(this._$AH=[],this._$AR());let n=this._$AH,r,i=0;for(let a of t)i===n.length?n.push(r=new e(this.O(ze()),this.O(ze()),this,this.options)):r=n[i],r._$AI(a),i++;i<n.length&&(this._$AR(r&&r._$AB.nextSibling,i),n.length=i)}_$AR(e=this._$AA.nextSibling,t){for(this._$AP?.(!1,!0,t);e!==this._$AB;){let t=je(e).nextSibling;je(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},st=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=v,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=i,n.length>2||n[0]!==``||n[1]!==``?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=v}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=it(this,e,t,0),a=!Be(e)||e!==this._$AH&&e!==Qe,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=it(this,r[n+o],t,o),s===Qe&&(s=this._$AH[o]),a||=!Be(s)||s!==this._$AH[o],s===v?e=v:e!==v&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===v?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},ct=class extends st{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===v?void 0:e}},lt=class extends st{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==v)}},ut=class extends st{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=it(this,e,t,0)??v)===Qe)return;let n=this._$AH,r=e===v&&n!==v||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==v&&(n===v||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH==`function`?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},dt=class{constructor(e,t,n){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=n}get _$AU(){return this._$AM._$AU}_$AI(e){it(this,e)}},ft={M:Pe,P:Fe,A:Ie,C:1,L:nt,R:at,D:He,V:it,I:ot,H:st,N:lt,U:ut,B:ct,F:dt},pt=Ae.litHtmlPolyfillSupport;pt?.(rt,ot),(Ae.litHtmlVersions??=[]).push(`3.3.3`);var mt=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new ot(t.insertBefore(ze(),e),e,void 0,n??{})}return i._$AI(e),i},ht=globalThis,y=class extends ke{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=mt(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Qe}};y._$litElement$=!0,y.finalized=!0,ht.litElementHydrateSupport?.({LitElement:y});var gt=ht.litElementPolyfillSupport;gt?.({LitElement:y}),(ht.litElementVersions??=[]).push(`4.2.2`);var b=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},_t={attribute:!0,type:String,converter:Ee,reflect:!1,hasChanged:De},vt=(e=_t,t,n)=>{let{kind:r,metadata:i}=n,a=globalThis.litPropertyMetadata.get(i);if(a===void 0&&globalThis.litPropertyMetadata.set(i,a=new Map),r===`setter`&&((e=Object.create(e)).wrapped=!0),a.set(n.name,e),r===`accessor`){let{name:r}=n;return{set(n){let i=t.get.call(this);t.set.call(this,n),this.requestUpdate(r,i,e,!0,n)},init(t){return t!==void 0&&this.C(r,void 0,e,t),t}}}if(r===`setter`){let{name:r}=n;return function(n){let i=this[r];t.call(this,n),this.requestUpdate(r,i,e,!0,n)}}throw Error(`Unsupported decorator location: `+r)};function x(e){return(t,n)=>typeof n==`object`?vt(e,t,n):((e,t,n)=>{let r=t.hasOwnProperty(n);return t.constructor.createProperty(n,e),r?Object.getOwnPropertyDescriptor(t,n):void 0})(e,t,n)}function S(e){return x({...e,state:!0,attribute:!1})}var yt=(e,t,n)=>(n.configurable=!0,n.enumerable=!0,Reflect.decorate&&typeof t!=`object`&&Object.defineProperty(e,t,n),n);function C(e,t){return(n,r,i)=>{let a=t=>t.renderRoot?.querySelector(e)??null;if(t){let{get:e,set:t}=typeof r==`object`?n:i??(()=>{let e=Symbol();return{get(){return this[e]},set(t){this[e]=t}}})();return yt(n,r,{get(){let n=e.call(this);return n===void 0&&(n=a(this),(n!==null||this.hasUpdated)&&t.call(this,n)),n}})}return yt(n,r,{get(){return a(this)}})}}function bt(e,t=St()){let n=new URL(t.viteBaseUrl,t.documentBaseUrl);return new URL(Ct(e),n).toString()}function xt(e,t=St()){let n=new URL(bt(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 St(){return{viteBaseUrl:`./`,documentBaseUrl:document.baseURI}}function Ct(e){return e.startsWith(`/`)?`.${e}`:e}async function w(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(bt(e),{...n,headers:r});if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(wt(e)??i.statusText)}return t(await i.json())}function wt(e){if(Tt(e))return typeof e.error==`string`?e.error:void 0}function Tt(e){return typeof e==`object`&&!!e}var T={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`},Et=1e3,Dt=32*1024,Ot=8*1024,kt=1e4;function At(e){return(e.split(/[\\/]/u).at(-1)?.toLowerCase()??e.toLowerCase()).replace(/(?:\.[cm]?js|\.exe|\.cmd)$/iu,``)===`pi`}function jt(e){return!e.includes(`/`)&&!e.includes(`\\`)&&At(e)}var Mt=new Set([`schemaVersion`,`revision`,`command`,`dir`,`sessionDirEnvKeys`]),Nt=/^sha256:[0-9a-f]{64}$/u,Pt=/^[A-Za-z0-9_][A-Za-z0-9._+-]*$/u,Ft=new Set([`PI_WEBUI_AGENT_SESSION_DIR`,`PI_CODING_AGENT_SESSION_DIR`]);function It(e){if(!Vt(e)||Object.keys(e).some(e=>!Mt.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`||!Nt.test(n))&&!(typeof r!=`string`||!Lt(r))&&!(typeof i!=`string`||!Rt(i))&&Bt(a)&&new Set(a).size===a.length&&!(a[0]!==`PI_WEBUI_AGENT_SESSION_DIR`||a.some(e=>!Ft.has(e))))return Object.freeze({schemaVersion:t,revision:n,command:r,dir:i,sessionDirEnvKeys:Object.freeze([...a])})}function Lt(e){return e!==e.trim()||/[\s;&|`$<>]/u.test(e)?!1:Rt(e)?!e.endsWith(`/`)&&!e.endsWith(`\\`):Pt.test(e)}function Rt(e){if(e===``||e!==e.trim()||zt(e))return!1;let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function zt(e){for(let t of e){let e=t.charCodeAt(0);if(e<32||e===127)return!0}return!1}function Bt(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function Vt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ht=Object.values(T),Ut=new Set(Ht);T.sessionsDeleteArchived,T.sessionsBulkMutations,T.sessionsCleanup,T.sessionsReload,T.sessionsClearQueue,T.sessionsMessageActions,T.sessionsSystemPrompt,T.sessionsPersistedState,T.sessionsNotifications,T.sessionsUnread,T.promptAttachments,T.workspaceFileSuggestions,T.piPackagesManage,T.selectedMachineSettings,T.agentProfileConfig,T.sessionsDeleteArchived,T.sessionsBulkMutations,T.sessionsCleanup,T.sessionsReload,T.sessionsClearQueue,T.sessionsMessageActions,T.sessionsSystemPrompt,T.sessionsPersistedState,T.sessionsNotifications,T.sessionsUnread,T.promptAttachments,T.sessionsDeleteArchived,T.sessionsBulkMutations,T.sessionsCleanup,T.sessionsReload,T.sessionsClearQueue,T.sessionsMessageActions,T.sessionsSystemPrompt,T.sessionsPersistedState,T.sessionsNotifications,T.sessionsUnread,T.promptAttachments,T.workspaceFileSuggestions,T.piPackagesManage,T.selectedMachineSettings,T.agentProfileConfig;function Wt(e){return typeof e==`string`&&Ut.has(e)}function Gt(e,t){return e?.capabilities?.includes(t)===!0}function Kt(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(Wt)}function qt(e){return typeof e==`object`&&!!e}function E(e){if(!qt(e))throw Error(`Expected object response`);return e}function D(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Expected string field: ${t}`);return n}function O(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw Error(`Expected optional string field: ${t}`);return n}}function k(e,t){let n=e[t];if(typeof n!=`number`)throw Error(`Expected number field: ${t}`);return n}function A(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Expected boolean field: ${t}`);return n}function j(e){return t=>{if(!Array.isArray(t))throw Error(`Expected array response`);return t.map(e)}}function Jt(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function Yt(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function Xt(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};let t=E(e);return{messages:Jt(t.messages),start:k(t,`start`),total:k(t,`total`)}}function Zt(e){let t=E(e);return j(Qt)(t.machines)}function Qt(e){let t=E(e),n=tn(t,`kind`),r=O(t,`baseUrl`),i=nn(t,`status`),a=O(t,`statusMessage`);return{id:D(t,`id`),name:D(t,`name`),kind:n,...r===void 0?{}:{baseUrl:r},createdAt:D(t,`createdAt`),updatedAt:D(t,`updatedAt`),...i===void 0?{}:{status:i},...a===void 0?{}:{statusMessage:a}}}function $t(e){let t=E(e),n=nn(t,`status`),r=O(t,`error`);return{machineId:D(t,`machineId`),ok:A(t,`ok`),checkedAt:D(t,`checkedAt`),...n===void 0?{}:{status:n},...t.web===void 0?{}:{web:Bi(t.web)},...t.sessiond===void 0?{}:{sessiond:Bi(t.sessiond)},...r===void 0?{}:{error:r}}}function en(e){let t=E(e),n=O(t,`error`);return{machineId:D(t,`machineId`),ok:A(t,`ok`),checkedAt:D(t,`checkedAt`),...N(`packageName`,O(t,`packageName`)),...N(`generatedAt`,O(t,`generatedAt`)),...t.components===void 0?{}:{components:Ri(t.components)},...t.capabilities===void 0?{}:{capabilities:Ki(t.capabilities)},...n===void 0?{}:{error:n}}}function tn(e,t){let n=D(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function nn(e,t){let n=O(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 rn(e){let t=E(e);return{id:D(t,`id`),name:D(t,`name`),path:D(t,`path`),createdAt:D(t,`createdAt`)}}function an(e){let t=E(e),n=O(t,`branch`);return{id:D(t,`id`),projectId:D(t,`projectId`),path:D(t,`path`),label:D(t,`label`),...n===void 0?{}:{branch:n},isMain:A(t,`isMain`),isGitRepo:A(t,`isGitRepo`),isGitWorktree:A(t,`isGitWorktree`),...N(`effectiveConfig`,on(t.effectiveConfig))}}function on(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid workspace effectiveConfig field`);return{...N(`uploads`,di(e.uploads))}}}function sn(e){let t=E(e),n=O(t,`name`),r=Pi(t.persisted,`persisted`),i=O(t,`parentSessionPath`),a=O(t,`archivedAt`),o=Pi(t.pinned,`pinned`);return{id:D(t,`id`),path:D(t,`path`),cwd:D(t,`cwd`),...r===void 0?{}:{persisted:r},...n===void 0?{}:{name:n},created:D(t,`created`),modified:D(t,`modified`),messageCount:k(t,`messageCount`),firstMessage:D(t,`firstMessage`),...i===void 0?{}:{parentSessionPath:i},...t.archived===!0?{archived:!0}:{},...a===void 0?{}:{archivedAt:a},...o===void 0?{}:{pinned:o}}}function cn(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function ln(e){if(e!==void 0)return{id:D(E(e),`id`)}}function un(e){let t=E(e),n=ln(t.dismiss);return{severity:cn(t.severity),message:D(t,`message`),...N(`source`,O(t,`source`)),...N(`path`,O(t,`path`)),...n===void 0?{}:{dismiss:n}}}function dn(e){return e===void 0?{}:{warnings:j(un)(e)}}function fn(e){let t=E(e);return{sessionId:D(t,`sessionId`),...N(`persisted`,Pi(t.persisted,`persisted`)),isStreaming:A(t,`isStreaming`),isCompacting:A(t,`isCompacting`),isBashRunning:A(t,`isBashRunning`),pendingMessageCount:k(t,`pendingMessageCount`),queuedMessages:t.queuedMessages===void 0?[]:j(qn)(t.queuedMessages),...N(`messageCount`,M(t,`messageCount`)),tokens:Jn(t.tokens),cost:k(t,`cost`),...Rr(t.generation),...Xn(t.model),...zr(t.contextUsage),...N(`thinkingLevel`,O(t,`thinkingLevel`)),...dn(t.warnings)}}function pn(e){let t=E(e);return{seq:k(t,`seq`),partial:t.partial??null}}function mn(e){let t=O(E(e),`systemPrompt`);return t===void 0?{}:{systemPrompt:t}}function hn(e){let t=E(e),n=Pn(t,`catalogRevision`),r=jn(t.sessions,_n,Et,`sessions`);if(vn(r),yn(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:bn(t,`catalogId`,512),catalogRevision:n,sessions:r}}function gn(e){let t=E(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=bn(t,`sessionId`,512),r=bn(t,`cwd`,Dt),i=xn(t,`catalogRevision`),a=t.unread===null?null:_n(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:bn(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function _n(e){let t=E(e),n=bn(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:bn(t,`sessionId`,512),cwd:bn(t,`cwd`,Dt),completionOrder:xn(t,`completionOrder`),completedAt:n}}function vn(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 yn(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 bn(e,t,n){let r=Nn(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function xn(e,t){let n=Pn(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function Sn(e){let t=E(e),n=wn(t.summary),r=jn(t.notifications,Tn,100,`notifications`);if(Fn(r),In(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==Rn(r))throw Error(`Notification snapshot severity mismatch`);let i=En(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:Nn(t,`daemonInstanceId`),catalogRevision:Pn(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function Cn(e){let t=E(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=wn(t.summary),r=En(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=Dn(t.delta);if(i.kind===`cleared`&&!Ln(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:Nn(t,`daemonInstanceId`),catalogRevision:Pn(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function wn(e){let t=E(e),n=Pn(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=Pn(t,`discardedCount`),i=kn(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:Nn(t,`sessionId`),cwd:Nn(t,`cwd`),inboxRevision:Pn(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function Tn(e){let t=E(e),n=D(t,`message`);if(new TextEncoder().encode(n).byteLength>8192)throw Error(`Notification message exceeds byte limit`);let r=D(t,`receivedAt`);if(!Number.isFinite(Date.parse(r)))throw Error(`Invalid notification receive time`);let i=Pn(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:Nn(t,`id`),message:n,truncated:A(t,`truncated`),severity:On(t.severity),receivedAt:r,order:i}}function En(e){let t=E(e);return{order:Pn(t,`order`),overflowWatermark:Pn(t,`overflowWatermark`)}}function Dn(e){let t=E(e);switch(t.kind){case`added`:{let e=O(t,`evictedNotificationId`);return{kind:`added`,notification:Tn(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=jn(t.notificationIds,Mn,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:An(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function On(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function kn(e){return e===void 0?void 0:On(e)}function An(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 jn(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 Mn(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function Nn(e,t){let n=D(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function Pn(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 Fn(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 In(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 Ln(e){return e.retainedCount===0&&e.discardedCount===0}function Rn(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function zn(e){let t=E(e),n=t.skippedBusySessionIds===void 0?void 0:Yt(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:D(t,`generatedAt`),thresholds:Wn(t.thresholds),projects:j(Gn)(t.projects),totals:Kn(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function Bn(e){let t=E(e);return{...zn(t),archivedSessionIds:Yt(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:Yt(t.deletedSessionIds,`deletedSessionIds`)}}function Vn(e){let t=E(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:Yt(t.archivedSessionIds,`archivedSessionIds`),failures:j(Un)(t.failures),generatedAt:D(t,`generatedAt`)}}function Hn(e){let t=E(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:Yt(t.deletedSessionIds,`deletedSessionIds`),failures:j(Un)(t.failures),generatedAt:D(t,`generatedAt`)}}function Un(e){let t=E(e);return{sessionId:D(t,`sessionId`),error:D(t,`error`)}}function Wn(e){let t=E(e);return{...N(`archiveIdleDays`,M(t,`archiveIdleDays`)),...N(`deleteArchivedDays`,M(t,`deleteArchivedDays`))}}function Gn(e){let t=E(e);return{cwd:D(t,`cwd`),archiveCount:k(t,`archiveCount`),deleteCount:k(t,`deleteCount`)}}function Kn(e){let t=E(e);return{archiveCount:k(t,`archiveCount`),deleteCount:k(t,`deleteCount`)}}function qn(e){let t=E(e),n=D(t,`kind`);if(n!==`steer`&&n!==`followUp`)throw Error(`Invalid queued message kind`);return{kind:n,text:D(t,`text`)}}function Jn(e){let t=E(e);return{input:k(t,`input`),output:k(t,`output`),cacheRead:k(t,`cacheRead`),cacheWrite:k(t,`cacheWrite`),total:k(t,`total`)}}function Yn(e){let t=E(e);return{...N(`provider`,O(t,`provider`)),...N(`id`,O(t,`id`)),...N(`name`,O(t,`name`)),...N(`contextWindow`,M(t,`contextWindow`)),...N(`reasoning`,t.reasoning)}}function Xn(e){return e===void 0?{}:{model:Yn(e)}}function Zn(e){let t=E(e);return{models:j(Yn)(t.models)}}function Qn(e){let t=E(e);return{...t.model===void 0?{}:{model:Yn(t.model)},thinkingLevel:D(t,`thinkingLevel`),models:j(Yn)(t.models),thinkingLevels:Yt(t.thinkingLevels,`thinkingLevels`)}}function $n(e){let t=nr(e,`models configuration`),n=t.providers;if(n===void 0)return{...t,providers:{}};let r=nr(n,`models configuration providers`),i={};for(let[e,t]of Object.entries(r))i[e]=er(t);return{...t,providers:i}}function er(e){let t=nr(e,`models configuration provider`),n={};for(let[e,r]of Object.entries(t))n[e]=r;let r=O(t,`baseUrl`);r!==void 0&&(n.baseUrl=r);let i=O(t,`api`);i!==void 0&&(n.api=i);let a=O(t,`apiKey`);a!==void 0&&(n.apiKey=a);let o=rr(t.headers,`models configuration provider headers`);o!==void 0&&(n.headers=ir(o,`models configuration provider headers`));let s=rr(t.compat,`models configuration provider compatibility`);s!==void 0&&(n.compat={...s});let c=rr(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(tr)}return n}function tr(e){let t=nr(e,`models configuration model`),n={id:D(t,`id`)};for(let[e,r]of Object.entries(t))n[e]=r;n.id=D(t,`id`);let r=O(t,`name`);r!==void 0&&(n.name=r);let i=O(t,`api`);i!==void 0&&(n.api=i);let a=_a(t,`reasoning`);a!==void 0&&(n.reasoning=a);let o=rr(t.thinkingLevelMap,`models configuration thinking level map`);o!==void 0&&(n.thinkingLevelMap=ar(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=M(t,`contextWindow`);c!==void 0&&(n.contextWindow=c);let l=M(t,`maxTokens`);l!==void 0&&(n.maxTokens=l);let u=rr(t.cost,`models configuration model cost`);u!==void 0&&(n.cost=or(u));let d=rr(t.compat,`models configuration model compatibility`);return d!==void 0&&(n.compat={...d}),n}function nr(e,t){if(!qt(e)||Array.isArray(e))throw Error(`Expected ${t} object`);return e}function rr(e,t){if(e!==void 0)return nr(e,t)}function ir(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 ar(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 or(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 sr(e){if(E(e).success!==!0)throw Error(`Expected successful models configuration save`);return{success:!0}}function cr(e){let t=E(e);return{models:j(lr)(t.models)}}function lr(e){let t=E(e),n=D(t,`id`),r=O(t,`name`);return r===void 0?{id:n}:{id:n,name:r}}function ur(e){let t=E(e),n=A(t,`ok`),r=O(t,`error`),i=t.latencyMs===void 0?void 0:k(t,`latencyMs`),a=t.status===void 0?void 0:k(t,`status`),o=O(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 dr(e){let t=E(e);return{skills:j(fr)(t.skills)}}function fr(e){let t=E(e),n=E(t.sourceInfo),r=O(n,`source`),i=O(n,`scope`);return{name:D(t,`name`),description:D(t,`description`),filePath:D(t,`filePath`),baseDir:D(t,`baseDir`),disableModelInvocation:A(t,`disableModelInvocation`),sourceInfo:{...r===void 0?{}:{source:r},...i===void 0?{}:{scope:i}},...t.install===void 0?{}:{install:pr(t.install)}}}function pr(e){let t=E(e),n=O(t,`sourceType`),r=O(t,`skillsShUrl`),i=O(t,`skillPath`),a=O(t,`ref`),o=O(t,`versionHash`);return{package:D(t,`package`),scope:mr(t.scope),source:D(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:A(t,`canCheckForUpdates`)}}function mr(e){if(e!==`global`&&e!==`project`)throw Error(`Expected skill install scope`);return e}function hr(e){if(E(e).success!==!0)throw Error(`Expected successful Skills mutation`);return{success:!0}}function gr(e){let t=E(e);return{results:j(_r)(t.results)}}function _r(e){let t=E(e);return{package:D(t,`package`),installs:D(t,`installs`),url:D(t,`url`)}}function vr(e){let t=E(e);return{updates:j(yr)(t.updates)}}function yr(e){let t=E(e),n=O(t,`currentVersion`),r=O(t,`latestVersion`),i=O(t,`message`);return{package:D(t,`package`),scope:mr(t.scope),state:br(t.state),...n===void 0?{}:{currentVersion:n},...r===void 0?{}:{latestVersion:r},...i===void 0?{}:{message:i}}}function br(e){if(e!==`up-to-date`&&e!==`update-available`&&e!==`unsupported`&&e!==`error`)throw Error(`Expected skill update state`);return e}function xr(e){let t=E(e);if(t.success!==!0)throw Error(`Expected successful Skills update`);let n=O(t,`output`);return{success:!0,...t.skill===void 0?{}:{skill:fr(t.skill)},...n===void 0?{}:{output:n}}}function Sr(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function Cr(e){let t=E(e);return{levels:j(Sr)(t.levels)}}function wr(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function Tr(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 Er(e){let t=E(e),n=t.source===void 0?void 0:Tr(t.source);return{configured:A(t,`configured`),...N(`source`,n),...N(`label`,O(t,`label`))}}function Dr(e){let t=E(e),n=t.loginFlow;if(n!==void 0&&n!==`interactive`)throw Error(`Invalid auth provider login flow`);return{id:D(t,`id`),name:D(t,`name`),authType:wr(t.authType),status:Er(t.status),...n===void 0?{}:{loginFlow:n}}}function Or(e){let t=E(e);return{providers:j(Dr)(t.providers)}}function kr(e){let t=E(e);return{flowId:D(t,`flowId`),providerId:D(t,`providerId`),providerName:D(t,`providerName`),status:Ar(t.status),progress:j(e=>{if(typeof e!=`string`)throw Error(`Expected progress item string`);return e})(t.progress),...N(`error`,O(t,`error`)),...N(`auth`,jr(t.auth)),...N(`prompt`,Nr(t.prompt)),...N(`select`,Fr(t.select)),...N(`info`,Ir(t.info))}}function Ar(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function jr(e){if(e===void 0)return;let t=E(e);return{url:D(t,`url`),...N(`instructions`,O(t,`instructions`)),...N(`deviceCode`,Mr(t.deviceCode))}}function Mr(e){if(e===void 0)return;let t=E(e);return{userCode:D(t,`userCode`),...N(`intervalSeconds`,M(t,`intervalSeconds`)),...N(`expiresInSeconds`,M(t,`expiresInSeconds`))}}function Nr(e){if(e===void 0)return;let t=E(e),n=D(t,`kind`);if(n!==`prompt`&&n!==`manual`)throw Error(`Invalid OAuth prompt kind`);let r=t.promptType===void 0?n===`manual`?`manual_code`:`text`:Pr(t.promptType);return{requestId:D(t,`requestId`),message:D(t,`message`),kind:n,promptType:r,...N(`placeholder`,O(t,`placeholder`)),...N(`allowEmpty`,_a(t,`allowEmpty`))}}function Pr(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function Fr(e){if(e===void 0)return;let t=E(e);return{requestId:D(t,`requestId`),message:D(t,`message`),options:j(ia)(t.options)}}function Ir(e){if(e!==void 0)return j(e=>{let t=E(e);return{message:D(t,`message`),...N(`links`,t.links===void 0?void 0:j(Lr)(t.links))}})(e)}function Lr(e){let t=E(e);return{url:D(t,`url`),...N(`label`,O(t,`label`))}}function Rr(e){if(e===void 0)return{};let t=E(e);return{generation:{outputTokens:k(t,`outputTokens`),...N(`tokensPerSecond`,M(t,`tokensPerSecond`)),...N(`estimated`,_a(t,`estimated`))}}}function zr(e){if(e===void 0)return{};let t=E(e);return{contextUsage:{tokens:va(t,`tokens`),contextWindow:k(t,`contextWindow`),percent:va(t,`percent`)}}}function Br(e){let t=E(e),n=D(t,`source`);if(n!==`extension`&&n!==`prompt`&&n!==`skill`&&n!==`builtin`)throw Error(`Invalid command source`);return{name:D(t,`name`),source:n,...N(`description`,O(t,`description`))}}function Vr(e){let t=E(e),n=D(t,`kind`);if(n!==`tracked`&&n!==`untracked`&&n!==`other`)throw Error(`Invalid file kind`);return{path:D(t,`path`),kind:n}}function Hr(e){let t=E(e);return{path:D(t,`path`),entries:j(Ur)(t.entries),scannedAt:D(t,`scannedAt`),truncated:A(t,`truncated`)}}function Ur(e){let t=E(e),n=D(t,`type`);if(n!==`file`&&n!==`directory`&&n!==`symlink`)throw Error(`Invalid file tree entry type`);return{name:D(t,`name`),path:D(t,`path`),type:n,...N(`size`,M(t,`size`)),...N(`modifiedAt`,O(t,`modifiedAt`))}}function Wr(e){let t=E(e),n=D(t,`encoding`);if(n!==`utf8`)throw Error(`Invalid file encoding`);return{path:D(t,`path`),...N(`language`,O(t,`language`)),...N(`mediaType`,Jr(t.mediaType)),...N(`mimeType`,O(t,`mimeType`)),encoding:n,size:k(t,`size`),modifiedAt:D(t,`modifiedAt`),content:D(t,`content`),truncated:A(t,`truncated`),binary:A(t,`binary`)}}function Gr(e){let t=E(e);return{path:D(t,`path`),size:k(t,`size`),modifiedAt:D(t,`modifiedAt`),created:A(t,`created`)}}function Kr(e){let t=E(e);return{path:D(t,`path`),existed:A(t,`existed`)}}function qr(e){let t=E(e);return{fromPath:D(t,`fromPath`),toPath:D(t,`toPath`),size:k(t,`size`),modifiedAt:D(t,`modifiedAt`)}}function Jr(e){if(e!==void 0){if(e!==`image`)throw Error(`Invalid file media type`);return e}}function Yr(e){let t=E(e);return{isGitRepo:A(t,`isGitRepo`),hash:D(t,`hash`),...N(`branch`,O(t,`branch`)),...N(`latestTag`,O(t,`latestTag`)),...N(`upstream`,O(t,`upstream`)),...N(`ahead`,M(t,`ahead`)),...N(`behind`,M(t,`behind`)),files:j(Xr)(t.files)}}function Xr(e){let t=E(e);return{path:D(t,`path`),...N(`oldPath`,O(t,`oldPath`)),index:Zr(t.index),workingTree:Zr(t.workingTree)}}function Zr(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 Qr(e){let t=E(e);return{...N(`path`,O(t,`path`)),staged:A(t,`staged`),hash:D(t,`hash`),diff:D(t,`diff`),truncated:A(t,`truncated`)}}function $r(e){let t=E(e);return{id:D(t,`id`),cwd:D(t,`cwd`),name:D(t,`name`),createdAt:D(t,`createdAt`),exited:A(t,`exited`),...N(`exitCode`,M(t,`exitCode`)),...N(`commandRunId`,O(t,`commandRunId`))}}function ei(e){let t=E(e);return{id:D(t,`id`),origin:D(t,`origin`),projectId:D(t,`projectId`),workspaceId:D(t,`workspaceId`),terminalId:D(t,`terminalId`),title:D(t,`title`),command:D(t,`command`),status:ti(t.status),...N(`exitCode`,M(t,`exitCode`)),createdAt:D(t,`createdAt`),...N(`startedAt`,O(t,`startedAt`)),...N(`completedAt`,O(t,`completedAt`)),metadata:ni(t.metadata,`metadata`)}}function ti(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function ni(e,t){let n=E(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 ri(e){let t=E(e);return{cwd:D(t,`cwd`),hasSessionActivity:A(t,`hasSessionActivity`),hasTerminalActivity:A(t,`hasTerminalActivity`),updatedAt:D(t,`updatedAt`)}}function ii(e){let t=E(e);return{workspaces:j(ri)(t.workspaces),generatedAt:D(t,`generatedAt`)}}function ai(e){let t=E(e);return{path:D(t,`path`),exists:A(t,`exists`),config:oi(t.config),effectiveConfig:oi(t.effectiveConfig),envOverrides:gi(t.envOverrides)}}function oi(e){let t=E(e);return{...N(`host`,O(t,`host`)),...N(`port`,M(t,`port`)),...N(`allowedHosts`,ci(t.allowedHosts)),...N(`shortcuts`,mi(t.shortcuts)),...N(`plugins`,hi(t.plugins)),...N(`pathAccess`,li(t.pathAccess)),...N(`uploads`,di(t.uploads)),...N(`maxUploadBytes`,M(t,`maxUploadBytes`)),...N(`agent`,si(t.agent)),...N(`spawnSessions`,_a(t,`spawnSessions`)),...N(`subsessions`,_a(t,`subsessions`))}}function si(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI agent field`);return{...N(`command`,O(e,`command`)),...N(`dir`,O(e,`dir`))}}}function ci(e){if(e!==void 0){if(e===!0)return!0;if(fi(e))return e;throw Error(`Invalid PI WEBUI allowedHosts field`)}}function li(e){if(e===void 0)return;if(!qt(e))throw Error(`Invalid PI WEBUI pathAccess field`);let t=e.allowedPaths;return{...N(`allowedPaths`,ui(t,`pathAccess.allowedPaths`))}}function ui(e,t){if(e!==void 0){if(pi(e))return e;throw Error(`Invalid PI WEBUI ${t} field`)}}function di(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI uploads field`);return{...N(`defaultFolder`,O(e,`defaultFolder`))}}}function fi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function pi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function mi(e){if(e!==void 0){if(!qt(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 hi(e){if(e!==void 0){if(!qt(e)||Array.isArray(e))throw Error(`Invalid PI WEBUI plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!qt(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&&(!qt(r)||Array.isArray(r)))throw Error(`Invalid PI WEBUI plugin settings field`);return[e,t]}))}}function gi(e){let t=E(e);return{host:A(t,`host`),port:A(t,`port`),allowedHosts:A(t,`allowedHosts`),spawnSessions:A(t,`spawnSessions`),subsessions:A(t,`subsessions`),agentCommand:_a(t,`agentCommand`)??!1,agentDir:_a(t,`agentDir`)??!1,..._i(t),agentSessionDir:_a(t,`agentSessionDir`)??!1}}function _i(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 vi(e){let t=E(e);return{packages:j(bi)(t.packages)}}function yi(e){let t=E(e),n=O(t,`source`),r=t.scope===void 0?void 0:xi(t.scope),i=Pi(t.removed,`removed`);return{action:Si(t.action),...N(`source`,n),...N(`scope`,r),...N(`removed`,i),packages:j(bi)(t.packages)}}function bi(e){let t=E(e);return{source:D(t,`source`),scope:xi(t.scope),filtered:A(t,`filtered`),...N(`installedPath`,O(t,`installedPath`))}}function xi(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function Si(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function Ci(e){let t=E(e);return{packages:j(wi)(t.packages),totals:Di(t.totals),diagnostics:j(Ai)(t.diagnostics)}}function wi(e){let t=E(e);return{source:D(t,`source`),scope:Ti(t.scope),filtered:A(t,`filtered`),disabled:A(t,`disabled`),...N(`installedPath`,O(t,`installedPath`)),...N(`packageName`,O(t,`packageName`)),...N(`version`,O(t,`version`)),...N(`configuredVersion`,O(t,`configuredVersion`)),counts:Di(t.counts),resources:j(Oi)(t.resources),status:Ei(t.status)}}function Ti(e){if(e!==`global`&&e!==`project`)throw Error(`Invalid Pi package plugin scope`);return e}function Ei(e){if(e!==`loaded`&&e!==`installed`&&e!==`missing`&&e!==`disabled`)throw Error(`Invalid Pi package plugin status`);return e}function Di(e){let t=E(e);return{extensions:k(t,`extensions`),skills:k(t,`skills`),prompts:k(t,`prompts`),themes:k(t,`themes`)}}function Oi(e){let t=E(e);return{kind:ki(t.kind),name:D(t,`name`),path:D(t,`path`),relativePath:D(t,`relativePath`)}}function ki(e){if(e!==`extension`&&e!==`skill`&&e!==`prompt`&&e!==`theme`)throw Error(`Invalid Pi package plugin resource kind`);return e}function Ai(e){let t=E(e),n=t.type;if(n!==`warning`&&n!==`error`)throw Error(`Invalid Pi package plugin diagnostic type`);return{type:n,message:D(t,`message`),...N(`source`,O(t,`source`)),...N(`path`,O(t,`path`))}}function ji(e){let t=E(e);return{plugins:j(Mi)(t.plugins)}}function Mi(e){let t=E(e);return{id:D(t,`id`),module:D(t,`module`),source:D(t,`source`),scope:Ni(t.scope),machineSpecific:Pi(t.machineSpecific,`machineSpecific`)??!1,enabled:A(t,`enabled`)}}function Ni(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEBUI plugin scope`);return e}function Pi(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function Fi(e){let t=E(e);return{packageName:D(t,`packageName`),generatedAt:D(t,`generatedAt`),components:Li(t.components),release:Hi(t.release),commands:Ui(t.commands),messages:j(Wi)(t.messages)}}function Ii(e){let t=E(e);return{packageName:D(t,`packageName`),generatedAt:D(t,`generatedAt`),components:Ri(t.components),capabilities:Ki(t.capabilities)}}function Li(e){let t=E(e);return{web:Bi(t.web),sessiond:Bi(t.sessiond)}}function Ri(e){let t=E(e);return{web:zi(t.web),sessiond:zi(t.sessiond)}}function zi(e){let t=E(e),n=Gi(t.component),r=t.activeAgentProfile,i=r===void 0?void 0:It(r);if(r!==void 0&&(n!==`sessiond`||i===void 0))throw Error(`Invalid active agent profile descriptor`);return{component:n,label:D(t,`label`),...N(`runtimeVersion`,O(t,`runtimeVersion`)),available:A(t,`available`),capabilities:Ki(t.capabilities),...N(`activeAgentProfile`,i),...N(`error`,O(t,`error`))}}function Bi(e){let t=E(e);return{component:Gi(t.component),label:D(t,`label`),...N(`runtimeVersion`,O(t,`runtimeVersion`)),...N(`installedVersion`,O(t,`installedVersion`)),stale:A(t,`stale`),available:A(t,`available`),...N(`installation`,Vi(t.installation)),...N(`error`,O(t,`error`))}}function Vi(e){if(e===void 0)return;let t=E(e),n=D(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,...N(`path`,O(t,`path`)),...N(`source`,O(t,`source`)),...r===void 0?{}:{scope:r},...N(`npmRoot`,O(t,`npmRoot`)),...i===void 0?{}:{dockerMode:i}}}function Hi(e){let t=E(e);return{packageName:D(t,`packageName`),...N(`latestVersion`,O(t,`latestVersion`)),updateAvailable:A(t,`updateAvailable`),...N(`checkedAt`,O(t,`checkedAt`)),...t.skipped===!0?{skipped:!0}:{},...N(`error`,O(t,`error`))}}function Ui(e){let t=E(e);return{...N(`update`,O(t,`update`)),...N(`restart`,O(t,`restart`)),...N(`restartWeb`,O(t,`restartWeb`)),...N(`restartSessiond`,O(t,`restartSessiond`)),...N(`status`,O(t,`status`))}}function Wi(e){let t=E(e);return{id:D(t,`id`),severity:qi(t.severity),title:D(t,`title`),body:D(t,`body`),...N(`command`,O(t,`command`))}}function Gi(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEBUI service component`);return e}function Ki(e){let t=Kt(e);if(t===void 0)throw Error(`Invalid PI WEBUI capabilities`);return t}function qi(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEBUI status severity`);return e}function Ji(e){let t=E(e),n=D(t,`type`);if(n===`unsupported`)return{type:n,message:D(t,`message`)};if(n===`select`)return{type:n,requestId:D(t,`requestId`),title:D(t,`title`),options:j(ia)(t.options)};if(n===`tree`)return{type:n,tree:Yi(t.tree)};if(n===`done`)return{type:n,...N(`message`,O(t,`message`)),...aa(t.session),...N(`promptDraft`,O(t,`promptDraft`))};throw Error(`Invalid command result type`)}function Yi(e){let t=E(e),n=j(Xi)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=ta(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:ra(t.activePathIds,`activePathIds`)}}function Xi(e){let t=E(e);return{id:na(t,`id`),parentId:ta(t,`parentId`),kind:Zi(t.kind),summary:D(t,`summary`),...N(`timestamp`,O(t,`timestamp`)),...N(`label`,O(t,`label`))}}function Zi(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 Qi(e){let t=E(e),n=A(t,`cancelled`);if(Object.hasOwn(t,`summaryEntry`))throw Error(`Invalid session tree navigation result field: summaryEntry`);if(n){ea(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 ea(t,`aborted`,`session tree navigation result`),{cancelled:n,...N(`editorText`,O(t,`editorText`))}}function $i(e){let t=E(e);return A(t,`cancelled`)?(ea(t,`session`,`session fork cancellation result`),{cancelled:!0}):{cancelled:!1,session:sn(t.session)}}function ea(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function ta(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 na(e,t){let n=D(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function ra(e,t){let n=Yt(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function ia(e){let t=E(e);return{value:D(t,`value`),label:D(t,`label`),...N(`description`,O(t,`description`))}}function aa(e){return e===void 0?{}:{session:sn(e)}}function oa(e){if(E(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function sa(e){let t=E(e);return j(ca)(t.attachments)}function ca(e){let t=E(e);return{path:D(t,`path`),mimeType:D(t,`mimeType`),size:k(t,`size`)}}function la(e){if(E(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function ua(e){if(E(e).aborted!==!0)throw Error(`Expected aborted response`);return{aborted:!0}}function da(e){if(E(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function fa(e){let t=E(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:Yt(t.sessionIds,`sessionIds`),r=M(t,`archivedCount`),i=M(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function pa(e){if(E(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function ma(e){if(E(e).deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0}}function ha(e){if(E(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function ga(e){if(E(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function _a(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEBUI ${t} field`);return n}}function M(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function va(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 N(e,t){return t===void 0?{}:{[e]:t}}function ya(e){let t=E(e),n=E(t.memory),r=E(t.network);return{generatedAt:D(t,`generatedAt`),memory:{totalBytes:k(n,`totalBytes`),usedBytes:k(n,`usedBytes`),freeBytes:k(n,`freeBytes`),usagePercent:k(n,`usagePercent`)},network:Sa(r)}}function ba(e){let t=E(e),n=E(t.os),r=E(t.cpu),i=E(t.memory),a=E(t.network),o=t.gpu,s;if(o!=null){let e=E(o),t={name:D(e,`name`)},n=O(e,`driverVersion`);n!==void 0&&(t.driverVersion=n);let r=M(e,`memoryTotalBytes`);r!==void 0&&(t.memoryTotalBytes=r);let i=M(e,`memoryUsedBytes`);i!==void 0&&(t.memoryUsedBytes=i);let a=M(e,`utilizationPercent`);a!==void 0&&(t.utilizationPercent=a);let c=M(e,`temperatureCelsius`);c!==void 0&&(t.temperatureCelsius=c),s=t}let c={generatedAt:D(t,`generatedAt`),os:{platform:D(n,`platform`),release:D(n,`release`),arch:D(n,`arch`),uptimeSeconds:k(n,`uptimeSeconds`)},cpu:{model:D(r,`model`),cores:k(r,`cores`),usagePercent:k(r,`usagePercent`)},memory:{totalBytes:k(i,`totalBytes`),usedBytes:k(i,`usedBytes`),freeBytes:k(i,`freeBytes`),usagePercent:k(i,`usagePercent`)},network:xa(a)};s!==void 0&&(c.gpu=s);let l=O(t,`piVersion`);l!==void 0&&(c.piVersion=l);let u=O(t,`piWebUiVersion`);return u!==void 0&&(c.piWebUiVersion=u),c}function xa(e){let t={hostname:D(e,`hostname`),localIpv4Addresses:Yt(e.localIpv4Addresses,`localIpv4Addresses`),...Sa(e)},n=O(e,`publicIpv4`);n!==void 0&&(t.publicIpv4=n);let r=O(e,`publicIpv6`);return r!==void 0&&(t.publicIpv6=r),t}function Sa(e){let t={},n=M(e,`downloadSpeedBytesPerSecond`);n!==void 0&&(t.downloadSpeedBytesPerSecond=n);let r=M(e,`uploadSpeedBytesPerSecond`);return r!==void 0&&(t.uploadSpeedBytesPerSecond=r),t}function Ca(e){return typeof e==`string`?e:e.id}function wa(e){return typeof e==`string`?void 0:e.cwd}function Ta(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 Ea(e,t,n=`local`){let r=new URLSearchParams,i=wa(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(Ca(e))}/messages${a===``?``:`?${a}`}`}function Da(e,t=`local`){let n=new URLSearchParams,r=wa(e);r!==void 0&&r!==``&&n.set(`cwd`,r);let i=n.toString();return`api/machines/${encodeURIComponent(t)}/sessions/${encodeURIComponent(Ca(e))}/export${i===``?``:`?${i}`}`}function Oa(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`),bt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`)}function ka(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),bt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`)}var P=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`;function Aa(e){return typeof e==`string`?e:e.id}function ja(e){return typeof e==`string`?void 0:e.cwd}function Ma(e,t=`local`){return`${P(t)}/sessions/${encodeURIComponent(Aa(e))}`}function F(e,t,n=`local`){return`${Ma(e,n)}/${t}`}function Na(e,t,n=`local`){return`${F(e,t,n)}${Fa(e)}`}function Pa(e,t=`local`){return`${Ma(e,t)}${Fa(e)}`}function Fa(e){let t=ja(e);return t===void 0||t===``?``:`?${new URLSearchParams({cwd:t}).toString()}`}function I(e,t={}){let n=ja(e);return JSON.stringify(n===void 0||n===``?t:{cwd:n,...t})}function Ia(e){return JSON.stringify({sessions:e.map(La)})}function La(e){let t=Aa(e),n=ja(e);return n===void 0||n===``?{id:t}:{id:t,cwd:n}}function Ra(e){return e===`local`?`api/pi-webui/status`:`${P(e)}/pi-webui/status`}var za={piWebUiStatus:(e=`local`)=>w(Ra(e),Fi),checkForUpdates:(e=`local`)=>w(`${Ra(e)}?refresh=1`,Fi,{cache:`no-store`}),piWebUiRuntime:()=>w(`api/pi-webui/runtime`,Ii),systemInfo:(e=`local`)=>w(`${P(e)}/pi-webui/system-info`,ba),systemMetrics:(e=`local`)=>w(`${P(e)}/pi-webui/system-metrics`,ya,{cache:`no-store`})},Ba={machines:()=>w(`api/machines`,Zt),addMachine:e=>w(`api/machines`,Qt,{method:`POST`,body:JSON.stringify(e)}),deleteMachine:e=>w(`api/machines/${encodeURIComponent(e)}`,e=>e,{method:`DELETE`}),health:e=>w(`api/machines/${encodeURIComponent(e)}/health`,$t),runtime:(e,t=!1)=>w(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,en,t?{cache:`no-store`}:{})};function Va(e){return e===void 0?`api/config`:`${P(e)}/config`}function Ha(e){return e===void 0?`api/plugins`:`${P(e)}/plugins`}var Ua={config:e=>w(Va(e),ai),saveConfig:(e,t)=>w(Va(t),ai,{method:`PUT`,body:JSON.stringify({config:e})})},Wa={plugins:e=>w(Ha(e),ji)};function Ga(e=`local`){return`${P(e)}/models-config`}var Ka={config:(e=`local`)=>w(Ga(e),$n),save:(e,t=`local`)=>w(Ga(t),sr,{method:`PUT`,body:JSON.stringify(e)}),test:(e,t=`local`)=>w(`${Ga(t)}/test`,ur,{method:`POST`,body:JSON.stringify(e)}),discover:(e,t=`local`)=>w(`${Ga(t)}/discover`,cr,{method:`POST`,body:JSON.stringify(e)})};function qa(e=`local`){return`${P(e)}/skills`}function Ja(e,t=`local`){return`${qa(t)}?${new URLSearchParams({cwd:e}).toString()}`}var Ya={list:(e,t=`local`)=>w(Ja(e,t),dr),toggle:(e,t=`local`)=>w(qa(t),hr,{method:`PATCH`,body:JSON.stringify(e)}),search:(e,t=`local`)=>w(`${qa(t)}/search`,gr,{method:`POST`,body:JSON.stringify(e)}),install:(e,t=`local`)=>w(`${qa(t)}/install`,hr,{method:`POST`,body:JSON.stringify(e)}),check:(e,t=`local`)=>w(`${qa(t)}/check`,vr,{method:`POST`,body:JSON.stringify(e)}),update:(e,t=`local`)=>w(`${qa(t)}/update`,xr,{method:`POST`,body:JSON.stringify(e)})};function Xa(e=``,t){let n=t===void 0?`api/pi-packages`:`${P(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var Za={packages:e=>w(Xa(``,e),vi),install:(e,t)=>{let n={source:e};return w(Xa(`install`,t),yi,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return w(Xa(`remove`,n),yi,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return w(Xa(`update`,t),yi,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}};function Qa(e=`local`){return`${P(e)}/package-plugins`}function $a(e,t=`local`){return`${Qa(t)}?${new URLSearchParams({cwd:e}).toString()}`}var eo={list:(e,t=`local`)=>w($a(e,t),Ci),mutate:(e,t=`local`)=>w(Qa(t),Ci,{method:`POST`,body:JSON.stringify(e)})},to={workspaceActivity:(e=`local`)=>w(`${P(e)}/activity`,ii)},no={projects:(e=`local`)=>w(`${P(e)}/projects`,j(rn)),addProject:(e,t,n,r=`local`)=>w(`${P(r)}/projects`,rn,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>w(`${P(t)}/projects/${encodeURIComponent(e)}`,la,{method:`DELETE`}),projectDirectories:(e,t=`local`)=>w(`${P(t)}/project-directories?q=${encodeURIComponent(e)}`,j(Vr))},ro={workspaces:(e,t=`local`)=>w(`${P(t)}/projects/${encodeURIComponent(e)}/workspaces`,j(an)),deleteWorkspace:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,ei,{method:`DELETE`}),workspaceTree:(e,t,n=``,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,Hr),workspaceFile:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,Wr),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 w(`${P(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,Gr,{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 w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`,Kr,{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`),w(`${P(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${o.toString()}`,qr,{method:`POST`})}},io={sessions:(e,t=`local`)=>w(`${P(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(sn)),unreadCatalog:(e=`local`)=>w(`${P(e)}/sessions/unread`,hn,{cache:`no-store`}),acknowledgeUnread:(e,t,n,r=`local`)=>{let i={cwd:e.cwd,catalogId:t,throughCompletionOrder:n};return w(F(e,`unread/acknowledge`,r),hn,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>w(Na(e,`notifications`,t),Sn),dismissNotification:(e,t,n,r=`local`)=>w(F(e,`notifications/dismiss`,r),Sn,{method:`POST`,body:I(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>w(F(e,`notifications/dismiss-all`,r),Sn,{method:`POST`,body:I(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`)=>w(`${P(t)}/sessions`,sn,{method:`POST`,body:JSON.stringify({cwd:e})}),sessionDefaults:(e,t=`local`)=>w(`${P(t)}/session-defaults?cwd=${encodeURIComponent(e)}`,Qn),updateSessionDefaults:(e,t,n=`local`)=>w(`${P(n)}/session-defaults`,Qn,{method:`PUT`,body:JSON.stringify({cwd:e,...t})}),cleanupPreview:(e,t=`local`)=>w(`${P(t)}/sessions/cleanup/preview`,zn,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>w(`${P(t)}/sessions/cleanup`,Bn,{method:`POST`,body:JSON.stringify(e)}),forceCleanup:(e=`local`)=>w(`${P(e)}/sessions/cleanup/force`,Bn,{method:`POST`}),archiveMany:(e,t=`local`)=>w(`${P(t)}/sessions/bulk/archive`,Vn,{method:`POST`,body:Ia(e)}),deleteArchivedMany:(e,t=`local`)=>w(`${P(t)}/sessions/bulk/delete-archived`,Hn,{method:`POST`,body:Ia(e)}),messages:(e,t,n=`local`)=>w(Ea(e,t,n),Xt),status:(e,t=`local`)=>w(Na(e,`status`,t),fn),systemPrompt:(e,t=`local`)=>w(Na(e,`system-prompt`,t),mn),streamSnapshot:(e,t=`local`)=>w(Na(e,`stream-snapshot`,t),pn),clearQueue:(e,t=`local`)=>w(F(e,`queue/clear`,t),fn,{method:`POST`,body:I(e)}),dismissWarning:(e,t,n=`local`)=>w(F(e,`warnings/dismiss`,n),fn,{method:`POST`,body:I(e,{dismissId:t})}),models:(e,t=`local`)=>w(Na(e,`models`,t),Zn),setModel:(e,t,n,r=`local`)=>w(F(e,`model`,r),fn,{method:`POST`,body:I(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>w(F(e,`model/cycle`,n),fn,{method:`POST`,body:I(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>w(Na(e,`thinking-levels`,t),Cr),setThinkingLevel:(e,t,n=`local`)=>w(F(e,`thinking-level`,n),fn,{method:`POST`,body:I(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>w(F(e,`thinking-level/cycle`,t),fn,{method:`POST`,body:I(e)}),commands:(e,t=`local`)=>w(Na(e,`commands`,t),j(Br)),prompt:(e,t,n,r=`local`,i)=>w(F(e,`prompt`,r),oa,{method:`POST`,body:I(e,{text:t,...n===void 0?{}:{streamingBehavior:n},...i!==void 0&&i.length>0?{attachments:i}:{}})}),saveAttachments:(e,t,n=`local`,r)=>w(F(e,`attachments`,n),sa,{method:`POST`,body:I(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>w(F(e,`shell`,n),oa,{method:`POST`,body:I(e,{text:t})}),runCommand:(e,t,n=`local`)=>w(F(e,`commands/run`,n),Ji,{method:`POST`,body:I(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>w(F(e,`commands/respond`,r),Ji,{method:`POST`,body:I(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>w(F(e,`tree/navigate`,n),Qi,{method:`POST`,body:I(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary})}),editFromHere:(e,t,n=`local`)=>w(F(e,`messages/edit-from-here`,n),Qi,{method:`POST`,body:I(e,{entryId:t})}),forkFromHere:(e,t,n=`local`)=>w(F(e,`messages/fork`,n),$i,{method:`POST`,body:I(e,{entryId:t})}),abort:(e,t=`local`)=>w(F(e,`abort`,t),ua,{method:`POST`,body:I(e)}),stop:(e,t=`local`)=>w(F(e,`stop`,t),da,{method:`POST`,body:I(e)}),archive:(e,t=`local`)=>w(F(e,`archive`,t),fa,{method:`POST`,body:I(e)}),archiveWithDescendants:(e,t=`local`)=>w(F(e,`archive-tree`,t),fa,{method:`POST`,body:I(e)}),restore:(e,t=`local`)=>w(F(e,`restore`,t),pa,{method:`POST`,body:I(e)}),deleteArchived:(e,t=`local`)=>w(Pa(e,t),ma,{method:`DELETE`}),detachParent:(e,t=`local`)=>w(F(e,`detach-parent`,t),ha,{method:`POST`,body:I(e)}),reloadSession:(e,t=`local`)=>w(F(e,`reload`,t),ga,{method:`POST`,body:I(e)}),pin:(e,t=`local`)=>w(F(e,`pin`,t),sn,{method:`POST`,body:I(e)}),unpin:(e,t=`local`)=>w(F(e,`unpin`,t),sn,{method:`POST`,body:I(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 w(`${P(e?.machineId)}/auth/providers${n===``?``:`?${n}`}`,Or)},saveApiKey:(e,t,n=`local`)=>w(`${P(n)}/auth/api-key`,oa,{method:`POST`,body:JSON.stringify({providerId:e,key:t})}),startInteractiveApiKeyLogin:(e,t=`local`)=>w(`${P(t)}/auth/api-key/interactive`,kr,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t=`local`)=>w(`${P(t)}/auth/logout`,oa,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t=`local`)=>w(`${P(t)}/auth/oauth`,kr,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t=`local`)=>w(`${P(t)}/auth/oauth/${encodeURIComponent(e)}`,kr),respondOAuthFlow:(e,t,n,r=`local`)=>w(`${P(r)}/auth/oauth/${encodeURIComponent(e)}/respond`,kr,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t=`local`)=>w(`${P(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,kr,{method:`POST`})},ao={terminals:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j($r)),startTerminal:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,$r,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,la,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,la,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,$r,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,ei,{method:`POST`,body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t=`local`)=>w(`${P(t)}/terminal-command-runs${so(e)}`,j(ei)),getCommandRun:(e,t=`local`)=>oo(e,t),cancelCommandRun:(e,t=`local`)=>w(`${P(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,ei,{method:`POST`})};async function oo(e,t){let n=await fetch(bt(`${P(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(n.status!==404){if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(co(e)??n.statusText)}return ei(await n.json())}}function so(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 co(e){if(!lo(e))return;let t=e.error;return typeof t==`string`?t:void 0}function lo(e){return typeof e==`object`&&!!e}var uo={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?w(`${P(n.machineId)}/projects/${encodeURIComponent(n.projectId)}/workspaces/${encodeURIComponent(n.workspaceId)}/files?${r.toString()}`,j(Vr)):(r.set(`cwd`,e),w(`${P(n.machineId)}/files?${r.toString()}`,j(Vr)))}},fo={gitStatus:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Yr),gitDiff:(e,t,n,r=`local`)=>w(Ta(r,e,t,n),Qr)},L={...za,...Ba,...Ua,...Wa,...Za,...eo,...to,...no,...ro,...io,...ao,...uo,...fo};function po(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(xt(`${go(t)}/sessions/${encodeURIComponent(i)}/events${r}`))}function mo(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(xt(`${go(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function ho(e=`local`){return new WebSocket(xt(`${go(e)}/events`))}function go(e){return`api/machines/${encodeURIComponent(e)}`}var _o=`.pi-webui/uploads`,vo=class extends Error{constructor(e=`Workspace upload cancelled`){super(e),this.name=`WorkspaceUploadCancelledError`}},yo=class extends Error{constructor(e,t){super(Ao(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function bo(e){return e?.uploads?.defaultFolder??`.pi-webui/uploads`}function xo(e,t){return e?.uploads?.defaultFolder??t}function So(e,t){let n=No(e,`upload destination`,{allowEmpty:!0}),r=No(t,`upload file name`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function Co(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`,Oa(e,t,n.path,Eo(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(Do(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(Gr(Fo(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(Io(i)))},i.onerror=()=>{l(Error(`Workspace upload failed`))},i.onabort=()=>{l(new vo(o?void 0:`Workspace upload aborted`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function wo(e,t,n,r={}){let i=r.destinationFolder??`.pi-webui/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:So(i,e.name),loaded:0,total:e.size,percent:ko(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(Oo(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 vo;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=Co(e,t,{path:p.path,file:f},{...To(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(Mo(e,c))throw e;let t=jo(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 yo(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function To(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 Eo(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Do(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:ko(e.loaded,n),lengthComputable:e.lengthComputable}}function Oo(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:ko(i,r),done:n}}function ko(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Ao(e){return e.length===1?e[0]?.error??`Workspace upload failed`:`${String(e.length)} files failed to upload`}function jo(e){return e instanceof Error?e.message:String(e)}function Mo(e,t){return t.requested||e instanceof vo}function No(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(Po(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 Po(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function Fo(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function Io(e){let t=Lo(e);return Ro(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function Lo(e){try{return Fo(e)}catch{return}}function Ro(e){return typeof e==`object`&&!!e}function zo(){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,selectedTerminalId:void 0,error:``}}function Bo(){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:[],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,activeTerminalCount:0,selectedTerminalId:void 0,piWebUiStatus:void 0,error:``}}function Vo(e,t){return t?.phase===`active`||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Ho(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}function Uo(e,t){return`${e}:${t}`}function Wo(e,t){return`${e}:${t}`}function R(e){return e.selectedMachine?.id??`local`}var Go=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}},Ko=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new Go,this.api=n.api??to,this.onActivityApplied=n.onActivityApplied}refresh(e=R(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,qo(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=R(this.getState())){let n=this.getState(),r=R(n)===t,i=Jo(n.machineActivities[t]??(r?n.workspaceActivities:{}),e);this.setState({machineActivities:{...n.machineActivities,[t]:i},...r?{workspaceActivities:i}:{}}),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 qo(e){let t={};for(let n of e.workspaces)Ho(n)&&(t[n.cwd]=n);return t}function Jo(e,t){let n={...e};return Ho(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}var Yo=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??L,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=Zo(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||Xo(n.flow)!==a)return;this.updateOAuthFlow(e,n.machineId)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||Xo(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`?Xo(n.flow):void 0,a=Xo(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=Xo(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||Xo(o.flow)!==a)return;this.updateOAuthFlow(i,t)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o?.machineId!==t||Xo(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 Xo(e){return e.prompt?.requestId??e.select?.requestId}function Zo(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 Qo(e){return e.replaceAll(`:`,`.`)}function $o(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 es(e,t){let n=$o(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function ts(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));ns(i,r)}function ns(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 rs(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:So(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:ls(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:ls(0,n),status:`uploading`,startedAt:e.startedAt}}function is(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 as(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=cs(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function os(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,...cs(r),status:`error`,error:t,completedAt:n}}function ss(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,...cs(r),status:`cancelled`,error:n,completedAt:t}}function cs(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function ls(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var us=Qo(`core:workspace.files`),ds=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??L,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??wo,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:hs(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`}),ts(us,`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(fs(t)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:``}),ts(us,`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=rs({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(ss(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:hs(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(is(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(as(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 yo)||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(ps(t)){let e=ss(n,this.now());return this.setUploadBatch(e),e}let r=ms(t),i=os(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 fs(e){let t=String(e);return t.includes(`Path does not exist`)||t.includes(`ENOENT`)||t.includes(`no such file or directory`)}function ps(e){return e instanceof vo}function ms(e){return e instanceof Error?e.message:String(e)}function hs(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var gs=Qo(`core:workspace.git`),_s=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 L.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}),ts(gs,`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`}),ts(gs,`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([L.gitDiff(n.id,r.id,{path:e},i),L.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}};function vs(e){let t=[],n=[];for(let r of e)ws(r.index)&&t.push(Cs(r,`staged`,r.index)),Ts(r.workingTree)&&n.push(Cs(r,`unstaged`,r.workingTree));return{staged:t,unstaged:n}}function ys(e){let t=vs(e);return new Set([...t.staged,...t.unstaged].map(e=>e.path)).size}function bs(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 xs(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 Ss(e){return e.oldPath===void 0?e.path:`${e.oldPath} → ${e.path}`}function Cs(e,t,n){return{id:`${t}:${e.path}`,path:e.path,...e.oldPath===void 0?{}:{oldPath:e.oldPath},scope:t,state:n}}function ws(e){return e!==`unmodified`&&e!==`untracked`&&e!==`ignored`&&e!==`conflicted`}function Ts(e){return e!==`unmodified`&&e!==`ignored`}var Es=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 L.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));this.setState({machines:t,selectedMachine:n,machineActivities:Os(this.getState().machineActivities,r),machineRuntimes:Os(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,...zo()}),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 L.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 L.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:Ds(this.getState().machineStatuses,e.id),machineRuntimes:Ds(this.getState().machineRuntimes,e.id),machineActivities:Ds(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 L.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 L.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 L.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=>L.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=>L.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 Ds(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Os(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var ks=`~/workspace`,As=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.api=r.api??L,this.onProjectsApplied=r.onProjectsApplied}async loadProjects(){let e=R(this.getState());this.setState({error:``,isLoadingProjects:!0});try{let t=await this.api.projects(e);if(R(this.getState())!==e)return;let n;if(t.length===0){if(n=await this.api.addProject(ks,void 0,!0,e),R(this.getState())!==e)return;t=[n]}let r=new Set(t.map(e=>e.id)),i=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([e])=>r.has(e)));this.setState({projects:t,workspacesByProjectId:i}),this.onProjectsApplied?.(e),n!==void 0&&await this.workspaces.selectProject(n)}catch(t){R(this.getState())===e&&this.setState({error:String(t)})}finally{R(this.getState())===e&&this.setState({isLoadingProjects:!1})}}async addProject(e,t){if(e.trim()===``)return;let n=R(this.getState());try{let r=await this.api.addProject(e.trim(),void 0,t,n);if(R(this.getState())!==n)return;let i=this.getState().projects;this.setState({projects:[...i.filter(e=>e.id!==r.id),r],projectDialogOpen:!1}),this.onProjectsApplied?.(n),await this.workspaces.selectProject(r)}catch(e){R(this.getState())===n&&this.setState({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)})}}};function js(e,t){return t[e.path]}function Ms(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function Ns(e,t,n){return Is(Ls(e,t,n))}function Ps(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function Fs(e){return Is(Object.values(e??{}))}function Is(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function Ls(e,t,n){return Object.values(n).filter(n=>Ps(e,t,n.cwd))}var Rs=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??ro,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])=>!zs(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=await this.api.workspaces(t.id,e.machineId);this.applyProjectWorkspaces(e,t,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&&!zs(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()))}applyProjectWorkspaces(e,t,n){if(this.activePass!==e||!this.isPassScopeCurrent(e))return;let r=this.getState();r.projects.find(e=>e.id===t.id)?.path===t.path&&r.workspacesByProjectId[t.id]===t.startingWorkspaces&&this.setState({workspacesByProjectId:{...r.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(Ho).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 zs(e,t,n){return e.some(e=>Ps(e,t[e.id]??[],n))}var Bs=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??za,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}),Vs(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 Vs(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 Hs=`pi-webui:cached-new-sessions:v1`,Us=`browserCachedNew`,Ws=`local`;function Gs(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Ks(e,t=Ws,n=Gs()){if(e.messageCount!==0||e.archived===!0)return;let r=Qs(n).filter(n=>n.id!==e.id||n.machineId!==t);$s([qs(e,t),...r],n)}function qs(e,t=Ws){return{...e,browserCachedNew:!0,machineId:t}}function Js(e,t=Ws,n=Gs()){$s(Qs(n).filter(n=>n.id!==e||n.machineId!==t),n)}function Ys(e,t,n=Ws,r=Gs()){let i=new Set(t.map(e=>e.id)),a=Qs(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&$s(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function Xs(e){return e!==void 0&&tc(e)&&e.browserCachedNew===!0}function Zs(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:Ws},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Qs(e=Gs()){try{let t=e?.getItem(Hs);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>ec(e)):[]}catch{return[]}}function $s(e,t=Gs()){try{e.length===0?t?.removeItem(Hs):t?.setItem(Hs,JSON.stringify(e))}catch{}}function ec(e){if(!nc(e))return[];let t=rc(e,`id`),n=rc(e,`path`),r=rc(e,`cwd`),i=rc(e,`created`),a=rc(e,`modified`),o=rc(e,`firstMessage`),s=ac(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=ic(e,`name`),l=ic(e,`parentSessionPath`),u=ic(e,`machineId`)??Ws;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},machineId:u,browserCachedNew:!0}]}function tc(e){return Us in e}function nc(e){return typeof e==`object`&&!!e}function rc(e,t){let n=e[t];return typeof n==`string`?n:void 0}function ic(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function ac(e,t){let n=e[t];return typeof n==`number`?n:void 0}function oc(e){return Tc(e.flatMap(dc)).filter(e=>e.parts.length>0)}function sc(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function cc(e,t){let n=_c(t),r=z(t,`entryId`),i=z(t,`previousAssistantEntryId`),a=Pc(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 lc(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,sc(t,n)]}function uc(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 dc(e){if(pc(e))return[e];if(z(e,`role`)===`bashExecution`)return[cc(bc(e),e)];let t=xc(z(e,`role`)),n=Sc(Nc(e,`content`),e),r=t===`user`?mc(n):void 0;if(r!==void 0)return r.map(t=>cc(t,e));let i=gc(e);if(t===`tool`)return[cc({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?[cc({role:o,parts:a,...i===void 0?{}:{source:i}},e)]:[],c=fc(e);return c===void 0?s:[...s,cc(c,e)]}function fc(e){if(z(e,`role`)!==`assistant`||z(e,`stopReason`)!==`error`)return;let t=z(e,`errorMessage`)?.trim();return sc(`system`,`Model response failed: ${t===void 0||t===``?`The model returned an error.`:t}`)}function pc(e){let t=z(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(Nc(e,`parts`))}function mc(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=hc(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 hc(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 gc(e){let t=z(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function _c(e){let t=vc(Nc(e,`timestamp`)),n=yc(e);if(!(t===void 0&&n===void 0))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n}}}function vc(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 yc(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 bc(e){let t=z(e,`command`)??``,n=Pc(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=Nc(e,`output`);r!=null&&n.push(``,Ic(r));let i=Nc(e,`exitCode`);i!=null&&n.push(``,`exit ${Ic(i)}`),Pc(e,`cancelled`)===!0&&n.push(``,`cancelled`),Pc(e,`truncated`)===!0&&n.push(``,`output truncated`);let a=z(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`full output: ${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
|
|
4
4
|
`)}]}}function xc(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function Sc(e,t){return typeof e==`string`?e===``?[]:[{type:`text`,text:e}]:Array.isArray(e)?e.flatMap(e=>{let t=z(e,`type`),n=z(e,`text`);if(t===`text`)return n!==void 0&&n!==``?[{type:`text`,text:n}]:[];if(t===`thinking`){let t=z(e,`thinking`)??n;return t!==void 0&&t!==``?[{type:`thinking`,text:t}]:[]}if(t===`toolCall`){let t=z(e,`name`)??`tool`,n=Nc(e,`arguments`),r=z(e,`id`),i=t===`read`?wc(z(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:Ac(n),...n===void 0?{}:{args:n}}]:[{type:`skillRead`,...i,...r===void 0?{}:{toolCallId:r}}]}if(t===`image`){let t=z(e,`data`),n=z(e,`mimeType`);return t!==void 0&&t!==``&&n!==void 0&&n!==``?[{type:`image`,mimeType:n,data:t}]:[{type:`text`,text:`[image]`}]}return kc(e)}).map(e=>e.type===`text`&&z(t,`role`)===`toolResult`?Cc(e.text,t):e):kc(e)}function Cc(e,t){let n=z(t,`toolCallId`),r=Nc(t,`content`),i=Nc(t,`details`);return{type:`toolResult`,...n===void 0?{}:{toolCallId:n},toolName:z(t,`toolName`)??`tool`,text:e,...r===void 0?{}:{content:r},...i===void 0?{}:{details:i},isError:Pc(t,`isError`)===!0}}function wc(e){if(e===void 0||e===``)return;let t=e.replace(/\\/g,`/`);if(!t.endsWith(`/SKILL.md`)&&t!==`SKILL.md`)return;let n=t.split(`/`).at(-2);if(!(n===void 0||n===``))return{name:n,path:e}}function Tc(e){let t=[],n=new Map;for(let r of e){let e=[],i={...r.entryId===void 0?{}:{entryId:r.entryId},...r.previousAssistantEntryId===void 0?{}:{previousAssistantEntryId:r.previousAssistantEntryId},...r.canFork===void 0?{}:{canFork:r.canFork},...r.source===void 0?{}:{source:r.source},...r.meta===void 0?{}:{meta:r.meta}},a=()=>{e.length!==0&&(t.push({role:r.role,parts:e,...i}),e=[])};for(let o of r.parts){if(o.type===`toolCall`){a();let e=Ec(o),r=t.length;t.push({role:`tool`,parts:[e],...i}),e.toolCallId!==void 0&&n.set(e.toolCallId,{lineIndex:r,partIndex:0});continue}if(o.type===`toolResult`){let e=o.toolCallId===void 0?void 0:n.get(o.toolCallId);if(e!==void 0&&Dc(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function Ec(e){return{type:`toolExecution`,...e.toolCallId===void 0?{}:{toolCallId:e.toolCallId},toolName:e.toolName,summary:e.summary,...e.args===void 0?{}:{args:e.args},status:`pending`}}function Dc(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=Oc(n.details)??i.preview,o={...i,status:n.isError?`error`:`success`,resultText:n.text,...n.content===void 0?{}:{content:n.content},...n.details===void 0?{}:{details:n.details},...a===void 0?{}:{preview:a}};return e[t.lineIndex]={...r,parts:[...r.parts.slice(0,t.partIndex),o,...r.parts.slice(t.partIndex+1)]},!0}function Oc(e){let t=Nc(e,`preview`);if(!Mc(t))return;let n=z(t,`diff`),r=z(t,`error`),i=Fc(t,`firstChangedLine`);if(!(n===void 0&&r===void 0&&i===void 0))return{...n===void 0?{}:{diff:n},...r===void 0?{}:{error:r},...i===void 0?{}:{firstChangedLine:i}}}function kc(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:Ac(e)}]:[{type:`text`,text:Ic(e)}]}function Ac(e){if(!Mc(e))return Ic(e);let t=z(e,`command`);if(t!==void 0)return t;let n=z(e,`path`);if(n!==void 0)return n;if(typeof e.oldText==`string`&&typeof e.newText==`string`)return`edit text replacement`;let r=e.edits;return Array.isArray(r)?`${String(r.length)} edit${r.length===1?``:`s`}`:Object.entries(e).filter(([,e])=>e!=null).slice(0,3).map(([e,t])=>`${e}: ${jc(t)}`).join(` · `)}function jc(e){return typeof e==`string`?e.length>80?`${e.slice(0,77)}…`:e:typeof e==`number`||typeof e==`boolean`?String(e):Array.isArray(e)?`${String(e.length)} item${e.length===1?``:`s`}`:typeof e==`object`&&e?`object`:``}function Mc(e){return typeof e==`object`&&!!e}function Nc(e,t){return Mc(e)?e[t]:void 0}function z(e,t){let n=Nc(e,t);return typeof n==`string`?n:void 0}function Pc(e,t){let n=Nc(e,t);return typeof n==`boolean`?n:void 0}function Fc(e,t){let n=Nc(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Ic(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var Lc=`pi-webui:prompt-draft:`;function Rc(e){return`${Lc}${e}`}function zc(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Bc(e,t=zc()){try{return t?.getItem(Rc(e))??``}catch{return``}}function Vc(e,t,n=zc()){try{t?n?.setItem(Rc(e),t):n?.removeItem(Rc(e))}catch{}}function Hc(e,t=zc()){try{t?.removeItem(Rc(e))}catch{}}function Uc(e,t,n=zc()){let r=Bc(e,n);r!==``&&(Vc(t,r,n),Hc(e,n))}function Wc(e,t){return sc(`bash`,`${t===!0?`excluded from context
|
|
@@ -1090,7 +1090,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1090
1090
|
.review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1091
1091
|
.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; }
|
|
1092
1092
|
footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
|
|
1093
|
-
`]}};B([x({attribute:!1})],im.prototype,`context`,void 0),B([C(`#workspace-upload-input`)],im.prototype,`uploadInput`,void 0),B([S()],im.prototype,`pendingUpload`,void 0),B([S()],im.prototype,`destinationFolder`,void 0),B([S()],im.prototype,`overwrite`,void 0),B([S()],im.prototype,`createDirs`,void 0),B([S()],im.prototype,`formError`,void 0),B([S()],im.prototype,`dragActive`,void 0),im=B([b(`workspace-files-panel`)],im);function am(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 om(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{So(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function sm(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function cm(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} · ${xm(t.size)}`}function lm(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function um(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function dm(e){return e==null?[]:Array.from(e)}function fm(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function pm(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function mm(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 hm(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return ym(e.percent)}}function gm(e){return e.status===`uploading`?e.percent:1}function _m(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return ym(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function vm(e){return e.error===void 0?e.response===void 0?`${e.path} · ${xm(e.loaded)} / ${xm(e.total)}`:`Wrote ${e.response.path}`:e.error}function ym(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function bm(){rm(()=>import(`./CodeViewer-
|
|
1093
|
+
`]}};B([x({attribute:!1})],im.prototype,`context`,void 0),B([C(`#workspace-upload-input`)],im.prototype,`uploadInput`,void 0),B([S()],im.prototype,`pendingUpload`,void 0),B([S()],im.prototype,`destinationFolder`,void 0),B([S()],im.prototype,`overwrite`,void 0),B([S()],im.prototype,`createDirs`,void 0),B([S()],im.prototype,`formError`,void 0),B([S()],im.prototype,`dragActive`,void 0),im=B([b(`workspace-files-panel`)],im);function am(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 om(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{So(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function sm(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function cm(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} · ${xm(t.size)}`}function lm(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function um(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function dm(e){return e==null?[]:Array.from(e)}function fm(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function pm(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function mm(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 hm(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return ym(e.percent)}}function gm(e){return e.status===`uploading`?e.percent:1}function _m(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return ym(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function vm(e){return e.error===void 0?e.response===void 0?`${e.path} · ${xm(e.loaded)} / ${xm(e.total)}`:`Wrote ${e.response.path}`:e.error}function ym(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function bm(){rm(()=>import(`./CodeViewer-Cm2qJjkP.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function xm(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`${Sm(t)} KB`;let n=t/1024;return n<1024?`${Sm(n)} MB`:`${Sm(n/1024)} GB`}function Sm(e){return e>=10?String(Math.round(e)):e.toFixed(1)}var Cm=2e3,wm=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 za.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)},Cm))}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 za.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">
|
|
1094
1094
|
<p class="error-text">Failed to load system information: ${this.error}</p>
|
|
1095
1095
|
<button @click=${()=>{this.loadSystemInfo()}}>Retry</button>
|
|
1096
1096
|
</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">
|
|
@@ -1334,7 +1334,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1334
1334
|
<div class="viewer-header"><strong>${e.path??`diff`}</strong><small>${e.staged?`staged`:`unstaged`}${e.truncated?` · truncated`:``}</small></div>
|
|
1335
1335
|
<unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
|
|
1336
1336
|
</section>
|
|
1337
|
-
`}function Lm(){rm(()=>import(`./UnifiedDiffViewer-
|
|
1337
|
+
`}function Lm(){rm(()=>import(`./UnifiedDiffViewer-XFd_Uipx.js`),[],import.meta.url)}function Rm(){rm(()=>Promise.resolve().then(()=>KD),void 0,import.meta.url)}function zm(e){return g`<workspace-info-panel .context=${e}></workspace-info-panel>`}function Bm(e){let t=Vm(e);return g`
|
|
1338
1338
|
<p class="summary">
|
|
1339
1339
|
<span class="summary-branch">${t.branch}</span>
|
|
1340
1340
|
${t.latestTag===void 0?null:g`<span class="summary-tag" aria-label=${`Latest tag ${t.latestTag}`}>${t.latestTag}</span>`}
|
|
@@ -1783,7 +1783,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1783
1783
|
.pinned-star { flex: 0 0 auto; border: 0; background: transparent; color: #d4a017; padding: 0; font: inherit; font-size: 14px; line-height: 1; }
|
|
1784
1784
|
.pinned-star:hover { border-radius: 4px; background: var(--pi-surface); box-shadow: 0 0 0 1px var(--pi-border); transform: scale(1.25); }
|
|
1785
1785
|
.pinned-star:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; border-radius: 2px; }
|
|
1786
|
-
`]}};B([x({attribute:!1})],H.prototype,`sessions`,void 0),B([x({attribute:!1})],H.prototype,`projectSessions`,void 0),B([x({type:String})],H.prototype,`currentWorkspacePath`,void 0),B([x({attribute:!1})],H.prototype,`workspaces`,void 0),B([x({attribute:!1})],H.prototype,`statuses`,void 0),B([x({attribute:!1})],H.prototype,`activities`,void 0),B([x({attribute:!1})],H.prototype,`sending`,void 0),B([x({attribute:!1})],H.prototype,`unreadSessionIds`,void 0),B([x({attribute:!1})],H.prototype,`selected`,void 0),B([x({type:Number})],H.prototype,`startingCount`,void 0),B([x({type:Boolean})],H.prototype,`canStart`,void 0),B([x({type:Boolean})],H.prototype,`canDeleteArchived`,void 0),B([x({type:Boolean})],H.prototype,`canReload`,void 0),B([x({type:Boolean})],H.prototype,`canCleanup`,void 0),B([x({type:Boolean})],H.prototype,`authoritativeSessionPersistence`,void 0),B([x({type:String})],H.prototype,`archivedDeleteUnavailableMessage`,void 0),B([x({type:String})],H.prototype,`cleanupUnavailableMessage`,void 0),B([x({type:Boolean,reflect:!0})],H.prototype,`collapsible`,void 0),B([x({type:Boolean,reflect:!0})],H.prototype,`collapsed`,void 0),B([x({attribute:!1})],H.prototype,`onSelect`,void 0),B([x({attribute:!1})],H.prototype,`onRenameStart`,void 0),B([x({attribute:!1})],H.prototype,`onRename`,void 0),B([x({attribute:!1})],H.prototype,`onStart`,void 0),B([x({attribute:!1})],H.prototype,`onToggleCollapsed`,void 0),B([x({attribute:!1})],H.prototype,`onArchivedCollapsed`,void 0),B([x({attribute:!1})],H.prototype,`onFocusPreviousSection`,void 0),B([x({attribute:!1})],H.prototype,`onFocusNextSection`,void 0),B([x({attribute:!1})],H.prototype,`onCancelKeyboardNavigation`,void 0),B([x({attribute:!1})],H.prototype,`onArchive`,void 0),B([x({attribute:!1})],H.prototype,`onArchiveWithDescendants`,void 0),B([x({attribute:!1})],H.prototype,`onArchiveMany`,void 0),B([x({attribute:!1})],H.prototype,`onRestore`,void 0),B([x({attribute:!1})],H.prototype,`onDelete`,void 0),B([x({attribute:!1})],H.prototype,`onDeleteArchived`,void 0),B([x({attribute:!1})],H.prototype,`onDeleteArchivedMany`,void 0),B([x({attribute:!1})],H.prototype,`onDetachParent`,void 0),B([x({attribute:!1})],H.prototype,`onReload`,void 0),B([x({attribute:!1})],H.prototype,`onPin`,void 0),B([x({attribute:!1})],H.prototype,`onUnpin`,void 0),B([x({attribute:!1})],H.prototype,`onCleanup`,void 0),B([S()],H.prototype,`openMenuSessionId`,void 0),B([S()],H.prototype,`menuStyle`,void 0),B([S()],H.prototype,`archivedExpanded`,void 0),B([S()],H.prototype,`selectionScopes`,void 0),B([S()],H.prototype,`selectedSessionIds`,void 0),B([S()],H.prototype,`renamingSessionId`,void 0),B([S()],H.prototype,`renameInputValue`,void 0),B([S()],H.prototype,`foldedSessionPaths`,void 0),H=B([b(`session-list`)],H);function X_(e,t,n={}){return e.filter(e=>tv(e,n.statuses?.[e.id],n.activities?.[e.id],n.sending?.[e.id]===!0,t.has(e.id))===`unread`).length}function Z_(e){return e!==null&&`value`in e&&typeof e.value==`string`}function Q_(e){return e.archived===!0?`archived`:`current`}function $_(e,t){let n=new Set(t);return new Set([...e].filter(e=>!n.has(e)))}function ev(e){let t=new Map;for(let n of e){if(n.parentSessionPath===void 0)continue;let e=t.get(n.parentSessionPath)??[];e.push(n),t.set(n.parentSessionPath,e)}let n=(e,r)=>{if(r.has(e.path))return 0;let i=new Set(r);i.add(e.path);let a=0;for(let r of t.get(e.path)??[])i.has(r.path)||(r.archived!==!0&&(a+=1),a+=n(r,i));return a};return new Map(e.map(e=>[e.id,n(e,new Set)]))}function tv(e,t,n,r,i=!1){if(!(Xs(e)||e.archived===!0))return r?`sending`:Vo(t,n)?`session`:i?`unread`:void 0}function nv(e,t={}){let n=e.filter(e=>t.knownWorkspacePaths===void 0||e.cwd===t.currentWorkspacePath||t.knownWorkspacePaths.has(e.cwd)),r=new Map(n.map(e=>[e.path,e])),i=iv(n,r),a=ov(av(n.filter(e=>t.currentWorkspacePath===void 0?e.archived!==!0:e.cwd===t.currentWorkspacePath).map(e=>e.path),r,i),r);return rv(n.filter(e=>a.has(e.path)),t)}function rv(e,t={}){let n=new Map(e.map(e=>[e.path,e])),r=iv(e,n),i=e.filter(e=>{let t=e.parentSessionPath;return t===void 0||!n.has(t)});i.sort(sv);let a=[],o=(e,i,s)=>{if(s.has(e.path))return;let c=e.parentSessionPath,l=r.get(e.path)??[];if(a.push({session:e,depth:i,hasMissingParent:c!==void 0&&!n.has(c),external:t.currentWorkspacePath!==void 0&&e.cwd!==t.currentWorkspacePath,hasChildren:l.length>0}),t.foldedSessionPaths?.has(e.path)===!0)return;let u=new Set(s);u.add(e.path),l.sort(sv);for(let e of l)o(e,i+1,u)};for(let e of i)o(e,0,new Set);return a}function iv(e,t){let n=new Map;for(let r of e){let e=r.parentSessionPath;if(e===void 0||!t.has(e))continue;let i=n.get(e)??[];i.push(r),n.set(e,i)}return n}function av(e,t,n){let r=new Set,i=[...e];for(;i.length>0;){let e=i.pop();if(e===void 0||r.has(e))continue;let a=t.get(e);if(a!==void 0){r.add(e),a.parentSessionPath!==void 0&&i.push(a.parentSessionPath);for(let t of n.get(e)??[])i.push(t.path)}}return r}function ov(e,t){let n=new Set;for(let r of e){let i=t.get(r);if(i?.archived===!0)continue;n.add(r);let a=i?.parentSessionPath,o=new Set([r]);for(;a!==void 0&&e.has(a)&&!o.has(a);){o.add(a);let e=t.get(a);if(e===void 0)break;n.add(a),a=e.parentSessionPath}}return n}function sv(e,t){let n=e.pinned===!0,r=t.pinned===!0;return n&&!r?-1:!n&&r?1:0}var
|
|
1786
|
+
`]}};B([x({attribute:!1})],H.prototype,`sessions`,void 0),B([x({attribute:!1})],H.prototype,`projectSessions`,void 0),B([x({type:String})],H.prototype,`currentWorkspacePath`,void 0),B([x({attribute:!1})],H.prototype,`workspaces`,void 0),B([x({attribute:!1})],H.prototype,`statuses`,void 0),B([x({attribute:!1})],H.prototype,`activities`,void 0),B([x({attribute:!1})],H.prototype,`sending`,void 0),B([x({attribute:!1})],H.prototype,`unreadSessionIds`,void 0),B([x({attribute:!1})],H.prototype,`selected`,void 0),B([x({type:Number})],H.prototype,`startingCount`,void 0),B([x({type:Boolean})],H.prototype,`canStart`,void 0),B([x({type:Boolean})],H.prototype,`canDeleteArchived`,void 0),B([x({type:Boolean})],H.prototype,`canReload`,void 0),B([x({type:Boolean})],H.prototype,`canCleanup`,void 0),B([x({type:Boolean})],H.prototype,`authoritativeSessionPersistence`,void 0),B([x({type:String})],H.prototype,`archivedDeleteUnavailableMessage`,void 0),B([x({type:String})],H.prototype,`cleanupUnavailableMessage`,void 0),B([x({type:Boolean,reflect:!0})],H.prototype,`collapsible`,void 0),B([x({type:Boolean,reflect:!0})],H.prototype,`collapsed`,void 0),B([x({attribute:!1})],H.prototype,`onSelect`,void 0),B([x({attribute:!1})],H.prototype,`onRenameStart`,void 0),B([x({attribute:!1})],H.prototype,`onRename`,void 0),B([x({attribute:!1})],H.prototype,`onStart`,void 0),B([x({attribute:!1})],H.prototype,`onToggleCollapsed`,void 0),B([x({attribute:!1})],H.prototype,`onArchivedCollapsed`,void 0),B([x({attribute:!1})],H.prototype,`onFocusPreviousSection`,void 0),B([x({attribute:!1})],H.prototype,`onFocusNextSection`,void 0),B([x({attribute:!1})],H.prototype,`onCancelKeyboardNavigation`,void 0),B([x({attribute:!1})],H.prototype,`onArchive`,void 0),B([x({attribute:!1})],H.prototype,`onArchiveWithDescendants`,void 0),B([x({attribute:!1})],H.prototype,`onArchiveMany`,void 0),B([x({attribute:!1})],H.prototype,`onRestore`,void 0),B([x({attribute:!1})],H.prototype,`onDelete`,void 0),B([x({attribute:!1})],H.prototype,`onDeleteArchived`,void 0),B([x({attribute:!1})],H.prototype,`onDeleteArchivedMany`,void 0),B([x({attribute:!1})],H.prototype,`onDetachParent`,void 0),B([x({attribute:!1})],H.prototype,`onReload`,void 0),B([x({attribute:!1})],H.prototype,`onPin`,void 0),B([x({attribute:!1})],H.prototype,`onUnpin`,void 0),B([x({attribute:!1})],H.prototype,`onCleanup`,void 0),B([S()],H.prototype,`openMenuSessionId`,void 0),B([S()],H.prototype,`menuStyle`,void 0),B([S()],H.prototype,`archivedExpanded`,void 0),B([S()],H.prototype,`selectionScopes`,void 0),B([S()],H.prototype,`selectedSessionIds`,void 0),B([S()],H.prototype,`renamingSessionId`,void 0),B([S()],H.prototype,`renameInputValue`,void 0),B([S()],H.prototype,`foldedSessionPaths`,void 0),H=B([b(`session-list`)],H);function X_(e,t,n={}){return e.filter(e=>tv(e,n.statuses?.[e.id],n.activities?.[e.id],n.sending?.[e.id]===!0,t.has(e.id))===`unread`).length}function Z_(e){return e!==null&&`value`in e&&typeof e.value==`string`}function Q_(e){return e.archived===!0?`archived`:`current`}function $_(e,t){let n=new Set(t);return new Set([...e].filter(e=>!n.has(e)))}function ev(e){let t=new Map;for(let n of e){if(n.parentSessionPath===void 0)continue;let e=t.get(n.parentSessionPath)??[];e.push(n),t.set(n.parentSessionPath,e)}let n=(e,r)=>{if(r.has(e.path))return 0;let i=new Set(r);i.add(e.path);let a=0;for(let r of t.get(e.path)??[])i.has(r.path)||(r.archived!==!0&&(a+=1),a+=n(r,i));return a};return new Map(e.map(e=>[e.id,n(e,new Set)]))}function tv(e,t,n,r,i=!1){if(!(Xs(e)||e.archived===!0))return r?`sending`:Vo(t,n)?`session`:i?`unread`:void 0}function nv(e,t={}){let n=e.filter(e=>t.knownWorkspacePaths===void 0||e.cwd===t.currentWorkspacePath||t.knownWorkspacePaths.has(e.cwd)),r=new Map(n.map(e=>[e.path,e])),i=iv(n,r),a=ov(av(n.filter(e=>t.currentWorkspacePath===void 0?e.archived!==!0:e.cwd===t.currentWorkspacePath).map(e=>e.path),r,i),r);return rv(n.filter(e=>a.has(e.path)),t)}function rv(e,t={}){let n=new Map(e.map(e=>[e.path,e])),r=iv(e,n),i=e.filter(e=>{let t=e.parentSessionPath;return t===void 0||!n.has(t)});i.sort(sv);let a=[],o=(e,i,s)=>{if(s.has(e.path))return;let c=e.parentSessionPath,l=r.get(e.path)??[];if(a.push({session:e,depth:i,hasMissingParent:c!==void 0&&!n.has(c),external:t.currentWorkspacePath!==void 0&&e.cwd!==t.currentWorkspacePath,hasChildren:l.length>0}),t.foldedSessionPaths?.has(e.path)===!0)return;let u=new Set(s);u.add(e.path),l.sort(sv);for(let e of l)o(e,i+1,u)};for(let e of i)o(e,0,new Set);return a}function iv(e,t){let n=new Map;for(let r of e){let e=r.parentSessionPath;if(e===void 0||!t.has(e))continue;let i=n.get(e)??[];i.push(r),n.set(e,i)}return n}function av(e,t,n){let r=new Set,i=[...e];for(;i.length>0;){let e=i.pop();if(e===void 0||r.has(e))continue;let a=t.get(e);if(a!==void 0){r.add(e),a.parentSessionPath!==void 0&&i.push(a.parentSessionPath);for(let t of n.get(e)??[])i.push(t.path)}}return r}function ov(e,t){let n=new Set;for(let r of e){let i=t.get(r);if(i?.archived===!0)continue;n.add(r);let a=i?.parentSessionPath,o=new Set([r]);for(;a!==void 0&&e.has(a)&&!o.has(a);){o.add(a);let e=t.get(a);if(e===void 0)break;n.add(a),a=e.parentSessionPath}}return n}function sv(e,t){let n=e.pinned===!0,r=t.pinned===!0;return n&&!r?-1:!n&&r?1:0}var U=class extends y{constructor(...e){super(...e),this.canCleanup=!0,this.unavailableMessage=`Update and restart Pi-Web on this machine to clean up sessions.`,this.loading=!1,this.running=!1,this.error=``,this.runningForce=!1,this.draft={...jf},this.formError=``}willUpdate(e){e.has(`preview`)&&(this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd))}render(){let e=Mf(this.draft),t=this.selectedPreview(),n=Pf({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest,loading:this.loading,running:this.running}),r=n?`Run cleanup`:t!==void 0&&!Ff(t)?`Select at least one project to run cleanup`:`Preview cleanup before running it`;return g`
|
|
1787
1787
|
<div class="backdrop" @mousedown=${()=>{this.onClose?.()}}>
|
|
1788
1788
|
<section role="dialog" aria-modal="true" aria-label="Clean up sessions" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
1789
1789
|
<header>
|
|
@@ -1812,15 +1812,15 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1812
1812
|
`}renderForm(e){let t=this.loading||this.running,n=Mf(this.draft),r=this.preview!==void 0&&n.ok&&Nf(n.request)!==Nf(this.previewRequest)&&Ff(this.preview);return g`
|
|
1813
1813
|
<fieldset ?disabled=${t}>
|
|
1814
1814
|
<label class="toggle-row">
|
|
1815
|
-
<input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:
|
|
1815
|
+
<input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:cv(e)})}}>
|
|
1816
1816
|
<span>Archive non-archived sessions idle for more than</span>
|
|
1817
|
-
<input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${t||!this.draft.archiveIdleEnabled} @input=${e=>{this.updateDraft({archiveIdleDays:
|
|
1817
|
+
<input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${t||!this.draft.archiveIdleEnabled} @input=${e=>{this.updateDraft({archiveIdleDays:lv(e)})}}>
|
|
1818
1818
|
<span>days</span>
|
|
1819
1819
|
</label>
|
|
1820
1820
|
<label class="toggle-row delete-row">
|
|
1821
|
-
<input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:
|
|
1821
|
+
<input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:cv(e)})}}>
|
|
1822
1822
|
<span>Delete archived sessions archived for more than</span>
|
|
1823
|
-
<input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${t||!this.draft.deleteArchivedEnabled} @input=${e=>{this.updateDraft({deleteArchivedDays:
|
|
1823
|
+
<input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${t||!this.draft.deleteArchivedEnabled} @input=${e=>{this.updateDraft({deleteArchivedDays:lv(e)})}}>
|
|
1824
1824
|
<span>days</span>
|
|
1825
1825
|
</label>
|
|
1826
1826
|
</fieldset>
|
|
@@ -1857,7 +1857,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1857
1857
|
${t.length===0?g`<p class="hint" role="status">Select at least one project to run cleanup.</p>`:null}
|
|
1858
1858
|
`}renderProjectRow(e,t){return g`
|
|
1859
1859
|
<tr class=${t?``:`unselected`}>
|
|
1860
|
-
<td class="select-cell"><input type="checkbox" aria-label=${`Clean up ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${t=>{this.setProjectSelected(e.cwd,
|
|
1860
|
+
<td class="select-cell"><input type="checkbox" aria-label=${`Clean up ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${t=>{this.setProjectSelected(e.cwd,cv(t))}}></td>
|
|
1861
1861
|
<th title=${e.cwd} dir="auto">${e.cwd}</th>
|
|
1862
1862
|
<td>${e.archiveCount}</td>
|
|
1863
1863
|
<td>${e.deleteCount}</td>
|
|
@@ -1924,7 +1924,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1924
1924
|
table { min-width: 560px; }
|
|
1925
1925
|
thead th:first-child, td.select-cell { width: 58px; }
|
|
1926
1926
|
}
|
|
1927
|
-
`}};B([x({type:Boolean})],
|
|
1927
|
+
`}};B([x({type:Boolean})],U.prototype,`canCleanup`,void 0),B([x({type:String})],U.prototype,`unavailableMessage`,void 0),B([x({attribute:!1})],U.prototype,`preview`,void 0),B([x({attribute:!1})],U.prototype,`previewRequest`,void 0),B([x({attribute:!1})],U.prototype,`result`,void 0),B([x({type:Boolean})],U.prototype,`loading`,void 0),B([x({type:Boolean})],U.prototype,`running`,void 0),B([x({type:String})],U.prototype,`error`,void 0),B([x({attribute:!1})],U.prototype,`onPreview`,void 0),B([x({attribute:!1})],U.prototype,`onRun`,void 0),B([x({attribute:!1})],U.prototype,`onForceCleanup`,void 0),B([x({attribute:!1})],U.prototype,`onClose`,void 0),B([x({attribute:!1})],U.prototype,`forceCleanupResult`,void 0),B([x({type:Boolean})],U.prototype,`runningForce`,void 0),B([S()],U.prototype,`draft`,void 0),B([S()],U.prototype,`formError`,void 0),B([S()],U.prototype,`selectedProjectCwds`,void 0),U=B([b(`session-cleanup-dialog`)],U);function cv(e){return e.target instanceof HTMLInputElement&&e.target.checked}function lv(e){return e.target instanceof HTMLInputElement?e.target.value:``}var uv=class extends y{constructor(...e){super(...e),this.machineId=`local`}render(){let e=this.session,t=e===void 0?void 0:bt(Da(e,this.machineId)),n=e===void 0?``:dv(e);return g`
|
|
1928
1928
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
1929
1929
|
<section class="history-window" role="dialog" aria-modal="true" aria-labelledby="session-history-window-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
1930
1930
|
<header>
|
|
@@ -1934,7 +1934,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1934
1934
|
${e===void 0?null:g`<span class="session-label" title=${n}>${n}</span>`}
|
|
1935
1935
|
</div>
|
|
1936
1936
|
<button class="icon-button" type="button" title="Close full history" aria-label="Close full history" @click=${()=>{this.close()}}>
|
|
1937
|
-
${
|
|
1937
|
+
${fv()}
|
|
1938
1938
|
</button>
|
|
1939
1939
|
</header>
|
|
1940
1940
|
<div class="history-body">
|
|
@@ -1971,11 +1971,11 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1971
1971
|
header, footer { padding: 12px; }
|
|
1972
1972
|
.session-label { max-width: 68vw; }
|
|
1973
1973
|
}
|
|
1974
|
-
`}};B([x({attribute:!1})],
|
|
1974
|
+
`}};B([x({attribute:!1})],uv.prototype,`session`,void 0),B([x({type:String})],uv.prototype,`machineId`,void 0),B([x({attribute:!1})],uv.prototype,`onClose`,void 0),uv=B([b(`session-history-window`)],uv);function dv(e){let t=e.name?.trim();if(t!==void 0&&t!==``)return t;let n=e.firstMessage.trim();return n===``?e.id:n}function fv(){return _`
|
|
1975
1975
|
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1976
1976
|
<path d="M6 6l12 12M18 6 6 18"></path>
|
|
1977
1977
|
</svg>
|
|
1978
|
-
`}function
|
|
1978
|
+
`}function pv(e){let t=new Map,n=[];for(let r of e.nodes)t.has(r.id)||(t.set(r.id,r),n.push(r.id));let r=yv(t,n),i=new Map;for(let e of n)i.set(e,[]);let a=[];for(let e of n){let t=r.get(e)??null;if(t===null){a.push(e);continue}i.get(t)?.push(e)}let o=new Map,s=new Map,c=new Set,l=[...a].reverse().map(e=>({id:e,depth:0,branchDepth:0}));for(;l.length>0;){let e=l.pop();if(e===void 0||c.has(e.id))continue;c.add(e.id),o.set(e.id,e.depth),s.set(e.id,e.branchDepth);let t=i.get(e.id)??[],n=e.branchDepth+ +(t.length>1);for(let r=t.length-1;r>=0;--r){let i=t[r];i!==void 0&&l.push({id:i,depth:e.depth+1,branchDepth:n})}}for(let e of n)c.has(e)||(a.push(e),r.set(e,null),o.set(e,0),s.set(e,0));let u=new Map;for(let[e,t]of i)u.set(e,t);let d=e.activeLeafId!==null&&t.has(e.activeLeafId)?e.activeLeafId:null;return{nodesById:t,orderedIds:n,rootIds:a,parentById:r,childrenById:u,depthById:o,branchDepthById:s,activePathIds:d===null?new Set:bv(d,r),activeLeafId:d}}function mv(e,t){let n=[],r=new Set,i=[...e.rootIds].reverse();for(;i.length>0;){let a=i.pop();if(a===void 0||r.has(a))continue;let o=e.nodesById.get(a);if(o===void 0)continue;r.add(a);let s=e.childrenById.get(a)??[];if(n.push({node:o,depth:e.depthById.get(a)??0,branchDepth:e.branchDepthById.get(a)??0,parentId:e.parentById.get(a)??null,childIds:s,activePath:e.activePathIds.has(a),activeLeaf:e.activeLeafId===a}),!t.has(a))for(let e=s.length-1;e>=0;--e){let t=s[e];t!==void 0&&i.push(t)}}return n}function hv(e){return e.activeLeafId===null?e.orderedIds.at(-1):e.activeLeafId}function gv(e,t,n){let r=mv(e,t.foldedIds).map(e=>e.node.id),i=xv(r,t.selectedId),a=i===void 0?-1:r.indexOf(i),o=()=>({...t,selectedId:i,handled:!1}),s=e=>({...t,selectedId:e,handled:!0});switch(n){case`ArrowUp`:return s(a>0?r[a-1]:i);case`ArrowDown`:return s(a>=0&&a<r.length-1?r[a+1]:i);case`Home`:return s(r[0]);case`End`:return s(r.at(-1));case`ArrowLeft`:if(i===void 0)return s(void 0);if((e.childrenById.get(i)??[]).length>0&&!t.foldedIds.has(i)){let e=new Set(t.foldedIds);return e.add(i),{selectedId:i,foldedIds:e,handled:!0}}return s(e.parentById.get(i)??i);case`ArrowRight`:{if(i===void 0)return s(void 0);let n=e.childrenById.get(i)??[];if(n.length===0)return s(i);if(t.foldedIds.has(i)){let e=new Set(t.foldedIds);return e.delete(i),{selectedId:i,foldedIds:e,handled:!0}}return s(n[0])}case`Enter`:return{...t,selectedId:i,handled:!0,...i===void 0?{}:{action:`confirm`}};case`Escape`:return{...t,selectedId:i,handled:!0,action:`cancel`};default:return o()}}function _v(e,t,n){if((e.childrenById.get(n)??[]).length===0)return{...t,selectedId:n};let r=new Set(t.foldedIds);return r.has(n)?r.delete(n):r.add(n),{selectedId:n,foldedIds:r}}function vv(e,t){return e===`none`||e==="default"?{ok:!0,choice:{mode:e}}:t.trim()===``?{ok:!1,error:`Enter custom summary focus instructions.`}:t.length>1e4?{ok:!1,error:`Custom summary focus must be ${String(kt)} characters or fewer.`}:{ok:!0,choice:{mode:`custom`,instructions:t.trim()}}}function yv(e,t){let n=new Map;for(let r of t){let t=e.get(r)?.parentId??null;n.set(r,t!==null&&t!==r&&e.has(t)?t:null)}let r=new Map;for(let e of t){if(r.has(e))continue;let t=[],i=e;for(;i!==null&&!r.has(i);)r.set(i,`visiting`),t.push(i),i=n.get(i)??null;if(i!==null&&r.get(i)===`visiting`){let e=t.at(-1);e!==void 0&&n.set(e,null)}for(let e of t)r.set(e,`visited`)}return n}function bv(e,t){let n=new Set,r=e;for(;r!==null&&!n.has(r);)n.add(r),r=t.get(r)??null;return n}function xv(e,t){return t!==void 0&&e.includes(t)?t:e.at(-1)}var Sv={nodes:[],activeLeafId:null,activePathIds:[]},Cv=8,wv=class extends y{constructor(...e){super(...e),this.tree=Sv,this.foldedIds=new Set,this.step=`tree`,this.summaryMode=`none`,this.customInstructions=``,this.busy=!1,this.aborting=!1,this.error=``,this.statusMessage=``,this.model=pv(Sv),this.operationGeneration=0}willUpdate(e){e.has(`tree`)&&this.resetTree()}updated(){let e=this.pendingFocus;e!==void 0&&(this.pendingFocus=void 0,e===`tree`?this.focusSelectedTreeItem():e===`custom`?this.renderRoot.querySelector(`#session-tree-custom-focus`)?.focus():this.renderRoot.querySelector(`input[name='session-tree-summary']:checked`)?.focus())}render(){return g`
|
|
1979
1979
|
<div class="backdrop" @mousedown=${e=>{this.handleBackdropMouseDown(e)}}>
|
|
1980
1980
|
<section
|
|
1981
1981
|
role="dialog"
|
|
@@ -1997,7 +1997,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1997
1997
|
${this.renderFooter()}
|
|
1998
1998
|
</section>
|
|
1999
1999
|
</div>
|
|
2000
|
-
`}renderTreeStep(){let e=
|
|
2000
|
+
`}renderTreeStep(){let e=mv(this.model,this.foldedIds);return g`
|
|
2001
2001
|
<div class="body tree-step">
|
|
2002
2002
|
<div class="tree-intro">
|
|
2003
2003
|
<p>Select where conversation context should continue. All retained branches stay in this session file.</p>
|
|
@@ -2016,7 +2016,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2016
2016
|
</div>
|
|
2017
2017
|
`}
|
|
2018
2018
|
</div>
|
|
2019
|
-
`}renderTreeRow(e){let t=e.node.id===this.selectedId,n=e.childIds.length>0&&!this.foldedIds.has(e.node.id),r=[`tree-row`,t?`selected`:``,e.activePath?`active-path`:``,e.activeLeaf?`active-leaf`:``,
|
|
2019
|
+
`}renderTreeRow(e){let t=e.node.id===this.selectedId,n=e.childIds.length>0&&!this.foldedIds.has(e.node.id),r=[`tree-row`,t?`selected`:``,e.activePath?`active-path`:``,e.activeLeaf?`active-leaf`:``,Ov(e.node.kind)?`bookkeeping`:``].filter(e=>e!==``).join(` `),i=Tv(e.branchDepth);return g`
|
|
2020
2020
|
<div
|
|
2021
2021
|
class=${r}
|
|
2022
2022
|
style=${`--tree-indent: ${String(i*16)}px; --tree-indent-mobile: ${String(i*12)}px;`}
|
|
@@ -2037,7 +2037,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2037
2037
|
@click=${t=>{this.toggleNode(e.node.id,t)}}
|
|
2038
2038
|
>${e.childIds.length===0?`·`:n?`▾`:`▸`}</span>
|
|
2039
2039
|
<span class="metadata">
|
|
2040
|
-
<span class="kind">${
|
|
2040
|
+
<span class="kind">${Dv(e.node.kind)}</span>
|
|
2041
2041
|
<span class="badges">
|
|
2042
2042
|
${e.activePath&&!e.activeLeaf?g`<span class="badge path">Active path</span>`:null}
|
|
2043
2043
|
${e.activeLeaf?g`<span class="badge leaf">Active leaf</span>`:null}
|
|
@@ -2049,7 +2049,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2049
2049
|
${e.node.timestamp===void 0?null:g`<time datetime=${e.node.timestamp}>${e.node.timestamp}</time>`}
|
|
2050
2050
|
</span>
|
|
2051
2051
|
</div>
|
|
2052
|
-
`}renderConfirmationStep(){let e=this.selectedId===void 0?void 0:this.model.nodesById.get(this.selectedId),t=
|
|
2052
|
+
`}renderConfirmationStep(){let e=this.selectedId===void 0?void 0:this.model.nodesById.get(this.selectedId),t=vv(this.summaryMode,this.customInstructions);return g`
|
|
2053
2053
|
<div class="body confirmation-step">
|
|
2054
2054
|
<div class="confirmation-card">
|
|
2055
2055
|
<div>
|
|
@@ -2058,9 +2058,9 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2058
2058
|
</div>
|
|
2059
2059
|
${e===void 0?g`<div class="empty">The selected history entry is no longer available.</div>`:g`
|
|
2060
2060
|
<div class="selected-entry">
|
|
2061
|
-
<span class="kind">${
|
|
2061
|
+
<span class="kind">${Dv(e.kind)}</span>
|
|
2062
2062
|
<strong dir="auto">${e.summary}</strong>
|
|
2063
|
-
${
|
|
2063
|
+
${Ev(e.kind)?g`<p>This message’s text will return to the prompt editor for optional editing and resubmission.</p>`:g`<p>The prompt editor will be empty after navigating to this entry.</p>`}
|
|
2064
2064
|
</div>
|
|
2065
2065
|
`}
|
|
2066
2066
|
<fieldset ?disabled=${this.busy}>
|
|
@@ -2117,7 +2117,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2117
2117
|
${this.busy?e?`Summarizing…`:`Navigating…`:e?`Summarize and navigate`:`Navigate`}
|
|
2118
2118
|
</button>
|
|
2119
2119
|
</footer>
|
|
2120
|
-
`}resetTree(){this.operationGeneration+=1,this.model=
|
|
2120
|
+
`}resetTree(){this.operationGeneration+=1,this.model=pv(this.tree),this.selectedId=hv(this.model),this.foldedIds=new Set,this.step=`tree`,this.summaryMode=`none`,this.customInstructions=``,this.busy=!1,this.aborting=!1,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`}selectNode(e){this.model.nodesById.has(e)&&(this.selectedId=e,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`)}toggleNode(e,t){t.preventDefault(),t.stopPropagation();let n=_v(this.model,{selectedId:this.selectedId,foldedIds:this.foldedIds},e);this.selectedId=n.selectedId,this.foldedIds=n.foldedIds,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`}handleTreeKeyDown(e){let t=gv(this.model,{selectedId:this.selectedId,foldedIds:this.foldedIds},e.key);if(t.handled){if(e.preventDefault(),e.stopPropagation(),t.action===`cancel`){this.onCancel?.();return}if(t.action===`confirm`){this.continueToConfirmation();return}this.selectedId=t.selectedId,this.foldedIds=t.foldedIds,this.pendingFocus=`tree`}}continueToConfirmation(){this.selectedId===void 0||!this.model.nodesById.has(this.selectedId)||(vv(this.summaryMode,this.customInstructions).ok||(this.summaryMode=`none`,this.customInstructions=``),this.step=`confirm`,this.error=``,this.statusMessage=``,this.pendingFocus=`summary`)}returnToTree(){this.busy||(this.step=`tree`,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`)}selectSummaryMode(e){this.busy||(this.summaryMode=e,this.error=``,this.statusMessage=``,this.pendingFocus=e===`custom`?`custom`:`summary`)}handleCustomInstructionsInput(e){e.currentTarget instanceof HTMLTextAreaElement&&(this.customInstructions=e.currentTarget.value,this.error=``,this.statusMessage=``)}async submitNavigation(){if(this.busy||this.selectedId===void 0)return;let e=vv(this.summaryMode,this.customInstructions);if(!e.ok){this.error=``,this.statusMessage=``,this.pendingFocus=`custom`,this.requestUpdate();return}let t=this.onNavigate;if(t===void 0){this.error=`Session tree navigation is unavailable. Close and reopen /tree, then try again.`;return}let n=this.selectedId,r=++this.operationGeneration;this.busy=!0,this.aborting=!1,this.error=``,this.statusMessage=``;try{let i=await t(n,e.choice);if(r!==this.operationGeneration||(this.busy=!1,this.aborting=!1,!i.cancelled))return;this.step=`tree`,this.statusMessage=i.aborted===!0?`Summarization cancelled. Your selected history entry is unchanged.`:`Navigation cancelled. Your selected history entry is unchanged.`,this.pendingFocus=`tree`}catch(e){if(r!==this.operationGeneration)return;this.busy=!1,this.aborting=!1,this.statusMessage=``,this.error=`Could not navigate session history: ${kv(e)}`}}async abortNavigation(){if(!this.busy||this.summaryMode===`none`||this.aborting)return;let e=this.onAbort;if(e===void 0){this.error=`Summarization cannot be cancelled from this client.`;return}let t=this.operationGeneration;this.aborting=!0,this.error=``,this.statusMessage=`Cancelling summarization…`;try{await e()}catch(e){if(t!==this.operationGeneration)return;this.aborting=!1,this.statusMessage=``,this.error=`Could not cancel summarization: ${kv(e)}`}}handleBackdropMouseDown(e){e.target===e.currentTarget&&!this.busy&&this.onCancel?.()}handleDialogKeyDown(e){if(e.key===`Tab`){this.trapTabFocus(e);return}if(e.key===`Escape`){if(e.preventDefault(),e.stopPropagation(),this.busy){this.summaryMode!==`none`&&this.abortNavigation();return}this.step===`confirm`?this.returnToTree():this.onCancel?.()}}trapTabFocus(e){let t=[...this.renderRoot.querySelectorAll(`button:not(:disabled), input:not(:disabled), textarea:not(:disabled), [tabindex='0']`)];if(t.length===0){e.preventDefault(),this.renderRoot.querySelector(`section[role='dialog']`)?.focus();return}let n=this.shadowRoot?.activeElement,r=t.findIndex(e=>e===n),i=!e.shiftKey&&r===t.length-1,a=e.shiftKey&&r<=0;!i&&!a||(e.preventDefault(),(e.shiftKey?t.at(-1):t[0])?.focus())}focusSelectedTreeItem(){let e=this.selectedId;if(e===void 0){this.renderRoot.querySelector(`.close-button`)?.focus();return}let t=this.renderRoot.querySelectorAll(`[data-tree-node-id]`);for(let n of t)if(n.dataset.treeNodeId===e){n.focus(),n.scrollIntoView({block:`nearest`});return}}static{this.styles=h`
|
|
2121
2121
|
:host { position: fixed; inset: 0; z-index: 40; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
2122
2122
|
* { box-sizing: border-box; }
|
|
2123
2123
|
.backdrop { width: 100%; height: 100dvh; background: var(--pi-overlay); overflow: hidden; }
|
|
@@ -2210,7 +2210,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2210
2210
|
.custom-focus, .validation-error { margin-inline-start: 0; }
|
|
2211
2211
|
footer { flex-wrap: wrap; }
|
|
2212
2212
|
}
|
|
2213
|
-
`}};B([x({attribute:!1})],Tv.prototype,`tree`,void 0),B([x({attribute:!1})],Tv.prototype,`onNavigate`,void 0),B([x({attribute:!1})],Tv.prototype,`onAbort`,void 0),B([x({attribute:!1})],Tv.prototype,`onCancel`,void 0),B([S()],Tv.prototype,`selectedId`,void 0),B([S()],Tv.prototype,`foldedIds`,void 0),B([S()],Tv.prototype,`step`,void 0),B([S()],Tv.prototype,`summaryMode`,void 0),B([S()],Tv.prototype,`customInstructions`,void 0),B([S()],Tv.prototype,`busy`,void 0),B([S()],Tv.prototype,`aborting`,void 0),B([S()],Tv.prototype,`error`,void 0),B([S()],Tv.prototype,`statusMessage`,void 0),Tv=B([b(`session-tree-navigator`)],Tv);function Ev(e){return Math.min(Math.max(0,e),wv)}function Dv(e){return e===`user`||e===`custom-message`}function Ov(e){switch(e){case`user`:return`User`;case`assistant`:return`Assistant`;case`tool-result`:return`Tool result`;case`bash`:return`Shell`;case`custom-message`:return`Custom message`;case`compaction`:return`Compaction`;case`branch-summary`:return`Branch summary`;case`model-change`:return`Model`;case`thinking-level-change`:return`Thinking`;case`session-info`:return`Session info`;case`label`:return`Label`;case`custom`:return`Custom`;case`other`:return`Other`}}function kv(e){return e===`model-change`||e===`thinking-level-change`||e===`session-info`||e===`label`||e===`custom`||e===`other`}function Av(e){return e instanceof Error?e.message:String(e)}var jv=`pi-webui:chat-groups:`,Mv={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(Pv(e));return t===null||t===``?void 0:Fv(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(Pv(e),JSON.stringify(t))}catch{}}},Nv=class{constructor(e=Mv){this.storage=e,this.sessionId=``,this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(e){if(this.sessionId===e)return;this.sessionId=e;let t=e===``?void 0:this.storage.read(e);this.openGroupKeys=new Set(t?.open??[]),this.closedDefaultOpenGroupKeys=new Set(t?.closedDefaultOpen??[])}isOpen(e,t){return t?!this.closedDefaultOpenGroupKeys.has(e):this.openGroupKeys.has(e)}applyToggle(e,t,n){let r=this.isOpen(e,n),i=new Set(this.openGroupKeys),a=new Set(this.closedDefaultOpenGroupKeys);return n?(i.delete(e),t?a.delete(e):a.add(e)):(a.delete(e),t?i.add(e):i.delete(e)),(n?!a.has(e):i.has(e))===r&&Lv(i,this.openGroupKeys)&&Lv(a,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=i,this.closedDefaultOpenGroupKeys=a,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==``&&this.storage.write(this.sessionId,this.snapshot())}};function Pv(e){return`${jv}${e}`}function Fv(e){if(Array.isArray(e))return{open:Iv(e),closedDefaultOpen:[]};if(Rv(e))return{open:Array.isArray(e.open)?Iv(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Iv(e.closedDefaultOpen):[]}}function Iv(e){return e.filter(e=>typeof e==`string`)}function Lv(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Rv(e){return typeof e==`object`&&!!e}function zv(e,t=0){let n=[],r=[],i=0,a=(e,t)=>{r.length||(i=t),r.push(e)},o=()=>{r.length&&(n.push({kind:`group`,messages:r,startIndex:i,endIndex:i+r.length-1}),r=[])};return e.forEach((e,r)=>{let i=e.parts.filter(t=>Uv(e,t)),s=e.parts.filter(t=>!Uv(e,t)),c=t+r,l={...e.source===void 0?{}:{source:e.source},...e.meta===void 0?{}:{meta:e.meta}},u={...l,...e.entryId===void 0?{}:{entryId:e.entryId},...e.previousAssistantEntryId===void 0?{}:{previousAssistantEntryId:e.previousAssistantEntryId},...e.canFork===void 0?{}:{canFork:e.canFork}};if(s.length&&a({role:e.role,parts:s,...l},c),i.length){o();let t={role:i.every(e=>e.type===`skillRead`)?`skill`:e.role,parts:i,...u};if(Vv(t)){let e=Hv(s);n.push({kind:`tool-image`,message:t,index:c,...e===void 0?{}:{toolName:e}})}else n.push({kind:`message`,message:t,index:c})}}),o(),n}function Bv(e){if(e.every(e=>e.source===`compaction`))return`${String(e.length)} history compaction ${e.length===1?`summary`:`summaries`}`;if(e.every(e=>e.source===`branch_summary`))return`${String(e.length)} branch ${e.length===1?`summary`:`summaries`}`;let t=e.reduce((e,t)=>(e[t.role]=(e[t.role]??0)+1,e),{}),n=Object.entries(t).map(([e,t])=>`${String(t)} ${e}`).join(` · `);return`${String(e.length)} ${e.length===1?`event`:`events`}${n===``?``:` · ${n}`}`}function Vv(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function Hv(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function Uv(e,t){return e.source===`compaction`||e.source===`branch_summary`?!1:t.type===`skillInvocation`||t.type===`skillRead`||t.type===`image`||t.type===`text`&&(e.role===`user`||e.role===`assistant`||e.role===`system`||e.role===`bash`)}async function Wv(e,t=Gv()){if(!t.isSecureContext)return t.fallbackWriteText(e);if(t.writeText!==void 0)try{return await t.writeText(e),!0}catch{return t.fallbackWriteText(e)}return t.fallbackWriteText(e)}function Gv(){let e=e=>Jv(e),t=qv();return t===void 0?{isSecureContext:Kv(),fallbackWriteText:e}:{isSecureContext:Kv(),writeText:t,fallbackWriteText:e}}function Kv(){return typeof window<`u`&&window.isSecureContext}function qv(){if(!(typeof navigator>`u`||!(`clipboard`in navigator)))return navigator.clipboard.writeText.bind(navigator.clipboard)}function Jv(e){if(typeof document>`u`)return!1;let t=document.activeElement,n=document.getSelection(),r=n===null?[]:Yv(n),i=document.createElement(`textarea`);i.value=e,i.readOnly=!0,i.setAttribute(`aria-hidden`,`true`),i.style.position=`fixed`,i.style.top=`0`,i.style.left=`-9999px`,i.style.width=`1px`,i.style.height=`1px`,i.style.padding=`0`,i.style.border=`0`,i.style.opacity=`0`,i.style.pointerEvents=`none`,document.body.append(i),i.focus(),i.select(),i.setSelectionRange(0,i.value.length);try{return document.execCommand(`copy`)}catch{return!1}finally{i.remove(),Xv(n,r),Zv(t)}}function Yv(e){let t=[];for(let n=0;n<e.rangeCount;n+=1)t.push(e.getRangeAt(n));return t}function Xv(e,t){if(e!==null)try{e.removeAllRanges();for(let n of t)e.addRange(n)}catch{}}function Zv(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))try{e.focus({preventScroll:!0})}catch{e.focus()}}function Qv(e,t){let n=ey(ry(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function $v(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=ty(r,t.markerOffset);return}e.scrollTop=ny(e.scrollHeight,t.distanceFromBottom)}function ey(e){let t,n=-1/0,r,i=1/0;for(let a of e)a.offset<=0&&a.offset>=n?(t=a,n=a.offset):a.offset>0&&a.offset<i&&(r=a,i=a.offset);return t??r}function ty(e,t){return e-t}function ny(e,t){return Math.max(0,e-t)}function ry(e,t){let n=e.getBoundingClientRect().top;return t.flatMap(e=>{let t=e.dataset.markerId;return t===void 0?[]:[{id:t,offset:e.getBoundingClientRect().top-n}]})}var iy=600,ay=1;function oy(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:sy(e)||cy(e)}function sy(e){return e.scrollTop<(e.topThreshold??Math.max(iy,e.clientHeight))}function cy(e){return e.scrollHeight<=e.clientHeight+ay}var ly=`pi-webui:chat-scroll:`,uy=180,dy=48,fy=2,py={getItem(e){return typeof localStorage>`u`?null:localStorage.getItem(e)},setItem(e,t){typeof localStorage>`u`||localStorage.setItem(e,t)},removeItem(e){typeof localStorage>`u`||localStorage.removeItem(e)}},my={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},hy=class{constructor(e=py,t=my){this.storage=e,this.scheduler=t}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(e,t,n=uy){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=fy){if(e===``||t===void 0||!vy(t))return`skipped`;try{if(by(t,r))return this.storage.setItem(gy(e),JSON.stringify({mode:`bottom`})),`saved`;let i=Sy(t,n);if(i===void 0)return`skipped`;let a=xy(t,i);return this.storage.setItem(gy(e),JSON.stringify(a)),`saved`}catch{return`skipped`}}restorePosition(e,t,n,r){let i=this.readPosition(e);return i===void 0?this.scrollToBottom(t):this.restoreExplicitPosition(i,t,n,r)}restoreExplicitPosition(e,t,n,r){if(e.mode===`bottom`)return this.scrollToBottom(t);if(t===void 0||!vy(t))return{status:`skipped`};let i=wy(n,e.anchorId);if(i===void 0)return r?.fallbackToBottom===!1?{status:`missing`,position:e}:this.scrollToBottom(t);let a=t.getBoundingClientRect().top,o=i.getBoundingClientRect().top-a;return t.scrollTop+=o-e.offset,{status:`restored`}}readPosition(e){if(e!==``)try{let t=this.storage.getItem(gy(e));if(t===null||t===``)return;let n=JSON.parse(t);return _y(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!vy(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function gy(e){return`${ly}${e}`}function _y(e){return typeof e!=`object`||!e||!(`mode`in e)?!1:e.mode===`bottom`||e.mode===`anchor`&&`anchorId`in e&&typeof e.anchorId==`string`&&e.anchorId!==``&&`offset`in e&&typeof e.offset==`number`}function vy(e){return e.clientHeight>0&&e.scrollHeight>0}function yy(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function by(e,t=dy){return yy(e)<t}function xy(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:Ty(t)??``,offset:t.getBoundingClientRect().top-n}}function Sy(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(Ty(e)===void 0)continue;let t=e.getBoundingClientRect();if(t.bottom<=t.top||t.bottom<n.top||t.top>n.bottom)continue;let s=t.top-n.top;s<=0&&s>=i?(r=e,i=s):s>0&&s<o&&(a=e,o=s)}return r??a}function Cy(e,t){let n=e.getBoundingClientRect();return t.find(e=>{let t=e.getBoundingClientRect();return t.bottom>=n.top&&t.top<=n.bottom})}function wy(e,t){return e.find(e=>Ty(e)===t)}function Ty(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}function Ey(e){let{scrollHeight:t,clientHeight:n,scrollTop:r}=e;if(n<=0||t<=0)return{scrollRatio:0,viewportRatio:1,visible:!1};let i=t-n;return i<=20?{scrollRatio:0,viewportRatio:1,visible:!1}:{scrollRatio:Dy(r/i),viewportRatio:Dy(n/t),visible:!0}}function Dy(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Oy(e,t){return Dy(e*(1-t))}function ky(e,t,n,r){return r<=0?0:Dy((e-t+n)/r)}var Ay=22,jy=2;function My(e,t){if(e.length===0)return[];let n=Number.isFinite(t)?Math.max(0,t):0,r=Math.max(0,n-Ay),i=e.map((e,t)=>({index:t,desiredTop:Dy(e.topRatio)*n-Ay/2})).sort((e,t)=>e.desiredTop-t.desiredTop||e.index-t.index),a=Array(e.length).fill(0),o=e=>{for(let t=0;t<i.length;t+=1){let n=i[t],r=e[t];n===void 0||r===void 0||(a[n.index]=Math.round(r))}return a};if(i.length===1)return o([Math.min(r,Math.max(0,i[0]?.desiredTop??0))]);if(i.length*Ay+(i.length-1)*jy>n)return o(i.map((e,t)=>r*t/(i.length-1)));let s=i.map(({desiredTop:e})=>Math.min(r,Math.max(0,e)));for(let e=1;e<s.length;e+=1){let t=s[e-1],n=s[e];t===void 0||n===void 0||(s[e]=Math.max(n,t+24))}let c=s.length-1,l=s[c];l!==void 0&&(s[c]=Math.min(l,r));for(let e=c-1;e>=0;--e){let t=s[e+1],n=s[e];t===void 0||n===void 0||(s[e]=Math.min(n,t-24))}return o(s)}function Ny(e){if(typeof e!=`object`||!e||!(`ratio`in e))return;let t=e.ratio;if(!(typeof t!=`number`||!Number.isFinite(t)))return Dy(t)}function Py(e){return Number.isFinite(e)?e<1e3?Math.round(e).toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${String(Math.round(e/1e3))}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${String(Math.round(e/1e6))}M`:`0`}function Fy(e){return!Number.isFinite(e)||e===0?`$0`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Iy(e){return!Number.isFinite(e)||e===0?`$0.0000`:`$${e.toFixed(4)}`}function Ly(e){return Number.isFinite(e)?Math.round(e).toLocaleString():`0`}function Ry(e){return Number.isFinite(e)?e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${String(Math.round(e/1e3))}k`:Math.round(e).toString():`0`}function zy(e){let t=[],n=e.tokens;t.push(`Input: ${Ly(n.input)}`),t.push(`Output: ${Ly(n.output)}`),t.push(`Cache read: ${Ly(n.cacheRead)}`),t.push(`Cache write: ${Ly(n.cacheWrite)}`),t.push(`Total: ${Ly(n.total)}`),e.cost>0&&t.push(`Cost: ${Iy(e.cost)}`);let r=e.contextUsage;if(r!==void 0){let e=r.percent===null?`unknown`:`${r.percent.toFixed(1)}%`;t.push(`Context: ${e} of ${Ly(r.contextWindow)} tokens`)}return t.join(` | `)}function By(e){let t=0,n=0,r=0,i=0;for(let a of e)a.role===`user`&&(t+=1),a.role===`assistant`&&(n+=1,r+=a.parts.filter(e=>e.type===`toolCall`).length),a.role===`tool`&&(i+=a.parts.filter(e=>e.type===`toolResult`).length);return{user:t,assistant:n,toolCalls:r,toolResults:i,total:e.length}}function Vy(e,t,n){let r=[];t?.name!==void 0&&t.name!==``&&r.push({label:`Name`,value:t.name}),r.push({label:`ID`,value:t?.id??e.sessionId,copyValue:t?.id??e.sessionId}),t?.path!==void 0&&t.path!==``?r.push({label:`File`,value:t.path,copyValue:t.path}):t?.persisted===!1?r.push({label:`File`,value:`In-memory (transient)`}):r.push({label:`File`,value:e.persisted===!1?`In-memory (transient)`:`Unknown`});let i=[];n===void 0?e.messageCount!==void 0&&i.push({label:`Total`,value:Ly(e.messageCount)}):(i.push({label:`User`,value:Ly(n.user)}),i.push({label:`Assistant`,value:Ly(n.assistant)}),i.push({label:`Tool calls`,value:Ly(n.toolCalls)}),i.push({label:`Tool results`,value:Ly(n.toolResults)}),i.push({label:`Total`,value:Ly(n.total)}));let a=e.tokens,o=[{label:`Input`,value:Ly(a.input)},{label:`Output`,value:Ly(a.output)}];a.cacheRead>0&&o.push({label:`Cache read`,value:Ly(a.cacheRead)}),a.cacheWrite>0&&o.push({label:`Cache write`,value:Ly(a.cacheWrite)}),o.push({label:`Total`,value:Ly(a.total)}),e.cost>0&&o.push({label:`Cost`,value:Iy(e.cost)});let s=e.contextUsage;if(s!==void 0){let e=s.percent===null?`?`:`${s.percent.toFixed(1)}%`;o.push({label:`Context`,value:`${e} / ${Ry(s.contextWindow)}`})}return{sessionRows:r,messageRows:i,tokenRows:o}}var Hy=class extends y{constructor(...e){super(...e),this.scrollRatio=0,this.viewportRatio=1,this.visible=!1,this.loadedPercent=100,this.markers=[],this._hovered=!1,this._nearestIndex=null,this._dragging=!1,this._grabOffset=0}_handlePointerDown(e){if(!this.visible)return;let t=this._rail;if(!t)return;this._dragging=!0,t.setPointerCapture(e.pointerId);let n=t.getBoundingClientRect(),r=Dy((e.clientY-n.top)/n.height),i=this._viewportTopRatio(),a=r>=i&&r<=i+this.viewportRatio;this._grabOffset=a?r-i:this.viewportRatio/2,this._dispatchScroll(r-this._grabOffset)}_handlePointerMove(e){if(!this._rail)return;let t=this._rail.getBoundingClientRect(),n=Dy((e.clientY-t.top)/t.height);if(this._dragging){this._dispatchScroll(n-this._grabOffset);return}this._nearestIndex=this._findNearestMarker(n)}_handlePointerUp(){this._dragging=!1}_handleKeyDown(e){if(e.key===`ArrowUp`||e.key===`ArrowDown`){e.preventDefault();let t=this.viewportRatio/2,n=e.key===`ArrowUp`?-t:t,r=Dy(this._viewportTopRatio()+n);this._dispatchScroll(r)}}_viewportTopRatio(){return Oy(this.scrollRatio,this.viewportRatio)}_dispatchScroll(e){let t=Dy(e);this.dispatchEvent(new CustomEvent(`minimap-scroll-to`,{detail:{ratio:t},bubbles:!0,composed:!0}))}_findNearestMarker(e){let t=this.markers;if(t.length===0)return null;let n=t[0];if(n===void 0)return null;let r=0,i=Math.abs(n.topRatio-e);for(let n=1;n<t.length;n++){let a=t[n];if(a===void 0)continue;let o=Math.abs(a.topRatio-e);o<i&&(i=o,r=n)}return r}render(){return this.visible?g`${this._renderRail()}${this._renderTooltips()}`:g``}_renderRail(){let e=this._viewportTopRatio()*100,t=this.viewportRatio*100,n=this.loadedPercent>=100?`all messages loaded`:`${String(Math.round(this.loadedPercent))}% of messages loaded`;return g`
|
|
2213
|
+
`}};B([x({attribute:!1})],wv.prototype,`tree`,void 0),B([x({attribute:!1})],wv.prototype,`onNavigate`,void 0),B([x({attribute:!1})],wv.prototype,`onAbort`,void 0),B([x({attribute:!1})],wv.prototype,`onCancel`,void 0),B([S()],wv.prototype,`selectedId`,void 0),B([S()],wv.prototype,`foldedIds`,void 0),B([S()],wv.prototype,`step`,void 0),B([S()],wv.prototype,`summaryMode`,void 0),B([S()],wv.prototype,`customInstructions`,void 0),B([S()],wv.prototype,`busy`,void 0),B([S()],wv.prototype,`aborting`,void 0),B([S()],wv.prototype,`error`,void 0),B([S()],wv.prototype,`statusMessage`,void 0),wv=B([b(`session-tree-navigator`)],wv);function Tv(e){return Math.min(Math.max(0,e),Cv)}function Ev(e){return e===`user`||e===`custom-message`}function Dv(e){switch(e){case`user`:return`User`;case`assistant`:return`Assistant`;case`tool-result`:return`Tool result`;case`bash`:return`Shell`;case`custom-message`:return`Custom message`;case`compaction`:return`Compaction`;case`branch-summary`:return`Branch summary`;case`model-change`:return`Model`;case`thinking-level-change`:return`Thinking`;case`session-info`:return`Session info`;case`label`:return`Label`;case`custom`:return`Custom`;case`other`:return`Other`}}function Ov(e){return e===`model-change`||e===`thinking-level-change`||e===`session-info`||e===`label`||e===`custom`||e===`other`}function kv(e){return e instanceof Error?e.message:String(e)}var Av=`pi-webui:chat-groups:`,jv={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(Nv(e));return t===null||t===``?void 0:Pv(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(Nv(e),JSON.stringify(t))}catch{}}},Mv=class{constructor(e=jv){this.storage=e,this.sessionId=``,this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(e){if(this.sessionId===e)return;this.sessionId=e;let t=e===``?void 0:this.storage.read(e);this.openGroupKeys=new Set(t?.open??[]),this.closedDefaultOpenGroupKeys=new Set(t?.closedDefaultOpen??[])}isOpen(e,t){return t?!this.closedDefaultOpenGroupKeys.has(e):this.openGroupKeys.has(e)}applyToggle(e,t,n){let r=this.isOpen(e,n),i=new Set(this.openGroupKeys),a=new Set(this.closedDefaultOpenGroupKeys);return n?(i.delete(e),t?a.delete(e):a.add(e)):(a.delete(e),t?i.add(e):i.delete(e)),(n?!a.has(e):i.has(e))===r&&Iv(i,this.openGroupKeys)&&Iv(a,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=i,this.closedDefaultOpenGroupKeys=a,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==``&&this.storage.write(this.sessionId,this.snapshot())}};function Nv(e){return`${Av}${e}`}function Pv(e){if(Array.isArray(e))return{open:Fv(e),closedDefaultOpen:[]};if(Lv(e))return{open:Array.isArray(e.open)?Fv(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Fv(e.closedDefaultOpen):[]}}function Fv(e){return e.filter(e=>typeof e==`string`)}function Iv(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Lv(e){return typeof e==`object`&&!!e}function Rv(e,t=0){let n=[],r=[],i=0,a=(e,t)=>{r.length||(i=t),r.push(e)},o=()=>{r.length&&(n.push({kind:`group`,messages:r,startIndex:i,endIndex:i+r.length-1}),r=[])};return e.forEach((e,r)=>{let i=e.parts.filter(t=>Hv(e,t)),s=e.parts.filter(t=>!Hv(e,t)),c=t+r,l={...e.source===void 0?{}:{source:e.source},...e.meta===void 0?{}:{meta:e.meta}},u={...l,...e.entryId===void 0?{}:{entryId:e.entryId},...e.previousAssistantEntryId===void 0?{}:{previousAssistantEntryId:e.previousAssistantEntryId},...e.canFork===void 0?{}:{canFork:e.canFork}};if(s.length&&a({role:e.role,parts:s,...l},c),i.length){o();let t={role:i.every(e=>e.type===`skillRead`)?`skill`:e.role,parts:i,...u};if(Bv(t)){let e=Vv(s);n.push({kind:`tool-image`,message:t,index:c,...e===void 0?{}:{toolName:e}})}else n.push({kind:`message`,message:t,index:c})}}),o(),n}function zv(e){if(e.every(e=>e.source===`compaction`))return`${String(e.length)} history compaction ${e.length===1?`summary`:`summaries`}`;if(e.every(e=>e.source===`branch_summary`))return`${String(e.length)} branch ${e.length===1?`summary`:`summaries`}`;let t=e.reduce((e,t)=>(e[t.role]=(e[t.role]??0)+1,e),{}),n=Object.entries(t).map(([e,t])=>`${String(t)} ${e}`).join(` · `);return`${String(e.length)} ${e.length===1?`event`:`events`}${n===``?``:` · ${n}`}`}function Bv(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function Vv(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function Hv(e,t){return e.source===`compaction`||e.source===`branch_summary`?!1:t.type===`skillInvocation`||t.type===`skillRead`||t.type===`image`||t.type===`text`&&(e.role===`user`||e.role===`assistant`||e.role===`system`||e.role===`bash`)}async function Uv(e,t=Wv()){if(!t.isSecureContext)return t.fallbackWriteText(e);if(t.writeText!==void 0)try{return await t.writeText(e),!0}catch{return t.fallbackWriteText(e)}return t.fallbackWriteText(e)}function Wv(){let e=e=>qv(e),t=Kv();return t===void 0?{isSecureContext:Gv(),fallbackWriteText:e}:{isSecureContext:Gv(),writeText:t,fallbackWriteText:e}}function Gv(){return typeof window<`u`&&window.isSecureContext}function Kv(){if(!(typeof navigator>`u`||!(`clipboard`in navigator)))return navigator.clipboard.writeText.bind(navigator.clipboard)}function qv(e){if(typeof document>`u`)return!1;let t=document.activeElement,n=document.getSelection(),r=n===null?[]:Jv(n),i=document.createElement(`textarea`);i.value=e,i.readOnly=!0,i.setAttribute(`aria-hidden`,`true`),i.style.position=`fixed`,i.style.top=`0`,i.style.left=`-9999px`,i.style.width=`1px`,i.style.height=`1px`,i.style.padding=`0`,i.style.border=`0`,i.style.opacity=`0`,i.style.pointerEvents=`none`,document.body.append(i),i.focus(),i.select(),i.setSelectionRange(0,i.value.length);try{return document.execCommand(`copy`)}catch{return!1}finally{i.remove(),Yv(n,r),Xv(t)}}function Jv(e){let t=[];for(let n=0;n<e.rangeCount;n+=1)t.push(e.getRangeAt(n));return t}function Yv(e,t){if(e!==null)try{e.removeAllRanges();for(let n of t)e.addRange(n)}catch{}}function Xv(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))try{e.focus({preventScroll:!0})}catch{e.focus()}}function Zv(e,t){let n=$v(ny(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function Qv(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=ey(r,t.markerOffset);return}e.scrollTop=ty(e.scrollHeight,t.distanceFromBottom)}function $v(e){let t,n=-1/0,r,i=1/0;for(let a of e)a.offset<=0&&a.offset>=n?(t=a,n=a.offset):a.offset>0&&a.offset<i&&(r=a,i=a.offset);return t??r}function ey(e,t){return e-t}function ty(e,t){return Math.max(0,e-t)}function ny(e,t){let n=e.getBoundingClientRect().top;return t.flatMap(e=>{let t=e.dataset.markerId;return t===void 0?[]:[{id:t,offset:e.getBoundingClientRect().top-n}]})}var ry=600,iy=1;function ay(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:oy(e)||sy(e)}function oy(e){return e.scrollTop<(e.topThreshold??Math.max(ry,e.clientHeight))}function sy(e){return e.scrollHeight<=e.clientHeight+iy}var cy=`pi-webui:chat-scroll:`,ly=180,uy=48,dy=2,fy={getItem(e){return typeof localStorage>`u`?null:localStorage.getItem(e)},setItem(e,t){typeof localStorage>`u`||localStorage.setItem(e,t)},removeItem(e){typeof localStorage>`u`||localStorage.removeItem(e)}},py={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},my=class{constructor(e=fy,t=py){this.storage=e,this.scheduler=t}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(e,t,n=ly){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=dy){if(e===``||t===void 0||!_y(t))return`skipped`;try{if(yy(t,r))return this.storage.setItem(hy(e),JSON.stringify({mode:`bottom`})),`saved`;let i=xy(t,n);if(i===void 0)return`skipped`;let a=by(t,i);return this.storage.setItem(hy(e),JSON.stringify(a)),`saved`}catch{return`skipped`}}restorePosition(e,t,n,r){let i=this.readPosition(e);return i===void 0?this.scrollToBottom(t):this.restoreExplicitPosition(i,t,n,r)}restoreExplicitPosition(e,t,n,r){if(e.mode===`bottom`)return this.scrollToBottom(t);if(t===void 0||!_y(t))return{status:`skipped`};let i=Cy(n,e.anchorId);if(i===void 0)return r?.fallbackToBottom===!1?{status:`missing`,position:e}:this.scrollToBottom(t);let a=t.getBoundingClientRect().top,o=i.getBoundingClientRect().top-a;return t.scrollTop+=o-e.offset,{status:`restored`}}readPosition(e){if(e!==``)try{let t=this.storage.getItem(hy(e));if(t===null||t===``)return;let n=JSON.parse(t);return gy(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!_y(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function hy(e){return`${cy}${e}`}function gy(e){return typeof e!=`object`||!e||!(`mode`in e)?!1:e.mode===`bottom`||e.mode===`anchor`&&`anchorId`in e&&typeof e.anchorId==`string`&&e.anchorId!==``&&`offset`in e&&typeof e.offset==`number`}function _y(e){return e.clientHeight>0&&e.scrollHeight>0}function vy(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function yy(e,t=uy){return vy(e)<t}function by(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:wy(t)??``,offset:t.getBoundingClientRect().top-n}}function xy(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(wy(e)===void 0)continue;let t=e.getBoundingClientRect();if(t.bottom<=t.top||t.bottom<n.top||t.top>n.bottom)continue;let s=t.top-n.top;s<=0&&s>=i?(r=e,i=s):s>0&&s<o&&(a=e,o=s)}return r??a}function Sy(e,t){let n=e.getBoundingClientRect();return t.find(e=>{let t=e.getBoundingClientRect();return t.bottom>=n.top&&t.top<=n.bottom})}function Cy(e,t){return e.find(e=>wy(e)===t)}function wy(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}function Ty(e){let{scrollHeight:t,clientHeight:n,scrollTop:r}=e;if(n<=0||t<=0)return{scrollRatio:0,viewportRatio:1,visible:!1};let i=t-n;return i<=20?{scrollRatio:0,viewportRatio:1,visible:!1}:{scrollRatio:Ey(r/i),viewportRatio:Ey(n/t),visible:!0}}function Ey(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Dy(e,t){return Ey(e*(1-t))}function Oy(e,t,n,r){return r<=0?0:Ey((e-t+n)/r)}var ky=22,Ay=2;function jy(e,t){if(e.length===0)return[];let n=Number.isFinite(t)?Math.max(0,t):0,r=Math.max(0,n-ky),i=e.map((e,t)=>({index:t,desiredTop:Ey(e.topRatio)*n-ky/2})).sort((e,t)=>e.desiredTop-t.desiredTop||e.index-t.index),a=Array(e.length).fill(0),o=e=>{for(let t=0;t<i.length;t+=1){let n=i[t],r=e[t];n===void 0||r===void 0||(a[n.index]=Math.round(r))}return a};if(i.length===1)return o([Math.min(r,Math.max(0,i[0]?.desiredTop??0))]);if(i.length*ky+(i.length-1)*Ay>n)return o(i.map((e,t)=>r*t/(i.length-1)));let s=i.map(({desiredTop:e})=>Math.min(r,Math.max(0,e)));for(let e=1;e<s.length;e+=1){let t=s[e-1],n=s[e];t===void 0||n===void 0||(s[e]=Math.max(n,t+24))}let c=s.length-1,l=s[c];l!==void 0&&(s[c]=Math.min(l,r));for(let e=c-1;e>=0;--e){let t=s[e+1],n=s[e];t===void 0||n===void 0||(s[e]=Math.min(n,t-24))}return o(s)}function My(e){if(typeof e!=`object`||!e||!(`ratio`in e))return;let t=e.ratio;if(!(typeof t!=`number`||!Number.isFinite(t)))return Ey(t)}function Ny(e){return Number.isFinite(e)?e<1e3?Math.round(e).toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${String(Math.round(e/1e3))}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${String(Math.round(e/1e6))}M`:`0`}function Py(e){return!Number.isFinite(e)||e===0?`$0`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Fy(e){return!Number.isFinite(e)||e===0?`$0.0000`:`$${e.toFixed(4)}`}function Iy(e){return Number.isFinite(e)?Math.round(e).toLocaleString():`0`}function Ly(e){return Number.isFinite(e)?e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${String(Math.round(e/1e3))}k`:Math.round(e).toString():`0`}function Ry(e){let t=[],n=e.tokens;t.push(`Input: ${Iy(n.input)}`),t.push(`Output: ${Iy(n.output)}`),t.push(`Cache read: ${Iy(n.cacheRead)}`),t.push(`Cache write: ${Iy(n.cacheWrite)}`),t.push(`Total: ${Iy(n.total)}`),e.cost>0&&t.push(`Cost: ${Fy(e.cost)}`);let r=e.contextUsage;if(r!==void 0){let e=r.percent===null?`unknown`:`${r.percent.toFixed(1)}%`;t.push(`Context: ${e} of ${Iy(r.contextWindow)} tokens`)}return t.join(` | `)}function zy(e){let t=0,n=0,r=0,i=0;for(let a of e)a.role===`user`&&(t+=1),a.role===`assistant`&&(n+=1,r+=a.parts.filter(e=>e.type===`toolCall`).length),a.role===`tool`&&(i+=a.parts.filter(e=>e.type===`toolResult`).length);return{user:t,assistant:n,toolCalls:r,toolResults:i,total:e.length}}function By(e,t,n){let r=[];t?.name!==void 0&&t.name!==``&&r.push({label:`Name`,value:t.name}),r.push({label:`ID`,value:t?.id??e.sessionId,copyValue:t?.id??e.sessionId}),t?.path!==void 0&&t.path!==``?r.push({label:`File`,value:t.path,copyValue:t.path}):t?.persisted===!1?r.push({label:`File`,value:`In-memory (transient)`}):r.push({label:`File`,value:e.persisted===!1?`In-memory (transient)`:`Unknown`});let i=[];n===void 0?e.messageCount!==void 0&&i.push({label:`Total`,value:Iy(e.messageCount)}):(i.push({label:`User`,value:Iy(n.user)}),i.push({label:`Assistant`,value:Iy(n.assistant)}),i.push({label:`Tool calls`,value:Iy(n.toolCalls)}),i.push({label:`Tool results`,value:Iy(n.toolResults)}),i.push({label:`Total`,value:Iy(n.total)}));let a=e.tokens,o=[{label:`Input`,value:Iy(a.input)},{label:`Output`,value:Iy(a.output)}];a.cacheRead>0&&o.push({label:`Cache read`,value:Iy(a.cacheRead)}),a.cacheWrite>0&&o.push({label:`Cache write`,value:Iy(a.cacheWrite)}),o.push({label:`Total`,value:Iy(a.total)}),e.cost>0&&o.push({label:`Cost`,value:Fy(e.cost)});let s=e.contextUsage;if(s!==void 0){let e=s.percent===null?`?`:`${s.percent.toFixed(1)}%`;o.push({label:`Context`,value:`${e} / ${Ly(s.contextWindow)}`})}return{sessionRows:r,messageRows:i,tokenRows:o}}var Vy=class extends y{constructor(...e){super(...e),this.scrollRatio=0,this.viewportRatio=1,this.visible=!1,this.loadedPercent=100,this.markers=[],this._hovered=!1,this._nearestIndex=null,this._dragging=!1,this._grabOffset=0}_handlePointerDown(e){if(!this.visible)return;let t=this._rail;if(!t)return;this._dragging=!0,t.setPointerCapture(e.pointerId);let n=t.getBoundingClientRect(),r=Ey((e.clientY-n.top)/n.height),i=this._viewportTopRatio(),a=r>=i&&r<=i+this.viewportRatio;this._grabOffset=a?r-i:this.viewportRatio/2,this._dispatchScroll(r-this._grabOffset)}_handlePointerMove(e){if(!this._rail)return;let t=this._rail.getBoundingClientRect(),n=Ey((e.clientY-t.top)/t.height);if(this._dragging){this._dispatchScroll(n-this._grabOffset);return}this._nearestIndex=this._findNearestMarker(n)}_handlePointerUp(){this._dragging=!1}_handleKeyDown(e){if(e.key===`ArrowUp`||e.key===`ArrowDown`){e.preventDefault();let t=this.viewportRatio/2,n=e.key===`ArrowUp`?-t:t,r=Ey(this._viewportTopRatio()+n);this._dispatchScroll(r)}}_viewportTopRatio(){return Dy(this.scrollRatio,this.viewportRatio)}_dispatchScroll(e){let t=Ey(e);this.dispatchEvent(new CustomEvent(`minimap-scroll-to`,{detail:{ratio:t},bubbles:!0,composed:!0}))}_findNearestMarker(e){let t=this.markers;if(t.length===0)return null;let n=t[0];if(n===void 0)return null;let r=0,i=Math.abs(n.topRatio-e);for(let n=1;n<t.length;n++){let a=t[n];if(a===void 0)continue;let o=Math.abs(a.topRatio-e);o<i&&(i=o,r=n)}return r}render(){return this.visible?g`${this._renderRail()}${this._renderTooltips()}`:g``}_renderRail(){let e=this._viewportTopRatio()*100,t=this.viewportRatio*100,n=this.loadedPercent>=100?`all messages loaded`:`${String(Math.round(this.loadedPercent))}% of messages loaded`;return g`
|
|
2214
2214
|
<div
|
|
2215
2215
|
class="rail"
|
|
2216
2216
|
role="scrollbar"
|
|
@@ -2244,7 +2244,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2244
2244
|
class=${`marker-dot${r?` user`:` assistant`}${n?` nearest`:``}`}
|
|
2245
2245
|
></div>
|
|
2246
2246
|
</div>
|
|
2247
|
-
`}_renderTooltips(){if(!this._hovered)return null;let e=
|
|
2247
|
+
`}_renderTooltips(){if(!this._hovered)return null;let e=jy(this.markers,this._rail?.clientHeight??600);return this.markers.map((t,n)=>{let r=e[n];if(t.preview===``||r===void 0)return null;let i=this._nearestIndex===n;return g`
|
|
2248
2248
|
<div
|
|
2249
2249
|
class=${`tooltip ${t.role}${i?` nearest`:``}`}
|
|
2250
2250
|
style=${`top:${String(r)}px`}
|
|
@@ -2382,14 +2382,14 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2382
2382
|
transition: none;
|
|
2383
2383
|
}
|
|
2384
2384
|
}
|
|
2385
|
-
`}};B([x({type:Number})],
|
|
2386
|
-
]`).replace(`lheading`,
|
|
2387
|
-
`),n=t.length-1;for(;n>=0&&
|
|
2388
|
-
`)}function
|
|
2385
|
+
`}};B([x({type:Number})],Vy.prototype,`scrollRatio`,void 0),B([x({type:Number})],Vy.prototype,`viewportRatio`,void 0),B([x({type:Boolean})],Vy.prototype,`visible`,void 0),B([x({type:Number})],Vy.prototype,`loadedPercent`,void 0),B([x({attribute:!1})],Vy.prototype,`markers`,void 0),B([S()],Vy.prototype,`_hovered`,void 0),B([S()],Vy.prototype,`_nearestIndex`,void 0),B([C(`.rail`)],Vy.prototype,`_rail`,void 0),Vy=B([b(`chat-minimap`)],Vy);var Hy=class extends C_{constructor(e){if(super(e),this.it=v,e.type!==x_.CHILD)throw Error(this.constructor.directiveName+`() can only be used in child bindings`)}render(e){if(e===v||e==null)return this._t=void 0,this.it=e;if(e===Qe)return e;if(typeof e!=`string`)throw Error(this.constructor.directiveName+`() called with a non-string value`);if(e===this.it)return this._t;this.it=e;let t=[e];return t.raw=t,this._t={_$litType$:this.constructor.resultType,strings:t,values:[]}}};Hy.directiveName=`unsafeHTML`,Hy.resultType=1;var Uy=S_(Hy);function Wy(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Gy=Wy();function Ky(e){Gy=e}var qy={exec:()=>null};function Jy(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function W(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(Xy.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var Yy=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),Xy={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:Jy(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Jy(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Jy(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Jy(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Jy(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:Jy(e=>RegExp(`^ {0,${e}}>`))},Zy=/^(?:[ \t]*(?:\n|$))+/,Qy=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,$y=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,eb=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,tb=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,nb=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,rb=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ib=W(rb).replace(/bull/g,nb).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),ab=W(rb).replace(/bull/g,nb).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),ob=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,sb=/^[^\n]+/,cb=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,lb=W(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,cb).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ub=W(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,nb).getRegex(),db=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,fb=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,pb=W(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n+|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n+|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n+|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,fb).replace(`tag`,db).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),mb=e=>W(ob).replace(`hr`,eb).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,e).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,db).getRegex(),hb=mb(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),gb=mb(/ {0,3}(?:[*+-]|\d{1,9}[.)])[ \t]+[^ \t\n]/),_b={blockquote:W(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,gb).getRegex(),code:Qy,def:lb,fences:$y,heading:tb,hr:eb,html:pb,lheading:ib,list:ub,newline:Zy,paragraph:hb,table:qy,text:sb},vb=W(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,eb).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,db).getRegex(),yb={..._b,lheading:ab,table:vb,paragraph:W(ob).replace(`hr`,eb).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,vb).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,db).getRegex()},bb={..._b,html:W(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,fb).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:qy,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:W(ob).replace(`hr`,eb).replace(`heading`,` *#{1,6} *[^
|
|
2386
|
+
]`).replace(`lheading`,ib).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},xb=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Sb=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Cb=/^( {2,}|\\)\n(?!\s*$)/,wb=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Tb=/[\p{P}\p{S}]/u,Eb=/[\s\p{P}\p{S}]/u,Db=/[^\s\p{P}\p{S}]/u,Ob=W(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,Eb).getRegex(),kb=/(?!~)[\p{P}\p{S}]/u,Ab=/(?!~)[\s\p{P}\p{S}]/u,jb=/(?:[^\s\p{P}\p{S}]|~)/u,Mb=W(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,Yy?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),Nb=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Pb=W(Nb,`u`).replace(/punct/g,Tb).getRegex(),Fb=W(Nb,`u`).replace(/punct/g,kb).getRegex(),Ib=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,Lb=W(Ib,`gu`).replace(/notPunctSpace/g,Db).replace(/punctSpace/g,Eb).replace(/punct/g,Tb).getRegex(),Rb=W(Ib,`gu`).replace(/notPunctSpace/g,jb).replace(/punctSpace/g,Ab).replace(/punct/g,kb).getRegex(),zb=W(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,Db).replace(/punctSpace/g,Eb).replace(/punct/g,Tb).getRegex(),Bb=W(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,Tb).getRegex(),Vb=W(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Db).replace(/punctSpace/g,Eb).replace(/punct/g,Tb).getRegex(),Hb=W(/\\(punct)/,`gu`).replace(/punct/g,Tb).getRegex(),Ub=W(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace(`scheme`,/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(`email`,/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Wb=W(fb).replace(`(?:-->|$)`,`-->`).getRegex(),Gb=W(`^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,Wb).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Kb=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,qb=W(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,Kb).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Jb=W(/^!?\[(label)\]\[(ref)\]/).replace(`label`,Kb).replace(`ref`,cb).getRegex(),Yb=W(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,cb).getRegex(),Xb=W(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,Jb).replace(`nolink`,Yb).getRegex(),Zb=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Qb={_backpedal:qy,anyPunctuation:Hb,autolink:Ub,blockSkip:Mb,br:Cb,code:Sb,del:qy,delLDelim:qy,delRDelim:qy,emStrongLDelim:Pb,emStrongRDelimAst:Lb,emStrongRDelimUnd:zb,escape:xb,link:qb,nolink:Yb,punctuation:Ob,reflink:Jb,reflinkSearch:Xb,tag:Gb,text:wb,url:qy},$b={...Qb,link:W(/^!?\[(label)\]\((.*?)\)/).replace(`label`,Kb).getRegex(),reflink:W(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,Kb).getRegex()},ex={...Qb,emStrongRDelimAst:Rb,emStrongLDelim:Fb,delLDelim:Bb,delRDelim:Vb,url:W(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,Zb).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:W(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,Zb).getRegex()},tx={...ex,br:W(Cb).replace(`{2,}`,`*`).getRegex(),text:W(ex.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},nx={normal:_b,gfm:yb,pedantic:bb},rx={normal:Qb,gfm:ex,breaks:tx,pedantic:$b},ix={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},ax=e=>ix[e];function ox(e,t){if(t){if(Xy.escapeTest.test(e))return e.replace(Xy.escapeReplace,ax)}else if(Xy.escapeTestNoEncode.test(e))return e.replace(Xy.escapeReplaceNoEncode,ax);return e}function sx(e){try{e=encodeURI(e).replace(Xy.percentDecode,`%`)}catch{return null}return e}function cx(e,t){let n=e.replace(Xy.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(Xy.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``);for(;r<n.length;r++)n[r]=n[r].trim().replace(Xy.slashPipe,`|`);return n}function lx(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function ux(e){let t=e.split(`
|
|
2387
|
+
`),n=t.length-1;for(;n>=0&&Xy.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
|
|
2388
|
+
`)}function dx(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]===`\\`)r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function fx(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function px(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`);r.state.inLink=!0;let c={type:e[0].charAt(0)===`!`?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:r.inlineTokens(s)};return r.state.inLink=!1,c}function mx(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
2389
2389
|
`).map(e=>{let t=e.match(n.other.beginningSpace);if(t===null)return e;let[r]=t;return r.length>=i.length?e.slice(i.length):e}).join(`
|
|
2390
|
-
`)}var
|
|
2391
|
-
`),depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:
|
|
2392
|
-
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=
|
|
2390
|
+
`)}var hx=class{options;rules;lexer;constructor(e){this.options=e||Gy}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:`space`,raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let e=this.options.pedantic?t[0]:ux(t[0]);return{type:`code`,raw:e,codeBlockStyle:`indented`,text:e.replace(this.rules.other.codeRemoveIndent,``)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=mx(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=lx(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:lx(t[0],`
|
|
2391
|
+
`),depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:lx(t[0],`
|
|
2392
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=lx(t[0],`
|
|
2393
2393
|
`).split(`
|
|
2394
2394
|
`),n=``,r=``,i=[];for(;e.length>0;){let t=!1,a=[],o;for(o=0;o<e.length;o++)if(this.rules.other.blockquoteStart.test(e[o]))a.push(e[o]),t=!0;else if(!t)a.push(e[o]);else break;e=e.slice(o);let s=a.join(`
|
|
2395
2395
|
`),c=s.replace(this.rules.other.blockquoteSetextReplace,`
|
|
@@ -2400,20 +2400,20 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
2400
2400
|
`),o=this.blockquote(a);i[i.length-1]=o,n=n.substring(0,n.length-t.raw.length)+o.raw,r=r.substring(0,r.length-t.text.length)+o.text;break}else if(u?.type===`list`){let t=u,a=t.raw+`
|
|
2401
2401
|
`+e.join(`
|
|
2402
2402
|
`),o=this.list(a);i[i.length-1]=o,n=n.substring(0,n.length-u.raw.length)+o.raw,r=r.substring(0,r.length-t.raw.length)+o.raw,e=a.substring(i.at(-1).raw.length).split(`
|
|
2403
|
-
`);continue}}return{type:`blockquote`,raw:n,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,i={type:`list`,raw:``,ordered:r,start:r?+n.slice(0,-1):``,loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:`[*+-]`);let a=this.rules.other.listItemRegex(n),o=!1;for(;e;){let n=!1,r=``,s=``;if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;r=t[0],e=e.substring(r.length);let c=
|
|
2403
|
+
`);continue}}return{type:`blockquote`,raw:n,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,i={type:`list`,raw:``,ordered:r,start:r?+n.slice(0,-1):``,loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:`[*+-]`);let a=this.rules.other.listItemRegex(n),o=!1;for(;e;){let n=!1,r=``,s=``;if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;r=t[0],e=e.substring(r.length);let c=fx(t[2].split(`
|
|
2404
2404
|
`,1)[0],t[1].length),l=e.split(`
|
|
2405
2405
|
`,1)[0],u=!c.trim(),d=0;if(this.options.pedantic?(d=2,s=c.trimStart()):u?d=t[1].length+1:(d=c.search(this.rules.other.nonSpaceChar),d=d>4?1:d,s=c.slice(d),d+=t[1].length),u&&this.rules.other.blankLine.test(l)&&(r+=l+`
|
|
2406
2406
|
`,e=e.substring(l.length+1),n=!0),!n){let t=this.rules.other.nextBulletRegex(d),n=this.rules.other.hrRegex(d),i=this.rules.other.fencesBeginRegex(d),a=this.rules.other.headingBeginRegex(d),o=this.rules.other.htmlBeginRegex(d),f=this.rules.other.blockquoteBeginRegex(d);for(;e;){let p=e.split(`
|
|
2407
2407
|
`,1)[0],m;if(l=p,this.options.pedantic?(l=l.replace(this.rules.other.listReplaceNesting,` `),m=l):m=l.replace(this.rules.other.tabCharGlobal,` `),i.test(l)||a.test(l)||o.test(l)||f.test(l)||t.test(l)||n.test(l))break;if(m.search(this.rules.other.nonSpaceChar)>=d||!l.trim())s+=`
|
|
2408
2408
|
`+m.slice(d);else{if(u||c.replace(this.rules.other.tabCharGlobal,` `).search(this.rules.other.nonSpaceChar)>=4||i.test(c)||a.test(c)||n.test(c))break;s+=`
|
|
2409
2409
|
`+l}u=!l.trim(),r+=p+`
|
|
2410
|
-
`,e=e.substring(p.length+1),c=m.slice(d)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(o=!0)),i.items.push({type:`list_item`,raw:r,task:!!this.options.gfm&&this.rules.other.listIsTask.test(s),loose:!1,text:s,tokens:[]}),i.raw+=r}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let e of i.items){this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]);let t=e.tokens[0];if(e.task&&(t?.type===`text`||t?.type===`paragraph`)){e.text=e.text.replace(this.rules.other.listReplaceTask,``),t.raw=t.raw.replace(this.rules.other.listReplaceTask,``),t.text=t.text.replace(this.rules.other.listReplaceTask,``);for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,``);break}let n=this.rules.other.listTaskCheckbox.exec(e.raw);if(n){let t={type:`checkbox`,raw:n[0]+` `,checked:n[0]!==`[ ]`};e.checked=t.checked,i.loose?e.tokens[0]&&[`paragraph`,`text`].includes(e.tokens[0].type)&&`tokens`in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=t.raw+e.tokens[0].raw,e.tokens[0].text=t.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(t)):e.tokens.unshift({type:`paragraph`,raw:t.raw,text:t.raw,tokens:[t]}):e.tokens.unshift(t)}}else e.task&&=!1;if(!i.loose){let t=e.tokens.filter(e=>e.type===`space`);i.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}}if(i.loose)for(let e of i.items){e.loose=!0;for(let t of e.tokens)t.type===`text`&&(t.type=`paragraph`)}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let e=
|
|
2411
|
-
`),href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=
|
|
2412
|
-
`):[],a={type:`table`,raw:
|
|
2413
|
-
`),header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e<n.length;e++)a.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:a.align[e]});for(let e of i)a.rows.push(
|
|
2410
|
+
`,e=e.substring(p.length+1),c=m.slice(d)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(o=!0)),i.items.push({type:`list_item`,raw:r,task:!!this.options.gfm&&this.rules.other.listIsTask.test(s),loose:!1,text:s,tokens:[]}),i.raw+=r}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let e of i.items){this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]);let t=e.tokens[0];if(e.task&&(t?.type===`text`||t?.type===`paragraph`)){e.text=e.text.replace(this.rules.other.listReplaceTask,``),t.raw=t.raw.replace(this.rules.other.listReplaceTask,``),t.text=t.text.replace(this.rules.other.listReplaceTask,``);for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,``);break}let n=this.rules.other.listTaskCheckbox.exec(e.raw);if(n){let t={type:`checkbox`,raw:n[0]+` `,checked:n[0]!==`[ ]`};e.checked=t.checked,i.loose?e.tokens[0]&&[`paragraph`,`text`].includes(e.tokens[0].type)&&`tokens`in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=t.raw+e.tokens[0].raw,e.tokens[0].text=t.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(t)):e.tokens.unshift({type:`paragraph`,raw:t.raw,text:t.raw,tokens:[t]}):e.tokens.unshift(t)}}else e.task&&=!1;if(!i.loose){let t=e.tokens.filter(e=>e.type===`space`);i.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}}if(i.loose)for(let e of i.items){e.loose=!0;for(let t of e.tokens)t.type===`text`&&(t.type=`paragraph`)}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let e=ux(t[0]);return{type:`html`,block:!0,raw:e,pre:t[1]===`pre`||t[1]===`script`||t[1]===`style`,text:e}}}def(e){let t=this.rules.block.def.exec(e);if(t){let e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,` `),n=t[2]?t[2].replace(this.rules.other.hrefBrackets,`$1`).replace(this.rules.inline.anyPunctuation,`$1`):``,r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,`$1`):t[3];return{type:`def`,tag:e,raw:lx(t[0],`
|
|
2411
|
+
`),href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=cx(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
|
|
2412
|
+
`):[],a={type:`table`,raw:lx(t[0],`
|
|
2413
|
+
`),header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e<n.length;e++)a.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:a.align[e]});for(let e of i)a.rows.push(cx(e,a.header.length).map((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let e=t[1].trim();return{type:`heading`,raw:lx(t[0],`
|
|
2414
2414
|
`),depth:t[2].charAt(0)===`=`?1:2,text:e,tokens:this.lexer.inline(e)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let e=t[1].charAt(t[1].length-1)===`
|
|
2415
|
-
`?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:`text`,raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:`escape`,raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:`html`,raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=
|
|
2416
|
-
`),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){let t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(
|
|
2415
|
+
`?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:`text`,raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:`escape`,raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:`html`,raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=lx(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=dx(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let n=t[2],r=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):``;return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),px(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,`$1`),title:r&&r.replace(this.rules.inline.anyPunctuation,`$1`)},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `).toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return px(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=0,c=r[0][0]===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(r=c.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i)continue;if(a=[...i].length,r[3]||r[4]){o+=a;continue}else if((r[5]||r[6])&&n%3&&!((n+a)%3)){s+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o+s);let t=[...r[0]][0].length,c=e.slice(0,n+r.index+t+a);if(Math.min(n,a)%2){let e=c.slice(1,-1);return{type:`em`,raw:c,text:e,tokens:this.lexer.inlineTokens(e)}}let l=c.slice(2,-2);return{type:`strong`,raw:c,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e,t,n=``){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=this.rules.inline.delRDelim;for(s.lastIndex=0,t=t.slice(-1*e.length+n);(r=s.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(a=[...i].length,a!==n))continue;if(r[3]||r[4]){o+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o);let t=[...r[0]][0].length,s=e.slice(0,n+r.index+t+a),c=s.slice(n,-n);return{type:`del`,raw:s,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:t[0],escaped:e}}}},gx=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Gy,this.options.tokenizer=this.options.tokenizer||new hx,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:Xy,block:nx.normal,inline:rx.normal};this.options.pedantic?(t.block=nx.pedantic,t.inline=rx.pedantic):this.options.gfm&&(t.block=nx.gfm,this.options.breaks?t.inline=rx.breaks:t.inline=rx.gfm),this.tokenizer.rules=t}static get rules(){return{block:nx,inline:rx}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(Xy.carriageReturn,`
|
|
2416
|
+
`),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){let t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(Xy.tabCharGlobal,` `).replace(Xy.spaceLine,``));let r=1/0;for(;e;){if(e.length<r)r=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let i;if(this.options.extensions?.block?.some(n=>(i=n.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let n=t.at(-1);i.raw.length===1&&n!==void 0?n.raw+=`
|
|
2417
2417
|
`:t.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(`
|
|
2418
2418
|
`)?``:`
|
|
2419
2419
|
`)+i.raw,n.text+=`
|
|
@@ -2426,9 +2426,9 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
2426
2426
|
`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(i),n=a.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`text`?(n.raw+=(n.raw.endsWith(`
|
|
2427
2427
|
`)?``:`
|
|
2428
2428
|
`)+i.raw,n.text+=`
|
|
2429
|
-
`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e,r=null;if(this.tokens.links){let e=Object.keys(this.tokens.links);if(e.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!==null;)e.includes(r[0].slice(r[0].lastIndexOf(`[`)+1,-1))&&(n=n.slice(0,r.index)+`[`+`a`.repeat(r[0].length-2)+`]`+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!==null;)n=n.slice(0,r.index)+`++`+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!==null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+`[`+`a`.repeat(r[0].length-i-2)+`]`+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let a=!1,o=``,s=1/0;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}a||(o=``),a=!1;let r;if(this.options.extensions?.inline?.some(n=>(r=n.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.escape(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.tag(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.link(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(r.raw.length);let n=t.at(-1);r.type===`text`&&n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(r=this.tokenizer.emStrong(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.codespan(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.br(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.del(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.autolink(e)){e=e.substring(r.raw.length),t.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(e))){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(i=e.substring(0,t+1))}if(r=this.tokenizer.inlineText(i)){e=e.substring(r.raw.length),r.raw.slice(-1)!==`_`&&(o=r.raw.slice(-1)),a=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t=`Infinite loop on byte: `+e;if(this.options.silent)console.error(t);else throw Error(t)}},
|
|
2430
|
-
`;return r?`<pre><code class="language-`+
|
|
2431
|
-
`:`<pre><code>`+(n?i:
|
|
2429
|
+
`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e,r=null;if(this.tokens.links){let e=Object.keys(this.tokens.links);if(e.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(n))!==null;)e.includes(r[0].slice(r[0].lastIndexOf(`[`)+1,-1))&&(n=n.slice(0,r.index)+`[`+`a`.repeat(r[0].length-2)+`]`+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(n))!==null;)n=n.slice(0,r.index)+`++`+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let i;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(n))!==null;)i=r[2]?r[2].length:0,n=n.slice(0,r.index+i)+`[`+`a`.repeat(r[0].length-i-2)+`]`+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let a=!1,o=``,s=1/0;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}a||(o=``),a=!1;let r;if(this.options.extensions?.inline?.some(n=>(r=n.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.escape(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.tag(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.link(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(r.raw.length);let n=t.at(-1);r.type===`text`&&n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(r=this.tokenizer.emStrong(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.codespan(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.br(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.del(e,n,o)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.autolink(e)){e=e.substring(r.raw.length),t.push(r);continue}if(!this.state.inLink&&(r=this.tokenizer.url(e))){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(i=e.substring(0,t+1))}if(r=this.tokenizer.inlineText(i)){e=e.substring(r.raw.length),r.raw.slice(-1)!==`_`&&(o=r.raw.slice(-1)),a=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=r.raw,n.text+=r.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t=`Infinite loop on byte: `+e;if(this.options.silent)console.error(t);else throw Error(t)}},_x=class{options;parser;constructor(e){this.options=e||Gy}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(Xy.notSpaceStart)?.[0],i=e.replace(Xy.endingNewline,``)+`
|
|
2430
|
+
`;return r?`<pre><code class="language-`+ox(r)+`">`+(n?i:ox(i,!0))+`</code></pre>
|
|
2431
|
+
`:`<pre><code>`+(n?i:ox(i,!0))+`</code></pre>
|
|
2432
2432
|
`}blockquote({tokens:e}){return`<blockquote>
|
|
2433
2433
|
${this.parser.parse(e)}</blockquote>
|
|
2434
2434
|
`}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
@@ -2444,19 +2444,19 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
2444
2444
|
`}tablerow({text:e}){return`<tr>
|
|
2445
2445
|
${e}</tr>
|
|
2446
2446
|
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
2447
|
-
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${
|
|
2448
|
-
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+
|
|
2447
|
+
`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${ox(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=sx(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+ox(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=sx(e);if(i===null)return ox(n);e=i;let a=`<img src="${e}" alt="${ox(n)}"`;return t&&(a+=` title="${ox(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:ox(e.text)}},vx=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},yx=class e{options;renderer;textRenderer;constructor(e){this.options=e||Gy,this.options.renderer=this.options.renderer||new _x,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new vx}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},bx=class{options;block;constructor(e){this.options=e||Gy}static passThroughHooks=new Set([`preprocess`,`postprocess`,`processAllTokens`,`emStrongMask`]);static passThroughHooksRespectAsync=new Set([`preprocess`,`postprocess`,`processAllTokens`]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?gx.lex:gx.lexInline}provideParser(e=this.block){return e?yx.parse:yx.parseInline}},xx=new class{defaults=Wy();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=yx;Renderer=_x;TextRenderer=vx;Lexer=gx;Tokenizer=hx;Hooks=bx;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new _x(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new hx(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new bx;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];bx.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&bx.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:t[r]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return gx.lex(e,t??this.defaults)}parser(e,t){return yx.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?gx.lex:gx.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?yx.parse:yx.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?gx.lex:gx.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?yx.parse:yx.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
|
|
2448
|
+
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+ox(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function G(e,t){return xx.parse(e,t)}G.options=G.setOptions=function(e){return xx.setOptions(e),G.defaults=xx.defaults,Ky(G.defaults),G},G.getDefaults=Wy,G.defaults=Gy,G.use=function(...e){return xx.use(...e),G.defaults=xx.defaults,Ky(G.defaults),G},G.walkTokens=function(e,t){return xx.walkTokens(e,t)},G.parseInline=xx.parseInline,G.Parser=yx,G.parser=yx.parse,G.Renderer=_x,G.TextRenderer=vx,G.Lexer=gx,G.lexer=gx.lex,G.Tokenizer=hx,G.Hooks=bx,G.parse=G,G.options,G.setOptions,G.use,G.walkTokens,G.parseInline,yx.parse,gx.lex;var Sx=new G.Renderer;Sx.html=({text:e})=>Ex(e);var Cx=300,wx=new Map;function Tx(e){let t=wx.get(e);if(t!==void 0)return t;let n=Dx(G.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:Sx}));if(wx.set(e,n),wx.size>Cx){let e=wx.keys().next().value;e!==void 0&&wx.delete(e)}return n}function Ex(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}function Dx(e){let t=document.createElement(`template`);return t.innerHTML=e,t.content.querySelectorAll(`script, style, iframe, object, embed`).forEach(e=>{e.remove()}),t.content.querySelectorAll(`*`).forEach(e=>{for(let t of[...e.attributes]){let n=t.name.toLowerCase();n.startsWith(`on`)&&e.removeAttribute(t.name),(n===`href`||n===`src`)&&!Ox(t.value)&&e.removeAttribute(t.name)}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),t.innerHTML}function Ox(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}var kx=class extends y{constructor(...e){super(...e),this.text=``,this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`.code-copy-button`);if(!(t instanceof HTMLButtonElement))return;let n=t.closest(`.code-block-wrapper`);if(!(n instanceof HTMLElement))return;let r=n.querySelector(`pre code`);r instanceof HTMLElement&&this.copyCode(r.textContent,t)}}render(){return g`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${Uy(Tx(this.text))}</div>`}updated(){this.enhanceCodeBlocks()}enhanceCodeBlocks(){this.renderRoot.querySelectorAll(`pre`).forEach(e=>{if(!(e instanceof HTMLPreElement)||e.parentElement?.classList.contains(`code-block-wrapper`)===!0||!(e.querySelector(`code`)instanceof HTMLElement))return;let t=document.createElement(`div`);t.className=`code-block-wrapper`;let n=document.createElement(`button`);n.type=`button`,n.className=`code-copy-button`,n.title=`Copy code block`,n.setAttribute(`aria-label`,`Copy code block`);let r=document.createElement(`span`);r.setAttribute(`aria-hidden`,`true`),r.textContent=`⧉`,n.append(r),e.before(t),t.append(e,n)})}async copyCode(e,t){let n=await Uv(e);this.setCopyButtonState(t,n?`copied`:`failed`),window.setTimeout(()=>{this.setCopyButtonState(t,`idle`)},1200)}setCopyButtonState(e,t){let n=e.querySelector(`span`);n!==null&&(n.textContent=t===`copied`?`✓`:`⧉`);let r=t===`copied`?`Copied code block`:t===`failed`?`Failed to copy code block`:`Copy code block`;e.title=r,e.setAttribute(`aria-label`,r)}static{this.styles=Yp}};B([x()],kx.prototype,`text`,void 0),kx=B([b(`formatted-text`)],kx);var Ax=180,jx=class extends y{constructor(...e){super(...e),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){let e=this.execution;if(e===void 0)return null;let t=Nx(e.args),n=Fx(e.details),r=e.preview,i=n??r?.diff,a=i===void 0?void 0:Ix(i),o=n!==void 0&&r?.diff!==void 0&&n!==r.diff,s=e.status===`error`?e.resultText:r?.error,c=i===void 0?e.resultText:void 0,l=Mx(e,t);return g`
|
|
2449
2449
|
<section class=${`tool-card ${e.status}`}>
|
|
2450
2450
|
<div class="tool-header">
|
|
2451
2451
|
<div class="tool-title">
|
|
2452
|
-
<span class="status-icon" aria-hidden="true">${
|
|
2452
|
+
<span class="status-icon" aria-hidden="true">${Bx(e.status)}</span>
|
|
2453
2453
|
<strong>${e.toolName}</strong>
|
|
2454
2454
|
${this.renderHeaderTarget(l)}
|
|
2455
2455
|
</div>
|
|
2456
2456
|
<div class="tool-meta">
|
|
2457
|
-
${
|
|
2457
|
+
${Px(e)===void 0?null:g`<span>${Px(e)}</span>`}
|
|
2458
2458
|
${a===void 0?null:g`<span class="diff-stats"><b class="added">+${a.added}</b><span>/</span><b class="removed">-${a.removed}</b></span>`}
|
|
2459
|
-
<span class="status-label">${
|
|
2459
|
+
<span class="status-label">${Vx(e.status)}</span>
|
|
2460
2460
|
</div>
|
|
2461
2461
|
</div>
|
|
2462
2462
|
|
|
@@ -2481,7 +2481,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2481
2481
|
`}
|
|
2482
2482
|
</details>
|
|
2483
2483
|
`}renderDiffBody(e,t,n){let r=e.split(`
|
|
2484
|
-
`),i=!this.showFullDiff&&r.length>
|
|
2484
|
+
`),i=!this.showFullDiff&&r.length>Ax,a=i?r.slice(0,Ax):r;return g`
|
|
2485
2485
|
<details class="diff-details" ?open=${this.diffOpen} @toggle=${e=>{this.onDiffToggle(e)}}>
|
|
2486
2486
|
<summary>
|
|
2487
2487
|
<span>${t}</span>
|
|
@@ -2492,14 +2492,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2492
2492
|
<span>${i?`Showing ${String(a.length)} of ${String(r.length)} lines`:`Full diff`}</span>
|
|
2493
2493
|
<button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?`Copied`:`Copy diff`}</button>
|
|
2494
2494
|
</div>
|
|
2495
|
-
<pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${
|
|
2495
|
+
<pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${Lx(e)}>${e}</span>`)}</code></pre>
|
|
2496
2496
|
${i?g`
|
|
2497
2497
|
<button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
|
|
2498
2498
|
Show all ${String(r.length)} diff lines
|
|
2499
2499
|
</button>
|
|
2500
2500
|
`:null}
|
|
2501
2501
|
</details>
|
|
2502
|
-
`}onDiffToggle(e){let t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){if(!await
|
|
2502
|
+
`}onDiffToggle(e){let t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){if(!await Uv(e)){this.copied=!1;return}this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}static{this.styles=h`
|
|
2503
2503
|
:host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
|
|
2504
2504
|
.tool-card { display: grid; gap: 8px; width: 100%; max-width: 100%; min-width: 0; box-sizing: border-box; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); padding: 9px; color: var(--pi-text); }
|
|
2505
2505
|
.tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
|
|
@@ -2543,18 +2543,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2543
2543
|
.diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
|
|
2544
2544
|
.diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
|
|
2545
2545
|
.show-more { justify-self: start; }
|
|
2546
|
-
`}};B([x({attribute:!1})],
|
|
2547
|
-
`))
|
|
2546
|
+
`}};B([x({attribute:!1})],jx.prototype,`execution`,void 0),B([S()],jx.prototype,`showFullDiff`,void 0),B([S()],jx.prototype,`copied`,void 0),B([S()],jx.prototype,`diffOpen`,void 0),jx=B([b(`tool-execution-view`)],jx);function Mx(e,t){if(t!==void 0&&t!==``)return{label:`File`,text:t};let n=Wx(e.args,`command`);if(n!==void 0&&n!==``)return{label:`Command`,text:n};if(e.summary!==``)return{label:`Input`,text:e.summary}}function Nx(e){return Wx(e,`path`)??Wx(e,`file_path`)}function Px(e){if(e.toolName!==`edit`)return;let t=Ux(e.args,`edits`);if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?``:`s`}`;if(typeof Ux(e.args,`oldText`)==`string`&&typeof Ux(e.args,`newText`)==`string`)return`1 edit`}function Fx(e){return Wx(e,`diff`)}function Ix(e){let t=0,n=0;for(let r of e.split(`
|
|
2547
|
+
`))Rx(r)?t++:zx(r)&&n++;return{added:t,removed:n}}function Lx(e){return Rx(e)?`added`:zx(e)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`+++`)||e.startsWith(`---`)?`file`:e.startsWith(`diff `)||e.startsWith(`index `)?`meta`:`context`}function Rx(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)}function zx(e){return e.startsWith(`-`)&&!e.startsWith(`---`)}function Bx(e){return e===`success`?`✓`:e===`error`?`✖`:e===`running`?`●`:`○`}function Vx(e){return e===`success`?`done`:e===`error`?`failed`:e===`running`?`running`:`pending`}function Hx(e){return typeof e==`object`&&!!e}function Ux(e,t){return Hx(e)?e[t]:void 0}function Wx(e,t){let n=Ux(e,t);return typeof n==`string`?n:void 0}var Gx=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`medium`}),Kx=new Intl.DateTimeFormat(void 0,{timeStyle:`short`});function qx(e){return g`
|
|
2548
2548
|
<svg class=${`notification-icon notification-disclosure-icon${e?``:` expanded`}`} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2549
2549
|
<path d="m9 18 6-6-6-6"></path>
|
|
2550
2550
|
</svg>
|
|
2551
|
-
`}function
|
|
2551
|
+
`}function Jx(){return g`
|
|
2552
2552
|
<svg class="notification-icon notification-close-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2553
2553
|
<path d="M6 6l12 12"></path>
|
|
2554
2554
|
<path d="M18 6 6 18"></path>
|
|
2555
2555
|
</svg>
|
|
2556
|
-
`}function
|
|
2557
|
-
`)}function
|
|
2556
|
+
`}function Yx(e){return typeof e==`object`&&!!e&&typeof Reflect.get(e,`machineId`)==`string`&&typeof Reflect.get(e,`cwd`)==`string`&&typeof Reflect.get(e,`sessionId`)==`string`}function Xx(e){return Zx(e,0,100)}function Zx(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function Qx(e,t){return[e.length===0?void 0:{source:`client`,heading:`Queued until session starts`,detail:`Will send once the backend session is ready`,messages:e},t.length===0?void 0:{source:`server`,heading:`Queued messages`,detail:`${String(t.length)} pending`,messages:t}].filter(e=>e!==void 0)}function $x(e){return{src:`data:${e.mimeType};base64,${e.data}`,alt:`attached image`}}function eS(e){return e===void 0||e===``?`tool output`:`${e} output`}function tS(e){return`m:${String(e)}`}function nS(e){return`g:${String(e)}`}function rS(e){return`e:${String(e)}`}function iS(e){return`g:${String(e)}`}function aS(e){return e?`msg event-group live`:`msg event-group`}function oS(e){return e?`live events`:`events`}function sS(e,t,n){return e.source===`server`&&t&&n}function cS(e){return(e?.warnings??[]).map(e=>({severity:e.severity,severityClass:`session-warning ${e.severity}`,message:e.message,...e.source===void 0?{}:{source:e.source},...e.path===void 0?{}:{path:e.path},...e.dismiss===void 0?{}:{dismissId:e.dismiss.id}}))}function lS(e){return e>=50?`generation-rate very-fast`:e>=30?`generation-rate fast`:e>=15?`generation-rate moderate`:`generation-rate slow`}function uS(e){if(e===void 0)return{afterStatus:[],trailing:[]};let t=e.contextUsage,n=t?t.percent==null?`context ${Ny(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Ny(t.contextWindow)}`:`context unknown`,r=e.generation;return{afterStatus:!e.isStreaming||r===void 0||!Number.isFinite(r.outputTokens)||r.outputTokens<=0?[]:[{label:r.estimated===!0?`Estimated received tokens`:`Received tokens`,text:`↓ ${Ny(r.outputTokens)}`},...r.tokensPerSecond===void 0||!Number.isFinite(r.tokensPerSecond)||r.tokensPerSecond<=0?[]:[{label:r.estimated===!0?`Estimated generation speed`:`Generation speed`,text:`${r.tokensPerSecond.toFixed(1)} t/s`,className:lS(r.tokensPerSecond)}]],trailing:[{label:`Input tokens`,text:`↑${Ny(e.tokens.input)}`},{label:`Output tokens`,text:`↓${Ny(e.tokens.output)}`},{label:`Context usage`,text:n},{label:`Session cost`,text:Py(e.cost)},...e.pendingMessageCount>0?[{label:`Queued messages`,text:`${String(e.pendingMessageCount)} queued`}]:[]]}}function dS(e,t){if(!Number.isInteger(e)||e<=0)return;let n=`${String(e)} ${e===1?`warning`:`warnings`}`;return{countText:String(e),accessibleLabel:t?`Minimise ${n}`:`Show ${n} in the warning area`}}function fS(e){let t=e.meta?.timestamp,n=[t===void 0?void 0:hS(t),gS(e)].filter(e=>e!==void 0&&e!==``);return n.length===0?`No Pi message metadata available`:n.join(` · `)}function pS(e,t){return!t.enabled||t.busy||e.role!==`user`?{}:{...e.previousAssistantEntryId===void 0?{}:{editFromHereEntryId:e.previousAssistantEntryId},...e.canFork===!0&&e.entryId!==void 0?{forkEntryId:e.entryId}:{}}}function mS(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2557
|
+
`)}function hS(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return Gx.format(t)}function gS(e){let t=e.meta?.model;if(t===void 0)return;let n=t.responseId??t.id;return n===void 0||n===``?t.provider:t.provider!==void 0&&t.provider!==``?`${t.provider}/${n}`:n}var K=class extends y{constructor(...e){super(...e),this.messages=[],this.sessionId=``,this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.clientQueuedMessages=[],this.warningCount=0,this.warningsExpanded=!1,this.canClearServerQueue=!1,this.canMessageActions=!1,this.warningsVisible=!0,this.pinnedToBottom=!0,this.zoomedImage=void 0,this.collapsedNotificationTargetKeys=new Set,this.disclosures=new Mv,this.scrollController=new my,this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageMetaCache=new WeakMap,this.messageCopyTextCache=new WeakMap,this.lastScrollTop=0,this.lastClientHeight=0,this.prependRestoreToken=0,this.loadMoreRequested=!1,this.sessionInfoOpen=!1,this._minimapMarkers=[],this._minimapViewport={scrollRatio:0,viewportRatio:1,visible:!1},this._minimapLoadedPercent=100,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.onImageLoad=()=>{this.pinnedToBottom&&this.scrollToBottom()},this.openImageZoom=(e,t)=>{this.zoomedImage={src:e,alt:t}},this.closeImageZoom=()=>{this.zoomedImage!==void 0&&(this.zoomedImage=void 0)},this.onImageZoomDialogClick=e=>{e.target===this.imageZoomDialog&&this.closeImageZoom()},this.onPageHide=()=>{this.saveScrollPosition()},this.handleClearServerQueue=()=>{this.onClearServerQueue?.()},this.handleToggleWarnings=()=>{this.onToggleWarnings?.()},this.handleUsageToggle=()=>{this.sessionInfoOpen=!this.sessionInfoOpen},this.handleUsageKeydown=e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),this.sessionInfoOpen=!this.sessionInfoOpen)},this.closeSessionInfoPopover=()=>{this.sessionInfoOpen&&(this.sessionInfoOpen=!1,this.removePopoverOutsideListener(),this.requestUpdate())},this.handlePopoverKeydown=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.closeSessionInfoPopover(),this.focusUsageToggle())},this.onPopoverGlobalClick=e=>{this.handlePopoverClickOutside(e)},this.popoverGlobalListenerAttached=!1}focusUsageToggle(){this.renderRoot!==void 0&&this.renderRoot.querySelector(`.usage-toggle`)?.focus()}handlePopoverClickOutside(e){let t=this.renderRoot.querySelector(`.session-info-popover`),n=this.renderRoot.querySelector(`.usage-toggle`);if(t===null||n===null)return;let r=e.target;r instanceof Node&&!t.contains(r)&&!n.contains(r)&&this.closeSessionInfoPopover()}ensurePopoverOutsideListener(){this.popoverGlobalListenerAttached||typeof window>`u`||(this.popoverGlobalListenerAttached=!0,window.addEventListener(`click`,this.onPopoverGlobalClick,!0))}removePopoverOutsideListener(){this.popoverGlobalListenerAttached&&(this.popoverGlobalListenerAttached=!1,!(typeof window>`u`)&&window.removeEventListener(`click`,this.onPopoverGlobalClick,!0))}connectedCallback(){super.connectedCallback(),window.addEventListener(`resize`,this.onViewportResize),window.addEventListener(`pagehide`,this.onPageHide),window.visualViewport?.addEventListener(`resize`,this.onViewportResize),this._setupResizeObserver()}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}_setupResizeObserver(){if(this._resizeObserver!==void 0)return;let e=this.chat;e&&(this._resizeObserver=new ResizeObserver(()=>{this._requestMinimapMeasure()}),this._resizeObserver.observe(e))}disconnectedCallback(){this.removePopoverOutsideListener(),this.saveScrollPosition(),this.scrollController.dispose(),this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.loadMoreCheckFrame!==void 0&&cancelAnimationFrame(this.loadMoreCheckFrame),this.scrollToBottomFrame!==void 0&&cancelAnimationFrame(this.scrollToBottomFrame),this.conversationRailFrame!==void 0&&cancelAnimationFrame(this.conversationRailFrame),this._minimapMeasureTimer!==void 0&&(clearTimeout(this._minimapMeasureTimer),this._minimapMeasureTimer=void 0),this._resizeObserver!==void 0&&(this._resizeObserver.disconnect(),this._resizeObserver=void 0),window.removeEventListener(`resize`,this.onViewportResize),window.removeEventListener(`pagehide`,this.onPageHide),window.visualViewport?.removeEventListener(`resize`,this.onViewportResize),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!=`string`||e===``||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.disclosures.syncSession(this.sessionId),this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0,this.sessionInfoOpen=!1,this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this._minimapMarkers=[],this._minimapViewport={scrollRatio:0,viewportRatio:1,visible:!1},this._minimapLoadedPercent=100,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0)}willUpdate(e){e.has(`sessionId`)?(this.savePreviousSessionScrollPosition(e.get(`sessionId`)),this.prepareSessionUiState()):e.has(`notificationInbox`)&&this.notificationTargetChanged(e.get(`notificationInbox`))&&(this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0),e.has(`messages`)&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){let t=this.isPrependingMessages(e)?this.capturePrependScrollAnchor():void 0;super.update(e),t!==void 0&&this.restorePrependScrollAnchor(t)}updated(e){e.has(`loadingMore`)&&!this.loadingMore&&(this.loadMoreRequested=!1),e.has(`hasMore`)&&!this.hasMore&&(this.loadMoreRequested=!1),e.has(`sessionId`)&&this.restoreScrollPosition(),!e.has(`sessionId`)&&e.has(`messages`)&&this.pinnedToBottom&&this.scrollToBottom(),(e.has(`messages`)||e.has(`messageStart`)||e.has(`messageTotal`)||e.has(`hasMore`)||e.has(`loadingMore`))&&(this.scheduleConversationRailUpdate(),this._requestMinimapMeasure()),e.has(`messages`)&&!e.has(`sessionId`)&&this._updateMinimapViewport(),(e.has(`messages`)||e.has(`messageStart`)||e.has(`hasMore`)||e.has(`loadingMore`))&&this.continuePendingScrollRestore(),(e.has(`messages`)||e.has(`hasMore`)||e.has(`loadingMore`))&&this.requestLoadMoreIfNeeded(),e.has(`notificationInbox`)&&this.pendingNotificationFocus!==void 0&&this.focusPendingNotificationTarget(),e.has(`zoomedImage`)&&this.syncImageZoomDialog(),this.syncPopoverOutsideListener()}syncPopoverOutsideListener(){this.sessionInfoOpen?this.ensurePopoverOutsideListener():this.removePopoverOutsideListener()}syncImageZoomDialog(){let e=this.imageZoomDialog;e!==void 0&&(this.zoomedImage!==void 0&&!e.open?e.showModal():this.zoomedImage===void 0&&e.open&&e.close())}notificationTargetChanged(e){let t=this.notificationInbox;return!Yx(e)||t===void 0?e!==t:hd(e)!==hd(t)}render(){let e=this.groupedMessages();return g`
|
|
2558
2558
|
${this.renderTopNotices()}
|
|
2559
2559
|
${this.renderNotificationLiveRegions()}
|
|
2560
2560
|
<div class="chat-wrap" style=${this._minimapViewport.visible?`--pi-minimap-right:36px`:``}>
|
|
@@ -2589,7 +2589,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2589
2589
|
aria-expanded=${String(!a)}
|
|
2590
2590
|
aria-controls="session-notification-list"
|
|
2591
2591
|
@click=${()=>{this.toggleNotificationTray(e,a)}}
|
|
2592
|
-
>${
|
|
2592
|
+
>${qx(a)}</button>
|
|
2593
2593
|
</div>
|
|
2594
2594
|
</header>
|
|
2595
2595
|
<div class="notification-list" id="session-notification-list" ?hidden=${a}>
|
|
@@ -2601,7 +2601,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2601
2601
|
<div class="notification-metadata">
|
|
2602
2602
|
<strong class="notification-severity">${n}</strong>
|
|
2603
2603
|
<span aria-hidden="true">·</span>
|
|
2604
|
-
<time datetime=${t.receivedAt}>${
|
|
2604
|
+
<time datetime=${t.receivedAt}>${Kx.format(new Date(t.receivedAt))}</time>
|
|
2605
2605
|
</div>
|
|
2606
2606
|
<p class="notification-message" dir="auto">${t.message}</p>
|
|
2607
2607
|
${r===void 0?null:g`<p class="notification-truncated">${r}</p>`}
|
|
@@ -2612,7 +2612,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2612
2612
|
title="Dismiss notification"
|
|
2613
2613
|
?disabled=${e.pendingDismissedIds.has(t.id)||e.dismissAllPending||this.onDismissNotification===void 0}
|
|
2614
2614
|
@click=${()=>{this.dismissNotification(t.id)}}
|
|
2615
|
-
>${
|
|
2615
|
+
>${Jx()}</button>
|
|
2616
2616
|
</article>
|
|
2617
2617
|
`})}
|
|
2618
2618
|
</div>
|
|
@@ -2620,7 +2620,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2620
2620
|
`}renderNotificationLiveRegions(){let e=this.notificationInbox?.sessionId===this.sessionId?this.notificationInbox.announcements:[],t=e.filter(e=>e.severity!==`error`),n=e.filter(e=>e.severity===`error`);return g`
|
|
2621
2621
|
<div class="visually-hidden notification-live" aria-live="polite" aria-atomic="false">${P_(t,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${ud(e)}</span>`)}</div>
|
|
2622
2622
|
<div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${P_(n,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${ud(e)}</span>`)}</div>
|
|
2623
|
-
`}toggleNotificationTray(e,t){this.collapsedNotificationTargetKeys=_d(this.collapsedNotificationTargetKeys,e,!t)}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=md(t.notifications,e),r=hd(t);this.pendingNotificationFocus={chatKey:r,focusTarget:n},n.kind===`header`&&(this.retainedEmptyNotificationTrayTargetKey=r),this.onDismissNotification(e)}dismissAllNotifications(){let e=this.notificationInbox;if(e===void 0||this.onDismissAllNotifications===void 0)return;let t=hd(e);this.pendingNotificationFocus={chatKey:t,focusTarget:{kind:`header`}},this.retainedEmptyNotificationTrayTargetKey=t,this.onDismissAllNotifications()}releaseEmptyNotificationTray(e){let t=e.currentTarget,n=e.relatedTarget;if(t instanceof HTMLElement&&n instanceof Node&&t.contains(n)||this.pendingNotificationFocus!==void 0)return;let r=this.notificationInbox;r!==void 0&&this.retainedEmptyNotificationTrayTargetKey===hd(r)&&dd(r)===0&&(this.retainedEmptyNotificationTrayTargetKey=void 0)}focusPendingNotificationTarget(){let e=this.pendingNotificationFocus;this.pendingNotificationFocus=void 0;let t=this.notificationInbox;if(e===void 0||t===void 0||hd(t)!==e.chatKey)return;let n=e.focusTarget;if(n.kind===`header`){this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus();return}let r=Array.from(this.renderRoot.querySelectorAll(`[data-notification-id]`)).find(e=>e.dataset.notificationId===n.notificationId);if(r!==void 0){r.focus();return}dd(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}renderWarnings(){let e=
|
|
2623
|
+
`}toggleNotificationTray(e,t){this.collapsedNotificationTargetKeys=_d(this.collapsedNotificationTargetKeys,e,!t)}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=md(t.notifications,e),r=hd(t);this.pendingNotificationFocus={chatKey:r,focusTarget:n},n.kind===`header`&&(this.retainedEmptyNotificationTrayTargetKey=r),this.onDismissNotification(e)}dismissAllNotifications(){let e=this.notificationInbox;if(e===void 0||this.onDismissAllNotifications===void 0)return;let t=hd(e);this.pendingNotificationFocus={chatKey:t,focusTarget:{kind:`header`}},this.retainedEmptyNotificationTrayTargetKey=t,this.onDismissAllNotifications()}releaseEmptyNotificationTray(e){let t=e.currentTarget,n=e.relatedTarget;if(t instanceof HTMLElement&&n instanceof Node&&t.contains(n)||this.pendingNotificationFocus!==void 0)return;let r=this.notificationInbox;r!==void 0&&this.retainedEmptyNotificationTrayTargetKey===hd(r)&&dd(r)===0&&(this.retainedEmptyNotificationTrayTargetKey=void 0)}focusPendingNotificationTarget(){let e=this.pendingNotificationFocus;this.pendingNotificationFocus=void 0;let t=this.notificationInbox;if(e===void 0||t===void 0||hd(t)!==e.chatKey)return;let n=e.focusTarget;if(n.kind===`header`){this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus();return}let r=Array.from(this.renderRoot.querySelectorAll(`[data-notification-id]`)).find(e=>e.dataset.notificationId===n.notificationId);if(r!==void 0){r.focus();return}dd(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}renderWarnings(){let e=cS(this.status);return!this.warningsVisible||e.length===0?null:g`
|
|
2624
2624
|
<aside class="session-warnings" role="alert" aria-live="polite">
|
|
2625
2625
|
${e.map(e=>{let t=e.dismissId;return g`
|
|
2626
2626
|
<div class=${e.severityClass}>
|
|
@@ -2644,7 +2644,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2644
2644
|
</div>
|
|
2645
2645
|
`})}
|
|
2646
2646
|
</aside>
|
|
2647
|
-
`}renderSessionInfoPopover(){if(!this.sessionInfoOpen)return null;let e=this.status;if(e===void 0)return null;let t=this.messages.length>0?
|
|
2647
|
+
`}renderSessionInfoPopover(){if(!this.sessionInfoOpen)return null;let e=this.status;if(e===void 0)return null;let t=this.messages.length>0?zy(this.messages):void 0,n=By(e,this.sessionInfo,t);return g`
|
|
2648
2648
|
<section
|
|
2649
2649
|
class="session-info-popover"
|
|
2650
2650
|
id=${`session-info-popover-${this.sessionId}`}
|
|
@@ -2694,14 +2694,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2694
2694
|
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
|
|
2695
2695
|
</svg>
|
|
2696
2696
|
</button>
|
|
2697
|
-
`}async copySessionValue(e){await
|
|
2697
|
+
`}async copySessionValue(e){await Uv(e)}renderImageZoom(){return g`
|
|
2698
2698
|
<dialog class="image-zoom" @click=${this.onImageZoomDialogClick} @close=${this.closeImageZoom} @cancel=${this.closeImageZoom}>
|
|
2699
2699
|
${this.zoomedImage===void 0?null:g`
|
|
2700
2700
|
<button type="button" class="image-zoom-close" aria-label="Close image" @click=${this.closeImageZoom}>×</button>
|
|
2701
2701
|
<img class="image-zoom-full" src=${this.zoomedImage.src} alt=${this.zoomedImage.alt} />
|
|
2702
2702
|
`}
|
|
2703
2703
|
</dialog>
|
|
2704
|
-
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=
|
|
2704
|
+
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Rv(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase===`active`}renderActivityDock(){if(this.isSendingPrompt)return this.renderActivityDockContent(`Sending your message…`,!0);let e=this.activityState();return e===void 0?null:this.renderActivityDockContent(this.activityText(e),e!==`idle`||this.activity?.phase===`active`)}renderActivityDockContent(e,t){let n=uS(this.status),r=dS(this.warningCount,this.warningsExpanded),i=n.trailing.length>0,a=this.status?Ry(this.status):``,o=i?`session-info-popover-${this.sessionId}`:void 0;return g`
|
|
2705
2705
|
<div class=${t?`activity-dock active`:`activity-dock`}>
|
|
2706
2706
|
${r===void 0||this.onToggleWarnings===void 0?null:g`
|
|
2707
2707
|
<button
|
|
@@ -2744,7 +2744,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2744
2744
|
`:null}
|
|
2745
2745
|
${this.renderSessionInfoPopover()}
|
|
2746
2746
|
</div>
|
|
2747
|
-
`}renderActivityMetrics(e){return e.map(e=>g`<span class=${e.className===void 0?`activity-metric`:`activity-metric ${e.className}`} title=${e.label}>${e.text}</span>`)}renderQueuedMessages(){let e=this.status?.queuedMessages??[];return g`${
|
|
2747
|
+
`}renderActivityMetrics(e){return e.map(e=>g`<span class=${e.className===void 0?`activity-metric`:`activity-metric ${e.className}`} title=${e.label}>${e.text}</span>`)}renderQueuedMessages(){let e=this.status?.queuedMessages??[];return g`${Qx(this.clientQueuedMessages,e).map(e=>this.renderQueuedMessageList(e))}`}renderQueuedMessageList(e){let t=sS(e,this.canClearServerQueue,this.onClearServerQueue!==void 0);return g`
|
|
2748
2748
|
<aside class="queued-messages" aria-live="polite">
|
|
2749
2749
|
<div class="queued-header">
|
|
2750
2750
|
<div class="queued-heading">
|
|
@@ -2768,7 +2768,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2768
2768
|
<span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
|
|
2769
2769
|
${this.pendingMessageCount>0?g`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?`message`:`messages`}</small>`:null}
|
|
2770
2770
|
</aside>
|
|
2771
|
-
`:null}activityState(){let e=this.status;return e===void 0?this.activity?.label:e.isCompacting?`compacting`:e.isBashRunning?`bash`:e.isStreaming?`running`:e.pendingMessageCount>0?`queued`:`idle`}activityText(e){let t=this.activity;return t===void 0||e!==`idle`&&t.phase===`idle`?e:t.detail!==void 0&&t.detail!==``?`${t.label}: ${t.detail}`:t.label}renderConversationRail(){return!this.messages.length||this.messageTotal<=0?null:(this._minimapLoadedPercent=this.hasMore?
|
|
2771
|
+
`:null}activityState(){let e=this.status;return e===void 0?this.activity?.label:e.isCompacting?`compacting`:e.isBashRunning?`bash`:e.isStreaming?`running`:e.pendingMessageCount>0?`queued`:`idle`}activityText(e){let t=this.activity;return t===void 0||e!==`idle`&&t.phase===`idle`?e:t.detail!==void 0&&t.detail!==``?`${t.label}: ${t.detail}`:t.label}renderConversationRail(){return!this.messages.length||this.messageTotal<=0?null:(this._minimapLoadedPercent=this.hasMore?Xx(this.messages.length/this.conversationDisplayTotal()*100):100,g`
|
|
2772
2772
|
<chat-minimap
|
|
2773
2773
|
.scrollRatio=${this._minimapViewport.scrollRatio}
|
|
2774
2774
|
.viewportRatio=${this._minimapViewport.viewportRatio}
|
|
@@ -2777,7 +2777,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2777
2777
|
.markers=${this._minimapMarkers}
|
|
2778
2778
|
@minimap-scroll-to=${e=>{this._onMinimapScrollTo(e)}}
|
|
2779
2779
|
></chat-minimap>
|
|
2780
|
-
`)}conversationDisplayTotal(){return!this.hasMore&&this.messageStart===0?Math.max(1,this.messages.length):Math.max(1,this.messageTotal,this.messageStart+this.messages.length)}conversationPositionPercent(e=this.conversationDisplayTotal()){if(e<=1)return 100;let t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart;return Zx(
|
|
2780
|
+
`)}conversationDisplayTotal(){return!this.hasMore&&this.messageStart===0?Math.max(1,this.messages.length):Math.max(1,this.messageTotal,this.messageStart+this.messages.length)}conversationPositionPercent(e=this.conversationDisplayTotal()){if(e<=1)return 100;let t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart;return Xx(Zx(this.currentConversationIndex??t,0,e-1)/(e-1)*100)}renderHistoryBoundary(){let e=this.historyRangeLabel();return this.loadingMore?g`<div class="history-boundary"><span>Loading earlier messages…</span>${e}</div>`:this.hasMore?g`
|
|
2781
2781
|
<div class="history-boundary">
|
|
2782
2782
|
<button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>Load earlier messages</button>
|
|
2783
2783
|
<span>Scroll up to load earlier messages</span>
|
|
@@ -2789,7 +2789,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2789
2789
|
${n?null:this.renderMessageHeader(e,String(t))}
|
|
2790
2790
|
${e.parts.map(t=>this.renderPart(t,e))}
|
|
2791
2791
|
</article>
|
|
2792
|
-
`}renderToolImageOutput(e,t,n){let r=
|
|
2792
|
+
`}renderToolImageOutput(e,t,n){let r=eS(n);return g`
|
|
2793
2793
|
${this.renderScrollMarker(this.messageScrollMarkerId(t))}
|
|
2794
2794
|
<article class="msg tool-image-output" data-index=${t} data-scroll-anchor-id=${this.messageAnchorKey(t)}>
|
|
2795
2795
|
${this.renderMessageHeader(e,String(t),r)}
|
|
@@ -2797,10 +2797,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2797
2797
|
</article>
|
|
2798
2798
|
`}isToolExecutionOnlyMessage(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`toolExecution`)}renderMessageGroup(e,t,n,r){let i=this.groupDisclosureKey(t,n,r),a=this.disclosures.isOpen(i,r);return g`
|
|
2799
2799
|
${this.renderScrollMarker(this.groupScrollMarkerId(n))}
|
|
2800
|
-
<details class=${
|
|
2800
|
+
<details class=${aS(r)} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${a} @toggle=${e=>{this.onGroupToggle(i,e,r)}}>
|
|
2801
2801
|
<summary>
|
|
2802
|
-
<b class="label">${
|
|
2803
|
-
<span>${
|
|
2802
|
+
<b class="label">${oS(r)}</b>
|
|
2803
|
+
<span>${zv(e)}</span>
|
|
2804
2804
|
</summary>
|
|
2805
2805
|
${a?this.renderMessageGroupBody(e,t):null}
|
|
2806
2806
|
</details>
|
|
@@ -2821,7 +2821,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2821
2821
|
<span class=${i?`msg-meta expanded`:`msg-meta`} role="button" tabindex="0" title=${r} aria-label=${r} aria-expanded=${String(i)} @click=${()=>{this.expandedMetaKey=i?void 0:t}} @keydown=${e=>{this.onMetaKeydown(e,t,i)}}>${r}</span>
|
|
2822
2822
|
</div>
|
|
2823
2823
|
</div>
|
|
2824
|
-
`}renderMessageActions(e,t){let n=this.isCopyableMessage(e),r=
|
|
2824
|
+
`}renderMessageActions(e,t){let n=this.isCopyableMessage(e),r=pS(e,{enabled:this.canMessageActions,busy:this.messageActionsBusy()}),i=this.onEditFromHere===void 0?void 0:r.editFromHereEntryId,a=this.onForkFromHere===void 0?void 0:r.forkEntryId;if(!n&&i===void 0&&a===void 0)return null;let o=this.copiedMessageKey===t,s=a!==void 0&&this.forkingEntryId===a;return g`
|
|
2825
2825
|
<div class=${`msg-actions${s?` forking`:``}`} aria-label="Message actions">
|
|
2826
2826
|
${n?g`
|
|
2827
2827
|
<button type="button" class="msg-action" title=${o?`Copied`:`Copy message`} aria-label=${`${o?`Copied`:`Copy`} ${e.role} message`} @click=${n=>{this.copyMessage(e,t,n)}}>
|
|
@@ -2829,7 +2829,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2829
2829
|
</button>
|
|
2830
2830
|
`:null}
|
|
2831
2831
|
${i===void 0?null:g`
|
|
2832
|
-
<button type="button" class="msg-action msg-history-action" data-message-action="edit-from-here" title="Edit from here — branches within this session" @click=${()=>{this.editFromHere(i,
|
|
2832
|
+
<button type="button" class="msg-action msg-history-action" data-message-action="edit-from-here" title="Edit from here — branches within this session" @click=${()=>{this.editFromHere(i,mS(e))}}>
|
|
2833
2833
|
<svg class="msg-history-action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
2834
2834
|
<polyline points="15 10 20 15 15 20"></polyline>
|
|
2835
2835
|
<path d="M4 4v7a4 4 0 0 0 4 4h12"></path>
|
|
@@ -2851,7 +2851,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2851
2851
|
</div>
|
|
2852
2852
|
`}messageActionsBusy(){return this.isSendingPrompt||this.isCompacting||this.status?.isStreaming===!0||this.status?.isBashRunning===!0||this.status?.isCompacting===!0||(this.status?.pendingMessageCount??this.pendingMessageCount)>0}async editFromHere(e,t){await this.onEditFromHere?.(e,t)}async forkFromHere(e){if(this.forkingEntryId===void 0){this.forkingEntryId=e;try{await this.onForkFromHere?.(e)}finally{this.forkingEntryId===e&&(this.forkingEntryId=void 0)}}}onMetaKeydown(e,t,n){e.key!==`Enter`&&e.key!==` `||(e.preventDefault(),this.expandedMetaKey=n?void 0:t)}isCopyableMessage(e){return(e.role===`user`||e.role===`assistant`)&&this.messageCopyText(e)!==``}messageCopyText(e){let t=this.messageCopyTextCache.get(e);if(t!==void 0)return t;let n=e.parts.filter(e=>e.type===`text`).map(e=>e.text.trim()).filter(e=>e!==``).join(`
|
|
2853
2853
|
|
|
2854
|
-
`);return this.messageCopyTextCache.set(e,n),n}async copyMessage(e,t,n){n.stopPropagation(),await
|
|
2854
|
+
`);return this.messageCopyTextCache.set(e,n),n}async copyMessage(e,t,n){n.stopPropagation(),await Uv(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}messageMetaLabel(e){let t=this.messageMetaCache.get(e);if(t!==void 0)return t;let n=fS(e);return this.messageMetaCache.set(e,n),n}renderPart(e,t){if(e.type===`text`&&t?.role===`bash`)return g`<pre class="part shell-output">${e.text}</pre>`;if(e.type===`text`)return g`<formatted-text class="part" .text=${e.text}></formatted-text>`;if(e.type===`thinking`)return g`<details class="part"><summary>thinking</summary><formatted-text .text=${e.text}></formatted-text></details>`;if(e.type===`skillInvocation`)return g`
|
|
2855
2855
|
<details class="part skill-invocation">
|
|
2856
2856
|
<summary><b>[skill]</b> ${e.name}</summary>
|
|
2857
2857
|
<small>${e.location}</small>
|
|
@@ -2862,58 +2862,58 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2862
2862
|
<strong>Loaded ${e.name}</strong>
|
|
2863
2863
|
<small>read ${e.path}</small>
|
|
2864
2864
|
</div>
|
|
2865
|
-
`;if(e.type===`image`){let{src:t,alt:n}
|
|
2865
|
+
`;if(e.type===`image`){let{src:t,alt:n}=$x(e);return g`<img class="part chat-image" src=${t} alt=${n} loading="lazy" role="button" tabindex="0" title="Click to enlarge" @load=${this.onImageLoad} @click=${()=>{this.openImageZoom(t,n)}} @keydown=${e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),this.openImageZoom(t,n))}} />`}return e.type===`toolCall`?g`<div class="part tool-line">▶ ${e.toolName}<span class="summary">${e.summary}</span></div>`:e.type===`toolExecution`?g`<tool-execution-view class="part" .execution=${e}></tool-execution-view>`:e.type===`toolResult`?g`
|
|
2866
2866
|
<details class="part" ?open=${e.isError}>
|
|
2867
2867
|
<summary>${e.isError?`✖`:`✓`} ${e.toolName} result</summary>
|
|
2868
2868
|
<formatted-text .text=${e.text}></formatted-text>
|
|
2869
2869
|
</details>
|
|
2870
|
-
`:null}onGroupToggle(e,t,n){let r=t.currentTarget;r instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,r.open,n)&&this.requestUpdate()}onScroll(){this.requestLoadMoreIfNeeded(),this.updatePinnedToBottomFromScroll(),this.scheduleConversationRailUpdate(),this._updateMinimapViewport(),this.suppressScrollSave||this.scheduleScrollPositionSave()}onWheel(e){e.deltaY<0&&this.canScrollUp()&&(this.pinnedToBottom=!1)}onTouchStart(e){this.touchStartY=e.touches[0]?.clientY}onTouchMove(e){let t=e.touches[0]?.clientY;this.touchStartY!==void 0&&t!==void 0&&t>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){let e=this.chat;if(!e)return;let t=this.didChatHeightChange(),n=this.pinnedToBottom,r=e.scrollTop<this.lastScrollTop;if(t&&n){this.lastClientHeight=e.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:r?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight}didChatHeightChange(){let e=this.chat;return e!==void 0&&this.lastClientHeight!==0&&e.clientHeight!==this.lastClientHeight}isPrependingMessages(e){let t=e.get(`messageStart`);return typeof t==`number`&&this.messageStart<t}requestLoadMoreIfNeeded(){this.loadMoreCheckFrame===void 0&&(this.loadMoreCheckFrame=requestAnimationFrame(()=>{if(this.loadMoreCheckFrame=void 0,this.suppressLoadMoreRequests)return;let e=this.chat;e&&oy({hasMore:this.hasMore,loadingMore:this.loadingMore||this.loadMoreRequested,canRequest:this.onLoadMore!==void 0,scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})&&this.requestLoadMore()}))}requestLoadMore(){this.loadMoreRequested||!this.hasMore||this.loadingMore||this.onLoadMore===void 0||(this.loadMoreRequested=!0,this.onLoadMore())}isNearBottom(){let e=this.chat;return!e||by(e)}isAtBottom(){let e=this.chat;return!e||yy(e)<2}canScrollUp(){let e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;let e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}restoreScrollPosition(){let e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{let t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){let e=this.pendingScrollRestoreSessionId,t=this.pendingScrollRestorePosition;e===void 0||t===void 0||e!==this.sessionId||this.restoreScrollFrame!==void 0||(this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{let n=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,n)})}))}handleScrollRestoreResult(e,t){if(this.syncScrollMetrics(),t.status!==`missing`){this.updatePinnedToBottomAfterRestore(t.status),(t.status===`restored`||t.status===`bottom`)&&this.cancelPrependRestore(),this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0;return}this.pinnedToBottom=!1,this.pendingScrollRestoreSessionId=e,this.pendingScrollRestorePosition=t.position;let n=this.chat;n===void 0||!this.hasMore||this.loadingMore||(n.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore}updatePinnedToBottomAfterRestore(e){e===`bottom`?this.pinnedToBottom=!0:e===`restored`&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){let e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){let e=this.chat;if(e)return Qv(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;let t=this.prependRestoreToken+1;this.prependRestoreToken=t;let n=0,r=()=>{let i=this.chat;if(!(!i||t!==this.prependRestoreToken)){if($v(i,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=i.scrollTop,n+=1,n<30){requestAnimationFrame(r);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};r()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){let e=this.sessionId;this.scrollController.scheduleSave(e,e=>{this.sessionId===e&&this.saveScrollPosition(e)})}scheduleConversationRailUpdate(){this.conversationRailFrame===void 0&&(this.conversationRailFrame=requestAnimationFrame(()=>{this.conversationRailFrame=void 0,this.updateConversationRailPosition()}))}updateConversationRailPosition(){if(!this.messages.length||this.messageTotal<=0){this.currentConversationIndex=void 0;return}let e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),n=Number(t?.dataset.index);if(Number.isFinite(n)){this.currentConversationIndex=Qx(n,0,Math.max(0,e-1));return}this.currentConversationIndex=Qx(this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,0,Math.max(0,e-1))}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(`.scroll-marker`))}scrollMarkerAt(e){return this.scrollMarkers().find(t=>t.dataset.markerId===e)}firstVisibleArticle(){let e=this.chat;if(e!==void 0)return Cy(e,Array.from(this.renderRoot.querySelectorAll(`article.msg`)))??Cy(e,this.articles())}articles(){return Array.from(this.renderRoot.querySelectorAll(`article.msg, details.msg`))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll(`[data-scroll-anchor-id]`))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,n){return n?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return nS(e)}groupRenderKey(e){return rS(e)}groupAnchorKey(e){return rS(e)}eventAnchorKey(e){return iS(e)}messageScrollMarkerId(e){return nS(e)}groupScrollMarkerId(e){return aS(e)}_updateMinimapViewport(){let e=this.chat;e&&(this._minimapViewport=Ey({scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,scrollTop:e.scrollTop}),this._minimapLoadedPercent=this.hasMore?Zx(this.messages.length/this.conversationDisplayTotal()*100):100)}_requestMinimapMeasure(){this._minimapMeasureTimer===void 0&&(this._minimapMeasureTimer=setTimeout(()=>{this._minimapMeasureTimer=void 0,this._measureMinimapMarkers(),this._updateMinimapViewport()},150))}_measureMinimapMarkers(){let e=this.chat;if(!e||!this.messages.length){this._minimapMarkers=[];return}let t=e.getBoundingClientRect(),n=e.scrollHeight;if(n<=0){this._minimapMarkers=[];return}let r=this.renderRoot.querySelectorAll(`article.msg.user, article.msg.assistant`),i=[];for(let a of r){let r=a.dataset.index;if(r===void 0)continue;let o=Number(r);if(!Number.isFinite(o))continue;let s=o-this.messageStart;if(s<0||s>=this.messages.length)continue;let c=this.messages[s];if(c===void 0)continue;let l=this._minimapMessagePreview(c);if(!l)continue;let u=ky(a.getBoundingClientRect().top,t.top,e.scrollTop,n);if(c.role!==`user`&&c.role!==`assistant`)continue;let d=c.role;i.push({topRatio:u,role:d,preview:l})}this._minimapMarkers=i}_minimapMessagePreview(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text.trim()).filter(e=>e!==``).join(` `).slice(0,200)}_onMinimapScrollTo(e){let t=Ny(e.detail);if(t===void 0)return;let n=this.chat;if(!n)return;let r=n.scrollHeight-n.clientHeight;r<=0||(n.scrollTop=Dy(t/(1-this._minimapViewport.viewportRatio))*r,this.pinnedToBottom=by(n))}static{this.styles=Jp}};B([x({attribute:!1})],G.prototype,`messages`,void 0),B([x()],G.prototype,`sessionId`,void 0),B([x({type:Number})],G.prototype,`messageStart`,void 0),B([x({type:Number})],G.prototype,`messageEnd`,void 0),B([x({type:Number})],G.prototype,`messageTotal`,void 0),B([x({type:Boolean})],G.prototype,`hasMore`,void 0),B([x({type:Boolean})],G.prototype,`loadingMore`,void 0),B([x({type:Boolean})],G.prototype,`isSendingPrompt`,void 0),B([x({type:Boolean})],G.prototype,`isCompacting`,void 0),B([x({type:Number})],G.prototype,`pendingMessageCount`,void 0),B([x({attribute:!1})],G.prototype,`clientQueuedMessages`,void 0),B([x({attribute:!1})],G.prototype,`status`,void 0),B([x({type:Number})],G.prototype,`warningCount`,void 0),B([x({type:Boolean})],G.prototype,`warningsExpanded`,void 0),B([x({attribute:!1})],G.prototype,`onToggleWarnings`,void 0),B([x({attribute:!1})],G.prototype,`activity`,void 0),B([x({attribute:!1})],G.prototype,`sessionInfo`,void 0),B([x({attribute:!1})],G.prototype,`notificationInbox`,void 0),B([x({type:Boolean})],G.prototype,`canClearServerQueue`,void 0),B([x({type:Boolean})],G.prototype,`canMessageActions`,void 0),B([x({attribute:!1})],G.prototype,`onEditFromHere`,void 0),B([x({attribute:!1})],G.prototype,`onForkFromHere`,void 0),B([x({attribute:!1})],G.prototype,`onClearServerQueue`,void 0),B([x({attribute:!1})],G.prototype,`onDismissWarning`,void 0),B([x({attribute:!1})],G.prototype,`onDismissNotification`,void 0),B([x({attribute:!1})],G.prototype,`onDismissAllNotifications`,void 0),B([x({type:Boolean})],G.prototype,`warningsVisible`,void 0),B([x({attribute:!1})],G.prototype,`onLoadMore`,void 0),B([C(`.chat`)],G.prototype,`chat`,void 0),B([C(`dialog.image-zoom`)],G.prototype,`imageZoomDialog`,void 0),B([S()],G.prototype,`pinnedToBottom`,void 0),B([S()],G.prototype,`zoomedImage`,void 0),B([S()],G.prototype,`expandedMetaKey`,void 0),B([S()],G.prototype,`copiedMessageKey`,void 0),B([S()],G.prototype,`forkingEntryId`,void 0),B([S()],G.prototype,`currentConversationIndex`,void 0),B([S()],G.prototype,`collapsedNotificationTargetKeys`,void 0),B([S()],G.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),B([S()],G.prototype,`loadMoreRequested`,void 0),B([S()],G.prototype,`sessionInfoOpen`,void 0),B([S()],G.prototype,`_minimapMarkers`,void 0),B([S()],G.prototype,`_minimapViewport`,void 0),G=B([b(`chat-view`)],G);var vS=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function yS(e){return typeof e==`string`&&vS.has(e)}function bS(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 xS=`application/octet-stream`,SS=`Failed to read an attachment.`;async function CS(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(DS(i,e))}catch{r=SS}return{attachments:n,...r===void 0?{}:{error:r}}}function wS(e){return e.kind===`image`&&yS(e.mimeType)}function TS(e){return e.every(e=>wS(e))}function ES(e,t){return TS(t)?e:`folder`}function DS(e,t){return yS(e.type)?{kind:`image`,name:kS(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:kS(e),mimeType:OS(e),data:t,size:e.size}}function OS(e){let t=e.type.trim();return t===``?xS:t}function kS(e){return e.name===``?yS(e.type)?`pasted-image.${bS(e.type)}`:`pasted-file.bin`:e.name}var AS=`pi-webui:attachment-delivery`;function jS(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function MS(e=jS()){try{return e?.getItem(AS)===`folder`?`folder`:`inline`}catch{return`inline`}}function NS(e,t=jS()){try{t?.setItem(AS,e)}catch{}}var PS=`(pointer: coarse), (max-width: 760px)`,FS=`pi-webui.promptEnterPreference`;function IS(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(PS):void 0}function LS(e){return e===`send`||e===`newline`?e:`auto`}function RS(e=US()){if(e===void 0)return`auto`;try{return LS(e.getItem(FS))}catch{return`auto`}}function zS(e,t=US()){if(t!==void 0)try{t.setItem(FS,e)}catch{}}function BS(e=IS(),t=RS()){return t===`send`||t!==`newline`&&e?.matches!==!0}function VS(e,t,n=IS()){return e?n?.matches!==!0||t:!1}function HS(e,t=IS(),n=RS()){let r=BS(t,n);return e?!r:r}function US(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function WS(){return _`
|
|
2870
|
+
`:null}onGroupToggle(e,t,n){let r=t.currentTarget;r instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,r.open,n)&&this.requestUpdate()}onScroll(){this.requestLoadMoreIfNeeded(),this.updatePinnedToBottomFromScroll(),this.scheduleConversationRailUpdate(),this._updateMinimapViewport(),this.suppressScrollSave||this.scheduleScrollPositionSave()}onWheel(e){e.deltaY<0&&this.canScrollUp()&&(this.pinnedToBottom=!1)}onTouchStart(e){this.touchStartY=e.touches[0]?.clientY}onTouchMove(e){let t=e.touches[0]?.clientY;this.touchStartY!==void 0&&t!==void 0&&t>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){let e=this.chat;if(!e)return;let t=this.didChatHeightChange(),n=this.pinnedToBottom,r=e.scrollTop<this.lastScrollTop;if(t&&n){this.lastClientHeight=e.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:r?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight}didChatHeightChange(){let e=this.chat;return e!==void 0&&this.lastClientHeight!==0&&e.clientHeight!==this.lastClientHeight}isPrependingMessages(e){let t=e.get(`messageStart`);return typeof t==`number`&&this.messageStart<t}requestLoadMoreIfNeeded(){this.loadMoreCheckFrame===void 0&&(this.loadMoreCheckFrame=requestAnimationFrame(()=>{if(this.loadMoreCheckFrame=void 0,this.suppressLoadMoreRequests)return;let e=this.chat;e&&ay({hasMore:this.hasMore,loadingMore:this.loadingMore||this.loadMoreRequested,canRequest:this.onLoadMore!==void 0,scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})&&this.requestLoadMore()}))}requestLoadMore(){this.loadMoreRequested||!this.hasMore||this.loadingMore||this.onLoadMore===void 0||(this.loadMoreRequested=!0,this.onLoadMore())}isNearBottom(){let e=this.chat;return!e||yy(e)}isAtBottom(){let e=this.chat;return!e||vy(e)<2}canScrollUp(){let e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;let e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}restoreScrollPosition(){let e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{let t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){let e=this.pendingScrollRestoreSessionId,t=this.pendingScrollRestorePosition;e===void 0||t===void 0||e!==this.sessionId||this.restoreScrollFrame!==void 0||(this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{let n=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,n)})}))}handleScrollRestoreResult(e,t){if(this.syncScrollMetrics(),t.status!==`missing`){this.updatePinnedToBottomAfterRestore(t.status),(t.status===`restored`||t.status===`bottom`)&&this.cancelPrependRestore(),this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0;return}this.pinnedToBottom=!1,this.pendingScrollRestoreSessionId=e,this.pendingScrollRestorePosition=t.position;let n=this.chat;n===void 0||!this.hasMore||this.loadingMore||(n.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore}updatePinnedToBottomAfterRestore(e){e===`bottom`?this.pinnedToBottom=!0:e===`restored`&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){let e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){let e=this.chat;if(e)return Zv(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;let t=this.prependRestoreToken+1;this.prependRestoreToken=t;let n=0,r=()=>{let i=this.chat;if(!(!i||t!==this.prependRestoreToken)){if(Qv(i,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=i.scrollTop,n+=1,n<30){requestAnimationFrame(r);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};r()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){let e=this.sessionId;this.scrollController.scheduleSave(e,e=>{this.sessionId===e&&this.saveScrollPosition(e)})}scheduleConversationRailUpdate(){this.conversationRailFrame===void 0&&(this.conversationRailFrame=requestAnimationFrame(()=>{this.conversationRailFrame=void 0,this.updateConversationRailPosition()}))}updateConversationRailPosition(){if(!this.messages.length||this.messageTotal<=0){this.currentConversationIndex=void 0;return}let e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),n=Number(t?.dataset.index);if(Number.isFinite(n)){this.currentConversationIndex=Zx(n,0,Math.max(0,e-1));return}this.currentConversationIndex=Zx(this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,0,Math.max(0,e-1))}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(`.scroll-marker`))}scrollMarkerAt(e){return this.scrollMarkers().find(t=>t.dataset.markerId===e)}firstVisibleArticle(){let e=this.chat;if(e!==void 0)return Sy(e,Array.from(this.renderRoot.querySelectorAll(`article.msg`)))??Sy(e,this.articles())}articles(){return Array.from(this.renderRoot.querySelectorAll(`article.msg, details.msg`))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll(`[data-scroll-anchor-id]`))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,n){return n?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return tS(e)}groupRenderKey(e){return nS(e)}groupAnchorKey(e){return nS(e)}eventAnchorKey(e){return rS(e)}messageScrollMarkerId(e){return tS(e)}groupScrollMarkerId(e){return iS(e)}_updateMinimapViewport(){let e=this.chat;e&&(this._minimapViewport=Ty({scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,scrollTop:e.scrollTop}),this._minimapLoadedPercent=this.hasMore?Xx(this.messages.length/this.conversationDisplayTotal()*100):100)}_requestMinimapMeasure(){this._minimapMeasureTimer===void 0&&(this._minimapMeasureTimer=setTimeout(()=>{this._minimapMeasureTimer=void 0,this._measureMinimapMarkers(),this._updateMinimapViewport()},150))}_measureMinimapMarkers(){let e=this.chat;if(!e||!this.messages.length){this._minimapMarkers=[];return}let t=e.getBoundingClientRect(),n=e.scrollHeight;if(n<=0){this._minimapMarkers=[];return}let r=this.renderRoot.querySelectorAll(`article.msg.user, article.msg.assistant`),i=[];for(let a of r){let r=a.dataset.index;if(r===void 0)continue;let o=Number(r);if(!Number.isFinite(o))continue;let s=o-this.messageStart;if(s<0||s>=this.messages.length)continue;let c=this.messages[s];if(c===void 0)continue;let l=this._minimapMessagePreview(c);if(!l)continue;let u=Oy(a.getBoundingClientRect().top,t.top,e.scrollTop,n);if(c.role!==`user`&&c.role!==`assistant`)continue;let d=c.role;i.push({topRatio:u,role:d,preview:l})}this._minimapMarkers=i}_minimapMessagePreview(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text.trim()).filter(e=>e!==``).join(` `).slice(0,200)}_onMinimapScrollTo(e){let t=My(e.detail);if(t===void 0)return;let n=this.chat;if(!n)return;let r=n.scrollHeight-n.clientHeight;r<=0||(n.scrollTop=Ey(t/(1-this._minimapViewport.viewportRatio))*r,this.pinnedToBottom=yy(n))}static{this.styles=Jp}};B([x({attribute:!1})],K.prototype,`messages`,void 0),B([x()],K.prototype,`sessionId`,void 0),B([x({type:Number})],K.prototype,`messageStart`,void 0),B([x({type:Number})],K.prototype,`messageEnd`,void 0),B([x({type:Number})],K.prototype,`messageTotal`,void 0),B([x({type:Boolean})],K.prototype,`hasMore`,void 0),B([x({type:Boolean})],K.prototype,`loadingMore`,void 0),B([x({type:Boolean})],K.prototype,`isSendingPrompt`,void 0),B([x({type:Boolean})],K.prototype,`isCompacting`,void 0),B([x({type:Number})],K.prototype,`pendingMessageCount`,void 0),B([x({attribute:!1})],K.prototype,`clientQueuedMessages`,void 0),B([x({attribute:!1})],K.prototype,`status`,void 0),B([x({type:Number})],K.prototype,`warningCount`,void 0),B([x({type:Boolean})],K.prototype,`warningsExpanded`,void 0),B([x({attribute:!1})],K.prototype,`onToggleWarnings`,void 0),B([x({attribute:!1})],K.prototype,`activity`,void 0),B([x({attribute:!1})],K.prototype,`sessionInfo`,void 0),B([x({attribute:!1})],K.prototype,`notificationInbox`,void 0),B([x({type:Boolean})],K.prototype,`canClearServerQueue`,void 0),B([x({type:Boolean})],K.prototype,`canMessageActions`,void 0),B([x({attribute:!1})],K.prototype,`onEditFromHere`,void 0),B([x({attribute:!1})],K.prototype,`onForkFromHere`,void 0),B([x({attribute:!1})],K.prototype,`onClearServerQueue`,void 0),B([x({attribute:!1})],K.prototype,`onDismissWarning`,void 0),B([x({attribute:!1})],K.prototype,`onDismissNotification`,void 0),B([x({attribute:!1})],K.prototype,`onDismissAllNotifications`,void 0),B([x({type:Boolean})],K.prototype,`warningsVisible`,void 0),B([x({attribute:!1})],K.prototype,`onLoadMore`,void 0),B([C(`.chat`)],K.prototype,`chat`,void 0),B([C(`dialog.image-zoom`)],K.prototype,`imageZoomDialog`,void 0),B([S()],K.prototype,`pinnedToBottom`,void 0),B([S()],K.prototype,`zoomedImage`,void 0),B([S()],K.prototype,`expandedMetaKey`,void 0),B([S()],K.prototype,`copiedMessageKey`,void 0),B([S()],K.prototype,`forkingEntryId`,void 0),B([S()],K.prototype,`currentConversationIndex`,void 0),B([S()],K.prototype,`collapsedNotificationTargetKeys`,void 0),B([S()],K.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),B([S()],K.prototype,`loadMoreRequested`,void 0),B([S()],K.prototype,`sessionInfoOpen`,void 0),B([S()],K.prototype,`_minimapMarkers`,void 0),B([S()],K.prototype,`_minimapViewport`,void 0),K=B([b(`chat-view`)],K);var _S=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function vS(e){return typeof e==`string`&&_S.has(e)}function yS(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 bS=`application/octet-stream`,xS=`Failed to read an attachment.`;async function SS(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(ES(i,e))}catch{r=xS}return{attachments:n,...r===void 0?{}:{error:r}}}function CS(e){return e.kind===`image`&&vS(e.mimeType)}function wS(e){return e.every(e=>CS(e))}function TS(e,t){return wS(t)?e:`folder`}function ES(e,t){return vS(e.type)?{kind:`image`,name:OS(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:OS(e),mimeType:DS(e),data:t,size:e.size}}function DS(e){let t=e.type.trim();return t===``?bS:t}function OS(e){return e.name===``?vS(e.type)?`pasted-image.${yS(e.type)}`:`pasted-file.bin`:e.name}var kS=`pi-webui:attachment-delivery`;function AS(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function jS(e=AS()){try{return e?.getItem(kS)===`folder`?`folder`:`inline`}catch{return`inline`}}function MS(e,t=AS()){try{t?.setItem(kS,e)}catch{}}var NS=`(pointer: coarse), (max-width: 760px)`,PS=`pi-webui.promptEnterPreference`;function FS(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(NS):void 0}function IS(e){return e===`send`||e===`newline`?e:`auto`}function LS(e=HS()){if(e===void 0)return`auto`;try{return IS(e.getItem(PS))}catch{return`auto`}}function RS(e,t=HS()){if(t!==void 0)try{t.setItem(PS,e)}catch{}}function zS(e=FS(),t=LS()){return t===`send`||t!==`newline`&&e?.matches!==!0}function BS(e,t,n=FS()){return e?n?.matches!==!0||t:!1}function VS(e,t=FS(),n=LS()){let r=zS(t,n);return e?!r:r}function HS(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function US(){return _`
|
|
2871
2871
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2872
2872
|
<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>
|
|
2873
2873
|
</svg>
|
|
2874
|
-
`}function
|
|
2874
|
+
`}function WS(){return _`
|
|
2875
2875
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2876
2876
|
<polyline points="4 14 10 14 10 20"></polyline>
|
|
2877
2877
|
<polyline points="20 10 14 10 14 4"></polyline>
|
|
2878
2878
|
<line x1="10" y1="14" x2="3" y2="21"></line>
|
|
2879
2879
|
<line x1="21" y1="3" x2="14" y2="10"></line>
|
|
2880
2880
|
</svg>
|
|
2881
|
-
`}function
|
|
2881
|
+
`}function GS(){return _`
|
|
2882
2882
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2883
2883
|
<path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
|
|
2884
2884
|
<path d="M21 3 11.5 12.5"></path>
|
|
2885
2885
|
</svg>
|
|
2886
|
-
`}function
|
|
2886
|
+
`}function KS(){return _`
|
|
2887
2887
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2888
2888
|
<path d="M4 7h11"></path>
|
|
2889
2889
|
<path d="M4 12h7"></path>
|
|
2890
2890
|
<path d="M4 17h7"></path>
|
|
2891
2891
|
<path d="m15 14 5 3-5 3z"></path>
|
|
2892
2892
|
</svg>
|
|
2893
|
-
`}function
|
|
2893
|
+
`}function qS(){return GS()}function JS(){return _`
|
|
2894
2894
|
<svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2895
2895
|
<rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
|
|
2896
2896
|
</svg>
|
|
2897
|
-
`}function
|
|
2897
|
+
`}function YS(e){let t=Math.max(e.total,1),n=t>1?1.2:0,r=(18-n*(t-1))/t;return _`
|
|
2898
2898
|
<svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2899
2899
|
${Array.from({length:t},(i,a)=>{let o=3+a*(r+n),s=4+(a+1)/t*12,c=20-s;return _`<rect class=${a<e.filled?`gauge-bar gauge-bar-active`:`gauge-bar`} x=${o} y=${c} width=${r} height=${s} rx="1"></rect>`})}
|
|
2900
2900
|
</svg>
|
|
2901
|
-
`}var
|
|
2901
|
+
`}var XS=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function ZS(e){return e===void 0||e===``?`off`:e}function QS(e,t){let n=t.length>=2?t:XS,r=n.length-1,i=ZS(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}var $S=S_(class extends C_{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===x_.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&&t.scrollIntoView({block:`nearest`})})}this.wasSelected=t,this.previousKey=n}render(e,t){}}),eC=class extends y{constructor(...e){super(...e),this.items=[],this.selectedIndex=0}render(){return this.items.length?g`
|
|
2902
2902
|
<div class="menu">
|
|
2903
2903
|
${this.items.map((e,t)=>g`
|
|
2904
|
-
<button class=${t===this.selectedIndex?`selected`:``} ${
|
|
2904
|
+
<button class=${t===this.selectedIndex?`selected`:``} ${$S(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
|
|
2905
2905
|
<strong>${e.insertText}</strong>
|
|
2906
2906
|
<span>${e.detail}</span>
|
|
2907
2907
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
2908
2908
|
</button>
|
|
2909
2909
|
`)}
|
|
2910
2910
|
</div>
|
|
2911
|
-
`:null}static{this.styles=Xp}};B([x({attribute:!1})],
|
|
2911
|
+
`:null}static{this.styles=Xp}};B([x({attribute:!1})],eC.prototype,`items`,void 0),B([x({type:Number})],eC.prototype,`selectedIndex`,void 0),B([x({attribute:!1})],eC.prototype,`onPick`,void 0),eC=B([b(`autocomplete-menu`)],eC);var q=class extends y{constructor(...e){super(...e),this.disabled=!1,this.machineId=`local`,this.workspaceScopedFileSuggestions=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.showSessionConfiguration=!1,this.availableThinkingLevels=[],this.draft=``,this.currentInputMode={kind:`normal`},this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=jS(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new s,this.readOnlyCompartment=new s,this.mobilePromptEnterMedia=FS(),this.explicitShiftKeyActive=!1}willUpdate(e){if(!e.has(`sessionId`)&&!e.has(`machineId`))return;let t=e.has(`sessionId`)?e.get(`sessionId`):this.sessionId,n=nC(e.has(`machineId`)?e.get(`machineId`):this.machineId,t);n!==void 0&&Vc(n,this.draft);let r=nC(this.machineId,this.sessionId);this.draft=r===void 0?``:Bc(r),this.currentInputMode=Yl(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has(`status`)&&e.size===1?!tC(e.get(`status`),this.status):!0}firstUpdated(){this.createEditor()}updated(e){e.has(`disabled`)&&this.updateEditorDisabledState(),(e.has(`sessionId`)||e.has(`machineId`))&&this.syncEditorDoc()}disconnectedCallback(){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.disabled||this.sending,i=r||this.canSteer||this.isCompacting||this.canStop;return g`
|
|
2912
2912
|
<footer class=${t?`shell-mode`:``} @paste=${e=>{this.handlePaste(e)}} @dragover=${e=>{this.handleDragOver(e)}} @drop=${e=>{this.handleDrop(e)}}>
|
|
2913
2913
|
<div class="editor-wrap">
|
|
2914
2914
|
<div class=${`markdown-editor${this.disabled?` markdown-editor-disabled`:``}`} aria-label="Message pi" aria-disabled=${this.disabled?`true`:`false`}></div>
|
|
2915
2915
|
<input class="attachment-input" type="file" multiple hidden @change=${e=>{this.handleFileInput(e)}} />
|
|
2916
|
-
<button class="editor-attach icon-button" ?disabled=${r} title="Attach files" aria-label="Attach files" @click=${()=>{this.attachmentInput?.click()}}>${
|
|
2916
|
+
<button class="editor-attach icon-button" ?disabled=${r} title="Attach files" aria-label="Attach files" @click=${()=>{this.attachmentInput?.click()}}>${US()}</button>
|
|
2917
2917
|
${t?g`<div class="mode-hint">Shell command${e.excludeFromContext?` · excluded from context`:``}</div>`:null}
|
|
2918
2918
|
${this.isCompacting&&!t?g`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
|
|
2919
2919
|
${this.renderAttachments()}
|
|
@@ -2921,21 +2921,21 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2921
2921
|
</div>
|
|
2922
2922
|
<div class="actions">
|
|
2923
2923
|
${this.renderCompactStatus()}
|
|
2924
|
-
${this.onCompact===void 0?null:g`<button class="compact-button" ?disabled=${i} title="Compact context" aria-label="Compact context" @click=${()=>this.onCompact?.()}>${
|
|
2925
|
-
<button class="icon-button send-button" ?disabled=${r} title=${n?`Queue until the current activity finishes`:`Send message`} aria-label=${n?`Queue message`:`Send message`} @click=${()=>{this.send(`followUp`)}}>${n?
|
|
2926
|
-
${this.canSteer&&!this.isCompacting?g`<button class="icon-button steer-button" ?disabled=${r} title="Steer the current response before the next model call" aria-label="Steer current response" @click=${()=>{this.send(`steer`)}}>${
|
|
2927
|
-
<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?.()}>${
|
|
2924
|
+
${this.onCompact===void 0?null:g`<button class="compact-button" ?disabled=${i} title="Compact context" aria-label="Compact context" @click=${()=>this.onCompact?.()}>${WS()}<span>Compact</span></button>`}
|
|
2925
|
+
<button class="icon-button send-button" ?disabled=${r} title=${n?`Queue until the current activity finishes`:`Send message`} aria-label=${n?`Queue message`:`Send message`} @click=${()=>{this.send(`followUp`)}}>${n?KS():GS()}</button>
|
|
2926
|
+
${this.canSteer&&!this.isCompacting?g`<button class="icon-button steer-button" ?disabled=${r} title="Steer the current response before the next model call" aria-label="Steer current response" @click=${()=>{this.send(`steer`)}}>${qS()}</button>`:null}
|
|
2927
|
+
<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?.()}>${JS()}</button>
|
|
2928
2928
|
</div>
|
|
2929
2929
|
</footer>
|
|
2930
|
-
`}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=
|
|
2930
|
+
`}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=nC(this.machineId,this.sessionId);t!==void 0&&Vc(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:i.cursor(e.length)})}this.requestVersion+=1,this.currentInputMode=Yl(e),this.completions=[],this.selectedIndex=0}get view(){return this.editor}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=t?.model?.id??(e?`Choose default model`:`no model`),r=t?.model?.provider!==void 0&&t.model.provider!==``?`${t.model.provider}/`:``,i=e?`Default thinking level: ${ZS(t?.thinkingLevel)}`:`Thinking level: ${ZS(t?.thinkingLevel)}`;return g`
|
|
2931
2931
|
<div class="compact-status" aria-label=${e?`Session defaults`:`Session status`}>
|
|
2932
2932
|
<button class="select-model" ?disabled=${this.onSelectModel===void 0} title="Select model" @click=${()=>this.onSelectModel?.()}>${r}${n}</button>
|
|
2933
|
-
<button class="select-thinking icon-button" ?disabled=${this.onSelectThinking===void 0} title=${i} aria-label=${i} @click=${()=>this.onSelectThinking?.()}>${
|
|
2933
|
+
<button class="select-thinking icon-button" ?disabled=${this.onSelectThinking===void 0} title=${i} aria-label=${i} @click=${()=>this.onSelectThinking?.()}>${YS(QS(t?.thinkingLevel,this.availableThinkingLevels))}</button>
|
|
2934
2934
|
</div>
|
|
2935
|
-
`}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=
|
|
2935
|
+
`}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=wS(this.attachments),t=this.effectiveAttachmentDelivery();return g`
|
|
2936
2936
|
<div class="attachments" aria-label="Pending attachments">
|
|
2937
2937
|
${this.attachments.map(e=>g`
|
|
2938
|
-
<div class=${`attachment-chip ${
|
|
2938
|
+
<div class=${`attachment-chip ${CS(e)?`attachment-chip-image`:`attachment-chip-file`}`} title=${e.name}>
|
|
2939
2939
|
${this.renderAttachmentPreview(e)}
|
|
2940
2940
|
<button type="button" class="attachment-remove" title="Remove attachment" aria-label=${`Remove ${e.name}`} @click=${()=>{this.removeAttachment(e.id)}}>×</button>
|
|
2941
2941
|
</div>
|
|
@@ -2950,10 +2950,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2950
2950
|
`:null}
|
|
2951
2951
|
${this.attachmentError===void 0?null:g`<div class="attachment-error">${this.attachmentError}</div>`}
|
|
2952
2952
|
</div>
|
|
2953
|
-
`}renderAttachmentPreview(e){return
|
|
2954
|
-
<div class="attachment-file-preview" aria-hidden="true">${
|
|
2953
|
+
`}renderAttachmentPreview(e){return CS(e)?g`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:g`
|
|
2954
|
+
<div class="attachment-file-preview" aria-hidden="true">${cC(e.name)}</div>
|
|
2955
2955
|
<span class="attachment-file-name">${e.name}</span>
|
|
2956
|
-
`}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;if(t===`inline`&&!
|
|
2956
|
+
`}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;if(t===`inline`&&!wS(this.attachments)){e.target.value=`folder`;return}this.attachmentDelivery=t,MS(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){let t=aC(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&oC(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=aC(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(!(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){this.attachmentError=void 0;let{attachments:t,error:n}=await SS(e,lC);t.length>0&&(this.attachments=[...this.attachments,...t.map(e=>({id:`attachment-${String(++this.attachmentSeq)}`,...e}))]),n!==void 0&&(this.attachmentError=n)}currentAttachments(){return this.attachments.map(e=>sC(e))}effectiveAttachmentDelivery(){return TS(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new p({parent:this.editorHost,state:e.create({doc:this.draft,extensions:[m(),ne(),t(),u.of(` `),r(a,{fallback:!0}),p.lineWrapping,p.contentAttributes.of(e=>fC(e.state.sliceDoc(0,e.state.selection.main.head))),p.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),o(`Message pi... Use / for commands, @ for tracked files, @ space for all files`),this.editableCompartment.of(p.editable.of(!this.disabled)),this.readOnlyCompartment.of(e.readOnly.of(this.disabled)),p.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),n.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=>l.shift?.(e)??!1},{key:`Backspace`,run:e=>ee(e)},...c,...d])]})}))}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:i.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(p.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(e.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;let t=nC(this.machineId,this.sessionId);t!==void 0&&Vc(t,this.draft);let n=Yl(this.draft);Zl(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 L.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(rC);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 L.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(iC);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=Wl(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 Ul(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(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=BS(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(!t&&this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return VS(t,this.mobilePromptEnterMedia,LS())?(this.send(this.canSteer||this.isCompacting?`followUp`:void 0),!0):te(e)||f(e)}handleEditorTab(e){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):l.run?.(e)??!1}pick(e){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,a=e.insertText.endsWith(`"`)&&this.draft.slice(e.replaceTo).startsWith(`"`)?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:a,insert:`${e.insertText}${n}`},selection:i.cursor(r),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending)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=nC(this.machineId,this.sessionId);e!==void 0&&Hc(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=$p}};B([x({type:Boolean})],q.prototype,`disabled`,void 0),B([x()],q.prototype,`sessionId`,void 0),B([x()],q.prototype,`cwd`,void 0),B([x()],q.prototype,`machineId`,void 0),B([x()],q.prototype,`projectId`,void 0),B([x()],q.prototype,`workspaceId`,void 0),B([x({type:Boolean})],q.prototype,`workspaceScopedFileSuggestions`,void 0),B([x({type:Boolean})],q.prototype,`canSteer`,void 0),B([x({type:Boolean})],q.prototype,`isCompacting`,void 0),B([x({type:Boolean})],q.prototype,`canStop`,void 0),B([x({attribute:!1})],q.prototype,`status`,void 0),B([x({type:Boolean})],q.prototype,`sending`,void 0),B([x({attribute:!1})],q.prototype,`onSend`,void 0),B([x({attribute:!1})],q.prototype,`onStop`,void 0),B([x({attribute:!1})],q.prototype,`onSelectModel`,void 0),B([x({attribute:!1})],q.prototype,`onSelectThinking`,void 0),B([x({attribute:!1})],q.prototype,`onCompact`,void 0),B([x({type:Boolean})],q.prototype,`showSessionConfiguration`,void 0),B([x({attribute:!1})],q.prototype,`sessionConfiguration`,void 0),B([x({attribute:!1})],q.prototype,`availableThinkingLevels`,void 0),B([C(`.markdown-editor`)],q.prototype,`editorHost`,void 0),B([C(`.attachment-input`)],q.prototype,`attachmentInput`,void 0),B([S()],q.prototype,`currentInputMode`,void 0),B([S()],q.prototype,`completions`,void 0),B([S()],q.prototype,`selectedIndex`,void 0),B([S()],q.prototype,`attachments`,void 0),B([S()],q.prototype,`attachmentDelivery`,void 0),B([S()],q.prototype,`attachmentError`,void 0),q=B([b(`prompt-editor`)],q);function tC(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}function nC(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return Wo(e,t)}function rC(){return[]}function iC(){return[]}function aC(e){return e===null?[]:Array.from(e.files)}function oC(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function sC(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 cC(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`FILE`}function lC(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 uC={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},dC={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function fC(e){return Yl(e).kind===`normal`?uC:dC}var pC=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`
|
|
2957
2957
|
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
2958
2958
|
<section @mousedown=${e=>{e.stopPropagation()}}>
|
|
2959
2959
|
<header>
|
|
@@ -2969,12 +2969,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2969
2969
|
`}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`
|
|
2970
2970
|
${t?g`<div class="group-header">${e.group}</div>`:null}
|
|
2971
2971
|
${e.items.map(({option:e,index:n})=>g`
|
|
2972
|
-
<button class="${n===this.selectedIndex?`selected`:``}${t?` grouped`:``}" ${
|
|
2972
|
+
<button class="${n===this.selectedIndex?`selected`:``}${t?` grouped`:``}" ${$S(n===this.selectedIndex,e.value)} @click=${()=>this.onPick?.(e.value)}>
|
|
2973
2973
|
<span>${e.label}</span>
|
|
2974
2974
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
2975
2975
|
</button>
|
|
2976
2976
|
`)}
|
|
2977
|
-
`})}handleKeyDown(e){let t=this.filteredOptions();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&&this.onPick?.(n.value)}}static{this.styles=Zp}};B([x()],
|
|
2977
|
+
`})}handleKeyDown(e){let t=this.filteredOptions();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&&this.onPick?.(n.value)}}static{this.styles=Zp}};B([x()],pC.prototype,`title`,void 0),B([x({type:Boolean})],pC.prototype,`searchable`,void 0),B([x({attribute:!1})],pC.prototype,`options`,void 0),B([x({attribute:!1})],pC.prototype,`selectedValue`,void 0),B([x({attribute:!1})],pC.prototype,`onPick`,void 0),B([x({attribute:!1})],pC.prototype,`onCancel`,void 0),B([S()],pC.prototype,`selectedIndex`,void 0),B([S()],pC.prototype,`query`,void 0),pC=B([b(`command-picker`)],pC);var mC=class extends y{constructor(...e){super(...e),this.actions=[],this.queryText=``,this.selectedIndex=0}render(){let e=this.filteredActions();return g`
|
|
2978
2978
|
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
2979
2979
|
<section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
2980
2980
|
<header>
|
|
@@ -2987,7 +2987,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2987
2987
|
</header>
|
|
2988
2988
|
<div class="options">
|
|
2989
2989
|
${e.length===0?g`<div class="empty">No actions found.</div>`:e.map((e,t)=>g`
|
|
2990
|
-
<button class=${`${t===this.selectedIndex?`selected`:``} ${e.enabled===!1?`disabled`:``}`} ?disabled=${e.enabled===!1} title=${e.disabledReason??e.title} ${
|
|
2990
|
+
<button class=${`${t===this.selectedIndex?`selected`:``} ${e.enabled===!1?`disabled`:``}`} ?disabled=${e.enabled===!1} title=${e.disabledReason??e.title} ${$S(t===this.selectedIndex,e.id)} @click=${()=>{this.run(e)}}>
|
|
2991
2991
|
<span class="main">
|
|
2992
2992
|
<strong>${e.title}</strong>
|
|
2993
2993
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
@@ -3000,7 +3000,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3000
3000
|
</div>
|
|
3001
3001
|
</section>
|
|
3002
3002
|
</div>
|
|
3003
|
-
`}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
|
|
3003
|
+
`}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 hC(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=Qp}};B([x({attribute:!1})],mC.prototype,`actions`,void 0),B([x({attribute:!1})],mC.prototype,`onRun`,void 0),B([x({attribute:!1})],mC.prototype,`onCancel`,void 0),B([C(`input`)],mC.prototype,`input`,void 0),B([S()],mC.prototype,`queryText`,void 0),B([S()],mC.prototype,`selectedIndex`,void 0),mC=B([b(`action-palette`)],mC);function hC(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 gC=class extends y{render(){let e=this.state;return e===void 0?null:g`
|
|
3004
3004
|
<div class="backdrop" @mousedown=${()=>{this.cancel()}}>
|
|
3005
3005
|
<section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
3006
3006
|
<header>
|
|
@@ -3023,13 +3023,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3023
3023
|
<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>
|
|
3024
3024
|
</div>
|
|
3025
3025
|
`;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`
|
|
3026
|
-
<button @click=${()=>{this.onLogoutProvider?.(e.id)}}><span>${e.name}</span><small>${e.id} · ${
|
|
3026
|
+
<button @click=${()=>{this.onLogoutProvider?.(e.id)}}><span>${e.name}</span><small>${e.id} · ${vC(e.authType)}</small></button>
|
|
3027
3027
|
`)}</div>`}}renderProviderButton(e){return g`
|
|
3028
3028
|
<button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
|
|
3029
|
-
<span>${e.name}${e.status.source===void 0?null:g` <em>${
|
|
3030
|
-
<small>${e.id} · ${
|
|
3029
|
+
<span>${e.name}${e.status.source===void 0?null:g` <em>${bC(e)}</em>`}</span>
|
|
3030
|
+
<small>${e.id} · ${vC(e.authType)}</small>
|
|
3031
3031
|
</button>
|
|
3032
|
-
`}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=
|
|
3032
|
+
`}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=_C(n?.promptType);return g`
|
|
3033
3033
|
<div class="form">
|
|
3034
3034
|
${t.auth===void 0?g`<p>Starting login flow…</p>`:g`
|
|
3035
3035
|
<p>Open this authorization link:</p>
|
|
@@ -3062,7 +3062,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3062
3062
|
${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}
|
|
3063
3063
|
${n===void 0&&r===void 0&&t.status===`running`?g`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
|
|
3064
3064
|
</div>
|
|
3065
|
-
`}focusInputIfNeeded(){let e=
|
|
3065
|
+
`}focusInputIfNeeded(){let e=yC(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=[Zp,h`
|
|
3066
3066
|
.form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
|
|
3067
3067
|
.form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
|
|
3068
3068
|
.form a { color: var(--pi-accent); overflow-wrap: anywhere; }
|
|
@@ -3080,7 +3080,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3080
3080
|
.inline-options button { display: grid; gap: 2px; text-align: left; }
|
|
3081
3081
|
.inline-options small { color: var(--pi-muted); }
|
|
3082
3082
|
em { color: var(--pi-success); font-style: normal; font-size: 12px; }
|
|
3083
|
-
`]}};B([x({attribute:!1})],
|
|
3083
|
+
`]}};B([x({attribute:!1})],gC.prototype,`state`,void 0),B([x({attribute:!1})],gC.prototype,`onChooseMethod`,void 0),B([x({attribute:!1})],gC.prototype,`onSelectProvider`,void 0),B([x({attribute:!1})],gC.prototype,`onApiKeyInput`,void 0),B([x({attribute:!1})],gC.prototype,`onSaveApiKey`,void 0),B([x({attribute:!1})],gC.prototype,`onLogoutProvider`,void 0),B([x({attribute:!1})],gC.prototype,`onOAuthInput`,void 0),B([x({attribute:!1})],gC.prototype,`onOAuthRespond`,void 0),B([x({attribute:!1})],gC.prototype,`onOAuthCancel`,void 0),B([x({attribute:!1})],gC.prototype,`onCancel`,void 0),B([C(`input`)],gC.prototype,`input`,void 0),gC=B([b(`auth-dialog`)],gC);function _C(e){return e===`secret`?`password`:`text`}function vC(e){return e===`oauth`?`subscription`:`credentials`}function yC(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 bC(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 xC=[`openai-completions`,`openai-responses`,`anthropic-messages`,`google-generative-ai`];function SC(e){return xC.map(t=>({api:t,selected:t===e}))}function CC(e,t){return e.map(e=>({candidate:e,selected:e.id===t}))}var wC=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function TC(e){let t=e.providers??{},n=IC(t);return{config:NC(e,{...t,[n]:{api:`openai-completions`}}),providerName:n}}function EC(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:NC(e,a)}}function DC(e,t,n){let r=e.providers??{};return r[t]===void 0?e:NC(e,{...r,[t]:n})}function OC(e,t){let n=e.providers??{};return n[t]===void 0?e:NC(e,PC(n,t))}function kC(e,t){let n=e.providers?.[t];if(n===void 0)return e;let r=[...n.models??[],{id:``}];return DC(e,t,{...n,models:r})}function AC(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,DC(e,t,{...i,models:o})}function jC(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,DC(e,t,n)}return DC(e,t,{...r,models:a})}function MC(e,t,n,r){let i=n==="default"?FC(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 NC(e,t){return{...e,providers:t}}function PC(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function FC(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function IC(e){let t=`new-provider`,n=1;for(;e[t]!==void 0;)t=`new-provider-${String(n++)}`;return t}var LC={thinkingFormat:`deepseek`,requiresReasoningContentOnAssistantMessages:!0},RC=class extends y{constructor(...e){super(...e),this.modelsApi=Ka,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`)&&VC(e.get(`machine`))!==this.machineId()&&(this.resetForMachineChange(),this.isConnected&&this.loadConfig())}render(){return g`
|
|
3084
3084
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
3085
3085
|
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="models-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
3086
3086
|
<header>
|
|
@@ -3091,10 +3091,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3091
3091
|
</div>
|
|
3092
3092
|
<div class="header-actions">
|
|
3093
3093
|
<button class="icon-button" type="button" title="Reload models configuration" aria-label="Reload models configuration" ?disabled=${this.loading} @click=${()=>{this.loadConfig()}}>
|
|
3094
|
-
${
|
|
3094
|
+
${hw()}
|
|
3095
3095
|
</button>
|
|
3096
3096
|
<button class="icon-button" type="button" title="Close models configuration" aria-label="Close models configuration" @click=${()=>{this.close()}}>
|
|
3097
|
-
${
|
|
3097
|
+
${gw()}
|
|
3098
3098
|
</button>
|
|
3099
3099
|
</div>
|
|
3100
3100
|
</header>
|
|
@@ -3112,7 +3112,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3112
3112
|
${this.savedMessage===``?null:g`<span class="saved-message">${this.savedMessage}</span>`}
|
|
3113
3113
|
</div>
|
|
3114
3114
|
<button type="button" class="secondary" @click=${()=>{this.configureAuth()}}>
|
|
3115
|
-
${
|
|
3115
|
+
${_w()} Authentication
|
|
3116
3116
|
</button>
|
|
3117
3117
|
<button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
|
|
3118
3118
|
<button type="button" class="primary" ?disabled=${this.saving||this.loading} @click=${()=>{this.saveConfig()}}>
|
|
@@ -3133,28 +3133,28 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3133
3133
|
</div>
|
|
3134
3134
|
<div class="tree-actions">
|
|
3135
3135
|
<button type="button" class="add-provider" @click=${()=>{this.addCustomProvider()}}>
|
|
3136
|
-
${
|
|
3136
|
+
${pw()} Add provider
|
|
3137
3137
|
</button>
|
|
3138
3138
|
<button type="button" class="auth-link" @click=${()=>{this.configureAuth()}}>
|
|
3139
|
-
${
|
|
3139
|
+
${_w()} Configure authentication
|
|
3140
3140
|
</button>
|
|
3141
3141
|
</div>
|
|
3142
3142
|
</aside>
|
|
3143
3143
|
`}renderProviderTreeNode(e,t){let n=this.selection?.type===`provider`&&this.selection.providerName===e,r=t.models??[];return g`
|
|
3144
3144
|
<div class="provider-node">
|
|
3145
3145
|
<button class="tree-row provider-row ${n?`selected`:``}" type="button" @click=${()=>{this.selectProvider(e)}}>
|
|
3146
|
-
${
|
|
3146
|
+
${dw()}
|
|
3147
3147
|
<span class="tree-label">${e}</span>
|
|
3148
3148
|
</button>
|
|
3149
3149
|
${r.map((t,n)=>g`
|
|
3150
3150
|
<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)}}>
|
|
3151
|
-
${
|
|
3151
|
+
${fw()}
|
|
3152
3152
|
<span class="tree-label">${t.id.trim()===``?`new model`:t.id}</span>
|
|
3153
3153
|
${t.reasoning===!0?g`<span class="thinking-mark" title="Reasoning enabled">T</span>`:null}
|
|
3154
3154
|
</button>
|
|
3155
3155
|
`)}
|
|
3156
3156
|
<button class="tree-row add-model" type="button" @click=${()=>{this.addModel(e)}}>
|
|
3157
|
-
${
|
|
3157
|
+
${pw()} <span>Add model</span>
|
|
3158
3158
|
</button>
|
|
3159
3159
|
</div>
|
|
3160
3160
|
`}renderDetail(){let e=this.selection;if(e===void 0)return g`
|
|
@@ -3162,7 +3162,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3162
3162
|
<strong>Select a provider or model</strong>
|
|
3163
3163
|
<span>Custom endpoints are saved in the selected machine's <code>models.json</code>.</span>
|
|
3164
3164
|
</div>
|
|
3165
|
-
`;if(e.type===`provider`){let t=this.config.providers?.[e.providerName];return t===void 0?this.renderMissingSelection():this.renderProviderDetail(e.providerName,t)}let t=this.config.providers?.[e.providerName],n=t?.models?.[e.index];return t===void 0||n===void 0?this.renderMissingSelection():this.renderModelDetail(e.providerName,t,n,e.index)}renderMissingSelection(){return g`<div class="empty-state"><strong>This entry was removed.</strong><span>Select another provider or add a new one.</span></div>`}renderProviderDetail(e,t){let n=this.discoveredModels[e],r=typeof t.baseUrl==`string`&&t.baseUrl.trim()
|
|
3165
|
+
`;if(e.type===`provider`){let t=this.config.providers?.[e.providerName];return t===void 0?this.renderMissingSelection():this.renderProviderDetail(e.providerName,t)}let t=this.config.providers?.[e.providerName],n=t?.models?.[e.index];return t===void 0||n===void 0?this.renderMissingSelection():this.renderModelDetail(e.providerName,t,n,e.index)}renderMissingSelection(){return g`<div class="empty-state"><strong>This entry was removed.</strong><span>Select another provider or add a new one.</span></div>`}renderProviderDetail(e,t){let n=this.discoveredModels[e],r=typeof t.baseUrl==`string`&&t.baseUrl.trim()!==``,i=t.api??`openai-completions`;return g`
|
|
3166
3166
|
<div class="detail-content">
|
|
3167
3167
|
<div class="detail-heading">
|
|
3168
3168
|
<div>
|
|
@@ -3171,16 +3171,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3171
3171
|
</div>
|
|
3172
3172
|
<div class="provider-actions">
|
|
3173
3173
|
<button type="button" class="secondary" ?disabled=${!r||n?.phase===`discovering`} @click=${()=>{this.discoverModels(e)}}>
|
|
3174
|
-
${n?.phase===`discovering`?
|
|
3174
|
+
${n?.phase===`discovering`?yw():hw()} ${n===void 0?`Fetch models`:n.phase===`discovering`?`Fetching models...`:`Refresh models`}
|
|
3175
3175
|
</button>
|
|
3176
|
-
<button type="button" class="danger" @click=${()=>{this.deleteProvider(e)}}>${
|
|
3176
|
+
<button type="button" class="danger" @click=${()=>{this.deleteProvider(e)}}>${mw()} Delete provider</button>
|
|
3177
3177
|
</div>
|
|
3178
3178
|
</div>
|
|
3179
3179
|
|
|
3180
3180
|
<div class="field-stack provider-name-field">
|
|
3181
3181
|
<label for="provider-name">Provider name</label>
|
|
3182
3182
|
<div class="inline-field">
|
|
3183
|
-
<input id="provider-name" class="mono" .value=${this.providerNameDraft} placeholder="provider-name" @input=${e=>{this.providerNameDraft=
|
|
3183
|
+
<input id="provider-name" class="mono" .value=${this.providerNameDraft} placeholder="provider-name" @input=${e=>{this.providerNameDraft=UC(e),this.renameError=``}}>
|
|
3184
3184
|
<button type="button" class="secondary" ?disabled=${this.providerNameDraft.trim()===``||this.providerNameDraft===e} @click=${()=>{this.renameSelectedProvider(e)}}>Rename</button>
|
|
3185
3185
|
</div>
|
|
3186
3186
|
${this.renameError===``?null:g`<span class="field-error">${this.renameError}</span>`}
|
|
@@ -3188,19 +3188,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3188
3188
|
|
|
3189
3189
|
<div class="field-stack">
|
|
3190
3190
|
<label for="provider-base-url">Base URL</label>
|
|
3191
|
-
<input id="provider-base-url" class="mono" .value=${t.baseUrl??``} placeholder="https://api.example.com/v1" @input=${n=>{this.replaceProvider(e,{...t,baseUrl:
|
|
3191
|
+
<input id="provider-base-url" class="mono" .value=${t.baseUrl??``} placeholder="https://api.example.com/v1" @input=${n=>{this.replaceProvider(e,{...t,baseUrl:HC(UC(n))})}}>
|
|
3192
3192
|
</div>
|
|
3193
3193
|
|
|
3194
3194
|
<div class="field-stack">
|
|
3195
3195
|
<label for="provider-api-key">API key source</label>
|
|
3196
|
-
<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:
|
|
3196
|
+
<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:HC(UC(n))})}}>
|
|
3197
3197
|
<span class="help-text">Use an environment variable name, prefix a command with <code>!</code>, or configure built-in provider credentials through Authentication.</span>
|
|
3198
3198
|
</div>
|
|
3199
3199
|
|
|
3200
3200
|
<div class="field-stack">
|
|
3201
3201
|
<label for="provider-api">API format</label>
|
|
3202
|
-
<select id="provider-api" .value=${
|
|
3203
|
-
${SC.map(e=>g`<option value=${e}>${e}</option>`)}
|
|
3202
|
+
<select id="provider-api" .value=${i} @change=${n=>{this.replaceProvider(e,{...t,api:UC(n)})}}>
|
|
3203
|
+
${SC(i).map(({api:e,selected:t})=>g`<option value=${e} .selected=${t}>${e}</option>`)}
|
|
3204
3204
|
</select>
|
|
3205
3205
|
</div>
|
|
3206
3206
|
|
|
@@ -3215,7 +3215,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3215
3215
|
</div>
|
|
3216
3216
|
</details>
|
|
3217
3217
|
</div>
|
|
3218
|
-
`}renderModelDetail(e,t,n,r){let i=this.modelTests[
|
|
3218
|
+
`}renderModelDetail(e,t,n,r){let i=this.modelTests[nw(e,r)];return g`
|
|
3219
3219
|
<div class="detail-content">
|
|
3220
3220
|
<div class="detail-heading">
|
|
3221
3221
|
<div>
|
|
@@ -3223,35 +3223,35 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3223
3223
|
<h2>${n.id.trim()===``?`New model`:n.id}</h2>
|
|
3224
3224
|
</div>
|
|
3225
3225
|
<div class="model-actions">
|
|
3226
|
-
${i===void 0?null:g`<span class="connection-state ${i.phase}">${
|
|
3226
|
+
${i===void 0?null:g`<span class="connection-state ${i.phase}">${sw(i)}</span>`}
|
|
3227
3227
|
<button type="button" class="secondary" ?disabled=${n.id.trim()===``||i?.phase===`testing`} @click=${()=>{this.testModel(e,r)}}>
|
|
3228
|
-
${i?.phase===`testing`?
|
|
3228
|
+
${i?.phase===`testing`?yw():vw()} ${i?.phase===`testing`?`Testing...`:`Test`}
|
|
3229
3229
|
</button>
|
|
3230
|
-
<button type="button" class="danger" @click=${()=>{this.deleteModel(e,r)}}>${
|
|
3230
|
+
<button type="button" class="danger" @click=${()=>{this.deleteModel(e,r)}}>${mw()} Remove</button>
|
|
3231
3231
|
</div>
|
|
3232
3232
|
</div>
|
|
3233
3233
|
|
|
3234
|
-
${i===void 0?null:g`<div class="connection-detail ${i.phase}">${
|
|
3234
|
+
${i===void 0?null:g`<div class="connection-detail ${i.phase}">${cw(i)}</div>`}
|
|
3235
3235
|
|
|
3236
3236
|
<div class="field-grid two-columns">
|
|
3237
3237
|
${this.renderModelIdField(e,n,r)}
|
|
3238
3238
|
<div class="field-stack">
|
|
3239
3239
|
<label for="model-name">Display name</label>
|
|
3240
|
-
<input id="model-name" .value=${n.name??``} placeholder="Display name" @input=${t=>{this.replaceModel(e,r,{...n,name:
|
|
3240
|
+
<input id="model-name" .value=${n.name??``} placeholder="Display name" @input=${t=>{this.replaceModel(e,r,{...n,name:HC(UC(t))})}}>
|
|
3241
3241
|
</div>
|
|
3242
3242
|
</div>
|
|
3243
3243
|
|
|
3244
3244
|
<div class="field-stack">
|
|
3245
3245
|
<label for="model-api">API override</label>
|
|
3246
|
-
<select id="model-api" .value=${n.api??``} @change=${t=>{this.replaceModel(e,r,{...n,api:
|
|
3246
|
+
<select id="model-api" .value=${n.api??``} @change=${t=>{this.replaceModel(e,r,{...n,api:HC(UC(t))})}}>
|
|
3247
3247
|
<option value="">Inherit provider API</option>
|
|
3248
|
-
${SC.map(e=>g`<option value=${e}>${e}</option>`)}
|
|
3248
|
+
${SC(n.api).map(({api:e,selected:t})=>g`<option value=${e} .selected=${t}>${e}</option>`)}
|
|
3249
3249
|
</select>
|
|
3250
3250
|
</div>
|
|
3251
3251
|
|
|
3252
3252
|
<div class="switch-row">
|
|
3253
3253
|
${this.renderCheck(`Reasoning / thinking`,n.reasoning===!0,t=>{this.replaceModel(e,r,{...n,reasoning:t||void 0})})}
|
|
3254
|
-
${this.renderCheck(`Image input`,n.input?.includes(`image`)===!0,t=>{this.replaceModel(e,r,{...n,input:t?
|
|
3254
|
+
${this.renderCheck(`Image input`,n.input?.includes(`image`)===!0,t=>{this.replaceModel(e,r,{...n,input:t?JC(n.input):YC(n.input)})})}
|
|
3255
3255
|
</div>
|
|
3256
3256
|
|
|
3257
3257
|
${n.reasoning===!0?g`
|
|
@@ -3261,10 +3261,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3261
3261
|
<span class="section-label">Thinking configuration</span>
|
|
3262
3262
|
<p>Map Pi thinking levels to values accepted by this model, or disable a level.</p>
|
|
3263
3263
|
</div>
|
|
3264
|
-
${this.renderCheck(`DeepSeek thinking compatibility`,
|
|
3264
|
+
${this.renderCheck(`DeepSeek thinking compatibility`,XC(n),t=>{this.replaceModel(e,r,ZC(n,t))})}
|
|
3265
3265
|
</div>
|
|
3266
3266
|
<div class="thinking-map">
|
|
3267
|
-
${
|
|
3267
|
+
${wC.map(t=>this.renderThinkingLevel(e,r,n,t))}
|
|
3268
3268
|
</div>
|
|
3269
3269
|
</section>
|
|
3270
3270
|
`:null}
|
|
@@ -3272,11 +3272,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3272
3272
|
<div class="field-grid two-columns">
|
|
3273
3273
|
<div class="field-stack">
|
|
3274
3274
|
<label for="context-window">Context window (tokens)</label>
|
|
3275
|
-
<input id="context-window" type="number" min="0" inputmode="numeric" .value=${
|
|
3275
|
+
<input id="context-window" type="number" min="0" inputmode="numeric" .value=${GC(n.contextWindow)} placeholder="128000" @input=${t=>{this.replaceModel(e,r,{...n,contextWindow:KC(UC(t))})}}>
|
|
3276
3276
|
</div>
|
|
3277
3277
|
<div class="field-stack">
|
|
3278
3278
|
<label for="max-tokens">Max output tokens</label>
|
|
3279
|
-
<input id="max-tokens" type="number" min="0" inputmode="numeric" .value=${
|
|
3279
|
+
<input id="max-tokens" type="number" min="0" inputmode="numeric" .value=${GC(n.maxTokens)} placeholder="16384" @input=${t=>{this.replaceModel(e,r,{...n,maxTokens:KC(UC(t))})}}>
|
|
3280
3280
|
</div>
|
|
3281
3281
|
</div>
|
|
3282
3282
|
|
|
@@ -3303,14 +3303,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3303
3303
|
`}renderModelIdField(e,t,n){let r=this.discoveredModels[e]?.models;if(r===void 0)return g`
|
|
3304
3304
|
<div class="field-stack">
|
|
3305
3305
|
<label for="model-id">Model ID <span aria-hidden="true">*</span></label>
|
|
3306
|
-
<input id="model-id" class="mono" .value=${t.id} placeholder="model-id" @input=${r=>{this.replaceModel(e,n,{...t,id:
|
|
3306
|
+
<input id="model-id" class="mono" .value=${t.id} placeholder="model-id" @input=${r=>{this.replaceModel(e,n,{...t,id:UC(r)})}}>
|
|
3307
3307
|
</div>
|
|
3308
3308
|
`;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`
|
|
3309
3309
|
<div class="field-stack">
|
|
3310
3310
|
<label for="model-id">Model ID <span aria-hidden="true">*</span></label>
|
|
3311
|
-
<select id="model-id" class="mono" .value=${t.id} @change=${t=>{this.selectDiscoveredModel(e,n,
|
|
3311
|
+
<select id="model-id" class="mono" .value=${t.id} @change=${t=>{this.selectDiscoveredModel(e,n,UC(t))}}>
|
|
3312
3312
|
${t.id.trim()===``?g`<option value="" disabled>Select a model</option>`:null}
|
|
3313
|
-
${i.map(e=>g`<option value=${e.id}>${e.name===void 0?e.id:`${e.name} (${e.id})`}</option>`)}
|
|
3313
|
+
${CC(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>`)}
|
|
3314
3314
|
</select>
|
|
3315
3315
|
</div>
|
|
3316
3316
|
`}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`
|
|
@@ -3322,26 +3322,26 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3322
3322
|
</div>
|
|
3323
3323
|
<label class="custom-thinking">
|
|
3324
3324
|
<span>Custom</span>
|
|
3325
|
-
<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`,
|
|
3325
|
+
<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`,UC(i))}}>
|
|
3326
3326
|
</label>
|
|
3327
3327
|
</div>
|
|
3328
3328
|
`}renderCostField(e,t,n,r,i){let a=`cost-${t}`;return g`
|
|
3329
3329
|
<div class="field-stack">
|
|
3330
3330
|
<label for=${a}>${e}</label>
|
|
3331
|
-
<input id=${a} type="number" min="0" step="any" inputmode="decimal" .value=${
|
|
3331
|
+
<input id=${a} type="number" min="0" step="any" inputmode="decimal" .value=${GC(i.cost?.[t])} placeholder="0" @input=${e=>{this.setCost(n,r,i,t,qC(UC(e)))}}>
|
|
3332
3332
|
</div>
|
|
3333
3333
|
`}renderCheck(e,t,n){return g`
|
|
3334
3334
|
<label class="check-row">
|
|
3335
|
-
<input type="checkbox" .checked=${t} @change=${e=>{n(
|
|
3335
|
+
<input type="checkbox" .checked=${t} @change=${e=>{n(WC(e))}}>
|
|
3336
3336
|
<span>${e}</span>
|
|
3337
3337
|
</label>
|
|
3338
3338
|
`}renderJsonField(e,t,n,r){let i=`advanced-${t}`,a=this.advancedErrors[t];return g`
|
|
3339
3339
|
<div class="field-stack">
|
|
3340
3340
|
<label for=${i}>${e} (JSON object)</label>
|
|
3341
|
-
<textarea id=${i} class="mono" rows="4" .value=${
|
|
3341
|
+
<textarea id=${i} class="mono" rows="4" .value=${$C(n)} @change=${e=>{r(UC(e))}}></textarea>
|
|
3342
3342
|
${a===void 0?null:g`<span class="field-error">${a}</span>`}
|
|
3343
3343
|
</div>
|
|
3344
|
-
`}async loadConfig(){let e=++this.loadRequestSequence,t=this.machineId();this.modelDiscoveryRequestSequences.clear(),this.discoveredModels={},this.loading=!0,this.error=``,this.savedMessage=``;try{let n=
|
|
3344
|
+
`}async loadConfig(){let e=++this.loadRequestSequence,t=this.machineId();this.modelDiscoveryRequestSequences.clear(),this.discoveredModels={},this.loading=!0,this.error=``,this.savedMessage=``;try{let n=zC(await this.modelsApi.config(t));if(!this.isCurrentLoad(e,t))return;this.config=n,this.selection=BC(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: ${uw(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: ${uw(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=nw(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}:ow(t)}}catch(e){a===this.machineId()&&(this.modelTests={...this.modelTests,[i]:{phase:`error`,message:uw(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?aw(this.discoveredModels,e):{...this.discoveredModels,[e]:i},this.error=`Failed to fetch models for ${e}: ${uw(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=TC(this.config);this.config=e.config,this.selectProvider(e.providerName)}deleteProvider(e){this.clearProviderDiscovery(e),this.config=OC(this.config,e),this.modelTests=rw(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=EC(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=iw(this.modelTests,e,n),this.selectProvider(n)}replaceProvider(e,t){this.invalidateProviderDiscovery(e),this.config=DC(this.config,e,t),this.modelTests=rw(this.modelTests,e)}addModel(e){let t=this.config.providers?.[e]?.models?.length??0;this.config=kC(this.config,e),this.selectModel(e,t)}deleteModel(e,t){this.config=jC(this.config,e,t),this.modelTests=rw(this.modelTests,e),this.selectProvider(e)}replaceModel(e,t,n){this.config=AC(this.config,e,t,n);let r=nw(e,t);this.modelTests[r]!==void 0&&(this.modelTests=aw(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=aw(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=aw(this.discoveredModels,e))}setThinkingLevel(e,t,n,r,i,a){this.replaceModel(e,t,{...n,thinkingLevelMap:MC(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=QC(n),i=`headers`;if(!r.ok){this.setAdvancedError(i,r.error);return}if(r.value!==void 0&&!ew(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:tw(r.value)})}updateProviderObject(e,t,n,r){let i=QC(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=QC(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=aw(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 VC(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`
|
|
3345
3345
|
:host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
|
|
3346
3346
|
.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); }
|
|
3347
3347
|
.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); }
|
|
@@ -3449,16 +3449,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3449
3449
|
.thinking-row { grid-template-columns: 58px minmax(0, 1fr); }
|
|
3450
3450
|
.custom-thinking { grid-column: 1 / -1; }
|
|
3451
3451
|
}
|
|
3452
|
-
`}};B([x({attribute:!1})],
|
|
3452
|
+
`}};B([x({attribute:!1})],RC.prototype,`machine`,void 0),B([x({attribute:!1})],RC.prototype,`modelsApi`,void 0),B([x({attribute:!1})],RC.prototype,`onClose`,void 0),B([x({attribute:!1})],RC.prototype,`onConfigureAuth`,void 0),B([x({attribute:!1})],RC.prototype,`onSaved`,void 0),B([S()],RC.prototype,`config`,void 0),B([S()],RC.prototype,`loading`,void 0),B([S()],RC.prototype,`saving`,void 0),B([S()],RC.prototype,`error`,void 0),B([S()],RC.prototype,`savedMessage`,void 0),B([S()],RC.prototype,`selection`,void 0),B([S()],RC.prototype,`providerNameDraft`,void 0),B([S()],RC.prototype,`renameError`,void 0),B([S()],RC.prototype,`advancedErrors`,void 0),B([S()],RC.prototype,`modelTests`,void 0),B([S()],RC.prototype,`discoveredModels`,void 0),RC=B([b(`models-config-dialog`)],RC);function zC(e){return e.providers===void 0?{...e,providers:{}}:e}function BC(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 VC(e){if(!lw(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function HC(e){return e.trim()===``?void 0:e}function UC(e){let t=e.target;return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.value:``}function WC(e){return e.target instanceof HTMLInputElement&&e.target.checked}function GC(e){return e===void 0?``:String(e)}function KC(e){let t=e.trim();if(t===``)return;let n=Number(t);return Number.isInteger(n)&&n>=0?n:void 0}function qC(e){let t=e.trim();if(t===``)return;let n=Number(t);return Number.isFinite(n)&&n>=0?n:void 0}function JC(e){let t=e??[`text`];return t.includes(`image`)?[...t]:[...t,`image`]}function YC(e){let t=(e??[]).filter(e=>e!==`image`);return t.length===0?void 0:t}function XC(e){return e.compat?.thinkingFormat===`deepseek`}function ZC(e,t){if(t)return{...e,compat:{...e.compat??{},...LC}};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 QC(e){if(e.trim()===``)return{ok:!0,value:void 0};try{let t=JSON.parse(e);return lw(t)?{ok:!0,value:t}:{ok:!1,error:`Value must be a JSON object.`}}catch(e){return{ok:!1,error:`Invalid JSON: ${uw(e)}`}}}function $C(e){return e===void 0?``:JSON.stringify(e,null,2)}function ew(e){return Object.values(e).every(e=>typeof e==`string`)}function tw(e){let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(t[n]=r);return t}function nw(e,t){return`${e}\u0000${String(t)}`}function rw(e,t){let n=`${t}\u0000`,r={};for(let[t,i]of Object.entries(e))t.startsWith(n)||(r[t]=i);return r}function iw(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 aw(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function ow(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 sw(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 cw(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 lw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function uw(e){return e instanceof Error?e.message:String(e)}function dw(){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 fw(){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 pw(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function mw(){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 hw(){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 gw(){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 _w(){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 vw(){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 yw(){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 J=class extends y{constructor(...e){super(...e),this.cwd=``,this.skillsApi=Ya,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`)&&bw(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`
|
|
3453
3453
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
3454
3454
|
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="skills-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
3455
3455
|
<header>
|
|
3456
3456
|
<div class="title-block">
|
|
3457
3457
|
<h1 id="skills-dialog-title">Skills</h1>
|
|
3458
|
-
<span class="target"><code>${
|
|
3458
|
+
<span class="target"><code>${ww(this.cwd)}</code> on ${this.machineLabel()}</span>
|
|
3459
3459
|
</div>
|
|
3460
3460
|
<button class="icon-button" type="button" title="Close skills configuration" aria-label="Close skills configuration" @click=${()=>{this.close()}}>
|
|
3461
|
-
${
|
|
3461
|
+
${zw()}
|
|
3462
3462
|
</button>
|
|
3463
3463
|
</header>
|
|
3464
3464
|
|
|
@@ -3484,21 +3484,21 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3484
3484
|
</div>
|
|
3485
3485
|
<div class="skill-list-actions">
|
|
3486
3486
|
<button class="add-skill" type="button" ?aria-pressed=${this.addMode} @click=${()=>{this.openAddMode()}}>
|
|
3487
|
-
${
|
|
3487
|
+
${Rw()} Add skill
|
|
3488
3488
|
</button>
|
|
3489
3489
|
</div>
|
|
3490
3490
|
</aside>
|
|
3491
|
-
`}renderSkillListItem(e){let t=!this.addMode&&e.filePath===this.selectedFilePath,n=
|
|
3491
|
+
`}renderSkillListItem(e){let t=!this.addMode&&e.filePath===this.selectedFilePath,n=Ow(e,this.updateStatuses);return g`
|
|
3492
3492
|
<button class="skill-row ${t?`selected`:``}" type="button" @click=${()=>{this.selectSkill(e)}}>
|
|
3493
3493
|
<span class="skill-indicator ${e.disableModelInvocation?`disabled`:``}" aria-hidden="true"></span>
|
|
3494
3494
|
<span class="skill-name">${e.name}</span>
|
|
3495
3495
|
${n?.state===`update-available`?g`<span class="update-available-mark" title="Update available" aria-label="Update available">↑</span>`:null}
|
|
3496
3496
|
</button>
|
|
3497
|
-
`}renderSkillDetail(e){let t=
|
|
3497
|
+
`}renderSkillDetail(e){let t=Sw(e),n=Dw(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`
|
|
3498
3498
|
<div class="detail-content">
|
|
3499
3499
|
<div class="skill-meta-row">
|
|
3500
3500
|
<span class="scope-tag ${t}">${t}</span>
|
|
3501
|
-
<code class="skill-path" title=${e.filePath}>${
|
|
3501
|
+
<code class="skill-path" title=${e.filePath}>${Cw(e,this.cwd)}</code>
|
|
3502
3502
|
<button
|
|
3503
3503
|
class="skill-toggle ${o?`enabled`:``}"
|
|
3504
3504
|
type="button"
|
|
@@ -3516,7 +3516,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3516
3516
|
<section class="detail-section">
|
|
3517
3517
|
<h2>Source</h2>
|
|
3518
3518
|
<a class="source-link" href=${e.install.skillsShUrl} target="_blank" rel="noreferrer" title=${e.install.skillsShUrl}>
|
|
3519
|
-
<code>${
|
|
3519
|
+
<code>${Tw(e.install.skillsShUrl)} ↗</code>
|
|
3520
3520
|
</a>
|
|
3521
3521
|
</section>
|
|
3522
3522
|
`}
|
|
@@ -3525,13 +3525,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3525
3525
|
<section class="detail-section">
|
|
3526
3526
|
<h2>Version</h2>
|
|
3527
3527
|
<div class="version-row">
|
|
3528
|
-
<code>${
|
|
3528
|
+
<code>${Ew(r?.currentVersion??e.install.versionHash)}</code>
|
|
3529
3529
|
${e.install.canCheckForUpdates?g`
|
|
3530
3530
|
<button type="button" class="secondary compact-button" ?disabled=${i||a} @click=${()=>{this.checkForUpdates(e)}}>
|
|
3531
3531
|
${i?`Checking...`:`Check`}
|
|
3532
3532
|
</button>
|
|
3533
3533
|
`:null}
|
|
3534
|
-
${r?.state===`update-available`?g`<code class="update-version">${
|
|
3534
|
+
${r?.state===`update-available`?g`<code class="update-version">${Ew(r.latestVersion)}</code>`:null}
|
|
3535
3535
|
${this.renderUpdateStatus(r,i)}
|
|
3536
3536
|
${r?.state===`update-available`?g`
|
|
3537
3537
|
<button type="button" class="primary compact-button" ?disabled=${a||i} @click=${()=>{this.updateInstalledSkill(e)}}>
|
|
@@ -3553,7 +3553,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3553
3553
|
<p>${e.description}</p>
|
|
3554
3554
|
</section>
|
|
3555
3555
|
</div>
|
|
3556
|
-
`}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/`:`${
|
|
3556
|
+
`}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/`:`${ww(this.cwd)}/.pi/skills/`;return g`
|
|
3557
3557
|
<div class="detail-content add-panel">
|
|
3558
3558
|
<div class="add-heading">
|
|
3559
3559
|
<h2>Add Skill</h2>
|
|
@@ -3565,7 +3565,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3565
3565
|
id="skill-search"
|
|
3566
3566
|
.value=${this.searchQuery}
|
|
3567
3567
|
placeholder="e.g. react, testing, deploy"
|
|
3568
|
-
@input=${e=>{this.searchQuery=
|
|
3568
|
+
@input=${e=>{this.searchQuery=Fw(e)}}
|
|
3569
3569
|
@keydown=${e=>{e.key===`Enter`&&(e.preventDefault(),this.searchSkills())}}
|
|
3570
3570
|
>
|
|
3571
3571
|
<button type="button" class="primary" ?disabled=${this.searching||this.searchQuery.trim()===``} @click=${()=>{this.searchSkills()}}>
|
|
@@ -3587,7 +3587,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3587
3587
|
|
|
3588
3588
|
${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>`}
|
|
3589
3589
|
</div>
|
|
3590
|
-
`}renderSearchResult(e){let t=this.isInstalled(e.package,this.installScope),n=this.installingPackage===e.package,r=
|
|
3590
|
+
`}renderSearchResult(e){let t=this.isInstalled(e.package,this.installScope),n=this.installingPackage===e.package,r=Aw(e.package);return g`
|
|
3591
3591
|
<article class="search-result">
|
|
3592
3592
|
<div class="search-result-copy">
|
|
3593
3593
|
<strong>${r.skill??r.repository}</strong>
|
|
@@ -3616,7 +3616,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3616
3616
|
</div>
|
|
3617
3617
|
<button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
|
|
3618
3618
|
</footer>
|
|
3619
|
-
`}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=
|
|
3619
|
+
`}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=xw(this.selectedFilePath,n.skills)}catch(n){this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loadError=`Failed to load skills: ${Iw(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=jw(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=Iw(e))}finally{this.isCurrentTarget(t)&&(this.togglingPaths=Nw(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=Iw(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=jw(this.newlyInstalledKeys,kw(n,e)),await this.loadSkills()}catch(e){this.isCurrentTarget(t)&&(this.installError=Iw(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=Dw(e);return t===void 0?[]:[t]});if(n.length!==0){this.updateError=``,this.checkingUpdateKeys=Mw(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=Iw(e))}finally{this.isCurrentTarget(t)&&(this.checkingUpdateKeys=Pw(this.checkingUpdateKeys,n),e===void 0&&(this.checkingAll=!1))}}}async updateInstalledSkill(e){let t=this.target(),n=e.install,r=Dw(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=Iw(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=>Sw(e)===`project`&&e.install?.skillsShUrl!==void 0},{label:`project`,matches:e=>Sw(e)===`project`&&e.install?.skillsShUrl===void 0},{label:`global / skills.sh`,matches:e=>Sw(e)===`global`&&e.install?.skillsShUrl!==void 0},{label:`global`,matches:e=>Sw(e)===`global`&&e.install?.skillsShUrl===void 0},{label:`path`,matches:e=>Sw(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(kw(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 bw(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`
|
|
3620
3620
|
:host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
|
|
3621
3621
|
.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); }
|
|
3622
3622
|
.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); }
|
|
@@ -3717,16 +3717,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3717
3717
|
.scope-row { align-items: flex-start; flex-direction: column; gap: 6px; }
|
|
3718
3718
|
.search-result { align-items: flex-start; }
|
|
3719
3719
|
}
|
|
3720
|
-
`}};B([x({attribute:!1})],
|
|
3720
|
+
`}};B([x({attribute:!1})],J.prototype,`machine`,void 0),B([x({type:String})],J.prototype,`cwd`,void 0),B([x({attribute:!1})],J.prototype,`skillsApi`,void 0),B([x({attribute:!1})],J.prototype,`onClose`,void 0),B([S()],J.prototype,`skills`,void 0),B([S()],J.prototype,`loading`,void 0),B([S()],J.prototype,`loadError`,void 0),B([S()],J.prototype,`selectedFilePath`,void 0),B([S()],J.prototype,`togglingPaths`,void 0),B([S()],J.prototype,`saveError`,void 0),B([S()],J.prototype,`addMode`,void 0),B([S()],J.prototype,`searchQuery`,void 0),B([S()],J.prototype,`searchResults`,void 0),B([S()],J.prototype,`searching`,void 0),B([S()],J.prototype,`searchError`,void 0),B([S()],J.prototype,`installingPackage`,void 0),B([S()],J.prototype,`installError`,void 0),B([S()],J.prototype,`newlyInstalledKeys`,void 0),B([S()],J.prototype,`installScope`,void 0),B([S()],J.prototype,`updateStatuses`,void 0),B([S()],J.prototype,`checkingUpdateKeys`,void 0),B([S()],J.prototype,`checkingAll`,void 0),B([S()],J.prototype,`updatingKey`,void 0),B([S()],J.prototype,`updateError`,void 0),B([C(`#skill-search`)],J.prototype,`searchInput`,void 0),J=B([b(`skills-config-dialog`)],J);function bw(e){if(!Lw(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function xw(e,t){return e!==void 0&&t.some(t=>t.filePath===e)?e:t[0]?.filePath}function Sw(e){let t=e.sourceInfo.source,n=e.sourceInfo.scope;return n===`user`||t===`user`?`global`:n===`project`||t===`project`?`project`:`path`}function Cw(e,t){return Sw(e)===`project`&&e.filePath.startsWith(t)?`./${e.filePath.slice(t.length).replace(/^[/\\]/u,``)}`:ww(e.filePath)}function ww(e){return e.replace(/^\/(?:Users|home)\/[^/]+/u,`~`)}function Tw(e){return e.replace(/^https?:\/\//u,``)}function Ew(e){return e===void 0||e===``?`unknown`:e.slice(0,8)}function Dw(e){return e.install===void 0?void 0:`${e.install.scope}\0${e.install.package}`}function Ow(e,t){let n=Dw(e);return n===void 0?void 0:t[n]}function kw(e,t){return`${e}\0${t}`}function Aw(e){let t=e.lastIndexOf(`@`);return t<0?{repository:e,skill:void 0}:{repository:e.slice(0,t),skill:e.slice(t+1)}}function jw(e,t){return new Set([...e,t])}function Mw(e,t){return new Set([...e,...t])}function Nw(e,t){let n=new Set(e);return n.delete(t),n}function Pw(e,t){let n=new Set(e);for(let e of t)n.delete(e);return n}function Fw(e){let t=e.target;return t instanceof HTMLInputElement?t.value:``}function Iw(e){return e instanceof Error?e.message:String(e)}function Lw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rw(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function zw(){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 Y=class extends y{constructor(...e){super(...e),this.cwd=``,this.pluginsApi=eo,this.sessionsApi=io,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`)&&qw(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`
|
|
3721
3721
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
3722
3722
|
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="plugins-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
3723
3723
|
<header>
|
|
3724
3724
|
<div class="title-block">
|
|
3725
3725
|
<h1 id="plugins-dialog-title">Plugins</h1>
|
|
3726
|
-
<span class="target"><code>${
|
|
3726
|
+
<span class="target"><code>${Jw(this.cwd)}</code> on ${this.machineLabel()}</span>
|
|
3727
3727
|
</div>
|
|
3728
3728
|
<button class="icon-button" type="button" title="Close Plugins configuration" aria-label="Close Plugins configuration" @click=${()=>{this.close()}}>
|
|
3729
|
-
${
|
|
3729
|
+
${eT()}
|
|
3730
3730
|
</button>
|
|
3731
3731
|
</header>
|
|
3732
3732
|
|
|
@@ -3752,20 +3752,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3752
3752
|
</div>
|
|
3753
3753
|
<div class="package-list-actions">
|
|
3754
3754
|
<button class="add-plugin" type="button" aria-pressed=${String(this.addMode)} @click=${()=>{this.openAddMode()}}>
|
|
3755
|
-
${
|
|
3755
|
+
${$w()} Add plugin
|
|
3756
3756
|
</button>
|
|
3757
3757
|
</div>
|
|
3758
3758
|
</aside>
|
|
3759
|
-
`}renderPackageListItem(e){let t=
|
|
3759
|
+
`}renderPackageListItem(e){let t=Bw(e),n=!this.addMode&&t===this.selectedKey;return g`
|
|
3760
3760
|
<button class="package-row ${n?`selected`:``}" type="button" aria-pressed=${String(n)} @click=${()=>{this.selectPackage(e)}}>
|
|
3761
|
-
<span class="package-indicator" style=${`background:${
|
|
3761
|
+
<span class="package-indicator" style=${`background:${Gw(e.status)}`} aria-hidden="true"></span>
|
|
3762
3762
|
<span class="package-copy">
|
|
3763
3763
|
<strong>${e.source}</strong>
|
|
3764
|
-
<small>${
|
|
3765
|
-
${e.version===void 0&&e.configuredVersion===void 0?null:g`<small>${
|
|
3764
|
+
<small>${Uw(e)}</small>
|
|
3765
|
+
${e.version===void 0&&e.configuredVersion===void 0?null:g`<small>${Ww(e)}</small>`}
|
|
3766
3766
|
</span>
|
|
3767
3767
|
</button>
|
|
3768
|
-
`}renderPackageDetail(e){let t=
|
|
3768
|
+
`}renderPackageDetail(e){let t=Bw(e),n=this.busyKey?.endsWith(t)??!1,r=this.busyKey===`reload`,i=!e.disabled;return g`
|
|
3769
3769
|
<div class="detail-content">
|
|
3770
3770
|
<div class="detail-heading">
|
|
3771
3771
|
<div class="package-title-row">
|
|
@@ -3797,12 +3797,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3797
3797
|
</div>
|
|
3798
3798
|
|
|
3799
3799
|
<dl class="metadata-grid">
|
|
3800
|
-
<dt>Status</dt><dd style=${`color:${
|
|
3801
|
-
<dt>Version</dt><dd><code>${
|
|
3800
|
+
<dt>Status</dt><dd style=${`color:${Gw(e.status)}`}>${e.status}</dd>
|
|
3801
|
+
<dt>Version</dt><dd><code>${Ww(e)}</code></dd>
|
|
3802
3802
|
<dt>Package</dt><dd><code>${e.packageName??`Unknown`}</code></dd>
|
|
3803
|
-
<dt>Resources</dt><dd>${
|
|
3804
|
-
<dt>Installed path</dt><dd class=${e.installedPath===void 0?`missing`:``}><code>${e.installedPath===void 0?`Not found`:
|
|
3805
|
-
<dt>Workspace</dt><dd><code>${
|
|
3803
|
+
<dt>Resources</dt><dd>${Uw(e)}</dd>
|
|
3804
|
+
<dt>Installed path</dt><dd class=${e.installedPath===void 0?`missing`:``}><code>${e.installedPath===void 0?`Not found`:Jw(e.installedPath)}</code></dd>
|
|
3805
|
+
<dt>Workspace</dt><dd><code>${Jw(this.cwd)}</code></dd>
|
|
3806
3806
|
</dl>
|
|
3807
3807
|
|
|
3808
3808
|
<section class="resource-section">
|
|
@@ -3831,7 +3831,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3831
3831
|
<div class="detail-content add-panel">
|
|
3832
3832
|
<div class="add-heading">
|
|
3833
3833
|
<h2>Add Plugin</h2>
|
|
3834
|
-
<code>${this.installScope===`project`?`${
|
|
3834
|
+
<code>${this.installScope===`project`?`${Jw(this.cwd)}/.pi/agent/{npm,git}`:`~/.pi/agent/{npm,git}`}</code>
|
|
3835
3835
|
</div>
|
|
3836
3836
|
|
|
3837
3837
|
<div class="field-stack">
|
|
@@ -3840,7 +3840,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3840
3840
|
id="plugin-source"
|
|
3841
3841
|
.value=${this.installSource}
|
|
3842
3842
|
placeholder="npm:@scope/package"
|
|
3843
|
-
@input=${e=>{this.installSource=
|
|
3843
|
+
@input=${e=>{this.installSource=Xw(e)}}
|
|
3844
3844
|
@keydown=${t=>{t.key!==`Enter`||this.installSource.trim()===``||e||(t.preventDefault(),this.installPlugin())}}
|
|
3845
3845
|
>
|
|
3846
3846
|
</div>
|
|
@@ -3867,7 +3867,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3867
3867
|
`}renderFooter(){let e=this.data,t=e?.diagnostics??[],n=this.busyKey!==void 0;return g`
|
|
3868
3868
|
<footer>
|
|
3869
3869
|
<div class="footer-summary">
|
|
3870
|
-
${t.length>0?g`<span class=${t.some(e=>e.type===`error`)?`error-message`:`warning-message`} title=${t.map(
|
|
3870
|
+
${t.length>0?g`<span class=${t.some(e=>e.type===`error`)?`error-message`:`warning-message`} title=${t.map(Yw).join(`
|
|
3871
3871
|
`)}>
|
|
3872
3872
|
${String(t.length)} diagnostic${t.length===1?``:`s`}
|
|
3873
3873
|
</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>`}
|
|
@@ -3875,7 +3875,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3875
3875
|
<button type="button" class="secondary" ?disabled=${this.loading||n} @click=${()=>{this.loadPlugins()}}>Refresh</button>
|
|
3876
3876
|
<button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
|
|
3877
3877
|
</footer>
|
|
3878
|
-
`}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=
|
|
3878
|
+
`}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=Vw(this.selectedKey,n.packages)}catch(n){this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loadError=`Failed to load plugins: ${Zw(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=Bw(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=Vw(void 0,r.packages),r.packages.length===0&&(this.addMode=!0),this.actionMessage=`Package removed.`):this.actionMessage=Kw(e)}catch(e){this.isCurrentTarget(n)&&(this.actionError=Zw(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=Hw(i.packages,t,n);this.selectedKey=a===void 0?r:Bw(a),this.addMode=!1,this.installSource=``,this.actionMessage=`Package installed.`}catch(t){this.isCurrentTarget(e)&&(this.actionError=Zw(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=Zw(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=>Bw(e)===this.selectedKey)}selectPackage(e){this.selectedKey=Bw(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 qw(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`
|
|
3879
3879
|
:host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
|
|
3880
3880
|
.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); }
|
|
3881
3881
|
.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); }
|
|
@@ -3977,7 +3977,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3977
3977
|
.package-actions { width: 100%; }
|
|
3978
3978
|
.metadata-grid { grid-template-columns: 96px minmax(0, 1fr); }
|
|
3979
3979
|
}
|
|
3980
|
-
`}};B([x({attribute:!1})],
|
|
3980
|
+
`}};B([x({attribute:!1})],Y.prototype,`machine`,void 0),B([x({type:String})],Y.prototype,`cwd`,void 0),B([x({attribute:!1})],Y.prototype,`session`,void 0),B([x({attribute:!1})],Y.prototype,`pluginsApi`,void 0),B([x({attribute:!1})],Y.prototype,`sessionsApi`,void 0),B([x({attribute:!1})],Y.prototype,`onClose`,void 0),B([x({attribute:!1})],Y.prototype,`onReloaded`,void 0),B([S()],Y.prototype,`data`,void 0),B([S()],Y.prototype,`loading`,void 0),B([S()],Y.prototype,`loadError`,void 0),B([S()],Y.prototype,`selectedKey`,void 0),B([S()],Y.prototype,`addMode`,void 0),B([S()],Y.prototype,`installSource`,void 0),B([S()],Y.prototype,`installScope`,void 0),B([S()],Y.prototype,`busyKey`,void 0),B([S()],Y.prototype,`actionError`,void 0),B([S()],Y.prototype,`actionMessage`,void 0),B([C(`#plugin-source`)],Y.prototype,`pluginSourceInput`,void 0),Y=B([b(`plugins-config-dialog`)],Y);function Bw(e){return`${e.scope}\0${e.source}`}function Vw(e,t){return e!==void 0&&t.some(t=>Bw(t)===e)?e:t[0]===void 0?void 0:Bw(t[0])}function Hw(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 Uw(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 Ww(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 Gw(e){return e===`loaded`?`var(--pi-accent)`:e===`installed`?`#d97706`:e===`disabled`?`var(--pi-muted)`:`var(--pi-danger)`}function Kw(e){switch(e){case`install`:return`Package installed.`;case`update`:return`Package updated.`;case`disable`:return`Package disabled.`;case`enable`:return`Package enabled.`}}function qw(e){if(!Qw(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function Jw(e){return e.replace(/^\/(?:Users|home)\/[^/]+/u,`~`)}function Yw(e){return`${e.type}: ${e.source===void 0?``:`${e.source}: `}${e.message}`}function Xw(e){return e.target instanceof HTMLInputElement?e.target.value:``}function Zw(e){return e instanceof Error?e.message:String(e)}function Qw(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function $w(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function eT(){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 tT=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 L.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`
|
|
3981
3981
|
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
3982
3982
|
<section @click=${e=>{e.stopPropagation()}}>
|
|
3983
3983
|
<header>
|
|
@@ -4027,7 +4027,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4027
4027
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
4028
4028
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
4029
4029
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
4030
|
-
`}};B([x({attribute:!1})],
|
|
4030
|
+
`}};B([x({attribute:!1})],tT.prototype,`onSubmit`,void 0),B([x({attribute:!1})],tT.prototype,`onCancel`,void 0),B([x()],tT.prototype,`machineId`,void 0),B([S()],tT.prototype,`path`,void 0),B([S()],tT.prototype,`createMissing`,void 0),B([S()],tT.prototype,`suggestions`,void 0),B([S()],tT.prototype,`selected`,void 0),B([S()],tT.prototype,`loading`,void 0),B([C(`input`)],tT.prototype,`pathInput`,void 0),tT=B([b(`project-dialog`)],tT);var nT=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=rT(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`&&iT(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===``||iT(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?iT(this.url):void 0,n=this.validInput()!==void 0&&!this.submitting;return g`
|
|
4031
4031
|
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
4032
4032
|
<section @click=${e=>{e.stopPropagation()}}>
|
|
4033
4033
|
<form @submit=${e=>{this.handleSubmit(e)}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
@@ -4082,7 +4082,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4082
4082
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
4083
4083
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
4084
4084
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
4085
|
-
`}};B([x({attribute:!1})],
|
|
4085
|
+
`}};B([x({attribute:!1})],nT.prototype,`onSubmit`,void 0),B([x({attribute:!1})],nT.prototype,`onCancel`,void 0),B([x()],nT.prototype,`error`,void 0),B([S()],nT.prototype,`url`,void 0),B([S()],nT.prototype,`name`,void 0),B([S()],nT.prototype,`token`,void 0),B([S()],nT.prototype,`submitting`,void 0),B([C(`input[name='baseUrl']`)],nT.prototype,`urlInput`,void 0),B([C(`input[name='name']`)],nT.prototype,`nameInput`,void 0),nT=B([b(`machine-dialog`)],nT);function rT(e){let t=e.trim();if(t===``)return``;let n=aT(t)??aT(`http://${t.replace(/^\/+/u,``)}`);return n!==void 0&&n.hostname!==``?n.hostname.replace(/^\[(.*)\]$/u,`$1`):oT(t)}function iT(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 aT(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:void 0}catch{return}}function oT(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 sT={availability:`error`,error:`error`,success:`success`,security:`warning`,warning:`warning`,info:`info`};function cT(e){return e.tone??sT[e.type]}var lT=class extends y{constructor(...e){super(...e),this.heading=``,this.description=``,this.actionLabel=``,this.actionTitle=``,this.actionDisabled=!1,this.notices=[]}render(){return g`
|
|
4086
4086
|
<section class="panel" aria-label=${this.heading||`Settings panel`}>
|
|
4087
4087
|
<header class="section-heading">
|
|
4088
4088
|
<div class="heading-copy">
|
|
@@ -4105,7 +4105,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4105
4105
|
<div class="notice-stack" aria-label="Settings notices">
|
|
4106
4106
|
${this.notices.map(e=>this.renderNotice(e))}
|
|
4107
4107
|
</div>
|
|
4108
|
-
`}renderNotice(e){let t=
|
|
4108
|
+
`}renderNotice(e){let t=cT(e),n=e.role??uT(t),r=e.title;return g`
|
|
4109
4109
|
<article class=${`notice ${t}`} role=${n}>
|
|
4110
4110
|
${r===void 0||r===``?v:g`<strong class="notice-title">${r}</strong>`}
|
|
4111
4111
|
<div class="notice-content">${e.content}</div>
|
|
@@ -4138,13 +4138,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4138
4138
|
.section-heading { display: grid; gap: 12px; }
|
|
4139
4139
|
.heading-actions { justify-self: start; }
|
|
4140
4140
|
}
|
|
4141
|
-
`}};B([x()],
|
|
4142
|
-
`):``}}function
|
|
4143
|
-
`)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function
|
|
4144
|
-
`).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!
|
|
4141
|
+
`}};B([x()],lT.prototype,`heading`,void 0),B([x({attribute:!1})],lT.prototype,`description`,void 0),B([x()],lT.prototype,`actionLabel`,void 0),B([x()],lT.prototype,`actionTitle`,void 0),B([x({type:Boolean})],lT.prototype,`actionDisabled`,void 0),B([x({attribute:!1})],lT.prototype,`notices`,void 0),B([x({attribute:!1})],lT.prototype,`onAction`,void 0),lT=B([b(`settings-panel-frame`)],lT);function uT(e){switch(e){case`error`:return`alert`;case`success`:return`status`;case`warning`:case`info`:return`note`}}function dT(){return{host:``,port:``,allowedHostsMode:`list`,allowedHostsText:``}}function fT(){return{allowedPathsText:``,uploadDefaultFolder:``}}function pT(){return{command:``,dir:``}}function mT(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(`
|
|
4142
|
+
`):``}}function hT(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
|
|
4143
|
+
`)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function gT(e){return{command:e.agent?.command??``,dir:e.agent?.dir??``}}function _T(e){let t=e.command.trim(),n=e.dir.trim();return{agent:{...t===``?{}:{command:t},...n===``?{}:{dir:n}}}}function vT(e,t){let n=_T(e).agent??{},r=t.agent??{};return n.command===r.command&&n.dir===r.dir}function yT(e,t={}){let n=xT(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`||ST(e.allowedHostsText),n}function bT(e){let t=CT(e.allowedPathsText),n=wT(e.uploadDefaultFolder);return{pathAccess:{allowedPaths:t},uploads:n===``?{}:{defaultFolder:n}}}function xT(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}}}function ST(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e!==``)}function CT(e){let t=e.split(`
|
|
4144
|
+
`).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!TT(e));if(n!==void 0)throw Error(`Allowed external paths must be absolute paths or start with ~: ${n}`);return t}function wT(e){let t=e.trim();if(t===``)return``;if(ET(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 TT(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)||e.startsWith(`/`)||e.startsWith(`\\`)||/^[A-Za-z]:[\\/]/u.test(e)}function ET(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function DT(e){return g`Gateway server fields edit this local gateway. File access and upload defaults edit ${e}.`}var OT=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.gatewayDraft=dT(),this.machineDraft=fT(),this.gatewayLocalError=``,this.machineLocalError=``}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.gatewayDraft=mT(this.configResponse.config),this.gatewayLocalError=``),e.has(`machineConfigResponse`)&&this.machineConfigResponse!==void 0&&(this.machineDraft=hT(this.machineConfigResponse.config),this.machineLocalError=``)}render(){return g`
|
|
4145
4145
|
<settings-panel-frame
|
|
4146
4146
|
heading="General configuration"
|
|
4147
|
-
.description=${
|
|
4147
|
+
.description=${DT(this.targetLabel)}
|
|
4148
4148
|
actionLabel="Reload"
|
|
4149
4149
|
.actionDisabled=${this.loading||this.machineLoading}
|
|
4150
4150
|
.notices=${this.panelNotices()}
|
|
@@ -4173,7 +4173,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4173
4173
|
<span>Host</span>
|
|
4174
4174
|
${this.renderOverrideBadge(`host`)}
|
|
4175
4175
|
</span>
|
|
4176
|
-
<input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:
|
|
4176
|
+
<input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:jT(e)})}}>
|
|
4177
4177
|
<small>Address the web server should bind to. Leave empty to use PI WEBUI's default.</small>
|
|
4178
4178
|
</label>
|
|
4179
4179
|
|
|
@@ -4182,7 +4182,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4182
4182
|
<span>Port</span>
|
|
4183
4183
|
${this.renderOverrideBadge(`port`)}
|
|
4184
4184
|
</span>
|
|
4185
|
-
<input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8808" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:
|
|
4185
|
+
<input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8808" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:jT(e)})}}>
|
|
4186
4186
|
<small>TCP port from 1 to 65535. Leave empty to use PI WEBUI's default.</small>
|
|
4187
4187
|
</label>
|
|
4188
4188
|
|
|
@@ -4191,11 +4191,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4191
4191
|
<span>Allowed hosts</span>
|
|
4192
4192
|
${this.renderOverrideBadge(`allowedHosts`)}
|
|
4193
4193
|
</span>
|
|
4194
|
-
<select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:
|
|
4194
|
+
<select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:MT(e)===`all`?`all`:`list`})}}>
|
|
4195
4195
|
<option value="list">Only listed hosts</option>
|
|
4196
4196
|
<option value="all">Allow every host</option>
|
|
4197
4197
|
</select>
|
|
4198
|
-
<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:
|
|
4198
|
+
<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:NT(e)})}}></textarea>
|
|
4199
4199
|
<small>Enter one host per line, or choose “Allow every host” to write <code>true</code>.</small>
|
|
4200
4200
|
</div>
|
|
4201
4201
|
|
|
@@ -4225,7 +4225,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4225
4225
|
<span class="field-heading">
|
|
4226
4226
|
<span>External filesystem roots</span>
|
|
4227
4227
|
</span>
|
|
4228
|
-
<textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs /opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:
|
|
4228
|
+
<textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs /opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:NT(e)})}}></textarea>
|
|
4229
4229
|
<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>
|
|
4230
4230
|
</label>
|
|
4231
4231
|
|
|
@@ -4233,7 +4233,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4233
4233
|
<span class="field-heading">
|
|
4234
4234
|
<span>Default upload folder</span>
|
|
4235
4235
|
</span>
|
|
4236
|
-
<input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${_o} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:
|
|
4236
|
+
<input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${_o} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:jT(e)})}}>
|
|
4237
4237
|
<small>Workspace-relative folder for manual file uploads on ${this.targetLabel}. Leave empty to use PI WEBUI's default <code>${_o}</code>.</small>
|
|
4238
4238
|
</label>
|
|
4239
4239
|
|
|
@@ -4251,18 +4251,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4251
4251
|
<dl>
|
|
4252
4252
|
<div><dt>Host</dt><dd>${e.host??g`<span class="muted">127.0.0.1 default</span>`}</dd></div>
|
|
4253
4253
|
<div><dt>Port</dt><dd>${e.port??g`<span class="muted">8808 default</span>`}</dd></div>
|
|
4254
|
-
<div><dt>Allowed hosts</dt><dd>${
|
|
4254
|
+
<div><dt>Allowed hosts</dt><dd>${kT(e.allowedHosts)}</dd></div>
|
|
4255
4255
|
</dl>
|
|
4256
4256
|
</section>
|
|
4257
4257
|
`}renderMachineEffectiveConfig(){let e=this.machineConfigResponse?.effectiveConfig??{};return g`
|
|
4258
4258
|
<section class="effective-card" aria-label="Effective selected machine file access and upload summary">
|
|
4259
4259
|
<h3>Effective selected-machine settings</h3>
|
|
4260
4260
|
<dl>
|
|
4261
|
-
<div><dt>External roots</dt><dd>${
|
|
4261
|
+
<div><dt>External roots</dt><dd>${AT(e.pathAccess?.allowedPaths)}</dd></div>
|
|
4262
4262
|
<div><dt>Upload folder</dt><dd>${e.uploads?.defaultFolder??g`<span class="muted">${`.pi-webui/uploads`} default</span>`}</dd></div>
|
|
4263
4263
|
</dl>
|
|
4264
4264
|
</section>
|
|
4265
|
-
`}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(
|
|
4265
|
+
`}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(yT(this.gatewayDraft,this.configResponse?.config??{}))}catch(e){this.gatewayLocalError=PT(e)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError=``;try{await this.onSaveMachineConfig?.(bT(this.machineDraft))}catch(e){this.machineLocalError=PT(e)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=``}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=``}static{this.styles=h`
|
|
4266
4266
|
:host { display: block; }
|
|
4267
4267
|
.card-heading { display: grid; gap: 6px; min-width: 0; }
|
|
4268
4268
|
h3, p { margin: 0; }
|
|
@@ -4301,10 +4301,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4301
4301
|
@media (max-width: 760px) {
|
|
4302
4302
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
4303
4303
|
}
|
|
4304
|
-
`}};B([x({attribute:!1})],
|
|
4304
|
+
`}};B([x({attribute:!1})],OT.prototype,`configResponse`,void 0),B([x({attribute:!1})],OT.prototype,`machineConfigResponse`,void 0),B([x({type:Boolean})],OT.prototype,`loading`,void 0),B([x({type:Boolean})],OT.prototype,`machineLoading`,void 0),B([x({type:Boolean})],OT.prototype,`saving`,void 0),B([x()],OT.prototype,`error`,void 0),B([x()],OT.prototype,`machineError`,void 0),B([x()],OT.prototype,`savedMessage`,void 0),B([x()],OT.prototype,`targetLabel`,void 0),B([x({attribute:!1})],OT.prototype,`onReload`,void 0),B([x({attribute:!1})],OT.prototype,`onReloadMachine`,void 0),B([x({attribute:!1})],OT.prototype,`onSave`,void 0),B([x({attribute:!1})],OT.prototype,`onSaveMachineConfig`,void 0),B([S()],OT.prototype,`gatewayDraft`,void 0),B([S()],OT.prototype,`machineDraft`,void 0),B([S()],OT.prototype,`gatewayLocalError`,void 0),B([S()],OT.prototype,`machineLocalError`,void 0),OT=B([b(`settings-general-panel`)],OT);function kT(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 AT(e){return e===void 0||e.length===0?g`<span class="muted">External paths denied</span>`:e.join(`, `)}function jT(e){return e.target instanceof HTMLInputElement?e.target.value:``}function MT(e){return e.target instanceof HTMLSelectElement?e.target.value:``}function NT(e){return e.target instanceof HTMLTextAreaElement?e.target.value:``}function PT(e){return e instanceof Error?e.message:String(e)}function FT(e){return{spawnSessions:e}}function IT(e){return{subsessions:e}}function LT(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`,...jt(n.command)?[`PI_CODING_AGENT_SESSION_DIR`]:[]];return n.command===t.command&&n.dir===t.dir&&BT(t.sessionDirEnvKeys,r)?`active`:`restart-required`}function RT(e,t){return e?.agentDirSource===`pi-webui`?!0:e?.agentDirSource===`pi-compatibility`?jt(t.trim()||`pi`):e?.agentDir===!0}function zT(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 BT(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var VT=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=pT(),this.agentDraftDirty=!1,this.agentLocalError=``}willUpdate(e){if(e.has(`configResponse`)){if(this.configResponse===void 0){this.agentDraft=pT(),this.agentDraftDirty=!1,this.agentLocalError=``;return}(!this.agentDraftDirty||vT(this.agentDraft,this.configResponse.config))&&(this.agentDraft=gT(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=RT(e?.envOverrides,s),l=e?.envOverrides.agentDir===!0,u=e?.effectiveConfig.agent,d=LT(e,this.activeAgentProfile);return g`
|
|
4305
4305
|
<settings-panel-frame
|
|
4306
4306
|
heading="Session daemon"
|
|
4307
|
-
.description=${
|
|
4307
|
+
.description=${GT(this.targetLabel)}
|
|
4308
4308
|
actionLabel="Reload"
|
|
4309
4309
|
.actionDisabled=${this.loading}
|
|
4310
4310
|
.notices=${this.panelNotices(e)}
|
|
@@ -4330,7 +4330,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4330
4330
|
.value=${this.agentDraft.command}
|
|
4331
4331
|
placeholder="pi"
|
|
4332
4332
|
?disabled=${this.loading||this.saving||!o||a}
|
|
4333
|
-
@input=${e=>{this.updateAgentDraft({command:
|
|
4333
|
+
@input=${e=>{this.updateAgentDraft({command:UT(e)})}}
|
|
4334
4334
|
>
|
|
4335
4335
|
<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>
|
|
4336
4336
|
</label>
|
|
@@ -4347,7 +4347,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4347
4347
|
.value=${this.agentDraft.dir}
|
|
4348
4348
|
placeholder="~/.pi/agent or ~/agent-profiles/work"
|
|
4349
4349
|
?disabled=${this.loading||this.saving||!o||c}
|
|
4350
|
-
@input=${e=>{this.updateAgentDraft({dir:
|
|
4350
|
+
@input=${e=>{this.updateAgentDraft({dir:UT(e)})}}
|
|
4351
4351
|
>
|
|
4352
4352
|
<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>
|
|
4353
4353
|
</label>
|
|
@@ -4395,14 +4395,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4395
4395
|
<div><dt>Desired state</dt><dd>${u?.dir??g`<span class="muted">Unavailable</span>`}</dd></div>
|
|
4396
4396
|
<div><dt>Active command</dt><dd>${this.activeAgentProfile?.command??g`<span class="muted">Unavailable</span>`}</dd></div>
|
|
4397
4397
|
<div><dt>Active state</dt><dd>${this.activeAgentProfile?.dir??g`<span class="muted">Unavailable</span>`}</dd></div>
|
|
4398
|
-
<div><dt>Profile status</dt><dd>${
|
|
4398
|
+
<div><dt>Profile status</dt><dd>${HT(d)}</dd></div>
|
|
4399
4399
|
<div><dt>Spawn sessions</dt><dd>${n?`Enabled`:g`<span class="muted">Disabled</span>`}</dd></div>
|
|
4400
4400
|
<div><dt>Subsessions</dt><dd>${i?`Enabled`:g`<span class="muted">Disabled</span>`}</dd></div>
|
|
4401
4401
|
</dl>
|
|
4402
4402
|
</section>
|
|
4403
4403
|
`}
|
|
4404
4404
|
</settings-panel-frame>
|
|
4405
|
-
`}panelNotices(e){return
|
|
4405
|
+
`}panelNotices(e){return KT(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?.(_T(this.agentDraft))}catch(e){this.agentLocalError=WT(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?.(FT(t))}async toggleSubsessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(IT(t))}static{this.styles=h`
|
|
4406
4406
|
:host { display: block; }
|
|
4407
4407
|
h3 { margin: 0; font-size: 13px; line-height: 1.3; }
|
|
4408
4408
|
button, input { font: inherit; }
|
|
@@ -4448,10 +4448,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4448
4448
|
@media (max-width: 760px) {
|
|
4449
4449
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
4450
4450
|
}
|
|
4451
|
-
`}};B([x({attribute:!1})],
|
|
4451
|
+
`}};B([x({attribute:!1})],VT.prototype,`configResponse`,void 0),B([x({type:Boolean})],VT.prototype,`loading`,void 0),B([x({type:Boolean})],VT.prototype,`saving`,void 0),B([x()],VT.prototype,`error`,void 0),B([x()],VT.prototype,`savedMessage`,void 0),B([x()],VT.prototype,`targetLabel`,void 0),B([x({attribute:!1})],VT.prototype,`activeAgentProfile`,void 0),B([x({attribute:!1})],VT.prototype,`agentProfileSupport`,void 0),B([x({attribute:!1})],VT.prototype,`onReload`,void 0),B([x({attribute:!1})],VT.prototype,`onSave`,void 0),B([S()],VT.prototype,`agentDraft`,void 0),B([S()],VT.prototype,`agentDraftDirty`,void 0),B([S()],VT.prototype,`agentLocalError`,void 0),VT=B([b(`settings-sessiond-panel`)],VT);function HT(e){return e===`active`?`Active`:e===`restart-required`?`Restart required`:g`<span class="muted">Unavailable</span>`}function UT(e){return e.target instanceof HTMLInputElement?e.target.value:``}function WT(e){return e instanceof Error?e.message:String(e)}function GT(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 KT(e,t){let n=[];t.error!==``&&n.push({type:`error`,content:t.error}),t.savedMessage!==``&&n.push({type:`success`,content:t.savedMessage});let r=LT(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 qT(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function JT(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function YT(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Gt(t,T.piPackagesManage)?{state:`supported`}:{state:`unsupported`,message:QT(e)}:{state:`unknown`}}function XT(e){return`${e.state}:${e.message??``}`}function ZT(e){return e?.state===`unsupported`}function QT(e){return`Pi package management is not available on ${e.name}. Update and restart Pi-Web on that machine, then try again.`}function $T(e){return e.kind===`local`}function eE(e){return e.trim()}function tE(e){if(eE(e)===``)return`Enter a Pi package source accepted by Pi, such as npm:@scope/package, a git/URL source, or a local path.`}function nE(e){return e.scope===`project`?`Project scope`:`User scope`}function rE(e){return e.filtered?`Filtered by current Pi package settings`:`Available in this PI WEBUI process`}function iE(e){return e.installedPath??`Installed path not reported by Pi`}function aE(e){return e.scope===`user`}function oE(e){if(!aE(e))return`Project-scope Pi packages are listed for visibility, but PI WEBUI only updates user-scope Pi packages safely from this view.`}function sE(e){return e.length>0&&e.every(aE)}function cE(e){if(e.length===0)return`No Pi packages are configured yet.`;if(!sE(e))return`Update all is disabled while project-scope Pi packages are listed; update user-scope packages individually.`}function lE(e,t,n){return e?.kind===t?n===void 0||e.source===n:!1}function uE(e,t=qT(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 dE(e,t){let n=e.trim();return t.kind===`remote`?fE(n)?QT(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 fE(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 pE=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=JT(t),r=this.packageManagementUnavailable,i=this.packagesResponse!==void 0&&!r;return g`
|
|
4452
4452
|
<settings-panel-frame
|
|
4453
4453
|
heading="Pi packages"
|
|
4454
|
-
.description=${
|
|
4454
|
+
.description=${mE(n)}
|
|
4455
4455
|
actionLabel="Reload"
|
|
4456
4456
|
actionTitle=${r?this.packageManagementUnavailableMessage(n):`Reload Pi packages from ${n}`}
|
|
4457
4457
|
.actionDisabled=${this.loading||this.isOperating||r}
|
|
@@ -4468,12 +4468,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4468
4468
|
<label for="package-source">Pi package source</label>
|
|
4469
4469
|
<div class="install-row">
|
|
4470
4470
|
<input id="package-source" .value=${this.installSource} ?disabled=${this.isOperating} placeholder="npm:@scope/package, git URL, or local path" @input=${e=>{this.updateInstallSource(e)}}>
|
|
4471
|
-
<button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${
|
|
4471
|
+
<button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${lE(this.operation,`install`)?`Installing…`:`Install`}</button>
|
|
4472
4472
|
</div>
|
|
4473
4473
|
${this.validationMessage===``?null:g`<div class="field-error">${this.validationMessage}</div>`}
|
|
4474
4474
|
<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>
|
|
4475
4475
|
</form>
|
|
4476
|
-
`}renderPackageList(e,t){let n=
|
|
4476
|
+
`}renderPackageList(e,t){let n=JT(t),r=this.packageManagementUnavailable?this.packageManagementUnavailableMessage(n):cE(e),i=r!==void 0&&e.length>0;return g`
|
|
4477
4477
|
<section class="package-section" aria-label="Configured Pi packages">
|
|
4478
4478
|
<div class="package-toolbar">
|
|
4479
4479
|
<div>
|
|
@@ -4481,7 +4481,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4481
4481
|
<p>This list comes from Pi's package manager settings on ${n}.</p>
|
|
4482
4482
|
</div>
|
|
4483
4483
|
<button class="secondary" title=${r??`Update all user-scope Pi packages`} ?disabled=${this.isOperating||r!==void 0} @click=${()=>{this.updatePackage()}}>
|
|
4484
|
-
${
|
|
4484
|
+
${lE(this.operation,`update-all`)?`Updating…`:`Update all`}
|
|
4485
4485
|
</button>
|
|
4486
4486
|
</div>
|
|
4487
4487
|
${i?g`<div class="action-note">${r}</div>`:null}
|
|
@@ -4492,12 +4492,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4492
4492
|
<div class="package-list">
|
|
4493
4493
|
${e.map(e=>this.renderPackage(e))}
|
|
4494
4494
|
</div>
|
|
4495
|
-
`}renderPackage(e){let t=
|
|
4495
|
+
`}renderPackage(e){let t=JT(this.packageTarget),n=this.packageManagementUnavailable,r=n?this.packageManagementUnavailableMessage(t):oE(e),i=n?this.packageManagementUnavailableMessage(t):`Remove this Pi package`,a=lE(this.operation,`update`,e.source),o=lE(this.operation,`remove`,e.source);return g`
|
|
4496
4496
|
<article class=${`package-card${e.filtered?` filtered`:``}`}>
|
|
4497
4497
|
<div class="package-main">
|
|
4498
4498
|
<strong>${e.source}</strong>
|
|
4499
|
-
<small>${
|
|
4500
|
-
<small>Installed path: <code>${
|
|
4499
|
+
<small>${nE(e)} · ${rE(e)}</small>
|
|
4500
|
+
<small>Installed path: <code>${iE(e)}</code></small>
|
|
4501
4501
|
${r===void 0?null:g`<small class="action-note">${r}</small>`}
|
|
4502
4502
|
</div>
|
|
4503
4503
|
<div class="package-actions">
|
|
@@ -4505,7 +4505,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4505
4505
|
<button class="danger" title=${i} ?disabled=${this.isOperating||n} @click=${()=>{this.removePackage(e)}}>${o?`Removing…`:`Remove`}</button>
|
|
4506
4506
|
</div>
|
|
4507
4507
|
</article>
|
|
4508
|
-
`}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t
|
|
4508
|
+
`}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=tE(this.installSource);if(t!==void 0){this.validationMessage=t;return}let n=eE(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??qT(void 0)}get packageManagementUnavailable(){return ZT(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`
|
|
4509
4509
|
:host { display: block; }
|
|
4510
4510
|
.package-toolbar { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
4511
4511
|
.package-toolbar > div, .package-main { display: grid; gap: 6px; min-width: 0; }
|
|
@@ -4540,10 +4540,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4540
4540
|
.package-actions { justify-self: start; flex-wrap: wrap; }
|
|
4541
4541
|
.package-main strong, .package-main small { white-space: normal; }
|
|
4542
4542
|
}
|
|
4543
|
-
`}};B([x({attribute:!1})],
|
|
4543
|
+
`}};B([x({attribute:!1})],pE.prototype,`packagesResponse`,void 0),B([x({type:Boolean})],pE.prototype,`loading`,void 0),B([x({attribute:!1})],pE.prototype,`operation`,void 0),B([x({attribute:!1})],pE.prototype,`targetMachine`,void 0),B([x({attribute:!1})],pE.prototype,`managementSupport`,void 0),B([x()],pE.prototype,`error`,void 0),B([x()],pE.prototype,`operationMessage`,void 0),B([x({attribute:!1})],pE.prototype,`onReload`,void 0),B([x({attribute:!1})],pE.prototype,`onInstallPackage`,void 0),B([x({attribute:!1})],pE.prototype,`onRemovePackage`,void 0),B([x({attribute:!1})],pE.prototype,`onUpdatePackage`,void 0),B([S()],pE.prototype,`installSource`,void 0),B([S()],pE.prototype,`validationMessage`,void 0),pE=B([b(`settings-packages-panel`)],pE);function mE(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 hE=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`
|
|
4544
4544
|
<settings-panel-frame
|
|
4545
4545
|
heading="PI WEBUI plugins"
|
|
4546
|
-
.description=${
|
|
4546
|
+
.description=${gE(this.targetLabel)}
|
|
4547
4547
|
actionLabel="Reload"
|
|
4548
4548
|
actionTitle=${`Reload PI WEBUI plugins from ${this.targetLabel}`}
|
|
4549
4549
|
.actionDisabled=${this.loading}
|
|
@@ -4589,10 +4589,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4589
4589
|
.plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
4590
4590
|
.toggle { justify-self: start; }
|
|
4591
4591
|
}
|
|
4592
|
-
`}};B([x({attribute:!1})],
|
|
4592
|
+
`}};B([x({attribute:!1})],hE.prototype,`pluginsResponse`,void 0),B([x({attribute:!1})],hE.prototype,`configResponse`,void 0),B([x({type:Boolean})],hE.prototype,`loading`,void 0),B([x({type:Boolean})],hE.prototype,`saving`,void 0),B([x()],hE.prototype,`error`,void 0),B([x()],hE.prototype,`savedMessage`,void 0),B([x()],hE.prototype,`targetLabel`,void 0),B([x({attribute:!1})],hE.prototype,`onReload`,void 0),B([x({attribute:!1})],hE.prototype,`onTogglePlugin`,void 0),hE=B([b(`settings-plugins-panel`)],hE);function gE(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.`}var _E={capture:!0},vE=[{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 yE(){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 bE=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=LS(),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=uf(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&&!df(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=wE(this.actions),t=this.shortcutResolutions();return g`
|
|
4593
4593
|
<settings-panel-frame
|
|
4594
4594
|
heading="Keyboard shortcuts"
|
|
4595
|
-
.description=${
|
|
4595
|
+
.description=${yE()}
|
|
4596
4596
|
actionLabel="Reload"
|
|
4597
4597
|
.actionDisabled=${this.loading}
|
|
4598
4598
|
.notices=${this.panelNotices()}
|
|
@@ -4623,7 +4623,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4623
4623
|
<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>
|
|
4624
4624
|
</div>
|
|
4625
4625
|
<div class="prompt-enter-options" role="radiogroup" aria-label="Enter and Shift Enter behavior in the chat composer">
|
|
4626
|
-
${
|
|
4626
|
+
${vE.map(e=>g`
|
|
4627
4627
|
<label class="prompt-enter-option">
|
|
4628
4628
|
<input
|
|
4629
4629
|
type="radio"
|
|
@@ -4640,8 +4640,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4640
4640
|
`)}
|
|
4641
4641
|
</div>
|
|
4642
4642
|
</section>
|
|
4643
|
-
`}updatePromptEnterPreference(e){this.promptEnterPreference=e,
|
|
4644
|
-
<article class=${
|
|
4643
|
+
`}updatePromptEnterPreference(e){this.promptEnterPreference=e,RS(e)}renderShortcutRow(e,t){let n=this.configResponse?.config.shortcuts,r=EE(e.id,n),i=kE(e,n),a=this.shortcutInputText(e),o=a.trim()===``?void 0:sf(a),s=o?.ok===!0?o.shortcut:OE(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=CE(t);return g`
|
|
4644
|
+
<article class=${xE(t)}>
|
|
4645
4645
|
<div class="shortcut-main">
|
|
4646
4646
|
<strong>${e.title}</strong>
|
|
4647
4647
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
@@ -4651,8 +4651,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4651
4651
|
<div class="shortcut-editor">
|
|
4652
4652
|
<div class="shortcut-status">
|
|
4653
4653
|
${s!==void 0&&s!==``?g`<kbd>${lf(s)}</kbd>`:g`<span class="unassigned">${i===`disabled`?`Disabled`:`Unassigned`}</span>`}
|
|
4654
|
-
<small class=${u}>${
|
|
4655
|
-
${f===void 0?null:g`<small class=${
|
|
4654
|
+
<small class=${u}>${AE(u)}${l?` · Unsaved`:``}</small>
|
|
4655
|
+
${f===void 0?null:g`<small class=${SE(t)}>${f}</small>`}
|
|
4656
4656
|
</div>
|
|
4657
4657
|
<label class="shortcut-input-label">
|
|
4658
4658
|
<span>Shortcut</span>
|
|
@@ -4665,7 +4665,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4665
4665
|
autocapitalize="off"
|
|
4666
4666
|
spellcheck="false"
|
|
4667
4667
|
?disabled=${this.saving}
|
|
4668
|
-
@input=${t=>{this.updateDraft(e.id,
|
|
4668
|
+
@input=${t=>{this.updateDraft(e.id,jE(t))}}
|
|
4669
4669
|
>
|
|
4670
4670
|
</label>
|
|
4671
4671
|
${d===``?null:g`<small class="recording-hint">${d}</small>`}
|
|
@@ -4677,7 +4677,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4677
4677
|
</div>
|
|
4678
4678
|
</div>
|
|
4679
4679
|
</article>
|
|
4680
|
-
`}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=
|
|
4680
|
+
`}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=EE(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: ${lf(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=sf(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?DE(r,e):{...r,[e]:t};Object.keys(i).length===0?delete n.shortcuts:n.shortcuts=i,await this.onSave?.(n)}shortcutResolutions(){return new Map(of(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=sf(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()},nf)}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,_E),!0)}removeRecordingListener(){this.recordingListenerActive&&=(window.removeEventListener(`keydown`,this.onRecordKeyDown,_E),!1)}static{this.styles=h`
|
|
4681
4681
|
:host { display: block; }
|
|
4682
4682
|
h3, p { margin: 0; }
|
|
4683
4683
|
h3 { font-size: 13px; line-height: 1.3; }
|
|
@@ -4733,7 +4733,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4733
4733
|
.shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
4734
4734
|
.shortcut-status, .shortcut-actions { justify-content: flex-start; }
|
|
4735
4735
|
}
|
|
4736
|
-
`}};B([x({attribute:!1})],
|
|
4736
|
+
`}};B([x({attribute:!1})],bE.prototype,`actions`,void 0),B([x({attribute:!1})],bE.prototype,`configResponse`,void 0),B([x({type:Boolean})],bE.prototype,`loading`,void 0),B([x({type:Boolean})],bE.prototype,`saving`,void 0),B([x()],bE.prototype,`error`,void 0),B([x()],bE.prototype,`savedMessage`,void 0),B([x({attribute:!1})],bE.prototype,`onReload`,void 0),B([x({attribute:!1})],bE.prototype,`onSave`,void 0),B([S()],bE.prototype,`drafts`,void 0),B([S()],bE.prototype,`localError`,void 0),B([S()],bE.prototype,`promptEnterPreference`,void 0),B([S()],bE.prototype,`recording`,void 0),bE=B([b(`settings-shortcuts-panel`)],bE);function xE(e){return e?.active===!1?`shortcut-row shadowed`:e?.active===!0&&e.shadows.length>0?`shortcut-row shadowing`:`shortcut-row`}function SE(e){return e?.active===!1?`conflict shadowed`:`conflict shadowing`}function CE(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 wE(e){let t=new Map;for(let n of[...e].sort(TE)){let e=n.group??`Other`;t.set(e,[...t.get(e)??[],n])}return[...t.entries()].map(([e,t])=>({name:e,actions:t}))}function TE(e,t){return(e.group??`Other`).localeCompare(t.group??`Other`)||e.title.localeCompare(t.title)}function EE(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function DE(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function OE(e,t){let n=EE(e.id,t);if(n!==null)return n??e.shortcut}function kE(e,t){let n=EE(e.id,t);return n===null?`disabled`:n===void 0?e.shortcut===void 0||e.shortcut===``?`unassigned`:`default`:`custom`}function AE(e){switch(e){case`default`:return`Default`;case`custom`:return`Custom`;case`disabled`:return`Disabled`;case`unassigned`:return`No default`}}function jE(e){return e.target instanceof HTMLInputElement?e.target.value:``}async function ME(e){let[t,n]=await Promise.allSettled([e.loadConfig(),e.loadPlugins()]),r={error:``},i=[];return t.status===`fulfilled`?r.config=t.value:i.push(`config: ${PE(t.reason)}`),n.status===`fulfilled`?r.plugins=n.value:i.push(`PI WEBUI plugins: ${PE(n.reason)}`),i.length>0&&(r.error=`Failed to load settings: ${i.join(`; `)}`),r}async function NE(e,t,n){if(ZT(n))return{error:n.message??`Pi package management is not available on ${JT(e)}.`,skipped:!0};try{return{packagesResponse:await t(e.id),error:``}}catch(t){return{error:`Failed to load Pi packages from ${JT(e)}: ${dE(PE(t),e)}`}}}function PE(e){return e instanceof Error?e.message:String(e)}function FE(e,t){return{...e,config:IE(e.config,t.config),effectiveConfig:IE(e.effectiveConfig,t.effectiveConfig)}}function IE(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 LE(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function RE(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function zE(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Gt(t,T.selectedMachineSettings)?{state:`supported`}:{state:`unsupported`,message:WE(e)}:{state:`unknown`}}function BE(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Gt(t,T.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 VE(e){return`${e.state}:${e.message??``}`}function HE(e){return e?.state===`unsupported`}function UE(e){return e?.state===`supported`}function WE(e){return`Selected-machine settings are not available on ${e.name}. Update and restart PI WEBUI on that machine, then try again.`}function GE(e,t){let n=e.trim();return t.kind===`remote`?KE(n)?WE(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 KE(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 qE(e,t,n){let r=e.plugins??{},i=r[t]??{};return{plugins:{...r,[t]:{...i,enabled:n}}}}function JE(e,t){return{...e,config:YE(e.config,t.config),effectiveConfig:YE(e.effectiveConfig,t.effectiveConfig)}}function YE(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.loading=!0,this.accessLoading=!0,this.sessiondLoading=!0,this.pluginLoading=!0,this.packageLoading=!0,this.saving=!1,this.error=``,this.accessError=``,this.sessiondError=``,this.pluginError=``,this.packageError=``,this.savedMessage=``,this.packageMessage=``,this.loadRequestSeq=0,this.accessLoadRequestSeq=0,this.sessiondLoadRequestSeq=0,this.pluginLoadRequestSeq=0,this.packageLoadRequestSeq=0,this.packageMutationSeq=0}connectedCallback(){super.connectedCallback(),this.loadConfig(),this.loadAccessConfigForTarget(),this.reloadSessiondState(),this.loadPluginsForTarget(),this.loadPackagesForTarget()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}updated(e){let t=this.settingsTarget();if(e.has(`machine`)&&LE(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);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.packageManagementSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t)))}render(){return g`
|
|
4737
4737
|
<div class="backdrop" @mousedown=${()=>this.onClose?.()}>
|
|
4738
4738
|
<section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEBUI settings" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
4739
4739
|
<header class="settings-header">
|
|
@@ -4764,7 +4764,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4764
4764
|
.saving=${this.saving}
|
|
4765
4765
|
.error=${this.sessiondError}
|
|
4766
4766
|
.savedMessage=${this.savedMessage}
|
|
4767
|
-
.targetLabel=${
|
|
4767
|
+
.targetLabel=${RE(this.settingsTarget())}
|
|
4768
4768
|
.activeAgentProfile=${this.machineRuntime?.components?.sessiond.activeAgentProfile}
|
|
4769
4769
|
.agentProfileSupport=${this.agentProfileSettingsSupport()}
|
|
4770
4770
|
.onReload=${()=>this.reloadSessiondState()}
|
|
@@ -4803,7 +4803,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4803
4803
|
.saving=${this.saving}
|
|
4804
4804
|
.error=${this.pluginError}
|
|
4805
4805
|
.savedMessage=${this.savedMessage}
|
|
4806
|
-
.targetLabel=${
|
|
4806
|
+
.targetLabel=${RE(this.settingsTarget())}
|
|
4807
4807
|
.onReload=${()=>this.loadPluginsForTarget()}
|
|
4808
4808
|
.onTogglePlugin=${(e,t)=>this.togglePlugin(e,t)}
|
|
4809
4809
|
></settings-plugins-panel>
|
|
@@ -4817,7 +4817,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4817
4817
|
.error=${this.error}
|
|
4818
4818
|
.machineError=${this.accessError}
|
|
4819
4819
|
.savedMessage=${this.savedMessage}
|
|
4820
|
-
.targetLabel=${
|
|
4820
|
+
.targetLabel=${RE(this.settingsTarget())}
|
|
4821
4821
|
.onReload=${()=>this.loadConfig()}
|
|
4822
4822
|
.onReloadMachine=${()=>this.loadAccessConfigForTarget()}
|
|
4823
4823
|
.onSave=${e=>this.saveConfig(e)}
|
|
@@ -4828,7 +4828,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4828
4828
|
<strong>${t}</strong>
|
|
4829
4829
|
<small>${n}</small>
|
|
4830
4830
|
</button>
|
|
4831
|
-
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await AE({loadConfig:()=>Ua.config(),loadPlugins:()=>Wa.plugins()});if(!this.isCurrentLoad(e))return;t.config!==void 0&&(this.configResponse=t.config),t.plugins!==void 0&&(this.pluginsResponse=t.plugins),this.error=t.error}finally{this.isCurrentLoad(e)&&(this.loading=!1)}}async loadAccessConfigForTarget(e=this.settingsTarget()){let t=++this.accessLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(BE(n)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=n.message??`Selected-machine settings are not available on ${IE(e)}.`;return}this.accessLoading=!0,this.accessError=``;try{let n=await Ua.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 ${IE(e)}: ${UE(JE(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(BE(n)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=n.message??`Selected-machine settings are not available on ${IE(e)}.`;return}this.sessiondLoading=!0,this.sessiondError=``;try{let n=await Ua.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 ${IE(e)}: ${UE(JE(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(BE(n)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=n.message??`Selected-machine settings are not available on ${IE(e)}.`;return}this.pluginLoading=!0,this.pluginError=``;try{let[n,r]=await Promise.allSettled([Ua.config(e.id),Wa.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let i=[];n.status===`fulfilled`?this.selectedPluginConfigResponse=n.value:i.push(`config: ${UE(JE(n.reason),e)}`),r.status===`fulfilled`?this.selectedPluginsResponse=r.value:i.push(`PI WEBUI plugins: ${UE(JE(r.reason),e)}`),this.pluginError=i.length===0?``:`Failed to load PI WEBUI plugin settings from ${IE(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 jE(e,e=>Za.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 togglePlugin(e,t){if(this.saving)return;let n=this.settingsTarget(),r=this.selectedMachineSettingsSupport(n);if(BE(r)){this.pluginError=r.message??`Selected-machine settings are not available on ${IE(n)}.`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${IE(n)}. Reload before changing plugin enablement.`;return}let i=GE(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await Ua.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=KE(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 ${IE(n)}: ${UE(JE(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await Ua.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`Failed to save config: ${JE(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(BE(n)){this.accessError=n.message??`Selected-machine settings are not available on ${IE(t)}.`;return}this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await Ua.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=NE(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 ${IE(t)}: ${UE(JE(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(BE(n)){this.sessiondError=n.message??`Selected-machine settings are not available on ${IE(t)}.`;return}if(e.agent!==void 0){let e=this.agentProfileSettingsSupport(t);if(!VE(e)){this.sessiondError=e.message??`Pi-compatible agent profile settings are not available on ${IE(t)}.`;return}}this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await Ua.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=LT(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${IE(t)}: ${UE(JE(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`install Pi package`,t,()=>Za.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`remove Pi package`,n,()=>Za.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,()=>Za.update(e,t.id))}async runPiPackageMutation(e,t,n,r){let i=this.packageManagementSupport(n);if(YT(i))throw this.packageError=i.message??`Pi package management is not available on ${KT(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=ZT(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(a,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=cE(e.action,n)}catch(e){throw this.isCurrentPackageMutation(a,n)&&(this.packageError=`Failed to ${t} on ${KT(n)}: ${lE(JE(e),n)}`),e}finally{this.packageMutationSeq===a&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await Wa.plugins();return}catch(e){return`Failed to refresh gateway PI WEBUI plugins: ${JE(e)}`}}async refreshPluginsForTarget(e){try{let t=await Wa.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`Config saved, but failed to refresh PI WEBUI plugins from ${IE(e)}: ${UE(JE(t),e)}`}}settingsTarget(){return FE(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return LE(e,this.machineRuntime)}agentProfileSettingsSupport(e=this.settingsTarget()){return RE(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){let n=LE(t,e),r=this.selectedMachineSettingsSupport(t);return zE(n)!==zE(r)}packageManagementSupport(e=this.packageTarget()){return qT(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){let n=qT(t,e),r=this.packageManagementSupport(t);return JT(n)===JT(r)?!1:n.state===`unsupported`||r.state===`unsupported`}isCurrentLoad(e){return e===this.loadRequestSeq}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)}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)}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`
|
|
4831
|
+
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await ME({loadConfig:()=>Ua.config(),loadPlugins:()=>Wa.plugins()});if(!this.isCurrentLoad(e))return;t.config!==void 0&&(this.configResponse=t.config),t.plugins!==void 0&&(this.pluginsResponse=t.plugins),this.error=t.error}finally{this.isCurrentLoad(e)&&(this.loading=!1)}}async loadAccessConfigForTarget(e=this.settingsTarget()){let t=++this.accessLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(HE(n)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=n.message??`Selected-machine settings are not available on ${RE(e)}.`;return}this.accessLoading=!0,this.accessError=``;try{let n=await Ua.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 ${RE(e)}: ${GE(XE(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(HE(n)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=n.message??`Selected-machine settings are not available on ${RE(e)}.`;return}this.sessiondLoading=!0,this.sessiondError=``;try{let n=await Ua.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 ${RE(e)}: ${GE(XE(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(HE(n)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=n.message??`Selected-machine settings are not available on ${RE(e)}.`;return}this.pluginLoading=!0,this.pluginError=``;try{let[n,r]=await Promise.allSettled([Ua.config(e.id),Wa.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let i=[];n.status===`fulfilled`?this.selectedPluginConfigResponse=n.value:i.push(`config: ${GE(XE(n.reason),e)}`),r.status===`fulfilled`?this.selectedPluginsResponse=r.value:i.push(`PI WEBUI plugins: ${GE(XE(r.reason),e)}`),this.pluginError=i.length===0?``:`Failed to load PI WEBUI plugin settings from ${RE(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 NE(e,e=>Za.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 togglePlugin(e,t){if(this.saving)return;let n=this.settingsTarget(),r=this.selectedMachineSettingsSupport(n);if(HE(r)){this.pluginError=r.message??`Selected-machine settings are not available on ${RE(n)}.`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${RE(n)}. Reload before changing plugin enablement.`;return}let i=qE(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await Ua.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=JE(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 ${RE(n)}: ${GE(XE(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await Ua.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`Failed to save config: ${XE(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(HE(n)){this.accessError=n.message??`Selected-machine settings are not available on ${RE(t)}.`;return}this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await Ua.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=FE(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 ${RE(t)}: ${GE(XE(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(HE(n)){this.sessiondError=n.message??`Selected-machine settings are not available on ${RE(t)}.`;return}if(e.agent!==void 0){let e=this.agentProfileSettingsSupport(t);if(!UE(e)){this.sessiondError=e.message??`Pi-compatible agent profile settings are not available on ${RE(t)}.`;return}}this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await Ua.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=zT(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${RE(t)}: ${GE(XE(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`install Pi package`,t,()=>Za.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`remove Pi package`,n,()=>Za.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,()=>Za.update(e,t.id))}async runPiPackageMutation(e,t,n,r){let i=this.packageManagementSupport(n);if(ZT(i))throw this.packageError=i.message??`Pi package management is not available on ${JT(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=$T(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(a,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=uE(e.action,n)}catch(e){throw this.isCurrentPackageMutation(a,n)&&(this.packageError=`Failed to ${t} on ${JT(n)}: ${dE(XE(e),n)}`),e}finally{this.packageMutationSeq===a&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await Wa.plugins();return}catch(e){return`Failed to refresh gateway PI WEBUI plugins: ${XE(e)}`}}async refreshPluginsForTarget(e){try{let t=await Wa.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`Config saved, but failed to refresh PI WEBUI plugins from ${RE(e)}: ${GE(XE(t),e)}`}}settingsTarget(){return LE(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return zE(e,this.machineRuntime)}agentProfileSettingsSupport(e=this.settingsTarget()){return BE(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){let n=zE(t,e),r=this.selectedMachineSettingsSupport(t);return VE(n)!==VE(r)}packageManagementSupport(e=this.packageTarget()){return YT(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){let n=YT(t,e),r=this.packageManagementSupport(t);return XT(n)===XT(r)?!1:n.state===`unsupported`||r.state===`unsupported`}isCurrentLoad(e){return e===this.loadRequestSeq}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)}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)}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`
|
|
4832
4832
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
4833
4833
|
.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; }
|
|
4834
4834
|
.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; }
|
|
@@ -4855,7 +4855,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4855
4855
|
.settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
|
|
4856
4856
|
.settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
|
|
4857
4857
|
}
|
|
4858
|
-
`}};B([x({attribute:!1})],X.prototype,`section`,void 0),B([x({attribute:!1})],X.prototype,`actions`,void 0),B([x({attribute:!1})],X.prototype,`machine`,void 0),B([x({attribute:!1})],X.prototype,`machineRuntime`,void 0),B([x({attribute:!1})],X.prototype,`onNavigate`,void 0),B([x({attribute:!1})],X.prototype,`onClose`,void 0),B([x({attribute:!1})],X.prototype,`onConfigSaved`,void 0),B([x({attribute:!1})],X.prototype,`onRefreshMachineRuntime`,void 0),B([S()],X.prototype,`configResponse`,void 0),B([S()],X.prototype,`accessConfigResponse`,void 0),B([S()],X.prototype,`sessiondConfigResponse`,void 0),B([S()],X.prototype,`pluginsResponse`,void 0),B([S()],X.prototype,`selectedPluginConfigResponse`,void 0),B([S()],X.prototype,`selectedPluginsResponse`,void 0),B([S()],X.prototype,`packagesResponse`,void 0),B([S()],X.prototype,`loading`,void 0),B([S()],X.prototype,`accessLoading`,void 0),B([S()],X.prototype,`sessiondLoading`,void 0),B([S()],X.prototype,`pluginLoading`,void 0),B([S()],X.prototype,`packageLoading`,void 0),B([S()],X.prototype,`saving`,void 0),B([S()],X.prototype,`packageOperation`,void 0),B([S()],X.prototype,`error`,void 0),B([S()],X.prototype,`accessError`,void 0),B([S()],X.prototype,`sessiondError`,void 0),B([S()],X.prototype,`pluginError`,void 0),B([S()],X.prototype,`packageError`,void 0),B([S()],X.prototype,`savedMessage`,void 0),B([S()],X.prototype,`packageMessage`,void 0),X=B([b(`settings-dialog`)],X);function
|
|
4858
|
+
`}};B([x({attribute:!1})],X.prototype,`section`,void 0),B([x({attribute:!1})],X.prototype,`actions`,void 0),B([x({attribute:!1})],X.prototype,`machine`,void 0),B([x({attribute:!1})],X.prototype,`machineRuntime`,void 0),B([x({attribute:!1})],X.prototype,`onNavigate`,void 0),B([x({attribute:!1})],X.prototype,`onClose`,void 0),B([x({attribute:!1})],X.prototype,`onConfigSaved`,void 0),B([x({attribute:!1})],X.prototype,`onRefreshMachineRuntime`,void 0),B([S()],X.prototype,`configResponse`,void 0),B([S()],X.prototype,`accessConfigResponse`,void 0),B([S()],X.prototype,`sessiondConfigResponse`,void 0),B([S()],X.prototype,`pluginsResponse`,void 0),B([S()],X.prototype,`selectedPluginConfigResponse`,void 0),B([S()],X.prototype,`selectedPluginsResponse`,void 0),B([S()],X.prototype,`packagesResponse`,void 0),B([S()],X.prototype,`loading`,void 0),B([S()],X.prototype,`accessLoading`,void 0),B([S()],X.prototype,`sessiondLoading`,void 0),B([S()],X.prototype,`pluginLoading`,void 0),B([S()],X.prototype,`packageLoading`,void 0),B([S()],X.prototype,`saving`,void 0),B([S()],X.prototype,`packageOperation`,void 0),B([S()],X.prototype,`error`,void 0),B([S()],X.prototype,`accessError`,void 0),B([S()],X.prototype,`sessiondError`,void 0),B([S()],X.prototype,`pluginError`,void 0),B([S()],X.prototype,`packageError`,void 0),B([S()],X.prototype,`savedMessage`,void 0),B([S()],X.prototype,`packageMessage`,void 0),X=B([b(`settings-dialog`)],X);function XE(e){return e instanceof Error?e.message:String(e)}var ZE=class extends y{constructor(...e){super(...e),this.sessionsApi=io,this.loading=!0,this.error=``,this.loadRequestSequence=0}connectedCallback(){super.connectedCallback(),this.loadSystemPrompt()}updated(e){let t=e.has(`session`)&&$E(e.get(`session`))!==$E(this.session),n=e.has(`machine`)&&QE(e.get(`machine`))!==QE(this.machine);(t||n)&&this.isConnected&&this.loadSystemPrompt()}render(){return g`
|
|
4859
4859
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
4860
4860
|
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="system-prompt-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
4861
4861
|
<header>
|
|
@@ -4864,7 +4864,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4864
4864
|
<h1 id="system-prompt-dialog-title">System prompt</h1>
|
|
4865
4865
|
</div>
|
|
4866
4866
|
<button class="icon-button" type="button" title="Close system prompt" aria-label="Close system prompt" @click=${()=>{this.close()}}>
|
|
4867
|
-
${
|
|
4867
|
+
${rD()}
|
|
4868
4868
|
</button>
|
|
4869
4869
|
</header>
|
|
4870
4870
|
<div class="prompt-body" aria-live="polite">
|
|
@@ -4875,7 +4875,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4875
4875
|
</footer>
|
|
4876
4876
|
</section>
|
|
4877
4877
|
</div>
|
|
4878
|
-
`}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
|
|
4878
|
+
`}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:tD(QE(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,QE(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: ${nD(e)}`}finally{this.isCurrentLoad(n,t)&&(this.loading=!1)}}isCurrentLoad(e,t){let n=this.session;return e===this.loadRequestSequence&&n!==void 0&&tD(QE(this.machine),n)===t}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}close(){this.onClose?.()}static{this.styles=h`
|
|
4879
4879
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
4880
4880
|
* { box-sizing: border-box; }
|
|
4881
4881
|
.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; }
|
|
@@ -4901,11 +4901,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4901
4901
|
header, footer { padding: 12px; }
|
|
4902
4902
|
.system-prompt, .prompt-state { padding: 12px; }
|
|
4903
4903
|
}
|
|
4904
|
-
`}};B([x({attribute:!1})],
|
|
4904
|
+
`}};B([x({attribute:!1})],ZE.prototype,`machine`,void 0),B([x({attribute:!1})],ZE.prototype,`session`,void 0),B([x({attribute:!1})],ZE.prototype,`sessionsApi`,void 0),B([x({attribute:!1})],ZE.prototype,`onClose`,void 0),B([S()],ZE.prototype,`systemPrompt`,void 0),B([S()],ZE.prototype,`loading`,void 0),B([S()],ZE.prototype,`error`,void 0),ZE=B([b(`system-prompt-dialog`)],ZE);function QE(e){return e?.id??`local`}function $E(e){return e===void 0?void 0:eD(e)}function eD(e){return JSON.stringify([e.id,e.cwd])}function tD(e,t){return JSON.stringify([e,t.id,t.cwd])}function nD(e){return e instanceof Error?e.message:String(e)}function rD(){return _`
|
|
4905
4905
|
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
4906
4906
|
<path d="M6 6l12 12M18 6 6 18"></path>
|
|
4907
4907
|
</svg>
|
|
4908
|
-
`}var
|
|
4908
|
+
`}var iD=class extends y{constructor(...e){super(...e),this.tool=`core:workspace.files`,this.panels=[],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(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:`Select a workspace`,body:`Choose a workspace to inspect files, Git, or terminals.`});let e=this.panelContext;if(e===void 0)return this.renderEmptyState({title:`Workspace tools unavailable`,body:`Try selecting the workspace again.`});let t=this.panels,n=t.filter(e=>!this.hiddenTools.includes(e.id)),r=t.find(e=>e.id===this.tool)??t[0];return g`
|
|
4909
4909
|
${this.hideToolTabs?null:g`
|
|
4910
4910
|
<header>
|
|
4911
4911
|
<div class=${this.workspaceHeaderFrameClass()}>
|
|
@@ -4935,10 +4935,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4935
4935
|
<h2>${e.title}</h2>
|
|
4936
4936
|
${e.body===void 0?null:g`<p>${e.body}</p>`}
|
|
4937
4937
|
</section>
|
|
4938
|
-
`}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=Kp}};B([x({attribute:!1})],
|
|
4939
|
-
`),lines:p,physicalLineCount:f.length,viewportLine:Math.min(d,Math.max(0,e.viewportY))}}function
|
|
4938
|
+
`}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=Kp}};B([x({attribute:!1})],iD.prototype,`workspace`,void 0),B([x({attribute:!1})],iD.prototype,`panelContext`,void 0),B([x({attribute:!1})],iD.prototype,`emptyState`,void 0),B([x()],iD.prototype,`tool`,void 0),B([x({attribute:!1})],iD.prototype,`panels`,void 0),B([x({attribute:!1})],iD.prototype,`hiddenTools`,void 0),B([x({type:Boolean})],iD.prototype,`hideToolTabs`,void 0),B([x({attribute:!1})],iD.prototype,`onSelectTool`,void 0),B([C(`.workspace-header-strip`)],iD.prototype,`workspaceHeaderStrip`,void 0),B([S()],iD.prototype,`workspaceHeaderCanScrollLeft`,void 0),B([S()],iD.prototype,`workspaceHeaderCanScrollRight`,void 0),iD=B([b(`workspace-panel`)],iD);var aD=`important`,oD=` !important`,sD=S_(class extends C_{constructor(e){if(super(e),e.type!==x_.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(oD);e.includes(`-`)||t?n.setProperty(e,t?r.slice(0,-11):r,t?aD:``):n[e]=r}}return Qe}}),cD=`#ffffff`,lD=`#000000`,uD=[`#2e3436`,`#cc0000`,`#4e9a06`,`#c4a000`,`#3465a4`,`#75507b`,`#06989a`,`#d3d7cf`,`#555753`,`#ef2929`,`#8ae234`,`#fce94f`,`#729fcf`,`#ad7fa8`,`#34e2e2`,`#eeeeec`],dD=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightBlack`,`brightRed`,`brightGreen`,`brightYellow`,`brightBlue`,`brightMagenta`,`brightCyan`,`brightWhite`],fD={black:uD[0],red:uD[1],green:uD[2],yellow:uD[3],blue:uD[4],magenta:uD[5],cyan:uD[6],white:uD[7],brightBlack:uD[8],brightRed:uD[9],brightGreen:uD[10],brightYellow:uD[11],brightBlue:uD[12],brightMagenta:uD[13],brightCyan:uD[14],brightWhite:uD[15]};function pD(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=xD(n.theme),a=n.theme?.foreground??cD,o=n.theme?.background??lD,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=mD(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,vD(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(`
|
|
4939
|
+
`),lines:p,physicalLineCount:f.length,viewportLine:Math.min(d,Math.max(0,e.viewportY))}}function mD(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:_D(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:hD(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,yD(s,{text:t.text,style:t.style}))}return{text:c,runs:s,wrapped:e.isWrapped}}function hD(e,t){let n=e.isInverse()!==0,r=gD(e,`foreground`,t),i=gD(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 gD(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?SD(a):i?n.palette[a]??(t===`foreground`?n.foreground:n.background):t===`foreground`?n.foreground:n.background}function _D(e){return{foreground:e.foreground,background:e.background,bold:!1,italic:!1,dim:!1,underline:!1,invisible:!1,strikethrough:!1,overline:!1}}function vD(e,t){for(let n of t)yD(e,n)}function yD(e,t){if(t.text===``)return;let n=e.at(-1);if(n!==void 0&&bD(n.style,t.style)){n.text+=t.text;return}e.push({text:t.text,style:t.style})}function bD(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 xD(e){let t=[...uD];for(let n=0;n<dD.length;n+=1){let r=dD[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(CD(r,i,a))}for(let e=0;e<24;e+=1){let n=8+e*10;t.push(CD(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 SD(e){return`#${(e&16777215).toString(16).padStart(6,`0`)}`}function CD(e,t,n){return`#${e.toString(16).padStart(2,`0`)}${t.toString(16).padStart(2,`0`)}${n.toString(16).padStart(2,`0`)}`}var wD=`pi-webui.terminal.softKeys`,TD=`(pointer: coarse), (max-width: 760px)`;function ED(e,t){return e??t}function DD(e){if(e===`true`)return!0;if(e===`false`)return!1}function OD(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(TD):void 0}function kD(e){return e?.matches===!0}function AD(e=OD()){return ED(MD(),kD(e))}function jD(){return MD()!==void 0}function MD(e=PD()){if(e!==void 0)try{return DD(e.getItem(wD))}catch{return}}function ND(e,t=PD()){if(t!==void 0)try{t.setItem(wD,String(e))}catch{}}function PD(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var FD=[{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`}],ID=`\x1B`,LD=``;function RD(e,t){switch(e){case`escape`:return ID;case`tab`:return` `;case`ctrl-c`:return zD(`c`);case`ctrl-d`:return zD(`d`);case`ctrl-z`:return zD(`z`);case`ctrl-l`:return zD(`l`);case`ctrl-r`:return zD(`r`);case`ctrl-u`:return zD(`u`);case`ctrl-w`:return zD(`w`);case`arrow-left`:return BD(`D`,t);case`arrow-up`:return BD(`A`,t);case`arrow-down`:return BD(`B`,t);case`arrow-right`:return BD(`C`,t);case`home`:return VD(`H`,t);case`end`:return VD(`F`,t);case`page-up`:return`${ID}[5~`;case`page-down`:return`${ID}[6~`;case`delete`:return`${ID}[3~`;case`backspace`:return LD;case`meta-backward-word`:return`${ID}b`;case`meta-forward-word`:return`${ID}f`}}function zD(e){return String.fromCharCode(e.toUpperCase().charCodeAt(0)-64)}function BD(e,t){return t?.applicationCursorKeysMode===!0?`${ID}O${e}`:`${ID}[${e}`}function VD(e,t){return t?.applicationCursorKeysMode===!0?`${ID}O${e}`:`${ID}[${e}`}var HD=8,UD=500,WD=class extends y{constructor(...e){super(...e),this.refocusOnClick=!0,this.onInput=()=>void 0,this.lastPointerFinishedAt=0}sendSoftKey(e,t){this.onInput(RD(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&&GD(t,e)&&this.finishSoftKeyPointer()}onSoftKeyPointerUp(e,t){let n=this.pointerStart;n?.pointerId===e.pointerId&&(e.preventDefault(),this.finishSoftKeyPointer(),!(n.key.id!==t.id||GD(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<UD){e.preventDefault();return}this.sendSoftKey(t,{refocus:this.refocusOnClick})}render(){return g`
|
|
4940
4940
|
<div class="terminal-soft-keys" role="toolbar" aria-label="Terminal soft keys">
|
|
4941
|
-
${
|
|
4941
|
+
${FD.map(e=>g`
|
|
4942
4942
|
<button
|
|
4943
4943
|
type="button"
|
|
4944
4944
|
class="soft-key"
|
|
@@ -4958,7 +4958,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4958
4958
|
.terminal-soft-keys::-webkit-scrollbar { display: none; }
|
|
4959
4959
|
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; }
|
|
4960
4960
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
4961
|
-
`}};B([x({attribute:!1})],HD.prototype,`modes`,void 0),B([x({type:Boolean})],HD.prototype,`refocusOnClick`,void 0),B([x({attribute:!1})],HD.prototype,`onInput`,void 0),HD=B([b(`terminal-soft-keys`)],HD);function UD(e,t){return Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)>BD}var WD=oe({TerminalPanel:()=>Z,filterTerminalInput:()=>nO,terminalBackgroundWithOpacity:()=>cO}),GD={allowTransparency:!0,cursorBlink:!0,convertEol:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,fontSize:13},KD={cols:100,rows:30},qD=1e3,JD=`--pi-terminal-effective-bg`,YD=`--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=OD(),this.suppressTerminalInput=!1,this.softKeysDefaultEnvironmentMedia=ED(),this.softKeysPreferenceStored=kD(),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=DD(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([ao.terminals(e.projectId,e.id,this.machineId),ao.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=ef(this.terminals,{targetTerminalId:this.selectedTerminalId});t===void 0&&this.selectedTerminalId!==void 0&&(t=tf(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(){if(this.workspace!==void 0){this.error=void 0;try{let e=this.measureTerminalSize()??KD,t=await ao.startTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);this.terminals=[...this.terminals,t],this.selectTerminal(t.id)}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 ao.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=tf(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 ao.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId);this.commandRuns=t,this.cancellingRunIds=this.cancellingRunIds.filter(e=>t.some(t=>t.id===e&&$D(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()},qD);return}!e&&this.commandRunPollTimer!==void 0&&(window.clearInterval(this.commandRunPollTimer),this.commandRunPollTimer=void 0)}hasPendingCommandRuns(e=this.commandRuns){return e.some($D)}async cancelCommandRun(e){if(!(!$D(e)||this.cancellingRunIds.includes(e.id))){this.error=void 0,this.cancellingRunIds=[...this.cancellingRunIds,e.id];try{await ao.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 ao.continueTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);this.terminals=this.terminals.map(n=>n.id===e?t:n),this.socket===void 0&&this.disposeTerminalView(),this.fitAndNotify(),this.terminal?.focus()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.continuingTerminalIds=this.continuingTerminalIds.filter(t=>t!==e)}}}ensureTerminalView(){let e=this.workspace,t=this.terminalHostElement();if(!this.visible||this.terminal!==void 0||this.selectedId===void 0||t===void 0||e===void 0)return;let n=new re(iO(this)),r=new ie;n.loadAddon(r),n.open(t),this.terminal=n,this.fitAddon=r,this.resizeObserver=new ResizeObserver(()=>{this.fitAndNotify()}),this.resizeObserver.observe(t),n.onData(e=>{this.suppressTerminalInput||this.copySnapshot!==void 0||this.sendTerminalInput(e)});let i=this.fitTerminal();this.connectSocket(e.projectId,e.id,this.selectedId,n,i),requestAnimationFrame(()=>{this.fitAndNotify()}),n.focus()}connectSocket(e,t,n,r,i){let a=mo(e,t,n,i,this.machineId);a.binaryType=`arraybuffer`,this.socket=a,a.addEventListener(`open`,()=>{this.fitAndNotify()}),a.addEventListener(`message`,e=>{this.handleSocketMessage(e.data,n,r)}),a.addEventListener(`close`,()=>{this.socket===a&&(this.socket=void 0)})}async handleSocketMessage(e,t,n){try{let r=tO(await rO(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.write(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=lO(this.fitAddon.proposeDimensions());if(e!==void 0)return this.fitAddon.fit(),e}measureTerminalSize(){let e=this.fitTerminal();if(e!==void 0)return e;let t=this.terminalHostElement();if(this.terminal!==void 0||t===void 0)return;let n=new re(iO(this)),r=new ie;n.loadAddon(r),n.open(t);let i=lO(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=aO(this))}syncTerminalBackground(){let e=sO(this.bgOpacity),t=cO(oO(this,`--pi-terminal-bg`,`#05070a`),e);this.style.setProperty(JD,t),this.style.setProperty(YD,`${String(e)}%`)}sendTerminalInput(e){let t=nO(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))}disposeTerminalView(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.socket?.close(),this.socket=void 0,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($D(e)){let t=this.cancellingRunIds.includes(e.id);return g`
|
|
4961
|
+
`}};B([x({attribute:!1})],WD.prototype,`modes`,void 0),B([x({type:Boolean})],WD.prototype,`refocusOnClick`,void 0),B([x({attribute:!1})],WD.prototype,`onInput`,void 0),WD=B([b(`terminal-soft-keys`)],WD);function GD(e,t){return Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)>HD}var KD=oe({TerminalPanel:()=>Z,filterTerminalInput:()=>iO,terminalBackgroundWithOpacity:()=>uO}),qD={allowTransparency:!0,cursorBlink:!0,convertEol:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,fontSize:13},JD={cols:100,rows:30},YD=1e3,XD=`--pi-terminal-effective-bg`,ZD=`--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=AD(),this.suppressTerminalInput=!1,this.softKeysDefaultEnvironmentMedia=OD(),this.softKeysPreferenceStored=jD(),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=kD(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([ao.terminals(e.projectId,e.id,this.machineId),ao.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=ef(this.terminals,{targetTerminalId:this.selectedTerminalId});t===void 0&&this.selectedTerminalId!==void 0&&(t=tf(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(){if(this.workspace!==void 0){this.error=void 0;try{let e=this.measureTerminalSize()??JD,t=await ao.startTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);this.terminals=[...this.terminals,t],this.selectTerminal(t.id)}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 ao.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=tf(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 ao.listCommandRuns({projectId:e.projectId,workspaceId:e.id},this.machineId);this.commandRuns=t,this.cancellingRunIds=this.cancellingRunIds.filter(e=>t.some(t=>t.id===e&&tO(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()},YD);return}!e&&this.commandRunPollTimer!==void 0&&(window.clearInterval(this.commandRunPollTimer),this.commandRunPollTimer=void 0)}hasPendingCommandRuns(e=this.commandRuns){return e.some(tO)}async cancelCommandRun(e){if(!(!tO(e)||this.cancellingRunIds.includes(e.id))){this.error=void 0,this.cancellingRunIds=[...this.cancellingRunIds,e.id];try{await ao.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 ao.continueTerminal(this.workspace.projectId,this.workspace.id,e,this.machineId);this.terminals=this.terminals.map(n=>n.id===e?t:n),this.socket===void 0&&this.disposeTerminalView(),this.fitAndNotify(),this.terminal?.focus()}catch(e){this.error=e instanceof Error?e.message:String(e)}finally{this.continuingTerminalIds=this.continuingTerminalIds.filter(t=>t!==e)}}}ensureTerminalView(){let e=this.workspace,t=this.terminalHostElement();if(!this.visible||this.terminal!==void 0||this.selectedId===void 0||t===void 0||e===void 0)return;let n=new re(oO(this)),r=new ie;n.loadAddon(r),n.open(t),this.terminal=n,this.fitAddon=r,this.resizeObserver=new ResizeObserver(()=>{this.fitAndNotify()}),this.resizeObserver.observe(t),n.onData(e=>{this.suppressTerminalInput||this.copySnapshot!==void 0||this.sendTerminalInput(e)});let i=this.fitTerminal();this.connectSocket(e.projectId,e.id,this.selectedId,n,i),requestAnimationFrame(()=>{this.fitAndNotify()}),n.focus()}connectSocket(e,t,n,r,i){let a=mo(e,t,n,i,this.machineId);a.binaryType=`arraybuffer`,this.socket=a,a.addEventListener(`open`,()=>{this.fitAndNotify()}),a.addEventListener(`message`,e=>{this.handleSocketMessage(e.data,n,r)}),a.addEventListener(`close`,()=>{this.socket===a&&(this.socket=void 0)})}async handleSocketMessage(e,t,n){try{let r=rO(await aO(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.write(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=dO(this.fitAddon.proposeDimensions());if(e!==void 0)return this.fitAddon.fit(),e}measureTerminalSize(){let e=this.fitTerminal();if(e!==void 0)return e;let t=this.terminalHostElement();if(this.terminal!==void 0||t===void 0)return;let n=new re(oO(this)),r=new ie;n.loadAddon(r),n.open(t);let i=dO(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=sO(this))}syncTerminalBackground(){let e=lO(this.bgOpacity),t=uO(cO(this,`--pi-terminal-bg`,`#05070a`),e);this.style.setProperty(XD,t),this.style.setProperty(ZD,`${String(e)}%`)}sendTerminalInput(e){let t=iO(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))}disposeTerminalView(){this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.socket?.close(),this.socket=void 0,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(tO(e)){let t=this.cancellingRunIds.includes(e.id);return g`
|
|
4962
4962
|
<section class="command-run-notice running">
|
|
4963
4963
|
<div>
|
|
4964
4964
|
<strong>${e.title}</strong>
|
|
@@ -4970,13 +4970,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4970
4970
|
`}if(t?.exited===!0){let n=this.continuingTerminalIds.includes(t.id);return g`
|
|
4971
4971
|
<section class=${`command-run-notice ${e.status}`}>
|
|
4972
4972
|
<div>
|
|
4973
|
-
<strong>${
|
|
4973
|
+
<strong>${nO(e)}</strong>
|
|
4974
4974
|
<p>Output is preserved. Continue in a shell to inspect or run follow-up commands.</p>
|
|
4975
4975
|
<code>${e.command}</code>
|
|
4976
4976
|
</div>
|
|
4977
4977
|
<button ?disabled=${n} @click=${()=>{this.continueTerminal(t.id)}}>${n?`Starting shell…`:`Continue in shell`}</button>
|
|
4978
4978
|
</section>
|
|
4979
|
-
`}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=
|
|
4979
|
+
`}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=pD(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=QD(e.scrollTop,n,r),t.scrollLeft=QD(e.scrollLeft,i,a)}async copyAllSnapshotText(){let e=this.copySnapshot?.text??``;if(e===``){this.copyStatus=`No terminal output to copy.`;return}this.copyStatus=await Uv(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`
|
|
4980
4980
|
<button
|
|
4981
4981
|
type="button"
|
|
4982
4982
|
class=${e?`copy-mode-toggle selected`:`copy-mode-toggle`}
|
|
@@ -4999,7 +4999,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4999
4999
|
${this.copyToolbarReplacesSoftKeys()?null:this.renderCopyModeToolbar()}
|
|
5000
5000
|
<div class="terminal-copy-layers">
|
|
5001
5001
|
<pre class="terminal-copy-content" aria-hidden="true">${e.lines.map((e,t)=>g`${t===0?null:`
|
|
5002
|
-
`}${e.runs.map(e=>g`<span style=${
|
|
5002
|
+
`}${e.runs.map(e=>g`<span style=${sD(eO(e.style))}>${e.text}</span>`)}`)}</pre>
|
|
5003
5003
|
<textarea
|
|
5004
5004
|
class="terminal-copy-selector"
|
|
5005
5005
|
readonly
|
|
@@ -5014,7 +5014,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5014
5014
|
></textarea>
|
|
5015
5015
|
</div>
|
|
5016
5016
|
</section>
|
|
5017
|
-
`}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,
|
|
5017
|
+
`}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,ND(this.softKeysEnabled),this.scheduleFitAndNotify())}renderSoftKeysToggle(){return this.shouldShowSoftKeysToggle()?g`
|
|
5018
5018
|
<button
|
|
5019
5019
|
type="button"
|
|
5020
5020
|
class=${this.softKeysEnabled?`soft-keys-toggle selected`:`soft-keys-toggle`}
|
|
@@ -5135,32 +5135,32 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5135
5135
|
.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); }
|
|
5136
5136
|
.muted { margin: 10px; color: var(--pi-muted); }
|
|
5137
5137
|
.xterm { height: 100%; }
|
|
5138
|
-
`}};B([x({attribute:!1})],Z.prototype,`workspace`,void 0),B([x()],Z.prototype,`machineId`,void 0),B([x({attribute:!1})],Z.prototype,`selectedTerminalId`,void 0),B([x({type:Boolean})],Z.prototype,`autoStart`,void 0),B([x({type:Number})],Z.prototype,`fontSize`,void 0),B([x({type:Number})],Z.prototype,`bgOpacity`,void 0),B([x({attribute:!1})],Z.prototype,`onSelectTerminal`,void 0),B([C(`.terminal-host`)],Z.prototype,`terminalHost`,void 0),B([C(`.terminal-copy-content`)],Z.prototype,`terminalCopyContent`,void 0),B([C(`.terminal-copy-selector`)],Z.prototype,`terminalCopySelector`,void 0),B([S()],Z.prototype,`terminals`,void 0),B([S()],Z.prototype,`commandRuns`,void 0),B([S()],Z.prototype,`selectedId`,void 0),B([S()],Z.prototype,`loading`,void 0),B([S()],Z.prototype,`error`,void 0),B([S()],Z.prototype,`visible`,void 0),B([S()],Z.prototype,`cancellingRunIds`,void 0),B([S()],Z.prototype,`continuingTerminalIds`,void 0),B([S()],Z.prototype,`defaultSoftKeysEnvironment`,void 0),B([S()],Z.prototype,`softKeysEnabled`,void 0),B([S()],Z.prototype,`copySnapshot`,void 0),B([S()],Z.prototype,`copyStatus`,void 0),Z=B([b(`terminal-panel`)],Z);function
|
|
5138
|
+
`}};B([x({attribute:!1})],Z.prototype,`workspace`,void 0),B([x()],Z.prototype,`machineId`,void 0),B([x({attribute:!1})],Z.prototype,`selectedTerminalId`,void 0),B([x({type:Boolean})],Z.prototype,`autoStart`,void 0),B([x({type:Number})],Z.prototype,`fontSize`,void 0),B([x({type:Number})],Z.prototype,`bgOpacity`,void 0),B([x({attribute:!1})],Z.prototype,`onSelectTerminal`,void 0),B([C(`.terminal-host`)],Z.prototype,`terminalHost`,void 0),B([C(`.terminal-copy-content`)],Z.prototype,`terminalCopyContent`,void 0),B([C(`.terminal-copy-selector`)],Z.prototype,`terminalCopySelector`,void 0),B([S()],Z.prototype,`terminals`,void 0),B([S()],Z.prototype,`commandRuns`,void 0),B([S()],Z.prototype,`selectedId`,void 0),B([S()],Z.prototype,`loading`,void 0),B([S()],Z.prototype,`error`,void 0),B([S()],Z.prototype,`visible`,void 0),B([S()],Z.prototype,`cancellingRunIds`,void 0),B([S()],Z.prototype,`continuingTerminalIds`,void 0),B([S()],Z.prototype,`defaultSoftKeysEnvironment`,void 0),B([S()],Z.prototype,`softKeysEnabled`,void 0),B([S()],Z.prototype,`copySnapshot`,void 0),B([S()],Z.prototype,`copyStatus`,void 0),Z=B([b(`terminal-panel`)],Z);function QD(e,t,n){return t<=0||n<=0?0:Math.min(1,Math.max(0,e/t))*n}function $D(e){return/^#[\da-f]{6}$/i.test(e)?`${e}80`:`color-mix(in srgb, ${e} 50%, transparent)`}function eO(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?$D(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 tO(e){return e.status===`queued`||e.status===`running`}function nO(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 rO(e){let t=JSON.parse(e);if(!pO(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 iO(e){return e.replaceAll(`\x1B[I`,``).replaceAll(`\x1B[O`,``)}async function aO(e){return typeof e==`string`?e:e instanceof ArrayBuffer?new TextDecoder().decode(e):e instanceof Blob?await e.text():String(e)}function oO(e){let t=qD;return e instanceof Z?{...t,fontSize:e.fontSize,theme:sO(e)}:{...t,theme:sO(e)}}function sO(e){let t=uO(cO(e,`--pi-terminal-bg`,`#05070a`),e instanceof Z?e.bgOpacity:100);return{...fD,background:t,foreground:cO(e,`--pi-terminal-text`,`#e6edf3`),cursor:cO(e,`--pi-accent`,`#58a6ff`),selectionBackground:cO(e,`--pi-terminal-selection`,`#264f78`)}}function cO(e,t,n){let r=getComputedStyle(e).getPropertyValue(t).trim();return r===``?n:r}function lO(e){return Math.max(0,Math.min(100,e))}function uO(e,t){let n=lO(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 dO(e){if(!(e===void 0||!fO(e.cols,e.rows)))return{cols:Math.floor(e.cols),rows:Math.floor(e.rows)}}function fO(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&e>0&&t>0}function pO(e){return typeof e==`object`&&!!e}var mO=class extends y{constructor(...e){super(...e),this.machines=[],this.canScrollLeft=!1,this.canScrollRight=!1,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=hO(this.machines),t=gO(this.machine),n=vO(this.project),r=bO(this.workspace),i=SO(this.session);return g`
|
|
5139
5139
|
<nav class=${this.contextBarClass()} aria-label="Current location">
|
|
5140
5140
|
<span class="context-bar-label">Location</span>
|
|
5141
5141
|
<ol class="context-items" @scroll=${this.onContextScroll}>
|
|
5142
5142
|
${e?g`
|
|
5143
5143
|
<li class="context-item">
|
|
5144
|
-
<button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${
|
|
5144
|
+
<button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${_O(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.(`machines`)}}>
|
|
5145
5145
|
<span class="context-kind">Machine</span>
|
|
5146
5146
|
<span class="context-value">${t}</span>
|
|
5147
5147
|
</button>
|
|
5148
5148
|
</li>
|
|
5149
5149
|
`:null}
|
|
5150
5150
|
<li class="context-item">
|
|
5151
|
-
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${
|
|
5151
|
+
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${yO(this.project)} aria-label=${`Project: ${n}. Open project selection.`} @click=${()=>{this.onOpenSection?.(`projects`)}}>
|
|
5152
5152
|
<span class="context-kind">Project</span>
|
|
5153
5153
|
<span class="context-value">${n}</span>
|
|
5154
5154
|
</button>
|
|
5155
5155
|
</li>
|
|
5156
5156
|
<li class="context-item">
|
|
5157
|
-
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${
|
|
5157
|
+
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${xO(this.workspace)} aria-label=${`Workspace: ${r}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
|
|
5158
5158
|
<span class="context-kind">Workspace</span>
|
|
5159
5159
|
<span class="context-value">${r}</span>
|
|
5160
5160
|
</button>
|
|
5161
5161
|
</li>
|
|
5162
5162
|
<li class="context-item">
|
|
5163
|
-
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${
|
|
5163
|
+
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${CO(this.session)} aria-label=${`Session: ${i}. Open session selection.`} @click=${()=>{this.onOpenSection?.(`sessions`)}}>
|
|
5164
5164
|
<span class="context-kind">Session</span>
|
|
5165
5165
|
<span class="context-value">${i}</span>
|
|
5166
5166
|
</button>
|
|
@@ -5200,7 +5200,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5200
5200
|
.context-kind { display: none; }
|
|
5201
5201
|
.context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
|
|
5202
5202
|
button { cursor: pointer; }
|
|
5203
|
-
`}};B([x({attribute:!1})],
|
|
5203
|
+
`}};B([x({attribute:!1})],mO.prototype,`machines`,void 0),B([x({attribute:!1})],mO.prototype,`machine`,void 0),B([x({attribute:!1})],mO.prototype,`project`,void 0),B([x({attribute:!1})],mO.prototype,`workspace`,void 0),B([x({attribute:!1})],mO.prototype,`session`,void 0),B([x({attribute:!1})],mO.prototype,`refreshControl`,void 0),B([x({attribute:!1})],mO.prototype,`onOpenSection`,void 0),B([x({attribute:!1})],mO.prototype,`onShowActions`,void 0),B([C(`.context-items`)],mO.prototype,`contextItems`,void 0),B([S()],mO.prototype,`canScrollLeft`,void 0),B([S()],mO.prototype,`canScrollRight`,void 0),mO=B([b(`app-context-bar`)],mO);function hO(e){return e.length>1}function gO(e){return e===void 0?`No machine`:`${e.name}${e.kind===`remote`?` · remote`:``}`}function _O(e){return e===void 0?`No machine selected`:e.baseUrl??e.name}function vO(e){return e?.name??`No project`}function yO(e){return e===void 0?`No project selected`:`${e.name} — ${e.path}`}function bO(e){return e===void 0?`No workspace`:`${e.label}${e.isMain?` · main`:``} · ${e.path}`}function xO(e){return e===void 0?`No workspace selected`:`${e.label}${e.isMain?` · main`:``} — ${e.path}`}function SO(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`:J_(e.id)}function CO(e){return e===void 0?`No session selected`:e.path}var wO=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`
|
|
5204
5204
|
<div class=${this.frameClass()}>
|
|
5205
5205
|
<div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
|
|
5206
5206
|
${this.tabs.map(t=>{let n=this.selectedView===t.id;return g`
|
|
@@ -5239,12 +5239,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5239
5239
|
.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; }
|
|
5240
5240
|
.tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
|
|
5241
5241
|
}
|
|
5242
|
-
`}};B([x({attribute:!1})],
|
|
5242
|
+
`}};B([x({attribute:!1})],wO.prototype,`tabs`,void 0),B([x({attribute:!1})],wO.prototype,`selectedView`,void 0),B([x({attribute:!1})],wO.prototype,`onSelect`,void 0),B([C(`.mobile-tabs`)],wO.prototype,`mobileTabs`,void 0),B([S()],wO.prototype,`canScrollLeft`,void 0),B([S()],wO.prototype,`canScrollRight`,void 0),wO=B([b(`app-mobile-main-tabs`)],wO);var TO=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=EO(e,this.statuses),n=e.name;return g`
|
|
5243
5243
|
<div class="machine-switcher">
|
|
5244
5244
|
<button
|
|
5245
5245
|
type="button"
|
|
5246
5246
|
class="machine-switcher-button"
|
|
5247
|
-
title=${
|
|
5247
|
+
title=${OO(e)}
|
|
5248
5248
|
aria-label=${this.machineSwitcherAriaLabel(e)}
|
|
5249
5249
|
aria-expanded=${String(this.open)}
|
|
5250
5250
|
@click=${e=>{this.toggleMenu(e.currentTarget)}}
|
|
@@ -5255,7 +5255,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5255
5255
|
<span class="machine-switcher-kicker">Machine</span>
|
|
5256
5256
|
<span class="machine-switcher-label">${n}</span>
|
|
5257
5257
|
</span>
|
|
5258
|
-
<span class=${`machine-status ${t}`}>${
|
|
5258
|
+
<span class=${`machine-status ${t}`}>${DO(t)}</span>
|
|
5259
5259
|
<span class="machine-chevron" aria-hidden="true">▾</span>
|
|
5260
5260
|
</button>
|
|
5261
5261
|
${this.open?g`
|
|
@@ -5264,18 +5264,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5264
5264
|
</div>
|
|
5265
5265
|
`:null}
|
|
5266
5266
|
</div>
|
|
5267
|
-
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=
|
|
5267
|
+
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=EO(e,this.statuses),r=y_(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return g`
|
|
5268
5268
|
<div class=${`machine-option ${t?`selected`:``} ${r?``:`no-actions`}`}>
|
|
5269
5269
|
<button
|
|
5270
5270
|
type="button"
|
|
5271
5271
|
class="machine-option-main"
|
|
5272
|
-
title=${
|
|
5272
|
+
title=${OO(e)}
|
|
5273
5273
|
data-machine-id=${e.id}
|
|
5274
5274
|
@click=${()=>{this.select(e)}}
|
|
5275
5275
|
@keydown=${e=>{this.handleMachineOptionKeydown(e)}}
|
|
5276
5276
|
>
|
|
5277
5277
|
<span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
|
|
5278
|
-
<small>${e.kind===`local`?`Local Pi WebUI`:e.baseUrl??`Remote Pi WebUI`} · ${
|
|
5278
|
+
<small>${e.kind===`local`?`Local Pi WebUI`:e.baseUrl??`Remote Pi WebUI`} · ${DO(n)}</small>
|
|
5279
5279
|
</button>
|
|
5280
5280
|
${r?g`
|
|
5281
5281
|
<div class="machine-option-actions">
|
|
@@ -5295,7 +5295,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5295
5295
|
</div>
|
|
5296
5296
|
`:null}
|
|
5297
5297
|
</div>
|
|
5298
|
-
`}renderActivity(e){let t=
|
|
5298
|
+
`}renderActivity(e){let t=EO(e,this.statuses);if(t===`offline`||t===`error`)return;let n=Fs(this.activities[e.id]);return r_(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=kO(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=kO(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=$g(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`
|
|
5299
5299
|
:host { min-width: 0; display: block; }
|
|
5300
5300
|
.machine-switcher { min-width: 0; }
|
|
5301
5301
|
.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; }
|
|
@@ -5328,10 +5328,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5328
5328
|
.machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
|
|
5329
5329
|
.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); }
|
|
5330
5330
|
@keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
|
|
5331
|
-
`}};B([x({attribute:!1})],
|
|
5331
|
+
`}};B([x({attribute:!1})],TO.prototype,`machines`,void 0),B([x({attribute:!1})],TO.prototype,`selected`,void 0),B([x({attribute:!1})],TO.prototype,`statuses`,void 0),B([x({attribute:!1})],TO.prototype,`activities`,void 0),B([x({attribute:!1})],TO.prototype,`onSelect`,void 0),B([x({attribute:!1})],TO.prototype,`onRemove`,void 0),B([x({attribute:!1})],TO.prototype,`onFocusNextSection`,void 0),B([x({attribute:!1})],TO.prototype,`onCancelKeyboardNavigation`,void 0),B([S()],TO.prototype,`open`,void 0),B([S()],TO.prototype,`menuStyle`,void 0),B([S()],TO.prototype,`openActionsMachineId`,void 0),B([S()],TO.prototype,`actionMenuStyle`,void 0),TO=B([b(`machine-switcher`)],TO);function EO(e,t){return t[e.id]?.status??e.status??`unknown`}function DO(e){return e===`online`?`online`:e===`offline`?`offline`:e===`error`?`error`:`unknown`}function OO(e){return e.baseUrl??e.name}function kO(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: ${AO(t.bottom)};`,`left: ${AO(r)};`,`width: ${AO(n)};`,`max-height: ${AO(i)};`].join(` `)}function AO(e){return`${String(Math.round(e))}px`}var jO=[{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.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}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`
|
|
5332
5332
|
<header>
|
|
5333
5333
|
<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>
|
|
5334
|
-
${
|
|
5334
|
+
${FO(this.machines)?g`
|
|
5335
5335
|
<machine-switcher
|
|
5336
5336
|
.machines=${this.machines}
|
|
5337
5337
|
.selected=${this.selectedMachine}
|
|
@@ -5348,7 +5348,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5348
5348
|
<button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.onShowActions?.()}}>Actions</button>
|
|
5349
5349
|
</div>
|
|
5350
5350
|
</header>
|
|
5351
|
-
${this.compact&&
|
|
5351
|
+
${this.compact&&FO(this.machines)?g`
|
|
5352
5352
|
<machine-list
|
|
5353
5353
|
.machines=${this.machines}
|
|
5354
5354
|
.selected=${this.selectedMachine}
|
|
@@ -5437,9 +5437,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5437
5437
|
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
5438
5438
|
></session-list>
|
|
5439
5439
|
<footer class="resource-underbar" aria-label="Resources">
|
|
5440
|
-
${
|
|
5440
|
+
${jO.map(e=>MO(e,e.id===`models`?()=>{this.onOpenModels?.()}:e.id===`skills`?()=>{this.onOpenSkills?.()}:()=>{this.onOpenPlugins?.()},this.skillsEnabled,this.pluginsEnabled))}
|
|
5441
5441
|
</footer>
|
|
5442
|
-
`}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=
|
|
5442
|
+
`}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=IO(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(LO(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
|
|
5443
5443
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
|
|
5444
5444
|
:host([compact]) { flex: 1 1 auto; }
|
|
5445
5445
|
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); }
|
|
@@ -5471,12 +5471,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5471
5471
|
:host([compact]) workspace-list[collapsed],
|
|
5472
5472
|
:host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
5473
5473
|
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
5474
|
-
`}};B([x({attribute:!1})],Q.prototype,`machines`,void 0),B([x({attribute:!1})],Q.prototype,`selectedMachine`,void 0),B([x({attribute:!1})],Q.prototype,`machineStatuses`,void 0),B([x({attribute:!1})],Q.prototype,`machineActivities`,void 0),B([x({attribute:!1})],Q.prototype,`projects`,void 0),B([x({attribute:!1})],Q.prototype,`selectedProject`,void 0),B([x({attribute:!1})],Q.prototype,`workspaces`,void 0),B([x({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`sessions`,void 0),B([x({attribute:!1})],Q.prototype,`projectSessions`,void 0),B([x({attribute:!1})],Q.prototype,`selectedSession`,void 0),B([x({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),B([x({attribute:!1})],Q.prototype,`sessionActivities`,void 0),B([x({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),B([x({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),B([x({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),B([x({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),B([x({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),B([x({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),B([x({type:String})],Q.prototype,`version`,void 0),B([x({attribute:!1})],Q.prototype,`refreshControl`,void 0),B([x({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),B([x({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),B([x({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),B([x({type:Number})],Q.prototype,`startingSessionCount`,void 0),B([x({type:Boolean})],Q.prototype,`canStartSession`,void 0),B([x({type:Boolean})],Q.prototype,`canDeleteArchivedSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canReloadSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canCleanupSessions`,void 0),B([x({type:Boolean})],Q.prototype,`authoritativeSessionPersistence`,void 0),B([x({type:String})],Q.prototype,`archivedDeleteUnavailableMessage`,void 0),B([x({type:String})],Q.prototype,`cleanupUnavailableMessage`,void 0),B([x({attribute:!1})],Q.prototype,`onShowActions`,void 0),B([x({type:Boolean})],Q.prototype,`skillsEnabled`,void 0),B([x({type:Boolean})],Q.prototype,`pluginsEnabled`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenModels`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenSkills`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenPlugins`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onAddProject`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenProjectBrowser`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectProject`,void 0),B([x({attribute:!1})],Q.prototype,`onCloseProject`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`onStartSession`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectSession`,void 0),B([x({attribute:!1})],Q.prototype,`onRenameSessionStart`,void 0),B([x({attribute:!1})],Q.prototype,`onRenameSession`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),B([x({attribute:!1})],Q.prototype,`onReloadSession`,void 0),B([x({attribute:!1})],Q.prototype,`onPinSession`,void 0),B([x({attribute:!1})],Q.prototype,`onUnpinSession`,void 0),B([x({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),B([x({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),B([x({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),B([x({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),B([C(`machine-list`)],Q.prototype,`machineList`,void 0),B([C(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),B([C(`project-list`)],Q.prototype,`projectList`,void 0),B([C(`workspace-list`)],Q.prototype,`workspaceList`,void 0),B([C(`session-list`)],Q.prototype,`sessionList`,void 0),Q=B([b(`app-navigation-panel`)],Q);function
|
|
5475
|
-
<button type="button" ?disabled=${!
|
|
5476
|
-
${
|
|
5474
|
+
`}};B([x({attribute:!1})],Q.prototype,`machines`,void 0),B([x({attribute:!1})],Q.prototype,`selectedMachine`,void 0),B([x({attribute:!1})],Q.prototype,`machineStatuses`,void 0),B([x({attribute:!1})],Q.prototype,`machineActivities`,void 0),B([x({attribute:!1})],Q.prototype,`projects`,void 0),B([x({attribute:!1})],Q.prototype,`selectedProject`,void 0),B([x({attribute:!1})],Q.prototype,`workspaces`,void 0),B([x({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`sessions`,void 0),B([x({attribute:!1})],Q.prototype,`projectSessions`,void 0),B([x({attribute:!1})],Q.prototype,`selectedSession`,void 0),B([x({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),B([x({attribute:!1})],Q.prototype,`sessionActivities`,void 0),B([x({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),B([x({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),B([x({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),B([x({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),B([x({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),B([x({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),B([x({type:String})],Q.prototype,`version`,void 0),B([x({attribute:!1})],Q.prototype,`refreshControl`,void 0),B([x({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),B([x({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),B([x({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),B([x({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),B([x({type:Number})],Q.prototype,`startingSessionCount`,void 0),B([x({type:Boolean})],Q.prototype,`canStartSession`,void 0),B([x({type:Boolean})],Q.prototype,`canDeleteArchivedSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canReloadSessions`,void 0),B([x({type:Boolean})],Q.prototype,`canCleanupSessions`,void 0),B([x({type:Boolean})],Q.prototype,`authoritativeSessionPersistence`,void 0),B([x({type:String})],Q.prototype,`archivedDeleteUnavailableMessage`,void 0),B([x({type:String})],Q.prototype,`cleanupUnavailableMessage`,void 0),B([x({attribute:!1})],Q.prototype,`onShowActions`,void 0),B([x({type:Boolean})],Q.prototype,`skillsEnabled`,void 0),B([x({type:Boolean})],Q.prototype,`pluginsEnabled`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenModels`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenSkills`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenPlugins`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),B([x({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onAddProject`,void 0),B([x({attribute:!1})],Q.prototype,`onOpenProjectBrowser`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectProject`,void 0),B([x({attribute:!1})],Q.prototype,`onCloseProject`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),B([x({attribute:!1})],Q.prototype,`onStartSession`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectSession`,void 0),B([x({attribute:!1})],Q.prototype,`onRenameSessionStart`,void 0),B([x({attribute:!1})],Q.prototype,`onRenameSession`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),B([x({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),B([x({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),B([x({attribute:!1})],Q.prototype,`onReloadSession`,void 0),B([x({attribute:!1})],Q.prototype,`onPinSession`,void 0),B([x({attribute:!1})],Q.prototype,`onUnpinSession`,void 0),B([x({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),B([x({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),B([x({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),B([x({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),B([x({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),B([C(`machine-list`)],Q.prototype,`machineList`,void 0),B([C(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),B([C(`project-list`)],Q.prototype,`projectList`,void 0),B([C(`workspace-list`)],Q.prototype,`workspaceList`,void 0),B([C(`session-list`)],Q.prototype,`sessionList`,void 0),Q=B([b(`app-navigation-panel`)],Q);function MO(e,t,n,r){return g`
|
|
5475
|
+
<button type="button" ?disabled=${!NO(e.id,n,r)} title=${e.label} aria-label=${e.label} @click=${t}>
|
|
5476
|
+
${PO(e.id)}
|
|
5477
5477
|
<span>${e.label}</span>
|
|
5478
5478
|
</button>
|
|
5479
|
-
`}function
|
|
5479
|
+
`}function NO(e,t=!1,n=t){return e===`models`||e===`skills`&&t||e===`plugins`&&n}function PO(e){switch(e){case`models`:return _`
|
|
5480
5480
|
<svg class="resource-underbar-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
5481
5481
|
<rect x="4" y="4" width="16" height="16" rx="2"></rect>
|
|
5482
5482
|
<rect x="9" y="9" width="6" height="6"></rect>
|
|
@@ -5494,7 +5494,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5494
5494
|
<path d="M6 13V8a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v5a6 6 0 0 1-12 0Z"></path>
|
|
5495
5495
|
<path d="M12 19v3"></path>
|
|
5496
5496
|
</svg>
|
|
5497
|
-
`}}function
|
|
5497
|
+
`}}function FO(e){return e.length>1}function IO(e,t){let n=RO(t);return n[n.indexOf(e)-1]}function LO(e,t){let n=RO(t);return n[n.indexOf(e)+1]??`chat`}function RO(e){return Fh.filter(t=>t!==`machines`||FO(e))}var zO=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),BO=420,VO=4,HO=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`
|
|
5498
5498
|
${this.renderResizeHandle()}
|
|
5499
5499
|
<button
|
|
5500
5500
|
type="button"
|
|
@@ -5524,7 +5524,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5524
5524
|
@dblclick=${e=>{this.onResizeDoubleClick(e)}}
|
|
5525
5525
|
@keydown=${e=>{this.onResizeKeyDown(e)}}
|
|
5526
5526
|
></div>
|
|
5527
|
-
`}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)<=
|
|
5527
|
+
`}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)<=VO)&&(t.moved=!0,this.commitPanelWidth($h(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||!zO.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=eg(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<=BO){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 tg(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(tg(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=Zh(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=h`
|
|
5528
5528
|
: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; }
|
|
5529
5529
|
:host([side="navigation"]) { grid-column: 2; }
|
|
5530
5530
|
:host([side="workspace"]) { grid-column: 4; }
|
|
@@ -5543,7 +5543,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5543
5543
|
@media (max-width: 760px) {
|
|
5544
5544
|
:host([side="navigation"]) { display: none; }
|
|
5545
5545
|
}
|
|
5546
|
-
`}};B([x({reflect:!0})],
|
|
5546
|
+
`}};B([x({reflect:!0})],HO.prototype,`side`,void 0),B([x({type:Boolean,reflect:!0})],HO.prototype,`collapsed`,void 0),B([x({type:Boolean})],HO.prototype,`resizable`,void 0),B([x({type:Number})],HO.prototype,`panelWidth`,void 0),B([x({type:Number})],HO.prototype,`minWidth`,void 0),B([x({type:Number})],HO.prototype,`maxWidth`,void 0),B([x()],HO.prototype,`controls`,void 0),B([x()],HO.prototype,`resizeLabel`,void 0),B([x()],HO.prototype,`expandLabel`,void 0),B([x()],HO.prototype,`collapseLabel`,void 0),B([x({attribute:!1})],HO.prototype,`onToggle`,void 0),B([x({attribute:!1})],HO.prototype,`onResizeStart`,void 0),B([x({attribute:!1})],HO.prototype,`onResize`,void 0),B([x({attribute:!1})],HO.prototype,`onResizeEnd`,void 0),B([x({attribute:!1})],HO.prototype,`onReset`,void 0),HO=B([b(`app-panel-edge-control`)],HO);var UO=class extends y{constructor(...e){super(...e),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){let e=`Full page reload`;return g`
|
|
5547
5547
|
<button
|
|
5548
5548
|
class="app-refresh-button"
|
|
5549
5549
|
title=${e}
|
|
@@ -5562,7 +5562,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5562
5562
|
:host, :host * { -webkit-user-select: none; user-select: none; }
|
|
5563
5563
|
.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; }
|
|
5564
5564
|
.app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
5565
|
-
`}};B([x({attribute:!1})],
|
|
5565
|
+
`}};B([x({attribute:!1})],UO.prototype,`onReload`,void 0),UO=B([b(`app-refresh-control`)],UO);var WO=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`],GO=`file-manager`,KO=`browser`,qO=[...WO],JO=new Set(WO),YO=`pi-webui:activity-rail-order`;function XO(){return typeof localStorage>`u`?void 0:localStorage}function ZO(e){return JO.has(e)}function QO(e){if(!Array.isArray(e))return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`)return;let e=r===GO?`git-update-manager`:r;if(e!==KO){if(!ZO(e)||n.has(e))return;n.add(e),t.push(e)}}if(t.length===WO.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===WO.length?r:void 0}function $O(){try{let e=XO();if(e===void 0)return;let t=e.getItem(YO);return t===null?void 0:QO(JSON.parse(t))}catch{return}}function ek(e){try{let t=XO();if(t===void 0)return;t.setItem(YO,JSON.stringify(e))}catch{}}var tk=`(min-width: 1181px)`,nk=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`];function rk(e){return nk.includes(e)}var ik=class extends y{constructor(){super(),this.terminalCount=0,this.gitUpdateManagerCount=0,this.systemPromptEnabled=!1,this.historyEnabled=!1,this.railOrder=[...qO],this.onDesktopMediaChange=()=>{},this.openTerminal=()=>{this.onOpenTerminal?.()},this.openGitUpdateManager=()=>{this.onOpenGitUpdateManager?.()},this.openTheme=()=>{this.onOpenTheme?.()},this.openSystemPrompt=()=>{this.onOpenSystemPrompt?.()},this.openHistory=()=>{this.onOpenHistory?.()},this.openInfo=()=>{this.onOpenInfo?.()},this.openSettings=()=>{this.onOpenSettings?.()},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||!rk(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(tk))}connectedCallback(){super.connectedCallback(),this.desktopMedia?.addEventListener(`change`,this.onDesktopMediaChange)}disconnectedCallback(){super.disconnectedCallback(),this.desktopMedia?.removeEventListener(`change`,this.onDesktopMediaChange)}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`
|
|
5566
5566
|
<button
|
|
5567
5567
|
type="button"
|
|
5568
5568
|
class="icon-button terminal-button"
|
|
@@ -5702,7 +5702,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5702
5702
|
<circle cx="12" cy="12" r="3"/>
|
|
5703
5703
|
</svg>
|
|
5704
5704
|
</button>
|
|
5705
|
-
`}render(){if(!(this.desktopMedia?.matches??!0))return g``;let e=this.railOrder.length===0?[...
|
|
5705
|
+
`}render(){if(!(this.desktopMedia?.matches??!0))return g``;let e=this.railOrder.length===0?[...qO]:this.railOrder;return g`
|
|
5706
5706
|
<nav
|
|
5707
5707
|
class="rail"
|
|
5708
5708
|
aria-label="Activity rail"
|
|
@@ -5776,7 +5776,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5776
5776
|
}
|
|
5777
5777
|
.rail-spacer { flex: 1 1 auto; min-height: 0; }
|
|
5778
5778
|
.settings-button { margin-bottom: 12px; }
|
|
5779
|
-
`}};B([x({attribute:!1})],
|
|
5779
|
+
`}};B([x({attribute:!1})],ik.prototype,`onOpenTerminal`,void 0),B([x({attribute:!1})],ik.prototype,`onOpenGitUpdateManager`,void 0),B([x({attribute:!1})],ik.prototype,`onOpenTheme`,void 0),B([x({attribute:!1})],ik.prototype,`onOpenSystemPrompt`,void 0),B([x({attribute:!1})],ik.prototype,`onOpenHistory`,void 0),B([x({attribute:!1})],ik.prototype,`onOpenInfo`,void 0),B([x({attribute:!1})],ik.prototype,`onOpenSettings`,void 0),B([x({type:Number})],ik.prototype,`terminalCount`,void 0),B([x({type:Number})],ik.prototype,`gitUpdateManagerCount`,void 0),B([x({type:Boolean})],ik.prototype,`systemPromptEnabled`,void 0),B([x({type:Boolean})],ik.prototype,`historyEnabled`,void 0),B([x({attribute:!1})],ik.prototype,`railOrder`,void 0),B([x({attribute:!1})],ik.prototype,`onRailOrderChange`,void 0),ik=B([b(`activity-rail`)],ik);var ak=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.api=fo,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:sk(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=uk(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=Pg(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`?Mg(t.bounds,n,this.viewport()):Ng(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`
|
|
5780
5780
|
<div class="git-update-manager-backdrop" role="dialog" aria-modal="true" aria-label="Git Update Manager">
|
|
5781
5781
|
<section class=${this.bounds===void 0?`git-update-manager-frame`:`git-update-manager-frame git-update-manager-frame-positioned`} style=${this.frameStyle()}>
|
|
5782
5782
|
<header class="git-update-manager-header">
|
|
@@ -5810,15 +5810,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5810
5810
|
></div>
|
|
5811
5811
|
</section>
|
|
5812
5812
|
</div>
|
|
5813
|
-
`}ensureWorkspaceScope(){let e=
|
|
5813
|
+
`}ensureWorkspaceScope(){let e=lk(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=vs(e.files);return t.staged.length===0&&t.unstaged.length===0?g`<p class="git-update-manager-empty">No Git changes.</p>`:g`
|
|
5814
5814
|
${this.renderChangeGroup(`staged`,t.staged)}
|
|
5815
5815
|
${this.renderChangeGroup(`unstaged`,t.unstaged)}
|
|
5816
|
-
`}renderChangeGroup(e,t){if(t.length===0)return null;let n=
|
|
5816
|
+
`}renderChangeGroup(e,t){if(t.length===0)return null;let n=ck(e);return g`
|
|
5817
5817
|
<section class="git-update-manager-change-group" aria-label=${`${n} changes`}>
|
|
5818
5818
|
<h2>${n} (${String(t.length)})</h2>
|
|
5819
5819
|
${t.map(e=>this.renderChange(e))}
|
|
5820
5820
|
</section>
|
|
5821
|
-
`}renderChange(e){let t=this.selectedChange?.id===e.id,n=Ss(e),r=xs(e.state),i=
|
|
5821
|
+
`}renderChange(e){let t=this.selectedChange?.id===e.id,n=Ss(e),r=xs(e.state),i=ck(e.scope);return g`
|
|
5822
5822
|
<button
|
|
5823
5823
|
type="button"
|
|
5824
5824
|
class=${`git-update-manager-entry ${t?`selected`:``}`}
|
|
@@ -5830,13 +5830,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5830
5830
|
<span class="git-update-manager-path">${n}</span>
|
|
5831
5831
|
<span class="git-update-manager-scope">${i}</span>
|
|
5832
5832
|
</button>
|
|
5833
|
-
`}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 ${Ss(e)}.</p>`;if(this.loadingDiff||this.selectedDiff===void 0)return g`<p class="git-update-manager-empty">Loading ${Ss(e)}…</p>`;let t=this.selectedDiff;return
|
|
5833
|
+
`}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 ${Ss(e)}.</p>`;if(this.loadingDiff||this.selectedDiff===void 0)return g`<p class="git-update-manager-empty">Loading ${Ss(e)}…</p>`;let t=this.selectedDiff;return ok(),g`
|
|
5834
5834
|
<header class="git-update-manager-diff-header">
|
|
5835
5835
|
<strong>${Ss(e)}</strong>
|
|
5836
|
-
<small>${
|
|
5836
|
+
<small>${ck(e.scope)} · ${xs(e.state)}${t.truncated?` · truncated`:``}</small>
|
|
5837
5837
|
</header>
|
|
5838
5838
|
<unified-diff-viewer .diff=${t.diff}></unified-diff-viewer>
|
|
5839
|
-
`}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=
|
|
5839
|
+
`}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=uk(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=Pg(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`
|
|
5840
5840
|
:host { position: fixed; inset: 0; z-index: 80; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
5841
5841
|
.git-update-manager-backdrop { width: 100%; height: 100dvh; display: grid; place-items: center; padding: 16px; background: rgba(0, 0, 0, .48); }
|
|
5842
5842
|
.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); }
|
|
@@ -5875,7 +5875,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5875
5875
|
.git-update-manager-workspace { grid-template-columns: 1fr; grid-template-rows: minmax(190px, 40%) minmax(0, 1fr); }
|
|
5876
5876
|
.git-update-manager-entries { border-right: 0; border-bottom: 1px solid var(--pi-border); }
|
|
5877
5877
|
}
|
|
5878
|
-
`}};B([x({attribute:!1})],rk.prototype,`onClose`,void 0),B([x({attribute:!1})],rk.prototype,`onStatusChange`,void 0),B([x({attribute:!1})],rk.prototype,`workspace`,void 0),B([x()],rk.prototype,`machineId`,void 0),B([x({attribute:!1})],rk.prototype,`api`,void 0),B([S()],rk.prototype,`status`,void 0),B([S()],rk.prototype,`selectedChange`,void 0),B([S()],rk.prototype,`selectedDiff`,void 0),B([S()],rk.prototype,`loadingStatus`,void 0),B([S()],rk.prototype,`loadingDiff`,void 0),B([S()],rk.prototype,`error`,void 0),B([S()],rk.prototype,`bounds`,void 0),rk=B([b(`git-update-manager-panel`)],rk);function ik(){rm(()=>import(`./UnifiedDiffViewer-iSh_gYQc.js`),[],import.meta.url)}function ak(e,t){let n=vs(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function ok(e){return e===`staged`?`Staged`:`Unstaged`}function sk(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function ck(e){return e instanceof Error?e.message:String(e)}var lk=900*1e3,uk=750,dk=[1e3,3e3,8e3,15e3,3e4],fk={capture:!0},pk=`auto:on`,mk=`auto:off`,hk=`theme:`,gk=Qo(`core:workspace.files`),_k=Qo(`core:workspace.git`),vk=Qo(`core:workspace.terminal`),yk=320,bk=2,xk=`(min-width: 1181px)`,$=class extends y{constructor(...e){super(...e),this.state=Bo(),this.sessionUnread=new qf({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 Dd(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new Pu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new wu,{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)}}),this.projectActivityOwnership=new Rs(()=>this.state,e=>{this.setState(e)},{api:ro,onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Ko(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new Yo(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new Fd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Nd),this.projects=new As(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new Es(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new Bs(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new ds(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new _s(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new af,this.realtime=new eu,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Bd,this.terminalSelection=new $d,this.appShell=new Oh(this),this.browserResume=new Ah({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new Kh(this),this.panelResize=new Xh(this),this.navigationSections=new Uh(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=Sk(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=fp()??cp,this.activeThemeId=sp,this.isRefreshingApp=!1,this.modelsConfigDialogOpen=!1,this.projectBrowserOpen=!1,this.skillsConfigDialogOpen=!1,this.pluginsConfigDialogOpen=!1,this.systemPromptDialogOpen=!1,this.gitUpdateManagerPanelOpen=!1,this.terminalModalOpen=!1,this.terminalModalMaximized=!1,this.initialTerminalModalPreferences=Vg(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.terminalTabHidden=Vk(),this.infoTabHidden=Wk(),this.railOrder=ZO()??[...GO],this.settingsSection=_g(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=bo(void 0),this.sessionWarningVisibility=tp(),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=Pg(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStartSessionPrompt=(e,t,n,r)=>{!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||(this.sessions.startSessionWithPrompt(e,t,n,r),this.focusChatComposer())},this.handleSelectStarterModel=()=>{this.openStarterModelDialog()},this.handleSelectStarterThinking=()=>{this.openStarterThinkingDialog()},this.handleOpenTerminalFromRail=()=>{this.state.selectedWorkspace!==void 0&&(this.terminalModalOpen=!0)},this.handleOpenGitUpdateManagerFromRail=()=>{this.state.selectedWorkspace!==void 0&&(this.gitUpdateManagerPanelOpen=!0)},this.handleCloseGitUpdateManagerPanel=()=>{this.gitUpdateManagerPanelOpen=!1},this.handleOpenThemeFromRail=()=>{this.openThemeDialog()},this.handleRailOrderChange=e=>{this.railOrder=e,QO(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`?Mg(t.bounds,n,r):Ng(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=zg(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=Bg(this.terminalModalOpacity+e);t!==this.terminalModalOpacity&&(this.terminalModalOpacity=t,this.persistTerminalModalPreferences())},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleCompact=()=>{this.sessions.runCommand(`/compact`)},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleEditFromHere=async(e,t)=>{let n=R(this.state),r=this.state.selectedSession?.id;try{!(await this.sessions.editFromHere(e,t)).cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer()}catch{}},this.handleForkFromHere=async e=>{await this.sessions.forkFromHere(e)},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=op(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility()}updated(){this.committedChatIdentity=Tk(this.state),this.syncSelectedSessionReadState()}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=rp(this.sessionWarningVisibility,e===void 0?void 0:Wo(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=wk(e,t);await this.updateComplete,!(!this.unreadConnected||Tk(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);jk(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=Jg(this.state.selectedProject?.name);this.windowTitleCleanup=Yg(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=wk(e,t);return Tk(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.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.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}connectedCallback(){super.connectedCallback(),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,fk),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},lk),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebUiStatusRefresh()}),this.syncWindowTitle()}disconnectedCallback(){this.finishTerminalModalPointerInteraction(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.unreadRuntimeRefreshes.clear(),this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),window.removeEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,fk),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.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(!Ak(this.state,e))return;let t=this.state;this.state={...this.state,...e},Tk(t)!==Tk(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),Ek(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),Dk(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=fg();await this.machines.loadMachines(e.machineId);let t=this.routeForSelectedMachine(e),n=this.state.machineStatuses[t.machineId??`local`];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,n)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebUiStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns()])}schedulePiWebUiStatusRefresh(e=uk){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=>kk(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 Ua.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=bo(e)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebUiStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let e=this.state.selectedWorkspace,t=this.state.mainView!==`chat`&&this.state.mainView!==`navigation`?this.state.mainView:this.state.workspaceTool;t===`core:workspace.files`?await this.files.refreshFiles():t===`core:workspace.git`?await this.git.refreshGit():t===`core:workspace.terminal`&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(fg(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?Pk():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===``?Pk():{selectedFilePath:es(gk,`file`),selectedDiffPath:es(_k,`diff`),selectedTerminalId:es(vk,`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){pg(e,{replace:!0}),ts(gk,`file`,void 0,{replace:!0}),ts(_k,`diff`,void 0,{replace:!0}),ts(vk,`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=Ik(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>=dk.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 zk(),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(),pg({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(Hd(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Hd(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){pg(Ud(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){ts(gk,`file`,e.selectedFilePath,{replace:!0}),ts(_k,`diff`,e.selectedDiffPath,{replace:!0}),ts(vk,`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)??Vd(e.id);if(await this.restoreRouteFor(Ud(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=Fk(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=wg(e,{api:{runTerminalCommand:(e,n)=>ao.runTerminalCommand(e,n,t),listCommandRuns:e=>ao.listCommandRuns(e,t),getCommandRun:e=>ao.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((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`});return}this.openTerminal(n)}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){ts(vk,`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,vg(e)}closeSettings(){this.settingsSection=void 0,vg(void 0)}navigateSettings(e){this.settingsSection=e,vg(e)}restoreSettingsRoute(){this.settingsSection=_g()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.starterSessionDefaults=void 0,this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let n=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:n}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(n,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}async loadStarterSessionDefaults(e){let t=R(this.state);try{let n=await io.sessionDefaults(e.path,t);if(R(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.starterSessionDefaults=n}catch(n){R(this.state)===t&&this.state.selectedWorkspace?.id===e.id&&console.warn(`Failed to load Pi session defaults`,n)}}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`:Gt(e,T.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)},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 eu;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=>Ok(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):Nk(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 ao.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=Mk(e),r=Mk(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&(this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebUiStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
|
|
5878
|
+
`}};B([x({attribute:!1})],ak.prototype,`onClose`,void 0),B([x({attribute:!1})],ak.prototype,`onStatusChange`,void 0),B([x({attribute:!1})],ak.prototype,`workspace`,void 0),B([x()],ak.prototype,`machineId`,void 0),B([x({attribute:!1})],ak.prototype,`api`,void 0),B([S()],ak.prototype,`status`,void 0),B([S()],ak.prototype,`selectedChange`,void 0),B([S()],ak.prototype,`selectedDiff`,void 0),B([S()],ak.prototype,`loadingStatus`,void 0),B([S()],ak.prototype,`loadingDiff`,void 0),B([S()],ak.prototype,`error`,void 0),B([S()],ak.prototype,`bounds`,void 0),ak=B([b(`git-update-manager-panel`)],ak);function ok(){rm(()=>import(`./UnifiedDiffViewer-XFd_Uipx.js`),[],import.meta.url)}function sk(e,t){let n=vs(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function ck(e){return e===`staged`?`Staged`:`Unstaged`}function lk(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function uk(e){return e instanceof Error?e.message:String(e)}var dk=900*1e3,fk=750,pk=[1e3,3e3,8e3,15e3,3e4],mk={capture:!0},hk=`auto:on`,gk=`auto:off`,_k=`theme:`,vk=Qo(`core:workspace.files`),yk=Qo(`core:workspace.git`),bk=Qo(`core:workspace.terminal`),xk=320,Sk=2,Ck=`(min-width: 1181px)`,$=class extends y{constructor(...e){super(...e),this.state=Bo(),this.sessionUnread=new qf({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 Dd(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new Pu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new wu,{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)}}),this.projectActivityOwnership=new Rs(()=>this.state,e=>{this.setState(e)},{api:ro,onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Ko(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new Yo(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new Fd(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new Nd),this.projects=new As(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new Es(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebUiStatusController=new Bs(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEBUI status for ${e}`,t)}}),this.files=new ds(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new _s(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new af,this.realtime=new eu,this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Bd,this.terminalSelection=new $d,this.appShell=new Oh(this),this.browserResume=new Ah({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new Kh(this),this.panelResize=new Xh(this),this.navigationSections=new Uh(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=wk(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=fp()??cp,this.activeThemeId=sp,this.isRefreshingApp=!1,this.modelsConfigDialogOpen=!1,this.projectBrowserOpen=!1,this.skillsConfigDialogOpen=!1,this.pluginsConfigDialogOpen=!1,this.systemPromptDialogOpen=!1,this.gitUpdateManagerPanelOpen=!1,this.terminalModalOpen=!1,this.terminalModalMaximized=!1,this.initialTerminalModalPreferences=Vg(),this.terminalModalFontSize=this.initialTerminalModalPreferences.fontSize,this.terminalModalOpacity=this.initialTerminalModalPreferences.opacity,this.terminalTabHidden=Uk(),this.infoTabHidden=Kk(),this.railOrder=$O()??[...qO],this.settingsSection=_g(),this.shortcutConfig={},this.workspaceUploadDefaultFolder=bo(void 0),this.sessionWarningVisibility=tp(),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=Pg(this.terminalModalBounds,this.terminalModalViewport()))},this.onKeyDown=e=>{this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStartSessionPrompt=(e,t,n,r)=>{!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||(this.sessions.startSessionWithPrompt(e,t,n,r),this.focusChatComposer())},this.handleSelectStarterModel=()=>{this.openStarterModelDialog()},this.handleSelectStarterThinking=()=>{this.openStarterThinkingDialog()},this.handleOpenTerminalFromRail=()=>{this.state.selectedWorkspace!==void 0&&(this.terminalModalOpen=!0)},this.handleOpenGitUpdateManagerFromRail=()=>{this.state.selectedWorkspace!==void 0&&(this.gitUpdateManagerPanelOpen=!0)},this.handleCloseGitUpdateManagerPanel=()=>{this.gitUpdateManagerPanelOpen=!1},this.handleOpenThemeFromRail=()=>{this.openThemeDialog()},this.handleRailOrderChange=e=>{this.railOrder=e,ek(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`?Mg(t.bounds,n,r):Ng(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=zg(this.terminalModalFontSize+e);t!==this.terminalModalFontSize&&(this.terminalModalFontSize=t,this.persistTerminalModalPreferences())},this.adjustTerminalOpacity=e=>{let t=Bg(this.terminalModalOpacity+e);t!==this.terminalModalOpacity&&(this.terminalModalOpacity=t,this.persistTerminalModalPreferences())},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleCompact=()=>{this.sessions.runCommand(`/compact`)},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleEditFromHere=async(e,t)=>{let n=R(this.state),r=this.state.selectedSession?.id;try{!(await this.sessions.editFromHere(e,t)).cancelled&&r!==void 0&&R(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer()}catch{}},this.handleForkFromHere=async e=>{await this.sessions.forkFromHere(e)},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=op(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility()}updated(){this.committedChatIdentity=Dk(this.state),this.syncSelectedSessionReadState()}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=rp(this.sessionWarningVisibility,e===void 0?void 0:Wo(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=Ek(e,t);await this.updateComplete,!(!this.unreadConnected||Dk(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);Nk(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncWindowTitle(){this.disconnectWindowTitle();let e=Jg(this.state.selectedProject?.name);this.windowTitleCleanup=Yg(e)}disconnectWindowTitle(){this.windowTitleCleanup?.(),this.windowTitleCleanup=void 0}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=Ek(e,t);return Dk(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.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.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}connectedCallback(){super.connectedCallback(),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,mk),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},dk),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebUiStatusRefresh()}),this.syncWindowTitle()}disconnectedCallback(){this.finishTerminalModalPointerInteraction(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.unreadRuntimeRefreshes.clear(),this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),window.removeEventListener(`resize`,this.onTerminalModalViewportResize),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,mk),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.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(!Mk(this.state,e))return;let t=this.state;this.state={...this.state,...e},Dk(t)!==Dk(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),Ok(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),kk(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedProject?.name!==this.state.selectedProject?.name&&this.syncWindowTitle()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=fg();await this.machines.loadMachines(e.machineId);let t=this.routeForSelectedMachine(e),n=this.state.machineStatuses[t.machineId??`local`];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,n)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebUiStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns()])}schedulePiWebUiStatusRefresh(e=fk){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=>jk(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 Ua.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEBUI config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=bo(e)}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()]),this.schedulePiWebUiStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let e=this.state.selectedWorkspace,t=this.state.mainView!==`chat`&&this.state.mainView!==`navigation`?this.state.mainView:this.state.workspaceTool;t===`core:workspace.files`?await this.files.refreshFiles():t===`core:workspace.git`?await this.git.refreshGit():t===`core:workspace.terminal`&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(fg(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=R(this.state),a=e.projectId===void 0||e.projectId===``?Ik():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===``?Ik():{selectedFilePath:es(vk,`file`),selectedDiffPath:es(yk,`diff`),selectedTerminalId:es(bk,`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){pg(e,{replace:!0}),ts(vk,`file`,void 0,{replace:!0}),ts(yk,`diff`,void 0,{replace:!0}),ts(bk,`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=Rk(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>=pk.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 Vk(),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(),pg({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(Hd(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Hd(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){pg(Ud(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){ts(vk,`file`,e.selectedFilePath,{replace:!0}),ts(yk,`diff`,e.selectedDiffPath,{replace:!0}),ts(bk,`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)??Vd(e.id);if(await this.restoreRouteFor(Ud(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=Lk(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=wg(e,{api:{runTerminalCommand:(e,n)=>ao.runTerminalCommand(e,n,t),listCommandRuns:e=>ao.listCommandRuns(e,t),getCommandRun:e=>ao.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((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`});return}this.openTerminal(n)}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){ts(bk,`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,vg(e)}closeSettings(){this.settingsSection=void 0,vg(void 0)}navigateSettings(e){this.settingsSection=e,vg(e)}restoreSettingsRoute(){this.settingsSection=_g()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.starterSessionDefaults=void 0,this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();let n=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:n}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(n,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}async loadStarterSessionDefaults(e){let t=R(this.state);try{let n=await io.sessionDefaults(e.path,t);if(R(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.starterSessionDefaults=n}catch(n){R(this.state)===t&&this.state.selectedWorkspace?.id===e.id&&console.warn(`Failed to load Pi session defaults`,n)}}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`:Gt(e,T.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)},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 eu;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=>Ak(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):Fk(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 ao.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=Pk(e),r=Pk(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&(this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebUiStatus:void 0}),this.git.updatePolling(),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
|
|
5879
5879
|
<workspace-panel
|
|
5880
5880
|
id="workspace-panel"
|
|
5881
5881
|
.workspace=${e}
|
|
@@ -5922,7 +5922,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5922
5922
|
.onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
|
|
5923
5923
|
.onReset=${()=>{this.resetResizablePanel(`workspace`)}}
|
|
5924
5924
|
></app-panel-edge-control>
|
|
5925
|
-
`}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-
|
|
5925
|
+
`}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-Sk-xk);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(Ck).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||Gt(e,T.sessionsDeleteArchived)}canReloadSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Gt(e,T.sessionsReload)}canClearServerQueue(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Gt(e,T.sessionsClearQueue)}canMessageActions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Gt(e,T.sessionsMessageActions)}canViewSystemPrompt(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Gt(e,T.sessionsSystemPrompt)}canCleanupSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&Gt(e,T.sessionsCleanup)}hasAuthoritativeSessionPersistence(){return du(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=R(this.state)){if(e===`local`)return!0;let t=this.state.machineRuntimes[e];return t?.ok===!0&&Gt(t,T.workspaceFileSuggestions)}archivedDeleteUnavailableMessage(){return`Update and restart Pi-Web on ${this.state.selectedMachine?.name??`this machine`} to delete archived sessions.`}sessionCleanupUnavailableMessage(){return Bf(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 io.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: ${zk(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||Nf(t.previewRequest)!==Nf(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 io.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: ${zk(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 io.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: ${zk(e)}`})}}renderNavigationPanel(){return g`
|
|
5926
5926
|
<app-navigation-panel
|
|
5927
5927
|
.machines=${this.state.machines}
|
|
5928
5928
|
.selectedMachine=${this.state.selectedMachine}
|
|
@@ -5997,7 +5997,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5997
5997
|
.onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
|
|
5998
5998
|
.onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
|
|
5999
5999
|
></app-navigation-panel>
|
|
6000
|
-
`}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){this.sessions.startSession().catch(t=>{e()&&this.setState({error:String(t)})}),e()&&await this.focusChatComposer()}async focusNavigationTarget(e){if(e===`chat`){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e===`machines`&&!
|
|
6000
|
+
`}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){this.sessions.startSession().catch(t=>{e()&&this.setState({error:String(t)})}),e()&&await this.focusChatComposer()}async focusNavigationTarget(e){if(e===`chat`){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e===`machines`&&!FO(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 Vk(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!==`chat`&&this.selectMainView(`chat`),await this.updateComplete,await Vk(),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`
|
|
6001
6001
|
<session-tree-navigator
|
|
6002
6002
|
.tree=${e.treeDialog}
|
|
6003
6003
|
.onNavigate=${(e,t)=>this.navigateSessionTree(e,t)}
|
|
@@ -6016,7 +6016,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6016
6016
|
<p class="session-start-hint">Describe a goal, paste a task, or attach a file to begin.</p>
|
|
6017
6017
|
</div>
|
|
6018
6018
|
</section>
|
|
6019
|
-
`}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=Ck(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=>ro.workspaceFile(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await ro.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await ro.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await ro.moveWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){let t=Ck(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return gh({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),prompt:this.createPromptEditor(),terminal:{open:t=>{this.openRuntimeTerminal(n,e,t)},runCommand:t=>a.runCommand({...t,workspace:e})},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:xo(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()},onSelectDiff:e=>{this.git.selectDiff(e)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(`core`)}getActions(){return xg(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`,...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`,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`,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`,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`,run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins(`PI WEBUI plugins`,()=>$m())}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}`,()=>$m(`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.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(){let e=t=>hh({state:this.state,prompt:this.createPromptEditor(),piWebUiUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(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()},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!Id(e)){this.setState({error:`Only secondary Git worktrees can be deleted`});return}if(Op(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 ro.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: ${Lk(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=kp(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(Tp(t.id));if(R(this.state)!==e)return;let r=Ep(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))Ap(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(Ap);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=Fk(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=kp(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:Rk(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}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()}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(`/`);t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openStarterModelDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=e.model?.provider,n=e.model?.id,r=[...e.models].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`,...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 pickStarterModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);t<=0||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?mk:pk;this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${hk}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${hk}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===pk||e===mk){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===pk},this.applyPreferredTheme(!0);return}if(!e.startsWith(hk))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,mp(t),e&&pp(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return hp({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return _p(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=Kk(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==``&&await this.sessions.setThinkingLevel(e)}openStarterThinkingDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=e.thinkingLevel;this.setState({thinkingDialog:{title:`Select Default Thinking Level`,source:`starter`,selectedValue:t,options:e.thinkingLevels.map(e=>{let n=Kk(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickStarterThinking(e){this.setState({thinkingDialog:void 0}),e!==``&&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 io.updateSessionDefaults(t.path,e,n);if(R(this.state)!==n||this.state.selectedWorkspace?.id!==t.id)return;this.starterSessionDefaults=r}catch(e){R(this.state)===n&&this.state.selectedWorkspace?.id===t.id&&this.setState({error:String(e)})}}sendPrompt(e,t,n,r){!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,n,r)}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=Pg(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(){Hg({fontSize:this.terminalModalFontSize,opacity:this.terminalModalOpacity})}toggleTerminalTab(){this.terminalTabHidden=!this.terminalTabHidden,Hk(this.terminalTabHidden)}toggleInfoTab(){this.infoTabHidden=!this.infoTabHidden,Gk(this.infoTabHidden)}renderChatView(e,t){return g`
|
|
6019
|
+
`}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=Tk(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=>ro.workspaceFile(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await ro.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await ro.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await ro.moveWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){let t=Tk(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return gh({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),prompt:this.createPromptEditor(),terminal:{open:t=>{this.openRuntimeTerminal(n,e,t)},runCommand:t=>a.runCommand({...t,workspace:e})},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:xo(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()},onSelectDiff:e=>{this.git.selectDiff(e)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(`core`)}getActions(){return xg(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`,...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`,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`,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`,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`,run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins(`PI WEBUI plugins`,()=>$m())}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}`,()=>$m(`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.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(){let e=t=>hh({state:this.state,prompt:this.createPromptEditor(),piWebUiUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(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()},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!Id(e)){this.setState({error:`Only secondary Git worktrees can be deleted`});return}if(Op(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 ro.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: ${zk(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=kp(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(Tp(t.id));if(R(this.state)!==e)return;let r=Ep(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))Ap(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(Ap);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=Lk(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=kp(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:Bk(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}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()}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(`/`);t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openStarterModelDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=e.model?.provider,n=e.model?.id,r=[...e.models].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`,...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 pickStarterModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);t<=0||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?gk:hk;this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${_k}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${_k}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===hk||e===gk){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===hk},this.applyPreferredTheme(!0);return}if(!e.startsWith(_k))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,mp(t),e&&pp(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return hp({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return _p(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=Jk(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==``&&await this.sessions.setThinkingLevel(e)}openStarterThinkingDialog(){let e=this.starterSessionDefaults;if(e===void 0)return;let t=e.thinkingLevel;this.setState({thinkingDialog:{title:`Select Default Thinking Level`,source:`starter`,selectedValue:t,options:e.thinkingLevels.map(e=>{let n=Jk(e);return{value:e,label:`${e}${e===t?` ✓ current`:``}`,...n===void 0?{}:{description:n}}})}})}async pickStarterThinking(e){this.setState({thinkingDialog:void 0}),e!==``&&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 io.updateSessionDefaults(t.path,e,n);if(R(this.state)!==n||this.state.selectedWorkspace?.id!==t.id)return;this.starterSessionDefaults=r}catch(e){R(this.state)===n&&this.state.selectedWorkspace?.id===t.id&&this.setState({error:String(e)})}}sendPrompt(e,t,n,r){!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,n,r)}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=Pg(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(){Hg({fontSize:this.terminalModalFontSize,opacity:this.terminalModalOpacity})}toggleTerminalTab(){this.terminalTabHidden=!this.terminalTabHidden,Wk(this.terminalTabHidden)}toggleInfoTab(){this.infoTabHidden=!this.infoTabHidden,qk(this.infoTabHidden)}renderChatView(e,t){return g`
|
|
6020
6020
|
<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=${cd(e.selectedNotificationInbox)} .canClearServerQueue=${this.canClearServerQueue()} .onClearServerQueue=${this.handleClearServerQueue} .canMessageActions=${this.canMessageActions()&&t.archived!==!0} .onEditFromHere=${this.handleEditFromHere} .onForkFromHere=${this.handleForkFromHere} .onDismissWarning=${this.handleDismissWarning} .onDismissNotification=${this.handleDismissNotification} .onDismissAllNotifications=${this.handleDismissAllNotifications} .warningsVisible=${!this.sessionWarningVisibility.collapsed} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
|
|
6021
6021
|
`}renderContextBar(){return this.appShell.isMobileNavigationLayout?g`
|
|
6022
6022
|
<app-context-bar
|
|
@@ -6173,4 +6173,4 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6173
6173
|
${this.terminalModalOpen?this.renderTerminalModal():null}
|
|
6174
6174
|
${this.settingsSection===void 0?null:g`<settings-dialog .section=${this.settingsSection} .machine=${e.selectedMachine} .machineRuntime=${this.selectedMachineRuntime()} .actions=${this.getDefaultActions()} .onNavigate=${e=>{this.navigateSettings(e)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${e=>{this.applyClientConfig(e)}} .onRefreshMachineRuntime=${async e=>{await this.machines.refreshMachineRuntime(e)}}></settings-dialog>`}
|
|
6175
6175
|
</div>
|
|
6176
|
-
`}static{this.styles=Gp}};B([S()],$.prototype,`state`,void 0),B([C(`chat-view`)],$.prototype,`chatView`,void 0),B([C(`prompt-editor`)],$.prototype,`promptEditor`,void 0),B([C(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),B([C(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),B([C(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),B([S()],$.prototype,`unreadSessionIds`,void 0),B([S()],$.prototype,`activeThemeId`,void 0),B([S()],$.prototype,`isRefreshingApp`,void 0),B([S()],$.prototype,`sessionCleanupDialog`,void 0),B([S()],$.prototype,`historyWindow`,void 0),B([S()],$.prototype,`starterSessionDefaults`,void 0),B([S()],$.prototype,`modelsConfigDialogOpen`,void 0),B([S()],$.prototype,`projectBrowserOpen`,void 0),B([S()],$.prototype,`skillsConfigDialogOpen`,void 0),B([S()],$.prototype,`pluginsConfigDialogOpen`,void 0),B([S()],$.prototype,`systemPromptDialogOpen`,void 0),B([S()],$.prototype,`gitUpdateManagerPanelOpen`,void 0),B([S()],$.prototype,`terminalModalOpen`,void 0),B([S()],$.prototype,`terminalModalBounds`,void 0),B([S()],$.prototype,`terminalModalMaximized`,void 0),B([S()],$.prototype,`terminalModalFontSize`,void 0),B([S()],$.prototype,`terminalModalOpacity`,void 0),B([S()],$.prototype,`terminalTabHidden`,void 0),B([S()],$.prototype,`infoTabHidden`,void 0),B([S()],$.prototype,`railOrder`,void 0),B([S()],$.prototype,`settingsSection`,void 0),B([S()],$.prototype,`shortcutConfig`,void 0),B([S()],$.prototype,`workspaceUploadDefaultFolder`,void 0),$=B([b(`pi-webui-app`)],$);function
|
|
6176
|
+
`}static{this.styles=Gp}};B([S()],$.prototype,`state`,void 0),B([C(`chat-view`)],$.prototype,`chatView`,void 0),B([C(`prompt-editor`)],$.prototype,`promptEditor`,void 0),B([C(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),B([C(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),B([C(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),B([S()],$.prototype,`unreadSessionIds`,void 0),B([S()],$.prototype,`activeThemeId`,void 0),B([S()],$.prototype,`isRefreshingApp`,void 0),B([S()],$.prototype,`sessionCleanupDialog`,void 0),B([S()],$.prototype,`historyWindow`,void 0),B([S()],$.prototype,`starterSessionDefaults`,void 0),B([S()],$.prototype,`modelsConfigDialogOpen`,void 0),B([S()],$.prototype,`projectBrowserOpen`,void 0),B([S()],$.prototype,`skillsConfigDialogOpen`,void 0),B([S()],$.prototype,`pluginsConfigDialogOpen`,void 0),B([S()],$.prototype,`systemPromptDialogOpen`,void 0),B([S()],$.prototype,`gitUpdateManagerPanelOpen`,void 0),B([S()],$.prototype,`terminalModalOpen`,void 0),B([S()],$.prototype,`terminalModalBounds`,void 0),B([S()],$.prototype,`terminalModalMaximized`,void 0),B([S()],$.prototype,`terminalModalFontSize`,void 0),B([S()],$.prototype,`terminalModalOpacity`,void 0),B([S()],$.prototype,`terminalTabHidden`,void 0),B([S()],$.prototype,`infoTabHidden`,void 0),B([S()],$.prototype,`railOrder`,void 0),B([S()],$.prototype,`settingsSection`,void 0),B([S()],$.prototype,`shortcutConfig`,void 0),B([S()],$.prototype,`workspaceUploadDefaultFolder`,void 0),$=B([b(`pi-webui-app`)],$);function wk(){let e=new fh;return e.register({id:`core`,plugin:Um}),e.register({id:`themes`,plugin:qm}),e}function Tk(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 Ek(e,t){return JSON.stringify([e,t.id,t.cwd])}function Dk(e){let t=e.selectedSession;return t===void 0?void 0:Ek(R(e),t)}function Ok(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function kk(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function Ak(e,t){return jk(e,t)}function jk(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function Mk(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function Nk(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function Pk(e){return Vo(e.status,e.activity)}function Fk(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function Ik(){return{}}function Lk(e,t){return JSON.stringify([e,t])}function Rk(e){return pk[Math.min(e,pk.length-1)]??3e4}function zk(e){return e instanceof Error?e.message:String(e)}function Bk(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Vk(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}var Hk=`pi-webui:terminal-tab-hidden`;function Uk(){try{let e=typeof localStorage>`u`?void 0:localStorage;return e!==void 0&&e.getItem(Hk)===`true`}catch{return!1}}function Wk(e){try{let t=typeof localStorage>`u`?void 0:localStorage;if(t===void 0)return;e?t.setItem(Hk,`true`):t.removeItem(Hk)}catch{}}var Gk=`pi-webui:info-tab-hidden`;function Kk(){try{let e=typeof localStorage>`u`?void 0:localStorage;return e!==void 0&&e.getItem(Gk)===`true`}catch{return!1}}function qk(e){try{let t=typeof localStorage>`u`?void 0:localStorage;if(t===void 0)return;e?t.setItem(Gk,`true`):t.removeItem(Gk)}catch{}}function Jk(e){switch(e){case`off`:return`No reasoning`;case`minimal`:return`Very brief reasoning (~1k tokens)`;case`low`:return`Light reasoning (~2k tokens)`;case`medium`:return`Moderate reasoning (~8k tokens)`;case`high`:return`Deep reasoning (~16k tokens)`;case`xhigh`:return`Maximum reasoning (~32k tokens)`;default:return}}export{y as a,b as i,C as n,g as o,x as r,h as s,B as t};
|