@hyperdreamer/pi-webui 1.10.0 → 1.10.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{CodeViewer-Cm2qJjkP.js → CodeViewer-BdULrLxb.js} +1 -1
- package/dist/client/assets/{UnifiedDiffViewer-XFd_Uipx.js → UnifiedDiffViewer-DDlEJGJ4.js} +1 -1
- package/dist/client/assets/{index-DtFX3SXN.js → index-Bq-PmNe2.js} +529 -406
- package/dist/client/index.html +1 -1
- package/dist/pi-webui-plugins/workspace-memory/memoryPanelElement.js +9 -4
- 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-BdULrLxb.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
|
|
@@ -448,7 +448,8 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
448
448
|
.tree-marker { color: var(--pi-dim); margin-right: 5px; }
|
|
449
449
|
.badge { display: inline-block; margin-left: 5px; border: 1px solid var(--pi-border); border-radius: 999px; color: var(--pi-muted); padding: 0 5px; font-size: 11px; font-weight: 400; }
|
|
450
450
|
.action-activity { position: absolute; top: 5px; right: 6px; z-index: 1; display: grid; place-items: center; width: 10px; height: 10px; }
|
|
451
|
-
.action-
|
|
451
|
+
.action-activities { position: absolute; top: 5px; right: 6px; z-index: 1; display: inline-flex; align-items: center; gap: 4px; min-height: 13px; }
|
|
452
|
+
.action-activity .activity-indicator, .action-activities .activity-indicator { margin: 0; vertical-align: 0; }
|
|
452
453
|
.activity-indicator { display: inline-block; width: 7px; height: 7px; margin-right: 6px; background: var(--pi-success); animation: pulse 1s ease-in-out infinite; vertical-align: 1px; }
|
|
453
454
|
.activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
|
|
454
455
|
.activity-indicator.terminal { border-radius: 2px; background: var(--pi-accent); }
|
|
@@ -456,6 +457,12 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
456
457
|
.activity-indicator.sending { border-radius: 50%; background: var(--pi-warning); }
|
|
457
458
|
/* Unread is a stable state, not ongoing work: keep it static and accent-colored. */
|
|
458
459
|
.activity-indicator.unread { border-radius: 50%; background: var(--pi-accent); animation: none; box-shadow: 0 0 0 2px color-mix(in srgb, var(--pi-accent) 20%, transparent); }
|
|
460
|
+
/* A blue ring, rather than another dot, makes delegated work distinguishable without color. */
|
|
461
|
+
.activity-indicator.descendant { display: inline-grid; place-items: center; width: 13px; height: 13px; border: 2px solid light-dark(#0969da, #58a6ff); border-radius: 50%; background: transparent; color: light-dark(#0969da, #58a6ff); animation: none; }
|
|
462
|
+
.activity-indicator.attention { display: inline-grid; place-items: center; width: 12px; height: 12px; border-radius: 3px; background: var(--pi-danger); color: var(--pi-bg); animation: none; transform: rotate(45deg); }
|
|
463
|
+
.activity-indicator-count { font-size: 8px; font-weight: 800; line-height: 1; transform: none; }
|
|
464
|
+
.activity-indicator.attention .activity-indicator-count { transform: rotate(-45deg); }
|
|
465
|
+
@media (prefers-reduced-motion: reduce) { .activity-indicator { animation: none; } }
|
|
459
466
|
.action-menu { position: relative; align-self: stretch; }
|
|
460
467
|
.action-menu-toggle { display: grid; place-items: center; height: 100%; min-width: 32px; padding: 0; color: var(--pi-muted); border-left: 0; border-top-left-radius: 0; border-bottom-left-radius: 0; }
|
|
461
468
|
.action-menu-toggle:hover { color: var(--pi-text); background: var(--pi-surface-hover); }
|
|
@@ -1090,7 +1097,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1090
1097
|
.review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1091
1098
|
.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
1099
|
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-
|
|
1100
|
+
`]}};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-BdULrLxb.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
1101
|
<p class="error-text">Failed to load system information: ${this.error}</p>
|
|
1095
1102
|
<button @click=${()=>{this.loadSystemInfo()}}>Retry</button>
|
|
1096
1103
|
</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">
|
|
@@ -1216,20 +1223,30 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1216
1223
|
<td class="info-label">Upload</td>
|
|
1217
1224
|
<td class="info-value">${Dm(t.uploadSpeedBytesPerSecond)}<span class="network-speed-arrow upload" aria-hidden="true">↑</span></td>
|
|
1218
1225
|
</tr>
|
|
1219
|
-
|
|
1226
|
+
</tbody>
|
|
1227
|
+
</table>
|
|
1228
|
+
${t.publicIpv4===void 0?null:g`
|
|
1229
|
+
<h4 class="info-subheading">Public IPv4 Addresses</h4>
|
|
1230
|
+
<table class="info-table">
|
|
1231
|
+
<tbody>
|
|
1220
1232
|
<tr>
|
|
1221
|
-
<td class="info-label">
|
|
1222
|
-
<td class="info-value">${t.publicIpv4}</td>
|
|
1233
|
+
<td class="info-label">WAN</td>
|
|
1234
|
+
<td class="info-value"><code class="ip-address">${t.publicIpv4}</code></td>
|
|
1223
1235
|
</tr>
|
|
1224
|
-
|
|
1225
|
-
|
|
1236
|
+
</tbody>
|
|
1237
|
+
</table>
|
|
1238
|
+
`}
|
|
1239
|
+
${t.publicIpv6===void 0?null:g`
|
|
1240
|
+
<h4 class="info-subheading">Public IPv6 Addresses</h4>
|
|
1241
|
+
<table class="info-table">
|
|
1242
|
+
<tbody>
|
|
1226
1243
|
<tr>
|
|
1227
|
-
<td class="info-label">
|
|
1244
|
+
<td class="info-label">WAN</td>
|
|
1228
1245
|
<td class="info-value"><code class="ip-address">${t.publicIpv6}</code></td>
|
|
1229
1246
|
</tr>
|
|
1230
|
-
|
|
1231
|
-
</
|
|
1232
|
-
|
|
1247
|
+
</tbody>
|
|
1248
|
+
</table>
|
|
1249
|
+
`}
|
|
1233
1250
|
${t.localIpv4Addresses.length===0?null:g`
|
|
1234
1251
|
<h4 class="info-subheading">Local IPv4 Addresses</h4>
|
|
1235
1252
|
<table class="info-table">
|
|
@@ -1334,12 +1351,12 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1334
1351
|
<div class="viewer-header"><strong>${e.path??`diff`}</strong><small>${e.staged?`staged`:`unstaged`}${e.truncated?` · truncated`:``}</small></div>
|
|
1335
1352
|
<unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
|
|
1336
1353
|
</section>
|
|
1337
|
-
`}function Lm(){rm(()=>import(`./UnifiedDiffViewer-
|
|
1354
|
+
`}function Lm(){rm(()=>import(`./UnifiedDiffViewer-DDlEJGJ4.js`),[],import.meta.url)}function Rm(){rm(()=>Promise.resolve().then(()=>oO),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
1355
|
<p class="summary">
|
|
1339
1356
|
<span class="summary-branch">${t.branch}</span>
|
|
1340
1357
|
${t.latestTag===void 0?null:g`<span class="summary-tag" aria-label=${`Latest tag ${t.latestTag}`}>${t.latestTag}</span>`}
|
|
1341
1358
|
</p>
|
|
1342
|
-
`}function Vm(e){let t=e.branch??`detached`,n=e.ahead??0,r=e.behind??0;return{branch:n===0&&r===0?t:`${t} · ↑${String(n)} ↓${String(r)}`,...e.latestTag===void 0?{}:{latestTag:e.latestTag}}}function Hm(e,t){return(t===`unmodified`?e:t).slice(0,1).toUpperCase()}var Um={apiVersion:1,name:`PI WEBUI Core`,activate:()=>({contributions:{actions:jp(),workspacePanels:jm()}})},Wm={"--pi-bg":`#0d1117`,"--pi-surface":`#161b22`,"--pi-surface-hover":`#21262d`,"--pi-terminal-bg":`#05070a`,"--pi-terminal-text":`#e6edf3`,"--pi-border":`#30363d`,"--pi-border-muted":`#21262d`,"--pi-text":`#e6edf3`,"--pi-text-secondary":`#c9d1d9`,"--pi-text-bright":`#f0f6fc`,"--pi-muted":`#8b949e`,"--pi-dim":`#6e7681`,"--pi-accent":`#58a6ff`,"--pi-accent-border":`#2f81f7`,"--pi-selection-bg":`#0d2847`,"--pi-success":`#3fb950`,"--pi-success-border":`#238636`,"--pi-success-bg":`#0f1b12`,"--pi-success-surface":`#0f2a16`,"--pi-success-ring":`#3fb95055`,"--pi-warning":`#d29922`,"--pi-warning-border":`#6e5200`,"--pi-warning-surface":`#1f1a10`,"--pi-danger":`#ff7b72`,"--pi-purple":`#d2a8ff`,"--pi-purple-border":`#a371f7`,"--pi-purple-surface":`#21132f`,"--pi-overlay":`#0008`,"--pi-shadow-soft":`#0006`,"--pi-shadow":`#0008`,"--pi-shadow-strong":`#000b`,"--pi-bg-overlay-soft":`#0d1117dd`,"--pi-bg-overlay":`#0d1117e6`,"--pi-success-bg-overlay":`#0f1b12ee`,"--pi-terminal-selection":`#264f78`},Gm={"--pi-bg":`#070912`,"--pi-surface":`#101527`,"--pi-surface-hover":`#151b31`,"--pi-terminal-bg":`#050710`,"--pi-terminal-text":`#f7f4ff`,"--pi-border":`#26304f`,"--pi-border-muted":`#26304f`,"--pi-text":`#f7f4ff`,"--pi-text-secondary":`#aaa4bd`,"--pi-text-bright":`#ffffff`,"--pi-muted":`#aaa4bd`,"--pi-dim":`#817a99`,"--pi-accent":`#7c3cff`,"--pi-accent-border":`#5a47b0`,"--pi-selection-bg":`#1d2547`,"--pi-success":`#00f0d8`,"--pi-success-border":`#00f0d8`,"--pi-success-bg":`#071e22`,"--pi-success-surface":`#092d31`,"--pi-success-ring":`#00f0d855`,"--pi-warning":`#ffb000`,"--pi-warning-border":`#ffb000`,"--pi-warning-surface":`#16140d`,"--pi-danger":`#ff4f7b`,"--pi-purple":`#b7a2ff`,"--pi-purple-border":`#7c3cff`,"--pi-purple-surface":`#181026`,"--pi-overlay":`#0008`,"--pi-shadow-soft":`#0006`,"--pi-shadow":`#0008`,"--pi-shadow-strong":`#000b`,"--pi-bg-overlay-soft":`#070912dd`,"--pi-bg-overlay":`#070912e6`,"--pi-success-bg-overlay":`#071e22ee`,"--pi-terminal-selection":`#3d4a78`},Km={"--pi-bg":`#f7f1e6`,"--pi-surface":`#fff9ee`,"--pi-surface-hover":`#f0e6d6`,"--pi-terminal-bg":`#15131b`,"--pi-terminal-text":`#fff9ee`,"--pi-border":`#c9bca8`,"--pi-border-muted":`#d8cdbc`,"--pi-text":`#15131b`,"--pi-text-secondary":`#15131b`,"--pi-text-bright":`#15131b`,"--pi-muted":`#5f586a`,"--pi-dim":`#766f7e`,"--pi-accent":`#6430d8`,"--pi-accent-border":`#6430d8`,"--pi-selection-bg":`#eadff8`,"--pi-success":`#008c82`,"--pi-success-border":`#008c82`,"--pi-success-bg":`#e1f4ef`,"--pi-success-surface":`#d7f0ec`,"--pi-success-ring":`#008c8255`,"--pi-warning":`#b05f00`,"--pi-warning-border":`#b05f00`,"--pi-warning-surface":`#fff2d2`,"--pi-danger":`#b51d49`,"--pi-purple":`#6430d8`,"--pi-purple-border":`#6430d8`,"--pi-purple-surface":`#eadff8`,"--pi-overlay":`#15131b66`,"--pi-shadow-soft":`#15131b22`,"--pi-shadow":`#15131b33`,"--pi-shadow-strong":`#15131b44`,"--pi-bg-overlay-soft":`#f7f1e6dd`,"--pi-bg-overlay":`#f7f1e6e6`,"--pi-success-bg-overlay":`#e1f4efee`,"--pi-terminal-selection":`#8d7b64`},qm={apiVersion:1,name:`PI WEBUI Themes`,activate:()=>({contributions:{themes:[{id:`pi-webui-dark`,name:`PI WEBUI Dark`,description:`Dark PI WEBUI palette.`,order:10,colorScheme:`dark`,tokens:Gm},{id:`pi-webui-light`,name:`PI WEBUI Light`,description:`Light PI WEBUI palette.`,order:20,colorScheme:`light`,tokens:Km},{id:`classic`,name:`PI WEBUI Classic`,description:`The original PI WEBUI dark palette.`,order:30,colorScheme:`dark`,tokens:Wm}],themePairs:[{id:`pi-webui`,name:`PI WEBUI`,description:`Follow the system light/dark preference with PI WEBUI themes.`,order:10,light:`pi-webui-light`,dark:`pi-webui-dark`}]}})},Jm=/^[a-z][a-z0-9.-]*$/u;function Ym(e){return Jm.test(e)}var Xm=`machine.`;function Zm(e,t){if(e===``)throw Error(`Machine id is required`);if(!Ym(t))throw Error(`Invalid PI WEBUI plugin id: ${t}`);return`${Xm}${Qm(e)}.${t}`}function Qm(e){return[...new TextEncoder().encode(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function $m(e=`pi-webui-plugins/manifest.json`,t={}){let n=bt(e),r=await nh(n);if(r===void 0)return[];let i=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=eh(e.module,n),a=ah(await(t.moduleLoader??th)(r),r);i.push({id:t.machineId===void 0?e.id:Zm(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){console.warn(`Failed to load PI WEBUI plugin ${e.module}`,t)}return i}function eh(e,t,n){return e.startsWith(`/`)?n===void 0?bt(e):bt(e,n):new URL(e,t).toString()}async function th(e){return rm(()=>import(e),[],import.meta.url)}async function nh(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(`Failed to load plugin manifest: ${t.statusText}`);return rh(await t.json())}}function rh(e){if(!sh(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);return{plugins:e.plugins.map(e=>{if(!sh(e)||typeof e.id!=`string`||e.id===``||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);return{id:e.id,module:e.module,machineSpecific:ih(e.machineSpecific)}})}}function ih(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function ah(e,t){if(!sh(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(!oh(n))throw Error(`Plugin module ${t} default export is not a PiWebUiPlugin`);return n}function oh(e){return sh(e)&&e.apiVersion===1&&typeof e.name==`string`&&typeof e.activate==`function`}function sh(e){return typeof e==`object`&&!!e}var ch=/^[a-z][a-z0-9.-]*$/u,lh=/^[a-z][a-z0-9.-]*$/u,uh=new WeakMap,dh=new WeakMap,fh=class{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{id:t,plugin:n}=e;this.validatePluginId(t);let r=this.parseMachineSpecific(t,e.machineSpecific);if(this.pluginIds.has(t))throw Error(`Duplicate plugin id: ${t}`);if(this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,r))return;this.pluginIds.add(t);let i=n.apiVersion;if(i!==1)throw Error(`Unsupported plugin API version for ${t}: ${String(i)}`);let a=n.activate({apiVersion:1,pluginId:t,html:g,svg:_}).contributions;for(let n of a.actions??[])this.actions.push(this.qualifyAction(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(t,n,e.machineId,e.sourcePluginId));if(e.machineId===void 0){for(let e of a.themes??[])this.themes.push(this.qualifyTheme(t,e));for(let e of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(t,e));this.gatewayPluginIds.add(t),r&&this.gatewayMachineSpecificPluginIds.add(t)}else e.sourcePluginId!==void 0&&r&&_h(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=yh(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=ph(e,t.pluginId),r=t.enabled?.(n),i=r===!1?t.disabledReason?.(n):void 0,a={id:t.id,pluginId:t.pluginId,localId:t.localId,...t.machineId===void 0?{}:{machineId:t.machineId},title:t.title,run:()=>t.run(n)};return t.description!==void 0&&(a.description=t.description),t.shortcut!==void 0&&(a.shortcut=t.shortcut),t.group!==void 0&&(a.group=t.group),r!==void 0&&(a.enabled=r),i!==void 0&&i!==``&&(a.disabledReason=i),a})}getWorkspacePanels(){return[...this.workspacePanels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}getThemes(){return[...this.themes].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getThemePairs(){return[...this.themePairs].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getWorkspaceLabelItems(e){return[...this.workspaceLabels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.id.localeCompare(t.id)).flatMap(t=>t.visible?.(e)===!1?[]:t.items(e))}qualifyAction(e,t,n,r){let i=this.qualify(e,t.id);return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r){let i=this.qualify(e,t.id),a=t.badge,o=t.visible;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(o?.(mh(t,e))??!0),...a===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?a(mh(t,e)):void 0},render:n=>t.render(mh(n,e))}}qualifyWorkspaceLabelContribution(e,t,n,r){let i=this.qualify(e,t.id),a=t.visible,o=t.items;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(a?.(t)??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?o(t):[]}}qualifyTheme(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id}}qualifyThemePair(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t){this.validateLocalId(t);let n=`${e}:${t}`;if(this.contributionIds.has(n))throw Error(`Duplicate contribution id: ${n}`);return this.contributionIds.add(n),n}qualifyReference(e,t){return this.validateLocalId(t),`${e}:${t}`}isContributionActive(e,t,n,r){return t===void 0?!this.isGatewayPluginHiddenForMachine(e,n):t===n&&!this.isRemotePluginHiddenByGateway(r,t)}isRemoteDuplicateHiddenByGateway(e,t,n){return e!==void 0&&t!==void 0&&this.gatewayPluginIds.has(e)&&!this.gatewayMachineSpecificPluginIds.has(e)&&!n}isRemotePluginHiddenByGateway(e,t){return e===void 0||this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0?!1:this.gatewayPluginIds.has(e)}isGatewayPluginHiddenForMachine(e,t){return t!==`local`&&(this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0)}validatePluginId(e){if(!ch.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!lh.test(e))throw Error(`Invalid contribution id: ${e}`)}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${vh(t)}`);return t}};function ph(e,t){return uh.get(e)?.(t)??e}function mh(e,t){return dh.get(e)?.(t)??e}function hh(e,t){return uh.set(e,t),e}function gh(e,t){return dh.set(e,t),e}function _h(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function vh(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`||typeof e==`function`||e==null)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function yh(e){return e.state.selectedMachine?.id??`local`}var bh=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function xh(){return typeof window>`u`||!(`matchMedia`in window)?[]:bh.map(e=>window.matchMedia(e))}function Sh(e,t=Ch()){return e.some(e=>e.matches)||wh(t)}function Ch(){return typeof navigator>`u`?void 0:navigator}function wh(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var Th=class{constructor(e=Eh()){this.scheduler=e}repair(e){if(!e){this.clear();return}this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},250)}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);let e=this.scheduler.documentElement;e!==void 0&&(e.scrollTop=0);let t=this.scheduler.body;t!==void 0&&(t.scrollTop=0)}};function Eh(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>`u`?void 0:document.documentElement},get body(){return typeof document>`u`?void 0:document.body}}}var Dh=`(max-width: 760px)`,Oh=class{constructor(e,t={}){this.host=e,this.onMobileNavigationMediaChange=e=>{this.isMobileNavigationLayout!==e.matches&&(this.isMobileNavigationLayout=e.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{let e=Sh(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??kh(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??xh(),this.viewportPositionRepairer=t.viewportPositionRepairer??new Th,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=Sh(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.addEventListener(`change`,this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.removeEventListener(`change`,this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.isMobileNavigationLayout?`navigation`:`chat`}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function kh(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(Dh)}var Ah=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new Go,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??jh(),this.documentTarget=t.documentTarget??Mh(),this.isDocumentVisible=t.isDocumentVisible??Nh,this.scheduleFrame=t.scheduleFrame??Ph}connect(){this.connected||(this.connected=!0,this.windowTarget?.addEventListener(`focus`,this.onFocus),this.documentTarget?.addEventListener(`visibilitychange`,this.onVisibilityChange))}disconnect(){this.connected&&(this.connected=!1,this.windowTarget?.removeEventListener(`focus`,this.onFocus),this.documentTarget?.removeEventListener(`visibilitychange`,this.onVisibilityChange),this.scheduledRefresh?.cancel(),this.scheduledRefresh=void 0)}handleResumeSignal(){this.callbacks.onResumeSignal(),this.scheduledRefresh===void 0&&(this.scheduledRefresh=this.scheduleFrame(()=>{this.scheduledRefresh=void 0,this.connected&&this.refreshes.request(`browser-resume`,async()=>{this.connected&&await this.callbacks.refreshAfterResume()}).catch(e=>{this.callbacks.onRefreshError(e)})}))}};function jh(){return typeof window>`u`?void 0:window}function Mh(){return typeof document>`u`?void 0:document}function Nh(){return typeof document>`u`||document.visibilityState===`visible`}function Ph(e){if(typeof window<`u`&&typeof window.requestAnimationFrame==`function`){let t=window.requestAnimationFrame(()=>{e()});return{cancel:()=>{window.cancelAnimationFrame(t)}}}let t=globalThis.setTimeout(e,0);return{cancel:()=>{globalThis.clearTimeout(t)}}}var Fh=[`machines`,`projects`,`workspaces`,`sessions`];function Ih(e){return e.selectedProject===void 0?`projects`:e.selectedWorkspace===void 0?`workspaces`:`sessions`}function Lh(e,t){if(e!==`none`)return e??Ih(t)}function Rh(e,t){return t.isMobileLayout?Lh(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function zh(e,t,n){return n.isMobileLayout?Lh(e,n.state)===t?`none`:t:e}function Bh(e,t,n){return n?t:e}function Vh(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Wh(n)}function Hh(e){return Fh[Fh.indexOf(e)+1]}var Uh=class{hostConnected(){}constructor(e,t,n){this.host=e,this.getState=t,this.isMobileLayout=n,this.collapsedSections=[],e.addController(this)}expandedSection(){return Lh(this.expanded,this.getState())}isCollapsed(e){return Rh(e,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(e){if(this.isMobileLayout()){this.setExpanded(zh(this.expanded,e,{isMobileLayout:!0,state:this.getState()}));return}this.setCollapsedSections(Vh(this.collapsedSections,e))}expand(e){if(this.isMobileLayout()){this.setExpanded(Bh(this.expanded,e,!0));return}this.setCollapsedSections(this.collapsedSections.filter(t=>t!==e))}advanceAfterSelection(e){if(!this.isMobileLayout())return;let t=Hh(e);t!==void 0&&this.expand(t)}open(e,t){this.isMobileLayout()&&(this.expand(e),t())}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}setCollapsedSections(e){Gh(this.collapsedSections,e)||(this.collapsedSections=e,this.host.requestUpdate())}};function Wh(e){let t=new Set(e);return Fh.filter(e=>t.has(e))}function Gh(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var Kh=class{hostConnected(){}constructor(e){this.host=e,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,e.addController(this)}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(e){return[`shell`,qh(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...this.workspacePanelCollapsed?[`workspace-panel-collapsed`]:[]].join(` `)}};function qh(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var Jh=`pi-webui:panel-sizes:v1`,Yh={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},Xh=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??ug(),this.panelSizes=ng(this.storage)}hostConnected(){}constraints(e){return Zh(e)}panelWidth(e,t){return tg(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=tg(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=og(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=sg(this.panelSizes,e),t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(e={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},e.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){rg(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${lg(tg(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${lg(tg(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function Zh(e){return Yh[e]}function Qh(e,t,n){return e===`navigation`?n-t:t-n}function $h(e,t,n,r,i=Zh(e)){return tg(e,t+Qh(e,n,r),i)}function eg(e,t,n,r={}){let i=r.constraints??Zh(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=cg(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return tg(e,t+a,i)}function tg(e,t,n=Zh(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function ng(e=ug()){try{let t=e?.getItem(Jh);return t==null||t===``?{}:ig(JSON.parse(t))}catch{return{}}}function rg(e,t=ug()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Jh);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=tg(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=tg(`workspace`,e.workspacePanelWidth)),t.setItem(Jh,JSON.stringify(n))}catch{}}function ig(e){if(!dg(e)||e.version!==1)return{};let t={},n=ag(e.navigationPanelWidth),r=ag(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=tg(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=tg(`workspace`,r)),t}function ag(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function og(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function sg(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function cg(e,t,n){if(e===`navigation`)return t===`ArrowRight`?n:t===`ArrowLeft`?-n:void 0;if(t===`ArrowLeft`)return n;if(t===`ArrowRight`)return-n}function lg(e){return`${String(Math.round(e))}px`}function ug(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function dg(e){return typeof e==`object`&&!!e}function fg(){let e=new URLSearchParams(window.location.search);return{machineId:e.get(`machine`)??void 0,projectId:e.get(`project`)??void 0,workspaceId:e.get(`workspace`)??void 0,sessionId:e.get(`session`)??void 0,tool:mg(e.get(`tool`)),view:hg(e.get(`view`))}}function pg(e,t){let n=new URL(window.location.href);n.searchParams.delete(`machine`),n.searchParams.delete(`project`),n.searchParams.delete(`workspace`),n.searchParams.delete(`session`),n.searchParams.delete(`tool`),n.searchParams.delete(`view`),e.machineId!==void 0&&e.machineId!==``&&e.machineId!==`local`&&n.searchParams.set(`machine`,e.machineId),e.projectId!==void 0&&e.projectId!==``&&n.searchParams.set(`project`,e.projectId),e.workspaceId!==void 0&&e.workspaceId!==``&&n.searchParams.set(`workspace`,e.workspaceId),e.sessionId!==void 0&&e.sessionId!==``&&n.searchParams.set(`session`,e.sessionId),e.tool!==void 0&&n.searchParams.set(`tool`,e.tool),e.view!==void 0&&n.searchParams.set(`view`,e.view),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function mg(e){return e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:gg(e)?e:void 0}function hg(e){return e===`chat`?`chat`:e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:gg(e)?e:void 0}function gg(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function _g(){return yg(new URLSearchParams(window.location.search).get(`settings`))}function vg(e,t){let n=new URL(window.location.href);e===void 0?n.searchParams.delete(`settings`):n.searchParams.set(`settings`,e),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function yg(e){if(e===`general`)return`general`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`}function bg(e,t){return t===void 0?e:e.map(e=>Sg(e,t))}function xg(e,t){let n=new Set(of(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return bg(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?Cg(e):e)}function Sg(e,t){if(!Object.hasOwn(t,e.id))return e;let n=t[e.id];return n===void 0?e:n===null?Cg(e):{...e,shortcut:n}}function Cg(e){let t={...e};return delete t.shortcut,t}function wg(e,t){let n=t.api??ao,r=t.pollIntervalMs??1e3,i=t.setTimeout??Dg(),a=t.clearTimeout??Og();return{async runCommand(o){let s=await n.runTerminalCommand(e,o);return o.open===!0&&t.openTerminal(o.workspace,{terminalId:s.terminalId}),{run:s,completed:Tg(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function Tg(e,t,n,r,i){return Eg(e)?Promise.resolve(e):new Promise((a,o)=>{let s,c=!1,l=e=>{c||(c=!0,s!==void 0&&i(s),a(e))},u=e=>{c||(c=!0,s!==void 0&&i(s),o(e instanceof Error?e:Error(String(e))))},d=()=>{t.getCommandRun(e.id).then(e=>{if(e!==void 0&&Eg(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function Eg(e){return e.status===`succeeded`||e.status===`failed`}function Dg(){return(e,t)=>globalThis.setTimeout(e,t)}function Og(){return e=>{globalThis.clearTimeout(e)}}var kg=16,Ag=320,jg=240;function Mg(e,t,n){let r=Pg(e,n),i=Fg(n.width,Ag),a=Fg(n.height,jg);return{...r,left:Ig(r.left+t.x,i.margin,i.viewportSize-i.margin-r.width),top:Ig(r.top+t.y,a.margin,a.viewportSize-a.margin-r.height)}}function Ng(e,t,n){let r=Pg(e,n),i=Fg(n.width,Ag),a=Fg(n.height,jg);return{...r,width:Ig(r.width+t.x,i.minSize,i.viewportSize-i.margin-r.left),height:Ig(r.height+t.y,a.minSize,a.viewportSize-a.margin-r.top)}}function Pg(e,t){let n=Fg(t.width,Ag),r=Fg(t.height,jg),i=Ig(e.width,n.minSize,n.maxSize),a=Ig(e.height,r.minSize,r.maxSize);return{left:Ig(e.left,n.margin,n.viewportSize-n.margin-i),top:Ig(e.top,r.margin,r.viewportSize-r.margin-a),width:i,height:a}}function Fg(e,t){let n=Math.max(0,e),r=Math.min(kg,n/2),i=n-r*2;return{viewportSize:n,margin:r,minSize:Math.min(t,i),maxSize:i}}function Ig(e,t,n){return Math.max(t,Math.min(n,e))}var Lg=`pi-webui:terminal-modal-preferences:v1`,Rg={fontSize:16,opacity:94};function zg(e){return Math.max(10,Math.min(28,Math.round(e)))}function Bg(e){return Math.max(20,Math.min(100,Math.round(e)))}function Vg(e=Gg()){if(e===void 0)return{...Rg};try{return Ug(e.getItem(Lg))}catch{return{...Rg}}}function Hg(e,t=Gg()){if(t!==void 0)try{t.setItem(Lg,JSON.stringify({fontSize:zg(e.fontSize),opacity:Bg(e.opacity)}))}catch{}}function Ug(e){if(e===null)return{...Rg};try{let t=JSON.parse(e);return Kg(t)?{fontSize:Wg(t.fontSize,Rg.fontSize,zg),opacity:Wg(t.opacity,Rg.opacity,Bg)}:{...Rg}}catch{return{...Rg}}}function Wg(e,t,n){return typeof e==`number`&&Number.isFinite(e)?n(e):t}function Gg(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function Kg(e){return typeof e==`object`&&!!e}var qg=`PI WEBUI`;function Jg(e){return e!==void 0&&e!==``?`${e} - ${qg}`:qg}function Yg(e){let t=()=>{document.title!==e&&(document.title=e)};t();let n=new MutationObserver(t);return n.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>{n.disconnect()}}var Xg=0,Zg=120;function Qg(e,t){return e.composedPath().some(e=>typeof HTMLElement>`u`||!(e instanceof HTMLElement)?!1:e.getRootNode()===t&&e.closest(`.action-menu`)!==null)}function $g(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?t_():e_(e),i=window.innerWidth,a=window.innerHeight,o=Math.max(0,r.left),s=Math.min(i,r.right),c=Math.max(0,r.top),l=Math.min(a,r.bottom),u=Math.min(n.right,s),d=l-n.bottom-Xg,f=n.top-c-Xg;return[...d<Zg&&f>d?[`bottom: ${n_(a-n.top+Xg)};`,`max-height: ${n_(Math.max(0,f))};`]:[`top: ${n_(n.bottom+Xg)};`,`max-height: ${n_(Math.max(0,d))};`],`right: ${n_(Math.max(0,i-u))};`,`max-width: ${n_(Math.max(0,u-o))};`].join(` `)}function e_(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():t_()}function t_(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function n_(e){return`${String(Math.round(e))}px`}function r_(e,t=`Active`){if(e!==void 0)return g`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function i_(e,t=`Active`){let n=r_(e,t);if(n!==void 0)return g`<span class="action-activity">${n}</span>`}var a_=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function o_(e){return e.composedPath().some(e=>s_(e,a_))}function s_(e,t){if(typeof Element<`u`&&e instanceof Element)return e.matches(t);if(!(`matches`in e))return!1;let{matches:n}=e;return typeof n==`function`&&n.call(e,t)===!0}function c_(e,t){o_(e)||t()}function l_(e,t){return o_(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?d_(e,()=>{f_(e.currentTarget,-1)}):e.key===`ArrowDown`?d_(e,()=>{f_(e.currentTarget,1)}):e.key===`Home`?d_(e,()=>{p_(e.currentTarget,0)}):e.key===`End`?d_(e,()=>{p_(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?d_(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?d_(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&d_(e,t.cancel)}function u_(e,t={}){let n=e.querySelector(`.action-row.selected`)??e.querySelector(`.action-row`)??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return n==null?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}function d_(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function f_(e,t){let n=h_(e),r=__(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||m_(n,i+t)}function p_(e,t){let n=h_(e);n.length!==0&&m_(n,t<0?n.length-1:t)}function m_(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function h_(e){let t=__(e)?.getRootNode();return t===void 0||!g_(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function g_(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function __(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var v_=class extends y{constructor(...e){super(...e),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has(`machines`)&&this.openMenuMachineId!==void 0&&!this.machines.some(e=>e.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,u_(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
|
|
1359
|
+
`}function Vm(e){let t=e.branch??`detached`,n=e.ahead??0,r=e.behind??0;return{branch:n===0&&r===0?t:`${t} · ↑${String(n)} ↓${String(r)}`,...e.latestTag===void 0?{}:{latestTag:e.latestTag}}}function Hm(e,t){return(t===`unmodified`?e:t).slice(0,1).toUpperCase()}var Um={apiVersion:1,name:`PI WEBUI Core`,activate:()=>({contributions:{actions:jp(),workspacePanels:jm()}})},Wm={"--pi-bg":`#0d1117`,"--pi-surface":`#161b22`,"--pi-surface-hover":`#21262d`,"--pi-terminal-bg":`#05070a`,"--pi-terminal-text":`#e6edf3`,"--pi-border":`#30363d`,"--pi-border-muted":`#21262d`,"--pi-text":`#e6edf3`,"--pi-text-secondary":`#c9d1d9`,"--pi-text-bright":`#f0f6fc`,"--pi-muted":`#8b949e`,"--pi-dim":`#6e7681`,"--pi-accent":`#58a6ff`,"--pi-accent-border":`#2f81f7`,"--pi-selection-bg":`#0d2847`,"--pi-success":`#3fb950`,"--pi-success-border":`#238636`,"--pi-success-bg":`#0f1b12`,"--pi-success-surface":`#0f2a16`,"--pi-success-ring":`#3fb95055`,"--pi-warning":`#d29922`,"--pi-warning-border":`#6e5200`,"--pi-warning-surface":`#1f1a10`,"--pi-danger":`#ff7b72`,"--pi-purple":`#d2a8ff`,"--pi-purple-border":`#a371f7`,"--pi-purple-surface":`#21132f`,"--pi-overlay":`#0008`,"--pi-shadow-soft":`#0006`,"--pi-shadow":`#0008`,"--pi-shadow-strong":`#000b`,"--pi-bg-overlay-soft":`#0d1117dd`,"--pi-bg-overlay":`#0d1117e6`,"--pi-success-bg-overlay":`#0f1b12ee`,"--pi-terminal-selection":`#264f78`},Gm={"--pi-bg":`#070912`,"--pi-surface":`#101527`,"--pi-surface-hover":`#151b31`,"--pi-terminal-bg":`#050710`,"--pi-terminal-text":`#f7f4ff`,"--pi-border":`#26304f`,"--pi-border-muted":`#26304f`,"--pi-text":`#f7f4ff`,"--pi-text-secondary":`#aaa4bd`,"--pi-text-bright":`#ffffff`,"--pi-muted":`#aaa4bd`,"--pi-dim":`#817a99`,"--pi-accent":`#7c3cff`,"--pi-accent-border":`#5a47b0`,"--pi-selection-bg":`#1d2547`,"--pi-success":`#00f0d8`,"--pi-success-border":`#00f0d8`,"--pi-success-bg":`#071e22`,"--pi-success-surface":`#092d31`,"--pi-success-ring":`#00f0d855`,"--pi-warning":`#ffb000`,"--pi-warning-border":`#ffb000`,"--pi-warning-surface":`#16140d`,"--pi-danger":`#ff4f7b`,"--pi-purple":`#b7a2ff`,"--pi-purple-border":`#7c3cff`,"--pi-purple-surface":`#181026`,"--pi-overlay":`#0008`,"--pi-shadow-soft":`#0006`,"--pi-shadow":`#0008`,"--pi-shadow-strong":`#000b`,"--pi-bg-overlay-soft":`#070912dd`,"--pi-bg-overlay":`#070912e6`,"--pi-success-bg-overlay":`#071e22ee`,"--pi-terminal-selection":`#3d4a78`},Km={"--pi-bg":`#f7f1e6`,"--pi-surface":`#fff9ee`,"--pi-surface-hover":`#f0e6d6`,"--pi-terminal-bg":`#15131b`,"--pi-terminal-text":`#fff9ee`,"--pi-border":`#c9bca8`,"--pi-border-muted":`#d8cdbc`,"--pi-text":`#15131b`,"--pi-text-secondary":`#15131b`,"--pi-text-bright":`#15131b`,"--pi-muted":`#5f586a`,"--pi-dim":`#766f7e`,"--pi-accent":`#6430d8`,"--pi-accent-border":`#6430d8`,"--pi-selection-bg":`#eadff8`,"--pi-success":`#008c82`,"--pi-success-border":`#008c82`,"--pi-success-bg":`#e1f4ef`,"--pi-success-surface":`#d7f0ec`,"--pi-success-ring":`#008c8255`,"--pi-warning":`#b05f00`,"--pi-warning-border":`#b05f00`,"--pi-warning-surface":`#fff2d2`,"--pi-danger":`#b51d49`,"--pi-purple":`#6430d8`,"--pi-purple-border":`#6430d8`,"--pi-purple-surface":`#eadff8`,"--pi-overlay":`#15131b66`,"--pi-shadow-soft":`#15131b22`,"--pi-shadow":`#15131b33`,"--pi-shadow-strong":`#15131b44`,"--pi-bg-overlay-soft":`#f7f1e6dd`,"--pi-bg-overlay":`#f7f1e6e6`,"--pi-success-bg-overlay":`#e1f4efee`,"--pi-terminal-selection":`#8d7b64`},qm={apiVersion:1,name:`PI WEBUI Themes`,activate:()=>({contributions:{themes:[{id:`pi-webui-dark`,name:`PI WEBUI Dark`,description:`Dark PI WEBUI palette.`,order:10,colorScheme:`dark`,tokens:Gm},{id:`pi-webui-light`,name:`PI WEBUI Light`,description:`Light PI WEBUI palette.`,order:20,colorScheme:`light`,tokens:Km},{id:`classic`,name:`PI WEBUI Classic`,description:`The original PI WEBUI dark palette.`,order:30,colorScheme:`dark`,tokens:Wm}],themePairs:[{id:`pi-webui`,name:`PI WEBUI`,description:`Follow the system light/dark preference with PI WEBUI themes.`,order:10,light:`pi-webui-light`,dark:`pi-webui-dark`}]}})},Jm=/^[a-z][a-z0-9.-]*$/u;function Ym(e){return Jm.test(e)}var Xm=`machine.`;function Zm(e,t){if(e===``)throw Error(`Machine id is required`);if(!Ym(t))throw Error(`Invalid PI WEBUI plugin id: ${t}`);return`${Xm}${Qm(e)}.${t}`}function Qm(e){return[...new TextEncoder().encode(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function $m(e=`pi-webui-plugins/manifest.json`,t={}){let n=bt(e),r=await nh(n);if(r===void 0)return[];let i=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=eh(e.module,n),a=ah(await(t.moduleLoader??th)(r),r);i.push({id:t.machineId===void 0?e.id:Zm(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){console.warn(`Failed to load PI WEBUI plugin ${e.module}`,t)}return i}function eh(e,t,n){return e.startsWith(`/`)?n===void 0?bt(e):bt(e,n):new URL(e,t).toString()}async function th(e){return rm(()=>import(e),[],import.meta.url)}async function nh(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(`Failed to load plugin manifest: ${t.statusText}`);return rh(await t.json())}}function rh(e){if(!sh(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);return{plugins:e.plugins.map(e=>{if(!sh(e)||typeof e.id!=`string`||e.id===``||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);return{id:e.id,module:e.module,machineSpecific:ih(e.machineSpecific)}})}}function ih(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function ah(e,t){if(!sh(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(!oh(n))throw Error(`Plugin module ${t} default export is not a PiWebUiPlugin`);return n}function oh(e){return sh(e)&&e.apiVersion===1&&typeof e.name==`string`&&typeof e.activate==`function`}function sh(e){return typeof e==`object`&&!!e}var ch=/^[a-z][a-z0-9.-]*$/u,lh=/^[a-z][a-z0-9.-]*$/u,uh=new WeakMap,dh=new WeakMap,fh=class{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{id:t,plugin:n}=e;this.validatePluginId(t);let r=this.parseMachineSpecific(t,e.machineSpecific);if(this.pluginIds.has(t))throw Error(`Duplicate plugin id: ${t}`);if(this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,r))return;this.pluginIds.add(t);let i=n.apiVersion;if(i!==1)throw Error(`Unsupported plugin API version for ${t}: ${String(i)}`);let a=n.activate({apiVersion:1,pluginId:t,html:g,svg:_}).contributions;for(let n of a.actions??[])this.actions.push(this.qualifyAction(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(t,n,e.machineId,e.sourcePluginId));if(e.machineId===void 0){for(let e of a.themes??[])this.themes.push(this.qualifyTheme(t,e));for(let e of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(t,e));this.gatewayPluginIds.add(t),r&&this.gatewayMachineSpecificPluginIds.add(t)}else e.sourcePluginId!==void 0&&r&&_h(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=yh(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=ph(e,t.pluginId),r=t.enabled?.(n),i=r===!1?t.disabledReason?.(n):void 0,a={id:t.id,pluginId:t.pluginId,localId:t.localId,...t.machineId===void 0?{}:{machineId:t.machineId},title:t.title,run:()=>t.run(n)};return t.description!==void 0&&(a.description=t.description),t.shortcut!==void 0&&(a.shortcut=t.shortcut),t.group!==void 0&&(a.group=t.group),r!==void 0&&(a.enabled=r),i!==void 0&&i!==``&&(a.disabledReason=i),a})}getWorkspacePanels(){return[...this.workspacePanels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}getThemes(){return[...this.themes].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getThemePairs(){return[...this.themePairs].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getWorkspaceLabelItems(e){return[...this.workspaceLabels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.id.localeCompare(t.id)).flatMap(t=>t.visible?.(e)===!1?[]:t.items(e))}qualifyAction(e,t,n,r){let i=this.qualify(e,t.id);return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r){let i=this.qualify(e,t.id),a=t.badge,o=t.visible;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(o?.(mh(t,e))??!0),...a===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?a(mh(t,e)):void 0},render:n=>t.render(mh(n,e))}}qualifyWorkspaceLabelContribution(e,t,n,r){let i=this.qualify(e,t.id),a=t.visible,o=t.items;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(a?.(t)??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?o(t):[]}}qualifyTheme(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id}}qualifyThemePair(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t){this.validateLocalId(t);let n=`${e}:${t}`;if(this.contributionIds.has(n))throw Error(`Duplicate contribution id: ${n}`);return this.contributionIds.add(n),n}qualifyReference(e,t){return this.validateLocalId(t),`${e}:${t}`}isContributionActive(e,t,n,r){return t===void 0?!this.isGatewayPluginHiddenForMachine(e,n):t===n&&!this.isRemotePluginHiddenByGateway(r,t)}isRemoteDuplicateHiddenByGateway(e,t,n){return e!==void 0&&t!==void 0&&this.gatewayPluginIds.has(e)&&!this.gatewayMachineSpecificPluginIds.has(e)&&!n}isRemotePluginHiddenByGateway(e,t){return e===void 0||this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0?!1:this.gatewayPluginIds.has(e)}isGatewayPluginHiddenForMachine(e,t){return t!==`local`&&(this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0)}validatePluginId(e){if(!ch.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!lh.test(e))throw Error(`Invalid contribution id: ${e}`)}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${vh(t)}`);return t}};function ph(e,t){return uh.get(e)?.(t)??e}function mh(e,t){return dh.get(e)?.(t)??e}function hh(e,t){return uh.set(e,t),e}function gh(e,t){return dh.set(e,t),e}function _h(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function vh(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`||typeof e==`function`||e==null)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function yh(e){return e.state.selectedMachine?.id??`local`}var bh=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function xh(){return typeof window>`u`||!(`matchMedia`in window)?[]:bh.map(e=>window.matchMedia(e))}function Sh(e,t=Ch()){return e.some(e=>e.matches)||wh(t)}function Ch(){return typeof navigator>`u`?void 0:navigator}function wh(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var Th=class{constructor(e=Eh()){this.scheduler=e}repair(e){if(!e){this.clear();return}this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},250)}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);let e=this.scheduler.documentElement;e!==void 0&&(e.scrollTop=0);let t=this.scheduler.body;t!==void 0&&(t.scrollTop=0)}};function Eh(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>`u`?void 0:document.documentElement},get body(){return typeof document>`u`?void 0:document.body}}}var Dh=`(max-width: 760px)`,Oh=class{constructor(e,t={}){this.host=e,this.onMobileNavigationMediaChange=e=>{this.isMobileNavigationLayout!==e.matches&&(this.isMobileNavigationLayout=e.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{let e=Sh(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??kh(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??xh(),this.viewportPositionRepairer=t.viewportPositionRepairer??new Th,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=Sh(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.addEventListener(`change`,this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.removeEventListener(`change`,this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.isMobileNavigationLayout?`navigation`:`chat`}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function kh(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(Dh)}var Ah=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new Go,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??jh(),this.documentTarget=t.documentTarget??Mh(),this.isDocumentVisible=t.isDocumentVisible??Nh,this.scheduleFrame=t.scheduleFrame??Ph}connect(){this.connected||(this.connected=!0,this.windowTarget?.addEventListener(`focus`,this.onFocus),this.documentTarget?.addEventListener(`visibilitychange`,this.onVisibilityChange))}disconnect(){this.connected&&(this.connected=!1,this.windowTarget?.removeEventListener(`focus`,this.onFocus),this.documentTarget?.removeEventListener(`visibilitychange`,this.onVisibilityChange),this.scheduledRefresh?.cancel(),this.scheduledRefresh=void 0)}handleResumeSignal(){this.callbacks.onResumeSignal(),this.scheduledRefresh===void 0&&(this.scheduledRefresh=this.scheduleFrame(()=>{this.scheduledRefresh=void 0,this.connected&&this.refreshes.request(`browser-resume`,async()=>{this.connected&&await this.callbacks.refreshAfterResume()}).catch(e=>{this.callbacks.onRefreshError(e)})}))}};function jh(){return typeof window>`u`?void 0:window}function Mh(){return typeof document>`u`?void 0:document}function Nh(){return typeof document>`u`||document.visibilityState===`visible`}function Ph(e){if(typeof window<`u`&&typeof window.requestAnimationFrame==`function`){let t=window.requestAnimationFrame(()=>{e()});return{cancel:()=>{window.cancelAnimationFrame(t)}}}let t=globalThis.setTimeout(e,0);return{cancel:()=>{globalThis.clearTimeout(t)}}}var Fh=[`machines`,`projects`,`workspaces`,`sessions`];function Ih(e){return e.selectedProject===void 0?`projects`:e.selectedWorkspace===void 0?`workspaces`:`sessions`}function Lh(e,t){if(e!==`none`)return e??Ih(t)}function Rh(e,t){return t.isMobileLayout?Lh(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function zh(e,t,n){return n.isMobileLayout?Lh(e,n.state)===t?`none`:t:e}function Bh(e,t,n){return n?t:e}function Vh(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Wh(n)}function Hh(e){return Fh[Fh.indexOf(e)+1]}var Uh=class{hostConnected(){}constructor(e,t,n){this.host=e,this.getState=t,this.isMobileLayout=n,this.collapsedSections=[],e.addController(this)}expandedSection(){return Lh(this.expanded,this.getState())}isCollapsed(e){return Rh(e,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(e){if(this.isMobileLayout()){this.setExpanded(zh(this.expanded,e,{isMobileLayout:!0,state:this.getState()}));return}this.setCollapsedSections(Vh(this.collapsedSections,e))}expand(e){if(this.isMobileLayout()){this.setExpanded(Bh(this.expanded,e,!0));return}this.setCollapsedSections(this.collapsedSections.filter(t=>t!==e))}advanceAfterSelection(e){if(!this.isMobileLayout())return;let t=Hh(e);t!==void 0&&this.expand(t)}open(e,t){this.isMobileLayout()&&(this.expand(e),t())}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}setCollapsedSections(e){Gh(this.collapsedSections,e)||(this.collapsedSections=e,this.host.requestUpdate())}};function Wh(e){let t=new Set(e);return Fh.filter(e=>t.has(e))}function Gh(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var Kh=class{hostConnected(){}constructor(e){this.host=e,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,e.addController(this)}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(e){return[`shell`,qh(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...this.workspacePanelCollapsed?[`workspace-panel-collapsed`]:[]].join(` `)}};function qh(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var Jh=`pi-webui:panel-sizes:v1`,Yh={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},Xh=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??ug(),this.panelSizes=ng(this.storage)}hostConnected(){}constraints(e){return Zh(e)}panelWidth(e,t){return tg(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=tg(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=og(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=sg(this.panelSizes,e),t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(e={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},e.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){rg(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${lg(tg(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${lg(tg(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function Zh(e){return Yh[e]}function Qh(e,t,n){return e===`navigation`?n-t:t-n}function $h(e,t,n,r,i=Zh(e)){return tg(e,t+Qh(e,n,r),i)}function eg(e,t,n,r={}){let i=r.constraints??Zh(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=cg(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return tg(e,t+a,i)}function tg(e,t,n=Zh(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function ng(e=ug()){try{let t=e?.getItem(Jh);return t==null||t===``?{}:ig(JSON.parse(t))}catch{return{}}}function rg(e,t=ug()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Jh);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=tg(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=tg(`workspace`,e.workspacePanelWidth)),t.setItem(Jh,JSON.stringify(n))}catch{}}function ig(e){if(!dg(e)||e.version!==1)return{};let t={},n=ag(e.navigationPanelWidth),r=ag(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=tg(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=tg(`workspace`,r)),t}function ag(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function og(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function sg(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function cg(e,t,n){if(e===`navigation`)return t===`ArrowRight`?n:t===`ArrowLeft`?-n:void 0;if(t===`ArrowLeft`)return n;if(t===`ArrowRight`)return-n}function lg(e){return`${String(Math.round(e))}px`}function ug(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function dg(e){return typeof e==`object`&&!!e}function fg(){let e=new URLSearchParams(window.location.search);return{machineId:e.get(`machine`)??void 0,projectId:e.get(`project`)??void 0,workspaceId:e.get(`workspace`)??void 0,sessionId:e.get(`session`)??void 0,tool:mg(e.get(`tool`)),view:hg(e.get(`view`))}}function pg(e,t){let n=new URL(window.location.href);n.searchParams.delete(`machine`),n.searchParams.delete(`project`),n.searchParams.delete(`workspace`),n.searchParams.delete(`session`),n.searchParams.delete(`tool`),n.searchParams.delete(`view`),e.machineId!==void 0&&e.machineId!==``&&e.machineId!==`local`&&n.searchParams.set(`machine`,e.machineId),e.projectId!==void 0&&e.projectId!==``&&n.searchParams.set(`project`,e.projectId),e.workspaceId!==void 0&&e.workspaceId!==``&&n.searchParams.set(`workspace`,e.workspaceId),e.sessionId!==void 0&&e.sessionId!==``&&n.searchParams.set(`session`,e.sessionId),e.tool!==void 0&&n.searchParams.set(`tool`,e.tool),e.view!==void 0&&n.searchParams.set(`view`,e.view),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function mg(e){return e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:gg(e)?e:void 0}function hg(e){return e===`chat`?`chat`:e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:gg(e)?e:void 0}function gg(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function _g(){return yg(new URLSearchParams(window.location.search).get(`settings`))}function vg(e,t){let n=new URL(window.location.href);e===void 0?n.searchParams.delete(`settings`):n.searchParams.set(`settings`,e),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function yg(e){if(e===`general`)return`general`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`}function bg(e,t){return t===void 0?e:e.map(e=>Sg(e,t))}function xg(e,t){let n=new Set(of(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return bg(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?Cg(e):e)}function Sg(e,t){if(!Object.hasOwn(t,e.id))return e;let n=t[e.id];return n===void 0?e:n===null?Cg(e):{...e,shortcut:n}}function Cg(e){let t={...e};return delete t.shortcut,t}function wg(e,t){let n=t.api??ao,r=t.pollIntervalMs??1e3,i=t.setTimeout??Dg(),a=t.clearTimeout??Og();return{async runCommand(o){let s=await n.runTerminalCommand(e,o);return o.open===!0&&t.openTerminal(o.workspace,{terminalId:s.terminalId}),{run:s,completed:Tg(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function Tg(e,t,n,r,i){return Eg(e)?Promise.resolve(e):new Promise((a,o)=>{let s,c=!1,l=e=>{c||(c=!0,s!==void 0&&i(s),a(e))},u=e=>{c||(c=!0,s!==void 0&&i(s),o(e instanceof Error?e:Error(String(e))))},d=()=>{t.getCommandRun(e.id).then(e=>{if(e!==void 0&&Eg(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function Eg(e){return e.status===`succeeded`||e.status===`failed`}function Dg(){return(e,t)=>globalThis.setTimeout(e,t)}function Og(){return e=>{globalThis.clearTimeout(e)}}var kg=16,Ag=320,jg=240;function Mg(e,t,n){let r=Pg(e,n),i=Fg(n.width,Ag),a=Fg(n.height,jg);return{...r,left:Ig(r.left+t.x,i.margin,i.viewportSize-i.margin-r.width),top:Ig(r.top+t.y,a.margin,a.viewportSize-a.margin-r.height)}}function Ng(e,t,n){let r=Pg(e,n),i=Fg(n.width,Ag),a=Fg(n.height,jg);return{...r,width:Ig(r.width+t.x,i.minSize,i.viewportSize-i.margin-r.left),height:Ig(r.height+t.y,a.minSize,a.viewportSize-a.margin-r.top)}}function Pg(e,t){let n=Fg(t.width,Ag),r=Fg(t.height,jg),i=Ig(e.width,n.minSize,n.maxSize),a=Ig(e.height,r.minSize,r.maxSize);return{left:Ig(e.left,n.margin,n.viewportSize-n.margin-i),top:Ig(e.top,r.margin,r.viewportSize-r.margin-a),width:i,height:a}}function Fg(e,t){let n=Math.max(0,e),r=Math.min(kg,n/2),i=n-r*2;return{viewportSize:n,margin:r,minSize:Math.min(t,i),maxSize:i}}function Ig(e,t,n){return Math.max(t,Math.min(n,e))}var Lg=`pi-webui:terminal-modal-preferences:v1`,Rg={fontSize:16,opacity:94};function zg(e){return Math.max(10,Math.min(28,Math.round(e)))}function Bg(e){return Math.max(20,Math.min(100,Math.round(e)))}function Vg(e=Gg()){if(e===void 0)return{...Rg};try{return Ug(e.getItem(Lg))}catch{return{...Rg}}}function Hg(e,t=Gg()){if(t!==void 0)try{t.setItem(Lg,JSON.stringify({fontSize:zg(e.fontSize),opacity:Bg(e.opacity)}))}catch{}}function Ug(e){if(e===null)return{...Rg};try{let t=JSON.parse(e);return Kg(t)?{fontSize:Wg(t.fontSize,Rg.fontSize,zg),opacity:Wg(t.opacity,Rg.opacity,Bg)}:{...Rg}}catch{return{...Rg}}}function Wg(e,t,n){return typeof e==`number`&&Number.isFinite(e)?n(e):t}function Gg(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function Kg(e){return typeof e==`object`&&!!e}var qg=`PI WEBUI`;function Jg(e){return e!==void 0&&e!==``?`${e} - ${qg}`:qg}function Yg(e){let t=()=>{document.title!==e&&(document.title=e)};t();let n=new MutationObserver(t);return n.observe(document.head,{childList:!0,subtree:!0,characterData:!0}),()=>{n.disconnect()}}var Xg=0,Zg=120;function Qg(e,t){return e.composedPath().some(e=>typeof HTMLElement>`u`||!(e instanceof HTMLElement)?!1:e.getRootNode()===t&&e.closest(`.action-menu`)!==null)}function $g(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?t_():e_(e),i=window.innerWidth,a=window.innerHeight,o=Math.max(0,r.left),s=Math.min(i,r.right),c=Math.max(0,r.top),l=Math.min(a,r.bottom),u=Math.min(n.right,s),d=l-n.bottom-Xg,f=n.top-c-Xg;return[...d<Zg&&f>d?[`bottom: ${n_(a-n.top+Xg)};`,`max-height: ${n_(Math.max(0,f))};`]:[`top: ${n_(n.bottom+Xg)};`,`max-height: ${n_(Math.max(0,d))};`],`right: ${n_(Math.max(0,i-u))};`,`max-width: ${n_(Math.max(0,u-o))};`].join(` `)}function e_(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():t_()}function t_(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function n_(e){return`${String(Math.round(e))}px`}function r_(e,t=`Active`,n){if(e!==void 0)return g`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}>${n===void 0?null:g`<span class="activity-indicator-count" aria-hidden="true">${String(n)}</span>`}</span>`}function i_(e,t=`Active`){let n=r_(e,t);if(n!==void 0)return g`<span class="action-activity">${n}</span>`}function a_(e){if(e.length!==0)return g`<span class="action-activities">${e.map(e=>r_(e.kind,e.label,e.count))}</span>`}var o_=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function s_(e){return e.composedPath().some(e=>c_(e,o_))}function c_(e,t){if(typeof Element<`u`&&e instanceof Element)return e.matches(t);if(!(`matches`in e))return!1;let{matches:n}=e;return typeof n==`function`&&n.call(e,t)===!0}function l_(e,t){s_(e)||t()}function u_(e,t){return s_(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?f_(e,()=>{p_(e.currentTarget,-1)}):e.key===`ArrowDown`?f_(e,()=>{p_(e.currentTarget,1)}):e.key===`Home`?f_(e,()=>{m_(e.currentTarget,0)}):e.key===`End`?f_(e,()=>{m_(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?f_(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?f_(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&f_(e,t.cancel)}function d_(e,t={}){let n=e.querySelector(`.action-row.selected`)??e.querySelector(`.action-row`)??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return n==null?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}function f_(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function p_(e,t){let n=g_(e),r=v_(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||h_(n,i+t)}function m_(e,t){let n=g_(e);n.length!==0&&h_(n,t<0?n.length-1:t)}function h_(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function g_(e){let t=v_(e)?.getRootNode();return t===void 0||!__(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function __(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function v_(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var y_=class extends y{constructor(...e){super(...e),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has(`machines`)&&this.openMenuMachineId!==void 0&&!this.machines.some(e=>e.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,d_(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
|
|
1343
1360
|
<section>
|
|
1344
1361
|
<h2>${this.renderHeading()}</h2>
|
|
1345
1362
|
${this.collapsed?null:g`
|
|
@@ -1348,12 +1365,12 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1348
1365
|
</div>
|
|
1349
1366
|
`}
|
|
1350
1367
|
</section>
|
|
1351
|
-
`}renderMachine(e){let t=this.statuses[e.id]?.status??e.status??`unknown`,n=t===`online`?`online`:t===`offline`?`offline`:t===`error`?`error`:`unknown`,r=
|
|
1368
|
+
`}renderMachine(e){let t=this.statuses[e.id]?.status??e.status??`unknown`,n=t===`online`?`online`:t===`offline`?`offline`:t===`error`?`error`:`unknown`,r=b_(e)&&this.onRemove!==void 0;return g`
|
|
1352
1369
|
<div
|
|
1353
1370
|
class=${`action-row machine-row ${this.selected?.id===e.id?`selected`:``} ${r?``:`no-actions`}`}
|
|
1354
1371
|
tabindex="0"
|
|
1355
1372
|
title=${e.baseUrl??e.name}
|
|
1356
|
-
@click=${t=>{
|
|
1373
|
+
@click=${t=>{l_(t,()=>this.onSelect?.(e))}}
|
|
1357
1374
|
@keydown=${t=>{this.handleMachineKeydown(t,e)}}
|
|
1358
1375
|
>
|
|
1359
1376
|
<div class="action-main">
|
|
@@ -1362,7 +1379,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1362
1379
|
</div>
|
|
1363
1380
|
${r?this.renderMachineMenu(e):null}
|
|
1364
1381
|
</div>
|
|
1365
|
-
`}renderActivity(e){let t=this.statuses[e.id]?.status??e.status;if(t===`offline`||t===`error`)return;let n=Fs(this.activities[e.id]);return i_(n,n===`terminal`?`Machine terminal active`:`Machine active`)}renderMachineMenu(e){let t=this.openMenuMachineId===e.id,n=
|
|
1382
|
+
`}renderActivity(e){let t=this.statuses[e.id]?.status??e.status;if(t===`offline`||t===`error`)return;let n=Fs(this.activities[e.id]);return i_(n,n===`terminal`?`Machine terminal active`:`Machine active`)}renderMachineMenu(e){let t=this.openMenuMachineId===e.id,n=x_(e.id);return g`
|
|
1366
1383
|
<div class="action-menu">
|
|
1367
1384
|
<button
|
|
1368
1385
|
class="action-menu-toggle"
|
|
@@ -1378,13 +1395,13 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1378
1395
|
</div>
|
|
1379
1396
|
`:null}
|
|
1380
1397
|
</div>
|
|
1381
|
-
`}renderHeading(){if(!this.collapsible)return g`<span>Machines</span>`;let e=this.selected?.name??`No machine selected`,t=this.selected?.baseUrl??e;return g`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} Machines</span>${this.collapsed?g`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=$g(t,{constrainTo:`viewport`}),this.openMenuMachineId=e}removeMachine(e){this.openMenuMachineId=void 0,this.onRemove?.(e)}handleMachineKeydown(e,t){if(e.key===`Escape`&&this.openMenuMachineId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuMachineId=void 0;return}
|
|
1398
|
+
`}renderHeading(){if(!this.collapsible)return g`<span>Machines</span>`;let e=this.selected?.name??`No machine selected`,t=this.selected?.baseUrl??e;return g`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} Machines</span>${this.collapsed?g`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=$g(t,{constrainTo:`viewport`}),this.openMenuMachineId=e}removeMachine(e){this.openMenuMachineId=void 0,this.onRemove?.(e)}handleMachineKeydown(e,t){if(e.key===`Escape`&&this.openMenuMachineId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuMachineId=void 0;return}u_(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}static{this.styles=[qp,h`
|
|
1382
1399
|
.machine-row.no-actions .action-main { border-radius: 8px; }
|
|
1383
1400
|
.machine-primary { display: flex; align-items: baseline; gap: 6px; }
|
|
1384
1401
|
.machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
1385
1402
|
.machine-menu-panel button.danger { color: var(--pi-danger); }
|
|
1386
1403
|
.machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
|
|
1387
|
-
`]}};B([x({attribute:!1})],
|
|
1404
|
+
`]}};B([x({attribute:!1})],y_.prototype,`machines`,void 0),B([x({attribute:!1})],y_.prototype,`selected`,void 0),B([x({attribute:!1})],y_.prototype,`statuses`,void 0),B([x({attribute:!1})],y_.prototype,`activities`,void 0),B([x({type:Boolean,reflect:!0})],y_.prototype,`collapsible`,void 0),B([x({type:Boolean,reflect:!0})],y_.prototype,`collapsed`,void 0),B([x({attribute:!1})],y_.prototype,`onSelect`,void 0),B([x({attribute:!1})],y_.prototype,`onRemove`,void 0),B([x({attribute:!1})],y_.prototype,`onToggleCollapsed`,void 0),B([x({attribute:!1})],y_.prototype,`onFocusNextSection`,void 0),B([x({attribute:!1})],y_.prototype,`onCancelKeyboardNavigation`,void 0),B([S()],y_.prototype,`openMenuMachineId`,void 0),B([S()],y_.prototype,`menuStyle`,void 0),y_=B([b(`machine-list`)],y_);function b_(e){return e.kind===`remote`}function x_(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}var S_={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},C_=e=>(...t)=>({_$litDirective$:e,values:t}),w_=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}},{I:T_}=ft,E_=e=>e,D_=()=>document.createComment(``),O_=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new T_(r.insertBefore(D_(),i),r.insertBefore(D_(),i),e,e.options);else{let t=n._$AB.nextSibling,a=n._$AM,o=a!==e;if(o){let t;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(t=e._$AU)!==a._$AU&&n._$AP(t)}if(t!==i||o){let e=n._$AA;for(;e!==t;){let t=E_(e).nextSibling;E_(r).insertBefore(e,i),e=t}}}return n},k_=(e,t,n=e)=>(e._$AI(t,n),e),A_={},j_=(e,t=A_)=>e._$AH=t,M_=e=>e._$AH,N_=e=>{e._$AR(),e._$AA.remove()},P_=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},F_=C_(class extends w_{constructor(e){if(super(e),e.type!==S_.CHILD)throw Error(`repeat() can only be used in text expressions`)}dt(e,t,n){let r;n===void 0?n=t:t!==void 0&&(r=t);let i=[],a=[],o=0;for(let t of e)i[o]=r?r(t,o):o,a[o]=n(t,o),o++;return{values:a,keys:i}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,r]){let i=M_(e),{values:a,keys:o}=this.dt(t,n,r);if(!Array.isArray(i))return this.ut=o,a;let s=this.ut??=[],c=[],l,u,d=0,f=i.length-1,p=0,m=a.length-1;for(;d<=f&&p<=m;)if(i[d]===null)d++;else if(i[f]===null)f--;else if(s[d]===o[p])c[p]=k_(i[d],a[p]),d++,p++;else if(s[f]===o[m])c[m]=k_(i[f],a[m]),f--,m--;else if(s[d]===o[m])c[m]=k_(i[d],a[m]),O_(e,c[m+1],i[d]),d++,m--;else if(s[f]===o[p])c[p]=k_(i[f],a[p]),O_(e,i[d],i[f]),f--,p++;else if(l===void 0&&(l=P_(o,p,m),u=P_(s,d,f)),l.has(s[d]))if(l.has(s[f])){let t=u.get(o[p]),n=t===void 0?null:i[t];if(n===null){let t=O_(e,i[d]);k_(t,a[p]),c[p]=t}else c[p]=k_(n,a[p]),O_(e,i[d],n),i[t]=null;p++}else N_(i[f]),f--;else N_(i[d]),d++;for(;p<=m;){let t=O_(e,c[m+1]);k_(t,a[p]),c[p++]=t}for(;d<=f;){let e=i[d++];e!==null&&N_(e)}return this.ut=o,j_(e,c),Qe}});function I_(e,t){let n=t.trim().toLowerCase();return n===``?[...e]:e.filter(e=>`${e.name} ${e.path}`.toLowerCase().includes(n))}function L_(e,t,n){let r=[],i=[];for(let a of e)(Ns(a,t[a.id]??[],n)===void 0?i:r).push(a);return[...r,...i]}function R_(e,t,n,r){return L_(I_(e,t),n,r)}var V=class extends y{constructor(...e){super(...e),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menuStyle=``,this.searchOpen=!1,this.searchQuery=``,this.onDocumentClick=e=>{Qg(e,this.renderRoot)||(this.openMenuProjectId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick,!0)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick,!0),super.disconnectedCallback()}updated(e){if(e.has(`projects`)&&this.openMenuProjectId!==void 0&&!this.projects.some(e=>e.id===this.openMenuProjectId)&&(this.openMenuProjectId=void 0),this.openMenuProjectId!==void 0&&(e.has(`projects`)||e.has(`activities`)||e.has(`workspacesByProjectId`))){let t=e.get(`projects`)??this.projects,n=e.get(`workspacesByProjectId`)??this.workspacesByProjectId,r=e.get(`activities`)??this.activities;z_(this.openMenuProjectId,R_(t,this.searchQuery,n,r),R_(this.projects,this.searchQuery,this.workspacesByProjectId,this.activities))&&(this.openMenuProjectId=void 0)}e.has(`collapsed`)&&this.collapsed&&(this.openMenuProjectId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,d_(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){let e=R_(this.projects,this.searchQuery,this.workspacesByProjectId,this.activities);return g`
|
|
1388
1405
|
<section>
|
|
1389
1406
|
<h2>
|
|
1390
1407
|
${this.renderHeading()}
|
|
@@ -1395,12 +1412,12 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1395
1412
|
${this.collapsed?null:g`
|
|
1396
1413
|
${this.searchOpen?this.renderSearchInput():null}
|
|
1397
1414
|
<div class="list-body">
|
|
1398
|
-
${
|
|
1415
|
+
${F_(e,e=>e.id,e=>g`
|
|
1399
1416
|
<div
|
|
1400
1417
|
class=${`action-row ${this.selected?.id===e.id?`selected`:``}`}
|
|
1401
1418
|
tabindex="0"
|
|
1402
1419
|
title=${e.path}
|
|
1403
|
-
@click=${t=>{
|
|
1420
|
+
@click=${t=>{l_(t,()=>this.onSelect?.(e))}}
|
|
1404
1421
|
@keydown=${t=>{this.handleProjectKeydown(t,e)}}
|
|
1405
1422
|
>
|
|
1406
1423
|
<div class="action-main">
|
|
@@ -1421,7 +1438,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1421
1438
|
</div>
|
|
1422
1439
|
`}
|
|
1423
1440
|
</section>
|
|
1424
|
-
`}handleProjectKeydown(e,t){
|
|
1441
|
+
`}handleProjectKeydown(e,t){u_(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}renderHeading(){if(!this.collapsible)return g`<span>Projects</span>`;let e=this.selected?.name??`No project selected`,t=this.selected?.path??e;return g`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} Projects</span>${this.collapsed?g`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderSearchButton(){let e=this.searchOpen?`Close project search`:`Search projects`;return g`
|
|
1425
1442
|
<button type="button" class="section-search-button" title=${e} aria-label=${e} aria-expanded=${String(this.searchOpen)} aria-controls="project-search" @click=${e=>{e.stopPropagation(),this.toggleProjectSearch()}}>
|
|
1426
1443
|
${_`<svg class="section-search-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="11" cy="11" r="6"></circle><path d="m16 16 4 4"></path></svg>`}
|
|
1427
1444
|
</button>
|
|
@@ -1440,7 +1457,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1440
1457
|
.project-search-input { box-sizing: border-box; width: 100%; border: 1px solid var(--pi-border); border-radius: 7px; background: var(--pi-surface); color: var(--pi-text); padding: 6px 8px; font: inherit; }
|
|
1441
1458
|
.project-search-input:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 1px; }
|
|
1442
1459
|
.project-search-empty { margin: 6px 0; color: var(--pi-muted); }
|
|
1443
|
-
`]}};B([x({attribute:!1})],V.prototype,`projects`,void 0),B([x({attribute:!1})],V.prototype,`selected`,void 0),B([x({attribute:!1})],V.prototype,`activities`,void 0),B([x({attribute:!1})],V.prototype,`workspacesByProjectId`,void 0),B([x({type:Boolean,reflect:!0})],V.prototype,`collapsible`,void 0),B([x({type:Boolean,reflect:!0})],V.prototype,`collapsed`,void 0),B([x({attribute:!1})],V.prototype,`onSelect`,void 0),B([x({attribute:!1})],V.prototype,`onClose`,void 0),B([x({attribute:!1})],V.prototype,`onAdd`,void 0),B([x({attribute:!1})],V.prototype,`onOpenExpanded`,void 0),B([x({attribute:!1})],V.prototype,`onToggleCollapsed`,void 0),B([x({attribute:!1})],V.prototype,`onFocusPreviousSection`,void 0),B([x({attribute:!1})],V.prototype,`onFocusNextSection`,void 0),B([x({attribute:!1})],V.prototype,`onCancelKeyboardNavigation`,void 0),B([C(`.project-search-input`)],V.prototype,`searchInput`,void 0),B([S()],V.prototype,`openMenuProjectId`,void 0),B([S()],V.prototype,`menuStyle`,void 0),B([S()],V.prototype,`searchOpen`,void 0),B([S()],V.prototype,`searchQuery`,void 0),V=B([b(`project-list`)],V);function
|
|
1460
|
+
`]}};B([x({attribute:!1})],V.prototype,`projects`,void 0),B([x({attribute:!1})],V.prototype,`selected`,void 0),B([x({attribute:!1})],V.prototype,`activities`,void 0),B([x({attribute:!1})],V.prototype,`workspacesByProjectId`,void 0),B([x({type:Boolean,reflect:!0})],V.prototype,`collapsible`,void 0),B([x({type:Boolean,reflect:!0})],V.prototype,`collapsed`,void 0),B([x({attribute:!1})],V.prototype,`onSelect`,void 0),B([x({attribute:!1})],V.prototype,`onClose`,void 0),B([x({attribute:!1})],V.prototype,`onAdd`,void 0),B([x({attribute:!1})],V.prototype,`onOpenExpanded`,void 0),B([x({attribute:!1})],V.prototype,`onToggleCollapsed`,void 0),B([x({attribute:!1})],V.prototype,`onFocusPreviousSection`,void 0),B([x({attribute:!1})],V.prototype,`onFocusNextSection`,void 0),B([x({attribute:!1})],V.prototype,`onCancelKeyboardNavigation`,void 0),B([C(`.project-search-input`)],V.prototype,`searchInput`,void 0),B([S()],V.prototype,`openMenuProjectId`,void 0),B([S()],V.prototype,`menuStyle`,void 0),B([S()],V.prototype,`searchOpen`,void 0),B([S()],V.prototype,`searchQuery`,void 0),V=B([b(`project-list`)],V);function z_(e,t,n){return t.findIndex(t=>t.id===e)!==n.findIndex(t=>t.id===e)}var B_=class extends y{constructor(...e){super(...e),this.projects=[],this.activities={},this.workspacesByProjectId={},this.searchQuery=``,this.menuStyle=``,this.onDocumentClick=e=>{this.openMenuProjectId===void 0||Qg(e,this.renderRoot)||(this.openMenuProjectId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick,!0)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick,!0),super.disconnectedCallback()}firstUpdated(){this.searchInput?.focus()}updated(e){if(e.has(`projects`)&&this.openMenuProjectId!==void 0&&!this.projects.some(e=>e.id===this.openMenuProjectId)){this.openMenuProjectId=void 0;return}if(this.openMenuProjectId===void 0||!e.has(`projects`)&&!e.has(`activities`)&&!e.has(`workspacesByProjectId`))return;let t=e.get(`projects`)??this.projects,n=e.get(`activities`)??this.activities,r=e.get(`workspacesByProjectId`)??this.workspacesByProjectId;V_(R_(t,this.searchQuery,r,n),this.visibleProjects)&&(this.openMenuProjectId=void 0)}get visibleProjects(){return R_(this.projects,this.searchQuery,this.workspacesByProjectId,this.activities)}close(){this.openMenuProjectId=void 0,this.onClose?.()}select(e){this.openMenuProjectId=void 0,this.hasProject(e.id)&&this.onSelect?.(e)}render(){return g`
|
|
1444
1461
|
<div class="backdrop" @mousedown=${e=>{this.handleBackdropMouseDown(e)}}>
|
|
1445
1462
|
<section
|
|
1446
1463
|
role="dialog"
|
|
@@ -1482,12 +1499,12 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1482
1499
|
</div>
|
|
1483
1500
|
`;let e=this.visibleProjects;return e.length===0?g`<p class="empty-state">No matching projects.</p>`:g`
|
|
1484
1501
|
<div class="project-list">
|
|
1485
|
-
${
|
|
1502
|
+
${F_(e,e=>e.id,e=>g`
|
|
1486
1503
|
<div
|
|
1487
1504
|
class=${`project-row action-row ${this.selected?.id===e.id?`selected`:``}`}
|
|
1488
1505
|
tabindex="0"
|
|
1489
1506
|
title=${e.path}
|
|
1490
|
-
@click=${t=>{
|
|
1507
|
+
@click=${t=>{l_(t,()=>{this.select(e)})}}
|
|
1491
1508
|
@keydown=${t=>{this.handleProjectKeydown(t,e)}}
|
|
1492
1509
|
>
|
|
1493
1510
|
<div class="project-main">
|
|
@@ -1508,7 +1525,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1508
1525
|
</div>
|
|
1509
1526
|
`)}
|
|
1510
1527
|
</div>
|
|
1511
|
-
`}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.searchQuery=e.target.value,this.openMenuProjectId=void 0)}handleProjectKeydown(e,t){
|
|
1528
|
+
`}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.searchQuery=e.target.value,this.openMenuProjectId=void 0)}handleProjectKeydown(e,t){u_(e,{activate:()=>{this.select(t)}})}handleBackdropMouseDown(e){e.target===e.currentTarget&&(e.preventDefault(),this.close())}handleDialogKeyDown(e){if(e.key===`Tab`){this.trapTabFocus(e);return}e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.close())}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())}toggleMenu(e,t){if(!this.hasProject(e)){this.openMenuProjectId=void 0;return}if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=$g(t,{constrainTo:`viewport`}),this.openMenuProjectId=e}closeProject(e){this.openMenuProjectId=void 0,this.hasProject(e.id)&&confirm(`Close ${e.name}?\n\nThis only removes it from PI WEBUI; it will not change the project folder.`)&&this.onCloseProject?.(e)}renderActivity(e){let t=Ns(e,this.workspacesByProjectId[e.id]??[],this.activities);return i_(t,t===`terminal`?`Project terminal active`:`Project active`)}hasProject(e){return this.projects.some(t=>t.id===e)}static{this.styles=h`
|
|
1512
1529
|
:host { position: fixed; inset: 0; z-index: 60; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
1513
1530
|
* { box-sizing: border-box; }
|
|
1514
1531
|
.backdrop { width: 100%; height: 100dvh; display: grid; 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); }
|
|
@@ -1559,90 +1576,19 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1559
1576
|
header { padding-top: max(12px, env(safe-area-inset-top)); }
|
|
1560
1577
|
.dialog-body { padding-bottom: max(12px, env(safe-area-inset-bottom)); }
|
|
1561
1578
|
}
|
|
1562
|
-
`}};B([x({attribute:!1})],
|
|
1579
|
+
`}};B([x({attribute:!1})],B_.prototype,`projects`,void 0),B([x({attribute:!1})],B_.prototype,`selected`,void 0),B([x({attribute:!1})],B_.prototype,`activities`,void 0),B([x({attribute:!1})],B_.prototype,`workspacesByProjectId`,void 0),B([x({attribute:!1})],B_.prototype,`onSelect`,void 0),B([x({attribute:!1})],B_.prototype,`onCloseProject`,void 0),B([x({attribute:!1})],B_.prototype,`onAdd`,void 0),B([x({attribute:!1})],B_.prototype,`onClose`,void 0),B([S()],B_.prototype,`searchQuery`,void 0),B([S()],B_.prototype,`openMenuProjectId`,void 0),B([S()],B_.prototype,`menuStyle`,void 0),B([C(`.project-browser-search`)],B_.prototype,`searchInput`,void 0),B_=B([b(`project-browser-dialog`)],B_);function V_(e,t){return e.length!==t.length||e.some((e,n)=>e.id!==t[n]?.id)}function H_(e,t,n,r,i=!1){if(G_(e))return r?`sending`:Vo(t,n)?`session`:i?`unread`:void 0}function U_(e,t,n={}){if(!G_(e))return[];let r=H_(e,n.statuses?.[e.id],n.activities?.[e.id],n.sending?.[e.id]===!0,n.unreadSessionIds?.has(e.id)===!0),i=K_(e,n),a=W_(e,t,n),o=[],s=a.attentionCount+ +!!i;return s>0&&o.push({kind:`attention`,...a.attentionCount===0?{}:{count:s},label:q_(i,a.attentionCount)}),r===`sending`?o.push({kind:`sending`,label:`Sending message`}):r===`session`&&o.push({kind:`session`,label:`This session is working`}),a.workingCount>0&&o.push({kind:`descendant`,count:a.workingCount,label:Y_(a.workingCount,`working`)}),r===`unread`&&o.push({kind:`unread`,label:`Unread session activity`}),o}function W_(e,t,n){let r=new Map;for(let e of t)r.set(e.path,e);let i=new Map;for(let e of r.values()){let t=e.parentSessionPath;if(t===void 0||!r.has(t))continue;let n=i.get(t)??[];n.push(e),i.set(t,n)}let a=0,o=0,s=(e,t)=>{for(let r of i.get(e)??[]){if(t.has(r.path)||!G_(r))continue;let e=new Set(t);e.add(r.path);let i=H_(r,n.statuses?.[r.id],n.activities?.[r.id],n.sending?.[r.id]===!0,n.unreadSessionIds?.has(r.id)===!0);(i===`sending`||i===`session`)&&(a+=1),K_(r,n)&&(o+=1),s(r.path,e)}};return s(e.path,new Set([e.path])),{workingCount:a,attentionCount:o}}function G_(e){return!Xs(e)&&e.archived!==!0}function K_(e,t){return G_(e)?t.activities?.[e.id]?.phase===`error`||t.statuses?.[e.id]?.warnings?.some(e=>e.severity===`warning`||e.severity===`error`)===!0:!1}function q_(e,t){return e&&t===0?`This session needs attention`:e?`This session and ${String(t)} ${t===1?`subsession`:`subsessions`} need attention`:J_(t)}function J_(e){return`${String(e)} ${e===1?`subsession needs`:`subsessions need`} attention`}function Y_(e,t){return`${String(e)} ${e===1?`subsession`:`subsessions`} ${t}`}function X_(e){return e.slice(-8)}function Z_(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?X_(e.id):e.firstMessage}function Q_(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=ev(n,r),a=nv(tv(n.filter(e=>t.currentWorkspacePath===void 0?e.archived!==!0:e.cwd===t.currentWorkspacePath).map(e=>e.path),r,i),r);return $_(n.filter(e=>a.has(e.path)),t)}function $_(e,t={}){let n=new Map(e.map(e=>[e.path,e])),r=ev(e,n),i=e.filter(e=>{let t=e.parentSessionPath;return t===void 0||!n.has(t)});i.sort(rv);let a=[],o=(e,i,s)=>{if(s.has(e.path))return;let c=e.parentSessionPath,l=r.get(e.path)??[],u=t.foldedSessionPaths?.has(e.path)===!0;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,folded:u}),u)return;let d=new Set(s);d.add(e.path),l.sort(rv);for(let e of l)o(e,i+1,d)};for(let e of i)o(e,0,new Set);return a}function ev(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 tv(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 nv(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 rv(e,t){let n=e.pinned===!0,r=t.pinned===!0;return n&&!r?-1:!n&&r?1:0}var H=class extends y{constructor(...e){super(...e),this.sessions=[],this.projectSessions=[],this.workspaces=[],this.statuses={},this.activities={},this.sending={},this.unreadSessionIds=new Set,this.startingCount=0,this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.canCleanup=!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.collapsible=!1,this.collapsed=!1,this.menuStyle=``,this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set,this.renameInputValue=``,this.expandedSessionPaths=new Set,this.onDocumentClick=e=>{Qg(e,this.renderRoot)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick,!0)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick,!0),super.disconnectedCallback()}updated(e){e.has(`sessions`)&&(this.openMenuSessionId!==void 0&&!this.sessions.some(e=>e.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),this.renamingSessionId!==void 0&&!this.sessions.some(e=>e.id===this.renamingSessionId)&&this.cancelSessionRename(),this.sessions.some(e=>e.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has(`currentWorkspacePath`)?this.expandedSessionPaths=new Set:(e.has(`sessions`)||e.has(`projectSessions`))&&this.pruneExpandedSessionPaths(),e.has(`collapsed`)&&this.collapsed&&(this.openMenuSessionId=void 0,this.cancelSessionRename());let t=e.get(`selected`);if(e.has(`selected`)&&this.selected?.archived===!0&&(t?.id!==this.selected.id||t.archived!==!0)&&!this.archivedExpanded){this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()});return}(e.has(`selected`)||e.has(`sessions`)||e.has(`collapsed`))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,d_(this.renderRoot,{fallbackSelector:`.section-toggle, h2 button:not([disabled])`})}render(){let e=this.sessionTreeSessions(),t=lv(e,{...this.currentSessionTreeOptions(),expandedSessionPaths:this.expandedSessionPaths,...this.selected===void 0?{}:{selectedSessionPath:this.selected.path}}),n=t.reduce((e,t)=>(t.depth===0?e.push([t]):e.at(-1)?.push(t),e),[]),r=new Set(t.map(e=>e.session.path)),i=t.filter(e=>!e.external).map(e=>e.session).filter(e=>ov(e)===`current`),a=$_(this.sessions.filter(e=>e.archived===!0&&!r.has(e.path))),o=cv(this.sessions),s=iv(i,this.unreadSessionIds,{statuses:this.statuses,activities:this.activities,sending:this.sending});return g`
|
|
1563
1580
|
<section>
|
|
1564
|
-
|
|
1581
|
+
${this.renderHeading(t.length+a.length,i,s)}
|
|
1565
1582
|
${this.collapsed?null:g`
|
|
1566
1583
|
<div class="list-body">
|
|
1567
|
-
${this.
|
|
1568
|
-
<div
|
|
1569
|
-
class=${`action-row workspace-row ${this.selected?.id===e.id?`selected`:``}`}
|
|
1570
|
-
tabindex="0"
|
|
1571
|
-
title=${t}
|
|
1572
|
-
@click=${t=>{c_(t,()=>this.onSelect?.(e))}}
|
|
1573
|
-
@keydown=${t=>{this.handleWorkspaceKeydown(t,e)}}
|
|
1574
|
-
>
|
|
1575
|
-
<div class="action-main">
|
|
1576
|
-
${this.renderWorkspaceMain(t,n,e)}
|
|
1577
|
-
</div>
|
|
1578
|
-
${this.renderWorkspaceMenu(t,n,e)}
|
|
1579
|
-
</div>
|
|
1580
|
-
`})}
|
|
1581
|
-
</div>
|
|
1582
|
-
`}
|
|
1583
|
-
</section>
|
|
1584
|
-
`}renderHeading(){if(!this.collapsible)return g`<span>Workspaces</span>`;let e=this.selected===void 0?`No workspace selected`:`${this.selected.label}${this.selected.isMain?` · main`:``} · ${this.selected.path}`,t=this.selected?.path??e;return g`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} Workspaces</span>${this.collapsed?g`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){let t=Ms(js(e,this.activities));return i_(t,t===`terminal`?`Workspace terminal active`:`Workspace active`)}renderWorkspaceMain(e,t,n){return g`
|
|
1585
|
-
<span class="workspace-primary">
|
|
1586
|
-
<span class="workspace-primary-label">${e}</span>
|
|
1587
|
-
${this.isDeleting(n)?g`<span class="workspace-status">Deleting…</span>`:null}
|
|
1588
|
-
</span>
|
|
1589
|
-
${t.length===0?null:g`
|
|
1590
|
-
<small class="workspace-secondary">
|
|
1591
|
-
<span class="workspace-label">${V_(t)}</span>
|
|
1592
|
-
</small>
|
|
1593
|
-
`}
|
|
1594
|
-
${this.renderActivity(n)}
|
|
1595
|
-
`}renderWorkspaceMenu(e,t,n){let r=this.openMenuWorkspaceId===n.id,i=q_(n.id);return g`
|
|
1596
|
-
<div class="action-menu">
|
|
1597
|
-
<button
|
|
1598
|
-
class="action-menu-toggle"
|
|
1599
|
-
title="Workspace actions and details"
|
|
1600
|
-
aria-label=${`Actions and details for ${e}`}
|
|
1601
|
-
aria-expanded=${String(r)}
|
|
1602
|
-
aria-controls=${i}
|
|
1603
|
-
@click=${e=>{e.stopPropagation(),this.toggleMenu(n.id,e.currentTarget)}}
|
|
1604
|
-
>⋯</button>
|
|
1605
|
-
${r?g`
|
|
1606
|
-
<div class="action-menu-panel workspace-menu-panel" id=${i} style=${this.menuStyle} @click=${e=>{e.stopPropagation()}}>
|
|
1607
|
-
${this.renderWorkspaceActions(n)}
|
|
1608
|
-
${this.renderWorkspaceDetails(e,t,n)}
|
|
1609
|
-
</div>
|
|
1610
|
-
`:null}
|
|
1611
|
-
</div>
|
|
1612
|
-
`}renderWorkspaceActions(e){if(!K_(e))return;let t=this.isDeleting(e);return g`
|
|
1613
|
-
<div class="workspace-menu-actions">
|
|
1614
|
-
<button class="danger" title=${t?`Workspace deletion in progress`:`Delete workspace`} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?`Deleting…`:`Delete workspace`}</button>
|
|
1615
|
-
</div>
|
|
1616
|
-
`}renderWorkspaceDetails(e,t,n){return g`
|
|
1617
|
-
<dl class="workspace-menu-details">
|
|
1618
|
-
<div class="workspace-detail-row">
|
|
1619
|
-
<dt>${n.branch===void 0?`Workspace`:`Branch`}</dt>
|
|
1620
|
-
<dd>${e}</dd>
|
|
1621
|
-
</div>
|
|
1622
|
-
<div class="workspace-detail-row">
|
|
1623
|
-
<dt>Path</dt>
|
|
1624
|
-
<dd title=${n.path}>${n.path}</dd>
|
|
1625
|
-
</div>
|
|
1626
|
-
${t.length===0?null:g`
|
|
1627
|
-
<div class="workspace-detail-row">
|
|
1628
|
-
<dt>Details</dt>
|
|
1629
|
-
<dd><span class="workspace-label">${V_(t)}</span></dd>
|
|
1630
|
-
</div>
|
|
1631
|
-
`}
|
|
1632
|
-
</dl>
|
|
1633
|
-
`}delete(e){this.isDeleting(e)||(this.openMenuWorkspaceId=void 0,this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuStyle=$g(t,{constrainTo:`viewport`}),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key===`Escape`&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}l_(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}scrollSelectedIntoView(){this.renderRoot.querySelector(`.action-row.selected`)?.scrollIntoView({block:`nearest`})}static{this.styles=qp}};B([x({attribute:!1})],W_.prototype,`workspaces`,void 0),B([x({attribute:!1})],W_.prototype,`selected`,void 0),B([x({type:Boolean,reflect:!0})],W_.prototype,`collapsible`,void 0),B([x({type:Boolean,reflect:!0})],W_.prototype,`collapsed`,void 0),B([x({attribute:!1})],W_.prototype,`workspaceLabelItems`,void 0),B([x({attribute:!1})],W_.prototype,`activities`,void 0),B([x({attribute:!1})],W_.prototype,`deletingWorkspaceIds`,void 0),B([x({attribute:!1})],W_.prototype,`onSelect`,void 0),B([x({attribute:!1})],W_.prototype,`onDelete`,void 0),B([x({attribute:!1})],W_.prototype,`onToggleCollapsed`,void 0),B([x({attribute:!1})],W_.prototype,`onFocusPreviousSection`,void 0),B([x({attribute:!1})],W_.prototype,`onFocusNextSection`,void 0),B([x({attribute:!1})],W_.prototype,`onCancelKeyboardNavigation`,void 0),B([S()],W_.prototype,`openMenuWorkspaceId`,void 0),B([S()],W_.prototype,`menuStyle`,void 0),W_=B([b(`workspace-list`)],W_);function G_(e){return`${e.branch??e.label}${e.isMain?` · main`:``}`}function K_(e){return e.isGitWorktree&&!e.isMain}function q_(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}function J_(e){return e.slice(-8)}function Y_(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?J_(e.id):e.firstMessage}var H=class extends y{constructor(...e){super(...e),this.sessions=[],this.projectSessions=[],this.workspaces=[],this.statuses={},this.activities={},this.sending={},this.unreadSessionIds=new Set,this.startingCount=0,this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.canCleanup=!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.collapsible=!1,this.collapsed=!1,this.menuStyle=``,this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set,this.renameInputValue=``,this.foldedSessionPaths=new Set,this.onDocumentClick=e=>{Qg(e,this.renderRoot)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick,!0)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick,!0),super.disconnectedCallback()}updated(e){e.has(`sessions`)&&(this.openMenuSessionId!==void 0&&!this.sessions.some(e=>e.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),this.renamingSessionId!==void 0&&!this.sessions.some(e=>e.id===this.renamingSessionId)&&this.cancelSessionRename(),this.sessions.some(e=>e.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has(`currentWorkspacePath`)?this.foldedSessionPaths=new Set:(e.has(`sessions`)||e.has(`projectSessions`))&&this.pruneFoldedSessionPaths(),e.has(`collapsed`)&&this.collapsed&&(this.openMenuSessionId=void 0,this.cancelSessionRename());let t=e.get(`selected`);if(e.has(`selected`)&&this.selected?.archived===!0&&(t?.id!==this.selected.id||t.archived!==!0)&&!this.archivedExpanded){this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()});return}(e.has(`selected`)||e.has(`sessions`)||e.has(`collapsed`))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,u_(this.renderRoot,{fallbackSelector:`.section-toggle, h2 button:not([disabled])`})}render(){let e=this.currentWorkspacePath,t=new Set(this.workspaces.map(e=>e.path));e!==void 0&&t.add(e);let n=nv([...this.sessions,...this.projectSessions.filter(t=>t.cwd!==e)],{...e===void 0?{}:{currentWorkspacePath:e,knownWorkspacePaths:t},foldedSessionPaths:this.foldedSessionPaths}),r=n.reduce((e,t)=>(t.depth===0?e.push([t]):e.at(-1)?.push(t),e),[]),i=new Set(n.map(e=>e.session.path)),a=n.filter(e=>!e.external).map(e=>e.session).filter(e=>Q_(e)===`current`),o=rv(this.sessions.filter(e=>e.archived===!0&&!i.has(e.path))),s=ev(this.sessions),c=X_(a,this.unreadSessionIds,{statuses:this.statuses,activities:this.activities,sending:this.sending});return g`
|
|
1634
|
-
<section>
|
|
1635
|
-
${this.renderHeading(n.length+o.length,a,c)}
|
|
1636
|
-
${this.collapsed?null:g`
|
|
1637
|
-
<div class="list-body">
|
|
1638
|
-
${this.renderCurrentSelectionToolbar(a)}
|
|
1584
|
+
${this.renderCurrentSelectionToolbar(i)}
|
|
1639
1585
|
${this.startingCount>0?this.renderStartingSession():null}
|
|
1640
|
-
${
|
|
1641
|
-
${
|
|
1642
|
-
${this.renderArchivedHeading(
|
|
1586
|
+
${n.map(t=>t[0]?.hasChildren===!0?g`<div class="session-family-frame">${t.map(t=>this.renderSession(t,o.get(t.session.id)??0,`current`,e))}</div>`:t.map(t=>this.renderSession(t,o.get(t.session.id)??0,`current`,e)))}
|
|
1587
|
+
${a.length>0?g`
|
|
1588
|
+
${this.renderArchivedHeading(a.map(e=>e.session))}
|
|
1643
1589
|
${this.archivedExpanded?g`
|
|
1644
|
-
${this.renderArchivedSelectionToolbar(
|
|
1645
|
-
${
|
|
1590
|
+
${this.renderArchivedSelectionToolbar(a.map(e=>e.session))}
|
|
1591
|
+
${a.map(t=>this.renderSession(t,o.get(t.session.id)??0,`archived`,e))}
|
|
1646
1592
|
`:null}
|
|
1647
1593
|
`:null}
|
|
1648
1594
|
</div>
|
|
@@ -1651,21 +1597,27 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1651
1597
|
`}renderHeading(e,t,n){if(!this.collapsible)return g`
|
|
1652
1598
|
<h2>
|
|
1653
1599
|
<span class="plain-heading">Sessions</span>
|
|
1600
|
+
${this.renderExpandedBrowserButton()}
|
|
1654
1601
|
${this.renderCurrentSelectionButton(t)}
|
|
1655
1602
|
${this.renderUnreadCount(n)}
|
|
1656
1603
|
${this.renderCleanupButton()}
|
|
1657
1604
|
${this.renderStartButton()}
|
|
1658
1605
|
</h2>
|
|
1659
|
-
`;let r=this.selected===void 0?`No session selected`:
|
|
1606
|
+
`;let r=this.selected===void 0?`No session selected`:Z_(this.selected),i=this.selected?.path??r;return g`
|
|
1660
1607
|
<h2>
|
|
1661
1608
|
<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} Sessions</span>${this.collapsed?g`<small class="section-selected" dir="auto" title=${i}>${r}</small>`:null}</span></button>
|
|
1609
|
+
${this.renderExpandedBrowserButton()}
|
|
1662
1610
|
${this.renderCurrentSelectionButton(t)}
|
|
1663
1611
|
${this.renderUnreadCount(n)}
|
|
1664
1612
|
<small class="section-count">${e}</small>
|
|
1665
1613
|
${this.renderCleanupButton()}
|
|
1666
1614
|
${this.renderStartButton()}
|
|
1667
1615
|
</h2>
|
|
1668
|
-
`}renderUnreadCount(e){if(e===0)return null;let t=`${String(e)} unread`;return g`<small class="section-unread-count" title=${t}>${t}</small>`}
|
|
1616
|
+
`}renderUnreadCount(e){if(e===0)return null;let t=`${String(e)} unread`;return g`<small class="section-unread-count" title=${t}>${t}</small>`}renderExpandedBrowserButton(){return this.onOpenExpanded===void 0?null:g`
|
|
1617
|
+
<button type="button" class="section-expand-button" title="Open expanded session browser" aria-label="Open expanded session browser" @click=${e=>{this.openExpandedBrowser(e)}}>
|
|
1618
|
+
${_`<svg class="section-expand-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M9 3H3v6M15 3h6v6M21 15v6h-6M9 21H3v-6"></path></svg>`}
|
|
1619
|
+
</button>
|
|
1620
|
+
`}openExpandedBrowser(e){e.stopPropagation();let t=e.currentTarget;this.onOpenExpanded?.(()=>{t instanceof HTMLButtonElement&&t.focus()})}renderCurrentSelectionButton(e){if(this.collapsed||e.length===0)return null;let t=this.selectionScopes.has(`current`);return g`<button class="bulk-select-entry ${t?`selected`:``}" title=${t?`Close current session selection`:`Select current sessions`} aria-label=${t?`Close current session selection`:`Select current sessions`} aria-expanded=${String(t)} aria-pressed=${String(t)} @click=${t=>{t.stopPropagation(),this.toggleSelection(`current`,e)}}>☑</button>`}renderCleanupButton(){return g`<button class="cleanup-entry" title=${this.canCleanup?`Preview session cleanup`:this.cleanupUnavailableMessage} @click=${e=>{e.stopPropagation(),this.onCleanup?.()}}>Clean up</button>`}renderStartButton(){let e=this.startingCount>0?`Start another session`:`Start a new session`;return g`<button class="section-add-button" title=${e} aria-label=${e} ?disabled=${!this.canStart} @click=${e=>{e.stopPropagation(),this.onStart?.()}}>+</button>`}renderStartingSession(){let e=this.startingCount!==1;return g`
|
|
1669
1621
|
<div class="pending-session-row starting-session" role="status" aria-live="polite">
|
|
1670
1622
|
<div class="action-main">
|
|
1671
1623
|
<span class="action-name"><span class="activity-indicator sending" aria-hidden="true"></span>${e?`Starting ${String(this.startingCount)} sessions…`:`Starting session…`}</span>
|
|
@@ -1695,46 +1647,47 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1695
1647
|
<button @click=${()=>{this.closeSelection(`archived`)}}>Done</button>
|
|
1696
1648
|
${this.canDeleteArchived?null:g`<small class="capability-hint">${this.archivedDeleteUnavailableMessage}</small>`}
|
|
1697
1649
|
</div>
|
|
1698
|
-
`}renderSession(e,t,n){let{session:
|
|
1650
|
+
`}renderSession(e,t,n,r){let{session:i}=e,a=Math.min(e.depth,2),o=!e.external&&ov(i)===n,s=this.selectionScopes.has(n)&&!e.external,c=s&&o,l=c&&this.selectedSessionIds.has(i.id),u=this.statuses[i.id],d=this.activities[i.id],f=H_(i,u,d,this.sending[i.id]===!0,this.unreadSessionIds.has(i.id)),p=this.sessionPersistenceOptions(),m=mu(i,u,p),ee=hu(i,u,p),te=this.canRenameSession(i,n,e.external),ne=m&&this.canReload,re=e.external?this.workspaces.find(e=>e.path===i.cwd):void 0,ie=re===void 0?void 0:re.branch??re.label;return g`
|
|
1699
1651
|
<div
|
|
1700
|
-
class="action-row ${this.selected?.id===
|
|
1701
|
-
style=${`--depth:${String(
|
|
1652
|
+
class="action-row ${this.selected?.id===i.id?`selected`:``} ${l?`bulk-selected`:``} ${i.archived===!0?`archived`:``} ${e.external?`external-session`:``} ${s?`selecting`:``} ${f===`unread`?`unread`:``}"
|
|
1653
|
+
style=${`--depth:${String(a)}`}
|
|
1702
1654
|
tabindex="0"
|
|
1703
|
-
title=${
|
|
1704
|
-
@dblclick=${t=>{this.startSessionRename(t,
|
|
1705
|
-
@click=${t=>{
|
|
1706
|
-
@keydown=${t=>{this.handleSessionKeydown(t,
|
|
1655
|
+
title=${i.path}
|
|
1656
|
+
@dblclick=${t=>{this.startSessionRename(t,i,n,e.external)}}
|
|
1657
|
+
@click=${t=>{l_(t,()=>{this.activateSessionRow(i,n,e.external)})}}
|
|
1658
|
+
@keydown=${t=>{this.handleSessionKeydown(t,i,n,e.external)}}
|
|
1707
1659
|
>
|
|
1708
|
-
<div class="action-main ${
|
|
1709
|
-
${
|
|
1660
|
+
<div class="action-main ${s?`selecting`:``}">
|
|
1661
|
+
${c?g`<input class="session-checkbox" type="checkbox" aria-label=${`Select ${Z_(i)}`} .checked=${l} @click=${e=>{e.stopPropagation()}} @change=${()=>{this.toggleSelected(i.id)}}>`:null}
|
|
1710
1662
|
<span class="action-name-line">
|
|
1711
|
-
${this.renamingSessionId===
|
|
1712
|
-
</span><small>${this.renderSessionMetaPrefix(
|
|
1713
|
-
${this.renderActivity(
|
|
1663
|
+
${this.renamingSessionId===i.id?this.renderSessionRenameInput(i):g`${this.renderSessionGroupToggle(e)}<span class="action-name" dir="auto">${e.depth>0?g`<span class="tree-marker">↳</span>`:null}${!e.external&&i.pinned===!0?g`<button class="pinned-star" type="button" title="Click to unpin session" aria-label="Unpin session" @click=${e=>{e.stopPropagation(),this.onUnpin?.(i)}}>★</button> `:null}${Z_(i)}${e.depth>2?g` <span class="badge">depth ${e.depth}</span>`:null}${ie===void 0?null:g` <span class="badge external-workspace" title=${`Open ${ie} workspace`}>${ie} ↗</span>`}${e.hasMissingParent?g` <span class="badge">parent unavailable</span>`:null}</span>`}
|
|
1664
|
+
</span><small>${this.renderSessionMetaPrefix(i,u,d)}${String(i.messageCount)} messages</small>
|
|
1665
|
+
${this.renderActivity(i,r)}
|
|
1714
1666
|
</div>
|
|
1715
1667
|
${e.external?null:g`
|
|
1716
1668
|
<div class="action-menu">
|
|
1717
|
-
<button class="action-menu-toggle" title="Session actions" @click=${e=>{e.stopPropagation(),this.toggleMenu(
|
|
1718
|
-
${this.openMenuSessionId===
|
|
1669
|
+
<button class="action-menu-toggle" title="Session actions" @click=${e=>{e.stopPropagation(),this.toggleMenu(i.id,e.currentTarget)}}>⋯</button>
|
|
1670
|
+
${this.openMenuSessionId===i.id?g`
|
|
1719
1671
|
<div class="action-menu-panel" style=${this.menuStyle}>
|
|
1720
|
-
${
|
|
1721
|
-
|
|
1722
|
-
<button
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1672
|
+
${te?g`<button title="Rename session" @click=${t=>{this.startSessionRenameFromMenu(t,i,n,e.external)}}>Rename</button>`:null}
|
|
1673
|
+
${i.archived===!0?g`
|
|
1674
|
+
<button title="Restore session" @click=${()=>{this.openMenuSessionId=void 0,this.onRestore?.(i)}}>Restore</button>
|
|
1675
|
+
<button class="danger" title=${this.canDeleteArchived?`Permanently delete archived session`:this.archivedDeleteUnavailableMessage} ?disabled=${!this.canDeleteArchived} @click=${()=>{this.openMenuSessionId=void 0,this.confirmDeleteArchived(i)}}>Delete archived session</button>
|
|
1676
|
+
`:ee?g`<button title="Delete transient new session" @click=${()=>{this.openMenuSessionId=void 0,this.onDelete?.(i)}}>Delete</button>`:g`
|
|
1677
|
+
${m?g`
|
|
1678
|
+
<button title="Archive session" @click=${()=>{this.openMenuSessionId=void 0,this.onArchive?.(i)}}>Archive</button>
|
|
1679
|
+
${t>0?g`<button title="Archive this session and its descendants" @click=${()=>{this.openMenuSessionId=void 0,this.confirmArchiveWithDescendants(i,t)}}>Archive with descendants (${t})</button>`:null}
|
|
1727
1680
|
`:null}
|
|
1728
|
-
${
|
|
1729
|
-
${
|
|
1730
|
-
${
|
|
1681
|
+
${i.parentSessionPath===void 0?null:g`<button title="Detach from parent" @click=${()=>{this.openMenuSessionId=void 0,this.onDetachParent?.(i)}}>Detach from parent</button>`}
|
|
1682
|
+
${ne?g`<button title=${Vo(this.statuses[i.id],this.activities[i.id])?`Stop current session activity before reloading from disk`:`Reload session from disk without refreshing Pi runtime resources`} ?disabled=${Vo(this.statuses[i.id],this.activities[i.id])} @click=${()=>{this.openMenuSessionId=void 0,this.onReload?.(i)}}>Reload from disk</button>`:null}
|
|
1683
|
+
${i.pinned===!0?g`<button title="Unpin session" @click=${()=>{this.openMenuSessionId=void 0,this.onUnpin?.(i)}}>Unpin</button>`:g`<button title="Pin session to keep it at the top of the list" @click=${()=>{this.openMenuSessionId=void 0,this.onPin?.(i)}}>Pin</button>`}
|
|
1731
1684
|
`}
|
|
1732
1685
|
</div>
|
|
1733
1686
|
`:null}
|
|
1734
1687
|
</div>
|
|
1735
1688
|
`}
|
|
1736
1689
|
</div>
|
|
1737
|
-
`}startSessionRename(e,t,n,r){r||
|
|
1690
|
+
`}startSessionRename(e,t,n,r){s_(e)||!this.canRenameSession(t,n,r)||this.beginSessionRename(e,t)}startSessionRenameFromMenu(e,t,n,r){this.canRenameSession(t,n,r)&&(this.openMenuSessionId=void 0,this.beginSessionRename(e,t))}canRenameSession(e,t,n){return!n&&e.archived!==!0&&!this.selectionScopes.has(t)&&!hu(e,this.statuses[e.id],this.sessionPersistenceOptions())}beginSessionRename(e,t){this.onRenameStart?.(t),e.preventDefault(),e.stopPropagation(),this.renamingSessionId=t.id,this.renameInputValue=t.name??Z_(t),this.updateComplete.then(()=>{if(this.renamingSessionId!==t.id)return;let e=this.renderRoot.querySelector(`.session-name-input`);e?.focus(),e?.select()})}renderSessionRenameInput(e){return g`
|
|
1738
1691
|
<input
|
|
1739
1692
|
class="session-name-input"
|
|
1740
1693
|
aria-label="Rename session"
|
|
@@ -1743,16 +1696,18 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1743
1696
|
@click=${e=>{e.stopPropagation()}}
|
|
1744
1697
|
@blur=${t=>{this.commitSessionRename(e,this.sessionRenameInputValue(t))}}
|
|
1745
1698
|
>
|
|
1746
|
-
`}handleSessionRenameKeydown(e,t){if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.cancelSessionRename();return}e.key===`Enter`&&(e.preventDefault(),e.stopPropagation(),this.commitSessionRename(t,this.sessionRenameInputValue(e)))}sessionRenameInputValue(e){return
|
|
1699
|
+
`}handleSessionRenameKeydown(e,t){if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.cancelSessionRename();return}e.key===`Enter`&&(e.preventDefault(),e.stopPropagation(),this.commitSessionRename(t,this.sessionRenameInputValue(e)))}sessionRenameInputValue(e){return av(e.currentTarget)?e.currentTarget.value:this.renameInputValue}commitSessionRename(e,t=this.renameInputValue){if(this.renamingSessionId!==e.id)return;let n=t.trim(),r=e.name??Z_(e);this.cancelSessionRename(),!(n===``||n===r)&&this.onRename?.(e,n)}cancelSessionRename(){this.renamingSessionId=void 0,this.renameInputValue=``}renderSessionGroupToggle(e){if(!e.hasChildren)return null;let{folded:t}=e,n=t?`Expand`:`Collapse`;return g`<button class="session-group-toggle" type="button" title=${`${n} ${Z_(e.session)}`} aria-label=${`${n} ${Z_(e.session)}`} aria-expanded=${String(!t)} @click=${n=>{n.stopPropagation(),this.toggleSessionGroup(e.session.path,t)}}>${t?`▸`:`▾`}</button>`}toggleSessionGroup(e,t){let n=new Set(this.expandedSessionPaths);if(t){let t=Q_(this.sessionTreeSessions(),this.currentSessionTreeOptions());for(let r of uv(e,t))n.add(r)}else n.delete(e);this.expandedSessionPaths=n}handleSessionKeydown(e,t,n,r){u_(e,{activate:()=>{this.activateSessionRow(t,n,r)},previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}activateSessionRow(e,t,n){if(!n&&this.selectionScopes.has(t)&&ov(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){let n=t===1?`descendant session`:`descendant sessions`;confirm(`Archive “${Z_(e)}” and ${String(t)} ${n}?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`Permanently delete archived session “${Z_(e)}”? This cannot be undone.`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;let e=this.selectedSessions(`archived`);if(e.length===0)return;let t=e.length===1?`archived session`:`archived sessions`;confirm(`Permanently delete ${String(e.length)} selected ${t}? This cannot be undone.`)&&(this.selectedSessionIds=sv(this.selectedSessionIds,e.map(e=>e.id)),this.onDeleteArchivedMany?.(e))}archiveSelectedCurrent(){let e=this.selectedSessions(`current`).filter(e=>mu(e,this.statuses[e.id],this.sessionPersistenceOptions()));this.selectedSessionIds=sv(this.selectedSessionIds,e.map(e=>e.id)),this.onArchiveMany?.(e)}toggleSelection(e,t){if(this.selectionScopes.has(e)){this.closeSelection(e);return}this.startSelection(e,t)}startSelection(e,t){this.selectionScopes=new Set([...this.selectionScopes,e]);let n=t.length===1?t[0]:void 0;n!==void 0&&(this.selectedSessionIds=new Set([...this.selectedSessionIds,n.id]))}closeSelection(e){this.selectionScopes=new Set([...this.selectionScopes].filter(t=>t!==e)),this.clearSelection(e)}clearSelection(e){let t=this.sessions.filter(t=>ov(t)===e).map(e=>e.id);this.selectedSessionIds=sv(this.selectedSessionIds,t)}toggleSelected(e){let t=new Set(this.selectedSessionIds);t.has(e)?t.delete(e):t.add(e),this.selectedSessionIds=t}toggleVisibleSelection(e,t){let n=new Set(this.selectedSessionIds);for(let r of e)t?n.add(r.id):n.delete(r.id);this.selectedSessionIds=n}selectedSessions(e){return this.sessions.filter(t=>this.selectedSessionIds.has(t.id)&&ov(t)===e)}sessionTreeSessions(){return[...this.sessions,...this.projectSessions.filter(e=>e.cwd!==this.currentWorkspacePath)]}currentSessionTreeOptions(){if(this.currentWorkspacePath===void 0)return{};let e=new Set(this.workspaces.map(e=>e.path));return e.add(this.currentWorkspacePath),{currentWorkspacePath:this.currentWorkspacePath,knownWorkspacePaths:e}}pruneExpandedSessionPaths(){let e=new Set([...this.sessions,...this.projectSessions].map(e=>e.path)),t=new Set([...this.expandedSessionPaths].filter(t=>e.has(t)));t.size!==this.expandedSessionPaths.size&&(this.expandedSessionPaths=t)}pruneSelectedSessionIds(){let e=new Set(this.sessions.map(e=>e.id)),t=new Set([...this.selectedSessionIds].filter(t=>e.has(t)));t.size!==this.selectedSessionIds.size&&(this.selectedSessionIds=t),this.selectionScopes.has(`archived`)&&!this.sessions.some(e=>e.archived===!0)&&this.closeSelection(`archived`),this.selectionScopes.has(`current`)&&!this.sessions.some(e=>e.archived!==!0)&&this.closeSelection(`current`)}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}this.menuStyle=$g(t,{constrainTo:`viewport`}),this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.selectionScopes.has(`archived`)&&this.closeSelection(`archived`),this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(`.action-row.selected`)?.scrollIntoView({block:`nearest`})}renderSessionMetaPrefix(e,t,n){return hu(e,t,this.sessionPersistenceOptions())?n?.phase===`active`?`creating · `:n?.phase===`error`?`error · `:`new · `:e.archived===!0?`read-only · `:``}sessionPersistenceOptions(){return{authoritative:this.authoritativeSessionPersistence}}renderActivity(e,t){return a_(U_(e,t,{statuses:this.statuses,activities:this.activities,sending:this.sending,unreadSessionIds:this.unreadSessionIds}))}static{this.styles=[qp,h`
|
|
1747
1700
|
h2 { min-height: 30px; }
|
|
1748
1701
|
h2 > .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
|
|
1749
1702
|
h2 > .section-unread-count { flex: 0 0 auto; display: inline; color: var(--pi-accent); font-size: inherit; text-transform: none; }
|
|
1750
|
-
.bulk-select-entry { box-sizing: border-box; flex: 0 0 auto; display: inline-grid; place-items: center; width: 30px; height: 30px; padding: 0; font-size: 13px; line-height: 1; text-transform: none; }
|
|
1703
|
+
.bulk-select-entry, .section-expand-button { box-sizing: border-box; flex: 0 0 auto; display: inline-grid; place-items: center; width: 30px; height: 30px; padding: 0; font-size: 13px; line-height: 1; text-transform: none; }
|
|
1704
|
+
.section-expand-icon { width: 15px; height: 15px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
|
|
1751
1705
|
.cleanup-entry { flex: 0 0 auto; padding: 5px 7px; font-size: 12px; text-transform: none; }
|
|
1752
1706
|
.bulk-row { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin: 0 0 6px; }
|
|
1753
1707
|
.bulk-row button { padding: 5px 7px; font-size: 12px; }
|
|
1754
1708
|
.bulk-row small { display: inline; min-width: 0; color: var(--pi-muted); }
|
|
1755
1709
|
.action-name, .section-selected { text-align: start; unicode-bidi: plaintext; }
|
|
1710
|
+
.action-main { padding-right: 56px; }
|
|
1756
1711
|
.action-row.unread .action-name { color: var(--pi-text-bright); font-weight: 650; }
|
|
1757
1712
|
.plain-heading { min-width: 0; }
|
|
1758
1713
|
.action-name-line { min-width: 0; display: flex; align-items: flex-start; gap: 6px; }
|
|
@@ -1783,7 +1738,162 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1783
1738
|
.pinned-star { flex: 0 0 auto; border: 0; background: transparent; color: #d4a017; padding: 0; font: inherit; font-size: 14px; line-height: 1; }
|
|
1784
1739
|
.pinned-star:hover { border-radius: 4px; background: var(--pi-surface); box-shadow: 0 0 0 1px var(--pi-border); transform: scale(1.25); }
|
|
1785
1740
|
.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,`
|
|
1741
|
+
`]}};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,`onOpenExpanded`,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,`expandedSessionPaths`,void 0),H=B([b(`session-list`)],H);function iv(e,t,n={}){return e.filter(e=>H_(e,n.statuses?.[e.id],n.activities?.[e.id],n.sending?.[e.id]===!0,t.has(e.id))===`unread`).length}function av(e){return e!==null&&`value`in e&&typeof e.value==`string`}function ov(e){return e.archived===!0?`archived`:`current`}function sv(e,t){let n=new Set(t);return new Set([...e].filter(e=>!n.has(e)))}function cv(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 lv(e,t={}){let{expandedSessionPaths:n,selectedSessionPath:r,...i}=t,a=Q_(e,i),o=new Set(a.filter(e=>e.hasChildren).map(e=>e.session.path));for(let e of n??[])o.delete(e);for(let e of dv(r,a))o.delete(e);return Q_(e,{...i,foldedSessionPaths:o})}function uv(e,t){let n=new Map;for(let e of t){let t=e.session.parentSessionPath;if(t===void 0)continue;let r=n.get(t)??[];r.push(e.session.path),n.set(t,r)}let r=new Set,i=[e];for(;i.length>0;){let e=i.pop();e===void 0||r.has(e)||(r.add(e),i.push(...n.get(e)??[]))}return r}function dv(e,t){if(e===void 0)return new Set;let n=new Map(t.map(e=>[e.session.path,e])),r=new Set,i=new Set([e]),a=n.get(e)?.session.parentSessionPath;for(;a!==void 0&&!i.has(a);){i.add(a);let e=n.get(a);if(e===void 0)break;r.add(a),a=e.session.parentSessionPath}return r}var fv=class extends y{constructor(...e){super(...e),this.projectName=`Project`,this.sessions=[],this.statuses={},this.activities={},this.sending={},this.unreadSessionIds=new Set,this.searchQuery=``,this.expandedSessionPaths=new Set}firstUpdated(){this.searchInput?.focus()}render(){return g`
|
|
1742
|
+
<div class="backdrop" @mousedown=${e=>{this.handleBackdropMouseDown(e)}}>
|
|
1743
|
+
<section
|
|
1744
|
+
role="dialog"
|
|
1745
|
+
aria-modal="true"
|
|
1746
|
+
aria-labelledby="session-browser-title"
|
|
1747
|
+
tabindex="-1"
|
|
1748
|
+
@mousedown=${e=>{e.stopPropagation()}}
|
|
1749
|
+
@keydown=${e=>{this.handleDialogKeyDown(e)}}
|
|
1750
|
+
>
|
|
1751
|
+
<header>
|
|
1752
|
+
<h1 id="session-browser-title">Sessions · ${this.projectName===``?`Project`:this.projectName}</h1>
|
|
1753
|
+
<button class="close-button" type="button" title="Close expanded session browser" aria-label="Close expanded session browser" @click=${()=>{this.close()}}>×</button>
|
|
1754
|
+
</header>
|
|
1755
|
+
<div class="dialog-body">
|
|
1756
|
+
<label class="search-label" for="session-browser-search">Search sessions</label>
|
|
1757
|
+
<input
|
|
1758
|
+
id="session-browser-search"
|
|
1759
|
+
class="session-browser-search"
|
|
1760
|
+
type="search"
|
|
1761
|
+
placeholder="Search sessions"
|
|
1762
|
+
.value=${this.searchQuery}
|
|
1763
|
+
@input=${e=>{this.handleSearchInput(e)}}
|
|
1764
|
+
>
|
|
1765
|
+
<div class="result-area">${this.renderResults()}</div>
|
|
1766
|
+
</div>
|
|
1767
|
+
</section>
|
|
1768
|
+
</div>
|
|
1769
|
+
`}renderResults(){if(this.sessions.length===0)return g`<p class="empty-state">No sessions in this project.</p>`;let e=this.visibleRows;return e.length===0?g`<p class="empty-state">No matching sessions.</p>`:g`
|
|
1770
|
+
<div class="session-list">
|
|
1771
|
+
${this.groupRows(e).map(e=>e.length>1||e[0]?.hasChildren===!0?g`<div class="session-family-frame">${e.map(e=>this.renderSession(e))}</div>`:e.map(e=>this.renderSession(e)))}
|
|
1772
|
+
</div>
|
|
1773
|
+
`}get visibleRows(){return pv(lv(this.sessions,{expandedSessionPaths:this.expandedSessionPaths,...this.selected===void 0?{}:{selectedSessionPath:this.selected.path}}),this.searchQuery)}groupRows(e){return e.reduce((e,t)=>(t.depth===0?e.push([t]):e.at(-1)?.push(t),e),[])}renderSession(e){let t=e.session,n=U_(t,this.sessions,{statuses:this.statuses,activities:this.activities,sending:this.sending,unreadSessionIds:this.unreadSessionIds}),r=Math.min(e.depth,2);return g`
|
|
1774
|
+
<div
|
|
1775
|
+
class=${`action-row session-browser-row ${this.selected?.id===t.id?`selected`:``}`}
|
|
1776
|
+
style=${`--depth:${String(r)}`}
|
|
1777
|
+
tabindex="0"
|
|
1778
|
+
title=${t.path}
|
|
1779
|
+
@click=${e=>{l_(e,()=>{this.select(t)})}}
|
|
1780
|
+
@keydown=${e=>{this.handleSessionKeydown(e,t)}}
|
|
1781
|
+
>
|
|
1782
|
+
<div class="action-main">
|
|
1783
|
+
<span class="action-name" dir="auto">${this.renderSessionGroupToggle(e)}${e.depth>0?g`<span class="tree-marker">↳</span>`:null}${Z_(t)}${e.depth>2?g` <span class="badge">depth ${e.depth}</span>`:null}${e.hasMissingParent?g` <span class="badge">parent unavailable</span>`:null}</span>
|
|
1784
|
+
<small>${t.cwd} · ${String(t.messageCount)} messages</small>
|
|
1785
|
+
${a_(n)}
|
|
1786
|
+
</div>
|
|
1787
|
+
</div>
|
|
1788
|
+
`}renderSessionGroupToggle(e){if(!e.hasChildren)return null;let{folded:t}=e,n=t?`Expand`:`Collapse`;return g`<button class="session-group-toggle" type="button" title=${`${n} ${Z_(e.session)}`} aria-label=${`${n} ${Z_(e.session)}`} aria-expanded=${String(!t)} @click=${n=>{n.stopPropagation(),this.toggleSessionGroup(e.session.path,t)}}>${t?`▸`:`▾`}</button>`}toggleSessionGroup(e,t){let n=new Set(this.expandedSessionPaths);t?n.add(e):n.delete(e),this.expandedSessionPaths=n}select(e){this.sessions.some(t=>t.id===e.id)&&this.onSelect?.(e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.searchQuery=e.target.value)}handleSessionKeydown(e,t){u_(e,{activate:()=>{this.select(t)}})}close(){this.onClose?.()}handleBackdropMouseDown(e){e.target===e.currentTarget&&(e.preventDefault(),this.close())}handleDialogKeyDown(e){if(e.key===`Tab`){this.trapTabFocus(e);return}e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.close())}trapTabFocus(e){let t=[...this.renderRoot.querySelectorAll(`button:not(:disabled), input:not(:disabled), [tabindex='0']`)];if(t.length===0){e.preventDefault(),this.renderRoot.querySelector(`section[role='dialog']`)?.focus();return}let n=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())}static{this.styles=[qp,h`
|
|
1789
|
+
:host { position: fixed; inset: 0; z-index: 60; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
1790
|
+
* { box-sizing: border-box; }
|
|
1791
|
+
.backdrop { width: 100%; height: 100dvh; display: grid; 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); }
|
|
1792
|
+
section[role="dialog"] { width: min(960px, 100%); height: min(760px, 100%); min-width: 0; display: grid; grid-template-rows: auto minmax(0, 1fr); overflow: hidden; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); padding: 0; }
|
|
1793
|
+
header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--pi-border); }
|
|
1794
|
+
h1, p { margin: 0; }
|
|
1795
|
+
h1 { font-size: 20px; line-height: 1.25; }
|
|
1796
|
+
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 8px 11px; font: inherit; cursor: pointer; }
|
|
1797
|
+
button:hover { background: var(--pi-surface-hover); }
|
|
1798
|
+
button:focus-visible, input:focus-visible, .session-browser-row:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; }
|
|
1799
|
+
.close-button { display: grid; place-items: center; width: 36px; height: 36px; padding: 0; color: var(--pi-muted); font-size: 20px; line-height: 1; }
|
|
1800
|
+
.close-button:hover { color: var(--pi-text); }
|
|
1801
|
+
.dialog-body { min-height: 0; display: grid; grid-template-rows: auto auto minmax(0, 1fr); gap: 7px; padding: 16px; }
|
|
1802
|
+
.search-label { font-weight: 700; }
|
|
1803
|
+
.session-browser-search { width: 100%; min-width: 0; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 8px 10px; font: inherit; }
|
|
1804
|
+
.result-area { min-height: 0; overflow-x: hidden; overflow-y: auto; overscroll-behavior: contain; }
|
|
1805
|
+
.session-list { display: grid; gap: 2px; }
|
|
1806
|
+
.session-family-frame { box-sizing: border-box; margin: 6px 0; border: 1px solid var(--pi-danger); border-radius: 10px; background: color-mix(in srgb, var(--pi-surface) 52%, transparent); padding: 5px 6px; }
|
|
1807
|
+
.session-family-frame > .action-row { margin: 4px 0; }
|
|
1808
|
+
.session-family-frame > .action-row:first-child { margin-top: 0; }
|
|
1809
|
+
.session-family-frame > .action-row:last-child { margin-bottom: 0; }
|
|
1810
|
+
.session-browser-row { grid-template-columns: minmax(0, 1fr); }
|
|
1811
|
+
.session-browser-row .action-main { border-radius: 8px; padding-right: 56px; }
|
|
1812
|
+
.session-group-toggle { flex: 0 0 auto; display: inline-grid; place-items: center; width: 18px; min-width: 18px; height: 18px; margin: 0 5px 0 0; border: 0; border-radius: 4px; background: transparent; color: var(--pi-muted); padding: 0; font: inherit; line-height: 1; vertical-align: text-bottom; cursor: pointer; }
|
|
1813
|
+
.session-group-toggle:hover { background: var(--pi-surface-hover); color: var(--pi-text); }
|
|
1814
|
+
.session-group-toggle:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 1px; }
|
|
1815
|
+
.empty-state { margin: 0; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-muted); padding: 14px; }
|
|
1816
|
+
|
|
1817
|
+
@media (max-width: 760px) {
|
|
1818
|
+
.backdrop { padding: 0; }
|
|
1819
|
+
section[role="dialog"] { width: 100%; height: 100%; border: 0; border-radius: 0; }
|
|
1820
|
+
header, .dialog-body { padding-inline: max(12px, env(safe-area-inset-left)) max(12px, env(safe-area-inset-right)); }
|
|
1821
|
+
header { padding-top: max(12px, env(safe-area-inset-top)); }
|
|
1822
|
+
.dialog-body { padding-bottom: max(12px, env(safe-area-inset-bottom)); }
|
|
1823
|
+
}
|
|
1824
|
+
`]}};B([x({type:String})],fv.prototype,`projectName`,void 0),B([x({attribute:!1})],fv.prototype,`sessions`,void 0),B([x({attribute:!1})],fv.prototype,`statuses`,void 0),B([x({attribute:!1})],fv.prototype,`activities`,void 0),B([x({attribute:!1})],fv.prototype,`sending`,void 0),B([x({attribute:!1})],fv.prototype,`unreadSessionIds`,void 0),B([x({attribute:!1})],fv.prototype,`selected`,void 0),B([x({attribute:!1})],fv.prototype,`onSelect`,void 0),B([x({attribute:!1})],fv.prototype,`onClose`,void 0),B([S()],fv.prototype,`searchQuery`,void 0),B([S()],fv.prototype,`expandedSessionPaths`,void 0),B([C(`.session-browser-search`)],fv.prototype,`searchInput`,void 0),fv=B([b(`session-browser-dialog`)],fv);function pv(e,t){let n=t.trim().toLocaleLowerCase();if(n===``)return[...e];let r=new Map(e.map(e=>[e.session.path,e])),i=new Set;for(let t of e){if(!mv(t.session).includes(n))continue;let e=t.session.path,a=new Set;for(;e!==void 0&&!a.has(e);){a.add(e);let t=r.get(e);if(t===void 0)break;i.add(e),e=t.session.parentSessionPath}}return e.filter(e=>i.has(e.session.path))}function mv(e){return[Z_(e),e.firstMessage,e.id,e.cwd].join(`
|
|
1825
|
+
`).toLocaleLowerCase()}function hv(e=[]){return e.map((e,t)=>g`${t===0?null:g`<span class="workspace-label-separator">·</span>`}${gv(e)}`)}function gv(e){if(e.type===`render`)return g`<span class="workspace-label-render">${e.render()}</span>`;if(e.type===`link`&&_v(e.href)){let t=e.target??`_blank`,n=t===`_blank`?`noopener noreferrer`:void 0;return g`<a class="workspace-label-item workspace-label-link" href=${e.href} title=${e.title??e.text} target=${t} rel=${n??void 0}>${e.text}</a>`}return g`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function _v(e){let t=e.trim().toLowerCase();return t!==``&&!t.startsWith(`javascript:`)&&!t.startsWith(`data:`)}var vv=class extends y{constructor(...e){super(...e),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.menuStyle=``,this.onDocumentClick=e=>{Qg(e,this.renderRoot)||(this.openMenuWorkspaceId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick,!0)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick,!0),super.disconnectedCallback()}updated(e){e.has(`workspaces`)&&this.openMenuWorkspaceId!==void 0&&!this.workspaces.some(e=>e.id===this.openMenuWorkspaceId)&&(this.openMenuWorkspaceId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuWorkspaceId=void 0),(e.has(`selected`)||e.has(`workspaces`)||e.has(`collapsed`))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,d_(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
|
|
1826
|
+
<section>
|
|
1827
|
+
<h2>${this.renderHeading()}</h2>
|
|
1828
|
+
${this.collapsed?null:g`
|
|
1829
|
+
<div class="list-body">
|
|
1830
|
+
${this.workspaces.map(e=>{let t=yv(e),n=this.workspaceLabelItems(e);return g`
|
|
1831
|
+
<div
|
|
1832
|
+
class=${`action-row workspace-row ${this.selected?.id===e.id?`selected`:``}`}
|
|
1833
|
+
tabindex="0"
|
|
1834
|
+
title=${t}
|
|
1835
|
+
@click=${t=>{l_(t,()=>this.onSelect?.(e))}}
|
|
1836
|
+
@keydown=${t=>{this.handleWorkspaceKeydown(t,e)}}
|
|
1837
|
+
>
|
|
1838
|
+
<div class="action-main">
|
|
1839
|
+
${this.renderWorkspaceMain(t,n,e)}
|
|
1840
|
+
</div>
|
|
1841
|
+
${this.renderWorkspaceMenu(t,n,e)}
|
|
1842
|
+
</div>
|
|
1843
|
+
`})}
|
|
1844
|
+
</div>
|
|
1845
|
+
`}
|
|
1846
|
+
</section>
|
|
1847
|
+
`}renderHeading(){if(!this.collapsible)return g`<span>Workspaces</span>`;let e=this.selected===void 0?`No workspace selected`:`${this.selected.label}${this.selected.isMain?` · main`:``} · ${this.selected.path}`,t=this.selected?.path??e;return g`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} Workspaces</span>${this.collapsed?g`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){let t=Ms(js(e,this.activities));return i_(t,t===`terminal`?`Workspace terminal active`:`Workspace active`)}renderWorkspaceMain(e,t,n){return g`
|
|
1848
|
+
<span class="workspace-primary">
|
|
1849
|
+
<span class="workspace-primary-label">${e}</span>
|
|
1850
|
+
${this.isDeleting(n)?g`<span class="workspace-status">Deleting…</span>`:null}
|
|
1851
|
+
</span>
|
|
1852
|
+
${t.length===0?null:g`
|
|
1853
|
+
<small class="workspace-secondary">
|
|
1854
|
+
<span class="workspace-label">${hv(t)}</span>
|
|
1855
|
+
</small>
|
|
1856
|
+
`}
|
|
1857
|
+
${this.renderActivity(n)}
|
|
1858
|
+
`}renderWorkspaceMenu(e,t,n){let r=this.openMenuWorkspaceId===n.id,i=xv(n.id);return g`
|
|
1859
|
+
<div class="action-menu">
|
|
1860
|
+
<button
|
|
1861
|
+
class="action-menu-toggle"
|
|
1862
|
+
title="Workspace actions and details"
|
|
1863
|
+
aria-label=${`Actions and details for ${e}`}
|
|
1864
|
+
aria-expanded=${String(r)}
|
|
1865
|
+
aria-controls=${i}
|
|
1866
|
+
@click=${e=>{e.stopPropagation(),this.toggleMenu(n.id,e.currentTarget)}}
|
|
1867
|
+
>⋯</button>
|
|
1868
|
+
${r?g`
|
|
1869
|
+
<div class="action-menu-panel workspace-menu-panel" id=${i} style=${this.menuStyle} @click=${e=>{e.stopPropagation()}}>
|
|
1870
|
+
${this.renderWorkspaceActions(n)}
|
|
1871
|
+
${this.renderWorkspaceDetails(e,t,n)}
|
|
1872
|
+
</div>
|
|
1873
|
+
`:null}
|
|
1874
|
+
</div>
|
|
1875
|
+
`}renderWorkspaceActions(e){if(!bv(e))return;let t=this.isDeleting(e);return g`
|
|
1876
|
+
<div class="workspace-menu-actions">
|
|
1877
|
+
<button class="danger" title=${t?`Workspace deletion in progress`:`Delete workspace`} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?`Deleting…`:`Delete workspace`}</button>
|
|
1878
|
+
</div>
|
|
1879
|
+
`}renderWorkspaceDetails(e,t,n){return g`
|
|
1880
|
+
<dl class="workspace-menu-details">
|
|
1881
|
+
<div class="workspace-detail-row">
|
|
1882
|
+
<dt>${n.branch===void 0?`Workspace`:`Branch`}</dt>
|
|
1883
|
+
<dd>${e}</dd>
|
|
1884
|
+
</div>
|
|
1885
|
+
<div class="workspace-detail-row">
|
|
1886
|
+
<dt>Path</dt>
|
|
1887
|
+
<dd title=${n.path}>${n.path}</dd>
|
|
1888
|
+
</div>
|
|
1889
|
+
${t.length===0?null:g`
|
|
1890
|
+
<div class="workspace-detail-row">
|
|
1891
|
+
<dt>Details</dt>
|
|
1892
|
+
<dd><span class="workspace-label">${hv(t)}</span></dd>
|
|
1893
|
+
</div>
|
|
1894
|
+
`}
|
|
1895
|
+
</dl>
|
|
1896
|
+
`}delete(e){this.isDeleting(e)||(this.openMenuWorkspaceId=void 0,this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuStyle=$g(t,{constrainTo:`viewport`}),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key===`Escape`&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}u_(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}scrollSelectedIntoView(){this.renderRoot.querySelector(`.action-row.selected`)?.scrollIntoView({block:`nearest`})}static{this.styles=qp}};B([x({attribute:!1})],vv.prototype,`workspaces`,void 0),B([x({attribute:!1})],vv.prototype,`selected`,void 0),B([x({type:Boolean,reflect:!0})],vv.prototype,`collapsible`,void 0),B([x({type:Boolean,reflect:!0})],vv.prototype,`collapsed`,void 0),B([x({attribute:!1})],vv.prototype,`workspaceLabelItems`,void 0),B([x({attribute:!1})],vv.prototype,`activities`,void 0),B([x({attribute:!1})],vv.prototype,`deletingWorkspaceIds`,void 0),B([x({attribute:!1})],vv.prototype,`onSelect`,void 0),B([x({attribute:!1})],vv.prototype,`onDelete`,void 0),B([x({attribute:!1})],vv.prototype,`onToggleCollapsed`,void 0),B([x({attribute:!1})],vv.prototype,`onFocusPreviousSection`,void 0),B([x({attribute:!1})],vv.prototype,`onFocusNextSection`,void 0),B([x({attribute:!1})],vv.prototype,`onCancelKeyboardNavigation`,void 0),B([S()],vv.prototype,`openMenuWorkspaceId`,void 0),B([S()],vv.prototype,`menuStyle`,void 0),vv=B([b(`workspace-list`)],vv);function yv(e){return`${e.branch??e.label}${e.isMain?` · main`:``}`}function bv(e){return e.isGitWorktree&&!e.isMain}function xv(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}var Sv=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
1897
|
<div class="backdrop" @mousedown=${()=>{this.onClose?.()}}>
|
|
1788
1898
|
<section role="dialog" aria-modal="true" aria-label="Clean up sessions" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
1789
1899
|
<header>
|
|
@@ -1812,15 +1922,15 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1812
1922
|
`}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
1923
|
<fieldset ?disabled=${t}>
|
|
1814
1924
|
<label class="toggle-row">
|
|
1815
|
-
<input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:
|
|
1925
|
+
<input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:Cv(e)})}}>
|
|
1816
1926
|
<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:
|
|
1927
|
+
<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:wv(e)})}}>
|
|
1818
1928
|
<span>days</span>
|
|
1819
1929
|
</label>
|
|
1820
1930
|
<label class="toggle-row delete-row">
|
|
1821
|
-
<input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:
|
|
1931
|
+
<input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:Cv(e)})}}>
|
|
1822
1932
|
<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:
|
|
1933
|
+
<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:wv(e)})}}>
|
|
1824
1934
|
<span>days</span>
|
|
1825
1935
|
</label>
|
|
1826
1936
|
</fieldset>
|
|
@@ -1857,7 +1967,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1857
1967
|
${t.length===0?g`<p class="hint" role="status">Select at least one project to run cleanup.</p>`:null}
|
|
1858
1968
|
`}renderProjectRow(e,t){return g`
|
|
1859
1969
|
<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,
|
|
1970
|
+
<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
1971
|
<th title=${e.cwd} dir="auto">${e.cwd}</th>
|
|
1862
1972
|
<td>${e.archiveCount}</td>
|
|
1863
1973
|
<td>${e.deleteCount}</td>
|
|
@@ -1924,7 +2034,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1924
2034
|
table { min-width: 560px; }
|
|
1925
2035
|
thead th:first-child, td.select-cell { width: 58px; }
|
|
1926
2036
|
}
|
|
1927
|
-
`}};B([x({type:Boolean})],
|
|
2037
|
+
`}};B([x({type:Boolean})],Sv.prototype,`canCleanup`,void 0),B([x({type:String})],Sv.prototype,`unavailableMessage`,void 0),B([x({attribute:!1})],Sv.prototype,`preview`,void 0),B([x({attribute:!1})],Sv.prototype,`previewRequest`,void 0),B([x({attribute:!1})],Sv.prototype,`result`,void 0),B([x({type:Boolean})],Sv.prototype,`loading`,void 0),B([x({type:Boolean})],Sv.prototype,`running`,void 0),B([x({type:String})],Sv.prototype,`error`,void 0),B([x({attribute:!1})],Sv.prototype,`onPreview`,void 0),B([x({attribute:!1})],Sv.prototype,`onRun`,void 0),B([x({attribute:!1})],Sv.prototype,`onForceCleanup`,void 0),B([x({attribute:!1})],Sv.prototype,`onClose`,void 0),B([x({attribute:!1})],Sv.prototype,`forceCleanupResult`,void 0),B([x({type:Boolean})],Sv.prototype,`runningForce`,void 0),B([S()],Sv.prototype,`draft`,void 0),B([S()],Sv.prototype,`formError`,void 0),B([S()],Sv.prototype,`selectedProjectCwds`,void 0),Sv=B([b(`session-cleanup-dialog`)],Sv);function Cv(e){return e.target instanceof HTMLInputElement&&e.target.checked}function wv(e){return e.target instanceof HTMLInputElement?e.target.value:``}var Tv=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?``:Ev(e);return g`
|
|
1928
2038
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
1929
2039
|
<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
2040
|
<header>
|
|
@@ -1934,7 +2044,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1934
2044
|
${e===void 0?null:g`<span class="session-label" title=${n}>${n}</span>`}
|
|
1935
2045
|
</div>
|
|
1936
2046
|
<button class="icon-button" type="button" title="Close full history" aria-label="Close full history" @click=${()=>{this.close()}}>
|
|
1937
|
-
${
|
|
2047
|
+
${Dv()}
|
|
1938
2048
|
</button>
|
|
1939
2049
|
</header>
|
|
1940
2050
|
<div class="history-body">
|
|
@@ -1971,11 +2081,11 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1971
2081
|
header, footer { padding: 12px; }
|
|
1972
2082
|
.session-label { max-width: 68vw; }
|
|
1973
2083
|
}
|
|
1974
|
-
`}};B([x({attribute:!1})],
|
|
2084
|
+
`}};B([x({attribute:!1})],Tv.prototype,`session`,void 0),B([x({type:String})],Tv.prototype,`machineId`,void 0),B([x({attribute:!1})],Tv.prototype,`onClose`,void 0),Tv=B([b(`session-history-window`)],Tv);function Ev(e){let t=e.name?.trim();if(t!==void 0&&t!==``)return t;let n=e.firstMessage.trim();return n===``?e.id:n}function Dv(){return _`
|
|
1975
2085
|
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1976
2086
|
<path d="M6 6l12 12M18 6 6 18"></path>
|
|
1977
2087
|
</svg>
|
|
1978
|
-
`}function
|
|
2088
|
+
`}function Ov(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=Pv(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:Fv(d,r),activeLeafId:d}}function kv(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 Av(e){return e.activeLeafId===null?e.orderedIds.at(-1):e.activeLeafId}function jv(e,t,n){let r=kv(e,t.foldedIds).map(e=>e.node.id),i=Iv(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 Mv(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 Nv(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 Pv(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 Fv(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 Iv(e,t){return t!==void 0&&e.includes(t)?t:e.at(-1)}var Lv={nodes:[],activeLeafId:null,activePathIds:[]},Rv=8,zv=class extends y{constructor(...e){super(...e),this.tree=Lv,this.foldedIds=new Set,this.step=`tree`,this.summaryMode=`none`,this.customInstructions=``,this.busy=!1,this.aborting=!1,this.error=``,this.statusMessage=``,this.model=Ov(Lv),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
2089
|
<div class="backdrop" @mousedown=${e=>{this.handleBackdropMouseDown(e)}}>
|
|
1980
2090
|
<section
|
|
1981
2091
|
role="dialog"
|
|
@@ -1997,7 +2107,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
1997
2107
|
${this.renderFooter()}
|
|
1998
2108
|
</section>
|
|
1999
2109
|
</div>
|
|
2000
|
-
`}renderTreeStep(){let e=
|
|
2110
|
+
`}renderTreeStep(){let e=kv(this.model,this.foldedIds);return g`
|
|
2001
2111
|
<div class="body tree-step">
|
|
2002
2112
|
<div class="tree-intro">
|
|
2003
2113
|
<p>Select where conversation context should continue. All retained branches stay in this session file.</p>
|
|
@@ -2016,7 +2126,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2016
2126
|
</div>
|
|
2017
2127
|
`}
|
|
2018
2128
|
</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`:``,
|
|
2129
|
+
`}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`:``,Uv(e.node.kind)?`bookkeeping`:``].filter(e=>e!==``).join(` `),i=Bv(e.branchDepth);return g`
|
|
2020
2130
|
<div
|
|
2021
2131
|
class=${r}
|
|
2022
2132
|
style=${`--tree-indent: ${String(i*16)}px; --tree-indent-mobile: ${String(i*12)}px;`}
|
|
@@ -2037,7 +2147,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2037
2147
|
@click=${t=>{this.toggleNode(e.node.id,t)}}
|
|
2038
2148
|
>${e.childIds.length===0?`·`:n?`▾`:`▸`}</span>
|
|
2039
2149
|
<span class="metadata">
|
|
2040
|
-
<span class="kind">${
|
|
2150
|
+
<span class="kind">${Hv(e.node.kind)}</span>
|
|
2041
2151
|
<span class="badges">
|
|
2042
2152
|
${e.activePath&&!e.activeLeaf?g`<span class="badge path">Active path</span>`:null}
|
|
2043
2153
|
${e.activeLeaf?g`<span class="badge leaf">Active leaf</span>`:null}
|
|
@@ -2049,7 +2159,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2049
2159
|
${e.node.timestamp===void 0?null:g`<time datetime=${e.node.timestamp}>${e.node.timestamp}</time>`}
|
|
2050
2160
|
</span>
|
|
2051
2161
|
</div>
|
|
2052
|
-
`}renderConfirmationStep(){let e=this.selectedId===void 0?void 0:this.model.nodesById.get(this.selectedId),t=
|
|
2162
|
+
`}renderConfirmationStep(){let e=this.selectedId===void 0?void 0:this.model.nodesById.get(this.selectedId),t=Nv(this.summaryMode,this.customInstructions);return g`
|
|
2053
2163
|
<div class="body confirmation-step">
|
|
2054
2164
|
<div class="confirmation-card">
|
|
2055
2165
|
<div>
|
|
@@ -2058,9 +2168,9 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2058
2168
|
</div>
|
|
2059
2169
|
${e===void 0?g`<div class="empty">The selected history entry is no longer available.</div>`:g`
|
|
2060
2170
|
<div class="selected-entry">
|
|
2061
|
-
<span class="kind">${
|
|
2171
|
+
<span class="kind">${Hv(e.kind)}</span>
|
|
2062
2172
|
<strong dir="auto">${e.summary}</strong>
|
|
2063
|
-
${
|
|
2173
|
+
${Vv(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
2174
|
</div>
|
|
2065
2175
|
`}
|
|
2066
2176
|
<fieldset ?disabled=${this.busy}>
|
|
@@ -2117,7 +2227,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2117
2227
|
${this.busy?e?`Summarizing…`:`Navigating…`:e?`Summarize and navigate`:`Navigate`}
|
|
2118
2228
|
</button>
|
|
2119
2229
|
</footer>
|
|
2120
|
-
`}resetTree(){this.operationGeneration+=1,this.model=
|
|
2230
|
+
`}resetTree(){this.operationGeneration+=1,this.model=Ov(this.tree),this.selectedId=Av(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=Mv(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=jv(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)||(Nv(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=Nv(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: ${Wv(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: ${Wv(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
2231
|
:host { position: fixed; inset: 0; z-index: 40; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
2122
2232
|
* { box-sizing: border-box; }
|
|
2123
2233
|
.backdrop { width: 100%; height: 100dvh; background: var(--pi-overlay); overflow: hidden; }
|
|
@@ -2210,7 +2320,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2210
2320
|
.custom-focus, .validation-error { margin-inline-start: 0; }
|
|
2211
2321
|
footer { flex-wrap: wrap; }
|
|
2212
2322
|
}
|
|
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`
|
|
2323
|
+
`}};B([x({attribute:!1})],zv.prototype,`tree`,void 0),B([x({attribute:!1})],zv.prototype,`onNavigate`,void 0),B([x({attribute:!1})],zv.prototype,`onAbort`,void 0),B([x({attribute:!1})],zv.prototype,`onCancel`,void 0),B([S()],zv.prototype,`selectedId`,void 0),B([S()],zv.prototype,`foldedIds`,void 0),B([S()],zv.prototype,`step`,void 0),B([S()],zv.prototype,`summaryMode`,void 0),B([S()],zv.prototype,`customInstructions`,void 0),B([S()],zv.prototype,`busy`,void 0),B([S()],zv.prototype,`aborting`,void 0),B([S()],zv.prototype,`error`,void 0),B([S()],zv.prototype,`statusMessage`,void 0),zv=B([b(`session-tree-navigator`)],zv);function Bv(e){return Math.min(Math.max(0,e),Rv)}function Vv(e){return e===`user`||e===`custom-message`}function Hv(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 Uv(e){return e===`model-change`||e===`thinking-level-change`||e===`session-info`||e===`label`||e===`custom`||e===`other`}function Wv(e){return e instanceof Error?e.message:String(e)}var Gv=`pi-webui:chat-groups:`,Kv={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(Jv(e));return t===null||t===``?void 0:Yv(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(Jv(e),JSON.stringify(t))}catch{}}},qv=class{constructor(e=Kv){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&&Zv(i,this.openGroupKeys)&&Zv(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 Jv(e){return`${Gv}${e}`}function Yv(e){if(Array.isArray(e))return{open:Xv(e),closedDefaultOpen:[]};if(Qv(e))return{open:Array.isArray(e.open)?Xv(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Xv(e.closedDefaultOpen):[]}}function Xv(e){return e.filter(e=>typeof e==`string`)}function Zv(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Qv(e){return typeof e==`object`&&!!e}function $v(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=>ry(e,t)),s=e.parts.filter(t=>!ry(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(ty(t)){let e=ny(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 ey(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 ty(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function ny(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function ry(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 iy(e,t=ay()){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 ay(){let e=e=>cy(e),t=sy();return t===void 0?{isSecureContext:oy(),fallbackWriteText:e}:{isSecureContext:oy(),writeText:t,fallbackWriteText:e}}function oy(){return typeof window<`u`&&window.isSecureContext}function sy(){if(!(typeof navigator>`u`||!(`clipboard`in navigator)))return navigator.clipboard.writeText.bind(navigator.clipboard)}function cy(e){if(typeof document>`u`)return!1;let t=document.activeElement,n=document.getSelection(),r=n===null?[]:ly(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(),uy(n,r),dy(t)}}function ly(e){let t=[];for(let n=0;n<e.rangeCount;n+=1)t.push(e.getRangeAt(n));return t}function uy(e,t){if(e!==null)try{e.removeAllRanges();for(let n of t)e.addRange(n)}catch{}}function dy(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))try{e.focus({preventScroll:!0})}catch{e.focus()}}function fy(e,t){let n=my(_y(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function py(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=hy(r,t.markerOffset);return}e.scrollTop=gy(e.scrollHeight,t.distanceFromBottom)}function my(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 hy(e,t){return e-t}function gy(e,t){return Math.max(0,e-t)}function _y(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 vy=600,yy=1;function by(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:xy(e)||Sy(e)}function xy(e){return e.scrollTop<(e.topThreshold??Math.max(vy,e.clientHeight))}function Sy(e){return e.scrollHeight<=e.clientHeight+yy}var Cy=`pi-webui:chat-scroll:`,wy=180,Ty=48,Ey=2,Dy={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)}},Oy={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},ky=class{constructor(e=Dy,t=Oy){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=wy){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=Ey){if(e===``||t===void 0||!My(t))return`skipped`;try{if(Py(t,r))return this.storage.setItem(Ay(e),JSON.stringify({mode:`bottom`})),`saved`;let i=Iy(t,n);if(i===void 0)return`skipped`;let a=Fy(t,i);return this.storage.setItem(Ay(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||!My(t))return{status:`skipped`};let i=Ry(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(Ay(e));if(t===null||t===``)return;let n=JSON.parse(t);return jy(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!My(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function Ay(e){return`${Cy}${e}`}function jy(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 My(e){return e.clientHeight>0&&e.scrollHeight>0}function Ny(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function Py(e,t=Ty){return Ny(e)<t}function Fy(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:zy(t)??``,offset:t.getBoundingClientRect().top-n}}function Iy(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(zy(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 Ly(e,t){let n=e.getBoundingClientRect();return t.find(e=>{let t=e.getBoundingClientRect();return t.bottom>=n.top&&t.top<=n.bottom})}function Ry(e,t){return e.find(e=>zy(e)===t)}function zy(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}function By(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{scrollRatio:i>0?Vy(r/i):0,viewportRatio:Vy(n/t),visible:!0}}function Vy(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):0}function Hy(e,t){return Vy(e*(1-t))}function Uy(e,t,n,r){return r<=0?0:Vy((e-t+n)/r)}var Wy=22,Gy=2;function Ky(e,t){if(e.length===0)return[];let n=Number.isFinite(t)?Math.max(0,t):0,r=Math.max(0,n-Wy),i=e.map((e,t)=>({index:t,desiredTop:Vy(e.topRatio)*n-Wy/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*Wy+(i.length-1)*Gy>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 qy(e){if(typeof e!=`object`||!e||!(`ratio`in e))return;let t=e.ratio;if(!(typeof t!=`number`||!Number.isFinite(t)))return Vy(t)}function Jy(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 Yy(e){return!Number.isFinite(e)||e===0?`$0`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function Xy(e){return!Number.isFinite(e)||e===0?`$0.0000`:`$${e.toFixed(4)}`}function Zy(e){return Number.isFinite(e)?Math.round(e).toLocaleString():`0`}function Qy(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 $y(e){let t=[],n=e.tokens;t.push(`Input: ${Zy(n.input)}`),t.push(`Output: ${Zy(n.output)}`),t.push(`Cache read: ${Zy(n.cacheRead)}`),t.push(`Cache write: ${Zy(n.cacheWrite)}`),t.push(`Total: ${Zy(n.total)}`),e.cost>0&&t.push(`Cost: ${Xy(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 ${Zy(r.contextWindow)} tokens`)}return t.join(` | `)}function eb(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 tb(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:Zy(e.messageCount)}):(i.push({label:`User`,value:Zy(n.user)}),i.push({label:`Assistant`,value:Zy(n.assistant)}),i.push({label:`Tool calls`,value:Zy(n.toolCalls)}),i.push({label:`Tool results`,value:Zy(n.toolResults)}),i.push({label:`Total`,value:Zy(n.total)}));let a=e.tokens,o=[{label:`Input`,value:Zy(a.input)},{label:`Output`,value:Zy(a.output)}];a.cacheRead>0&&o.push({label:`Cache read`,value:Zy(a.cacheRead)}),a.cacheWrite>0&&o.push({label:`Cache write`,value:Zy(a.cacheWrite)}),o.push({label:`Total`,value:Zy(a.total)}),e.cost>0&&o.push({label:`Cost`,value:Xy(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} / ${Qy(s.contextWindow)}`})}return{sessionRows:r,messageRows:i,tokenRows:o}}var nb=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=Vy((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=Vy((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=Vy(this._viewportTopRatio()+n);this._dispatchScroll(r)}}_viewportTopRatio(){return Hy(this.scrollRatio,this.viewportRatio)}_dispatchScroll(e){let t=Vy(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
2324
|
<div
|
|
2215
2325
|
class="rail"
|
|
2216
2326
|
role="scrollbar"
|
|
@@ -2244,7 +2354,7 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2244
2354
|
class=${`marker-dot${r?` user`:` assistant`}${n?` nearest`:``}`}
|
|
2245
2355
|
></div>
|
|
2246
2356
|
</div>
|
|
2247
|
-
`}_renderTooltips(){if(!this._hovered)return null;let e=
|
|
2357
|
+
`}_renderTooltips(){if(!this._hovered)return null;let e=Ky(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
2358
|
<div
|
|
2249
2359
|
class=${`tooltip ${t.role}${i?` nearest`:``}`}
|
|
2250
2360
|
style=${`top:${String(r)}px`}
|
|
@@ -2382,14 +2492,14 @@ This will delete every archived session on this machine regardless of age or cle
|
|
|
2382
2492
|
transition: none;
|
|
2383
2493
|
}
|
|
2384
2494
|
}
|
|
2385
|
-
`}};B([x({type:Number})],
|
|
2386
|
-
]`).replace(`lheading`,
|
|
2387
|
-
`),n=t.length-1;for(;n>=0&&
|
|
2388
|
-
`)}function
|
|
2495
|
+
`}};B([x({type:Number})],nb.prototype,`scrollRatio`,void 0),B([x({type:Number})],nb.prototype,`viewportRatio`,void 0),B([x({type:Boolean})],nb.prototype,`visible`,void 0),B([x({type:Number})],nb.prototype,`loadedPercent`,void 0),B([x({attribute:!1})],nb.prototype,`markers`,void 0),B([S()],nb.prototype,`_hovered`,void 0),B([S()],nb.prototype,`_nearestIndex`,void 0),B([C(`.rail`)],nb.prototype,`_rail`,void 0),nb=B([b(`chat-minimap`)],nb);var rb=class extends w_{constructor(e){if(super(e),this.it=v,e.type!==S_.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:[]}}};rb.directiveName=`unsafeHTML`,rb.resultType=1;var ib=C_(rb);function ab(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var ob=ab();function sb(e){ob=e}var cb={exec:()=>null};function lb(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 U(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(db.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var ub=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),db={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:lb(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:lb(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:lb(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:lb(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:lb(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:lb(e=>RegExp(`^ {0,${e}}>`))},fb=/^(?:[ \t]*(?:\n|$))+/,pb=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,mb=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,hb=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,gb=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,_b=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,vb=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,yb=U(vb).replace(/bull/g,_b).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(),bb=U(vb).replace(/bull/g,_b).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(),xb=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Sb=/^[^\n]+/,Cb=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,wb=U(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,Cb).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Tb=U(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,_b).getRegex(),Eb=`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`,Db=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ob=U(`^ {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`,Db).replace(`tag`,Eb).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),kb=e=>U(xb).replace(`hr`,hb).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`,Eb).getRegex(),Ab=kb(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),jb=kb(/ {0,3}(?:[*+-]|\d{1,9}[.)])[ \t]+[^ \t\n]/),Mb={blockquote:U(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,jb).getRegex(),code:pb,def:wb,fences:mb,heading:gb,hr:hb,html:Ob,lheading:yb,list:Tb,newline:fb,paragraph:Ab,table:cb,text:Sb},Nb=U(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,hb).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`,Eb).getRegex(),Pb={...Mb,lheading:bb,table:Nb,paragraph:U(xb).replace(`hr`,hb).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,Nb).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`,Eb).getRegex()},Fb={...Mb,html:U(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,Db).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:cb,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:U(xb).replace(`hr`,hb).replace(`heading`,` *#{1,6} *[^
|
|
2496
|
+
]`).replace(`lheading`,yb).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},Ib=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Lb=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Rb=/^( {2,}|\\)\n(?!\s*$)/,zb=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Bb=/[\p{P}\p{S}]/u,Vb=/[\s\p{P}\p{S}]/u,Hb=/[^\s\p{P}\p{S}]/u,Ub=U(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,Vb).getRegex(),Wb=/(?!~)[\p{P}\p{S}]/u,Gb=/(?!~)[\s\p{P}\p{S}]/u,Kb=/(?:[^\s\p{P}\p{S}]|~)/u,qb=U(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,ub?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),Jb=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Yb=U(Jb,`u`).replace(/punct/g,Bb).getRegex(),Xb=U(Jb,`u`).replace(/punct/g,Wb).getRegex(),Zb=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,Qb=U(Zb,`gu`).replace(/notPunctSpace/g,Hb).replace(/punctSpace/g,Vb).replace(/punct/g,Bb).getRegex(),$b=U(Zb,`gu`).replace(/notPunctSpace/g,Kb).replace(/punctSpace/g,Gb).replace(/punct/g,Wb).getRegex(),ex=U(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,Hb).replace(/punctSpace/g,Vb).replace(/punct/g,Bb).getRegex(),tx=U(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,Bb).getRegex(),nx=U(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Hb).replace(/punctSpace/g,Vb).replace(/punct/g,Bb).getRegex(),rx=U(/\\(punct)/,`gu`).replace(/punct/g,Bb).getRegex(),ix=U(/^<(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(),ax=U(Db).replace(`(?:-->|$)`,`-->`).getRegex(),ox=U(`^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`,ax).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),sx=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,cx=U(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,sx).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),lx=U(/^!?\[(label)\]\[(ref)\]/).replace(`label`,sx).replace(`ref`,Cb).getRegex(),ux=U(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,Cb).getRegex(),dx=U(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,lx).replace(`nolink`,ux).getRegex(),fx=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,px={_backpedal:cb,anyPunctuation:rx,autolink:ix,blockSkip:qb,br:Rb,code:Lb,del:cb,delLDelim:cb,delRDelim:cb,emStrongLDelim:Yb,emStrongRDelimAst:Qb,emStrongRDelimUnd:ex,escape:Ib,link:cx,nolink:ux,punctuation:Ub,reflink:lx,reflinkSearch:dx,tag:ox,text:zb,url:cb},mx={...px,link:U(/^!?\[(label)\]\((.*?)\)/).replace(`label`,sx).getRegex(),reflink:U(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,sx).getRegex()},hx={...px,emStrongRDelimAst:$b,emStrongLDelim:Xb,delLDelim:tx,delRDelim:nx,url:U(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,fx).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:U(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,fx).getRegex()},gx={...hx,br:U(Rb).replace(`{2,}`,`*`).getRegex(),text:U(hx.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},_x={normal:Mb,gfm:Pb,pedantic:Fb},vx={normal:px,gfm:hx,breaks:gx,pedantic:mx},yx={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},bx=e=>yx[e];function xx(e,t){if(t){if(db.escapeTest.test(e))return e.replace(db.escapeReplace,bx)}else if(db.escapeTestNoEncode.test(e))return e.replace(db.escapeReplaceNoEncode,bx);return e}function Sx(e){try{e=encodeURI(e).replace(db.percentDecode,`%`)}catch{return null}return e}function Cx(e,t){let n=e.replace(db.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(db.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(db.slashPipe,`|`);return n}function wx(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 Tx(e){let t=e.split(`
|
|
2497
|
+
`),n=t.length-1;for(;n>=0&&db.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
|
|
2498
|
+
`)}function Ex(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 Dx(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 Ox(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 kx(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
2389
2499
|
`).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=
|
|
2500
|
+
`)}var Ax=class{options;rules;lexer;constructor(e){this.options=e||ob}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]:Tx(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=kx(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=wx(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:wx(t[0],`
|
|
2501
|
+
`),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:wx(t[0],`
|
|
2502
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=wx(t[0],`
|
|
2393
2503
|
`).split(`
|
|
2394
2504
|
`),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
2505
|
`),c=s.replace(this.rules.other.blockquoteSetextReplace,`
|
|
@@ -2400,20 +2510,20 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
2400
2510
|
`),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
2511
|
`+e.join(`
|
|
2402
2512
|
`),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=
|
|
2513
|
+
`);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=Dx(t[2].split(`
|
|
2404
2514
|
`,1)[0],t[1].length),l=e.split(`
|
|
2405
2515
|
`,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
2516
|
`,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
2517
|
`,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
2518
|
`+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
2519
|
`+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(
|
|
2520
|
+
`,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=Tx(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:wx(t[0],`
|
|
2521
|
+
`),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(`
|
|
2522
|
+
`):[],a={type:`table`,raw:wx(t[0],`
|
|
2523
|
+
`),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:wx(t[0],`
|
|
2414
2524
|
`),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(
|
|
2525
|
+
`?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=wx(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=Ex(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)),Ox(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 Ox(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}}}},jx=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||ob,this.options.tokenizer=this.options.tokenizer||new Ax,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:db,block:_x.normal,inline:vx.normal};this.options.pedantic?(t.block=_x.pedantic,t.inline=vx.pedantic):this.options.gfm&&(t.block=_x.gfm,this.options.breaks?t.inline=vx.breaks:t.inline=vx.gfm),this.tokenizer.rules=t}static get rules(){return{block:_x,inline:vx}}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(db.carriageReturn,`
|
|
2526
|
+
`),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(db.tabCharGlobal,` `).replace(db.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
2527
|
`: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
2528
|
`)?``:`
|
|
2419
2529
|
`)+i.raw,n.text+=`
|
|
@@ -2426,9 +2536,9 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
2426
2536
|
`+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
2537
|
`)?``:`
|
|
2428
2538
|
`)+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:
|
|
2539
|
+
`+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)}},Mx=class{options;parser;constructor(e){this.options=e||ob}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(db.notSpaceStart)?.[0],i=e.replace(db.endingNewline,``)+`
|
|
2540
|
+
`;return r?`<pre><code class="language-`+xx(r)+`">`+(n?i:xx(i,!0))+`</code></pre>
|
|
2541
|
+
`:`<pre><code>`+(n?i:xx(i,!0))+`</code></pre>
|
|
2432
2542
|
`}blockquote({tokens:e}){return`<blockquote>
|
|
2433
2543
|
${this.parser.parse(e)}</blockquote>
|
|
2434
2544
|
`}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
@@ -2444,19 +2554,19 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
2444
2554
|
`}tablerow({text:e}){return`<tr>
|
|
2445
2555
|
${e}</tr>
|
|
2446
2556
|
`}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>`+
|
|
2557
|
+
`}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>${xx(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="`+xx(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 xx(n);e=i;let a=`<img src="${e}" alt="${xx(n)}"`;return t&&(a+=` title="${xx(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:xx(e.text)}},Nx=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}},Px=class e{options;renderer;textRenderer;constructor(e){this.options=e||ob,this.options.renderer=this.options.renderer||new Mx,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Nx}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}},Fx=class{options;block;constructor(e){this.options=e||ob}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?jx.lex:jx.lexInline}provideParser(e=this.block){return e?Px.parse:Px.parseInline}},Ix=new class{defaults=ab();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Px;Renderer=Mx;TextRenderer=Nx;Lexer=jx;Tokenizer=Ax;Hooks=Fx;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 Mx(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 Ax(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 Fx;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];Fx.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&Fx.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 jx.lex(e,t??this.defaults)}parser(e,t){return Px.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?jx.lex:jx.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?Px.parse:Px.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?jx.lex:jx.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?Px.parse:Px.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+=`
|
|
2558
|
+
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+xx(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function W(e,t){return Ix.parse(e,t)}W.options=W.setOptions=function(e){return Ix.setOptions(e),W.defaults=Ix.defaults,sb(W.defaults),W},W.getDefaults=ab,W.defaults=ob,W.use=function(...e){return Ix.use(...e),W.defaults=Ix.defaults,sb(W.defaults),W},W.walkTokens=function(e,t){return Ix.walkTokens(e,t)},W.parseInline=Ix.parseInline,W.Parser=Px,W.parser=Px.parse,W.Renderer=Mx,W.TextRenderer=Nx,W.Lexer=jx,W.lexer=jx.lex,W.Tokenizer=Ax,W.Hooks=Fx,W.parse=W,W.options,W.setOptions,W.use,W.walkTokens,W.parseInline,Px.parse,jx.lex;var Lx=new W.Renderer;Lx.html=({text:e})=>Vx(e);var Rx=300,zx=new Map;function Bx(e){let t=zx.get(e);if(t!==void 0)return t;let n=Hx(W.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:Lx}));if(zx.set(e,n),zx.size>Rx){let e=zx.keys().next().value;e!==void 0&&zx.delete(e)}return n}function Vx(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}function Hx(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`)&&!Ux(t.value)&&e.removeAttribute(t.name)}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),t.innerHTML}function Ux(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}var Wx=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}>${ib(Bx(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 iy(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()],Wx.prototype,`text`,void 0),Wx=B([b(`formatted-text`)],Wx);var Gx=180,Kx=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=Jx(e.args),n=Xx(e.details),r=e.preview,i=n??r?.diff,a=i===void 0?void 0:Zx(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=qx(e,t);return g`
|
|
2449
2559
|
<section class=${`tool-card ${e.status}`}>
|
|
2450
2560
|
<div class="tool-header">
|
|
2451
2561
|
<div class="tool-title">
|
|
2452
|
-
<span class="status-icon" aria-hidden="true">${
|
|
2562
|
+
<span class="status-icon" aria-hidden="true">${tS(e.status)}</span>
|
|
2453
2563
|
<strong>${e.toolName}</strong>
|
|
2454
2564
|
${this.renderHeaderTarget(l)}
|
|
2455
2565
|
</div>
|
|
2456
2566
|
<div class="tool-meta">
|
|
2457
|
-
${
|
|
2567
|
+
${Yx(e)===void 0?null:g`<span>${Yx(e)}</span>`}
|
|
2458
2568
|
${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">${
|
|
2569
|
+
<span class="status-label">${nS(e.status)}</span>
|
|
2460
2570
|
</div>
|
|
2461
2571
|
</div>
|
|
2462
2572
|
|
|
@@ -2481,7 +2591,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2481
2591
|
`}
|
|
2482
2592
|
</details>
|
|
2483
2593
|
`}renderDiffBody(e,t,n){let r=e.split(`
|
|
2484
|
-
`),i=!this.showFullDiff&&r.length>
|
|
2594
|
+
`),i=!this.showFullDiff&&r.length>Gx,a=i?r.slice(0,Gx):r;return g`
|
|
2485
2595
|
<details class="diff-details" ?open=${this.diffOpen} @toggle=${e=>{this.onDiffToggle(e)}}>
|
|
2486
2596
|
<summary>
|
|
2487
2597
|
<span>${t}</span>
|
|
@@ -2492,14 +2602,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2492
2602
|
<span>${i?`Showing ${String(a.length)} of ${String(r.length)} lines`:`Full diff`}</span>
|
|
2493
2603
|
<button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?`Copied`:`Copy diff`}</button>
|
|
2494
2604
|
</div>
|
|
2495
|
-
<pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${
|
|
2605
|
+
<pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${Qx(e)}>${e}</span>`)}</code></pre>
|
|
2496
2606
|
${i?g`
|
|
2497
2607
|
<button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
|
|
2498
2608
|
Show all ${String(r.length)} diff lines
|
|
2499
2609
|
</button>
|
|
2500
2610
|
`:null}
|
|
2501
2611
|
</details>
|
|
2502
|
-
`}onDiffToggle(e){let t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){if(!await
|
|
2612
|
+
`}onDiffToggle(e){let t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){if(!await iy(e)){this.copied=!1;return}this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}static{this.styles=h`
|
|
2503
2613
|
:host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
|
|
2504
2614
|
.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
2615
|
.tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
|
|
@@ -2543,25 +2653,25 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2543
2653
|
.diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
|
|
2544
2654
|
.diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
|
|
2545
2655
|
.show-more { justify-self: start; }
|
|
2546
|
-
`}};B([x({attribute:!1})],
|
|
2547
|
-
`))
|
|
2656
|
+
`}};B([x({attribute:!1})],Kx.prototype,`execution`,void 0),B([S()],Kx.prototype,`showFullDiff`,void 0),B([S()],Kx.prototype,`copied`,void 0),B([S()],Kx.prototype,`diffOpen`,void 0),Kx=B([b(`tool-execution-view`)],Kx);function qx(e,t){if(t!==void 0&&t!==``)return{label:`File`,text:t};let n=aS(e.args,`command`);if(n!==void 0&&n!==``)return{label:`Command`,text:n};if(e.summary!==``)return{label:`Input`,text:e.summary}}function Jx(e){return aS(e,`path`)??aS(e,`file_path`)}function Yx(e){if(e.toolName!==`edit`)return;let t=iS(e.args,`edits`);if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?``:`s`}`;if(typeof iS(e.args,`oldText`)==`string`&&typeof iS(e.args,`newText`)==`string`)return`1 edit`}function Xx(e){return aS(e,`diff`)}function Zx(e){let t=0,n=0;for(let r of e.split(`
|
|
2657
|
+
`))$x(r)?t++:eS(r)&&n++;return{added:t,removed:n}}function Qx(e){return $x(e)?`added`:eS(e)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`+++`)||e.startsWith(`---`)?`file`:e.startsWith(`diff `)||e.startsWith(`index `)?`meta`:`context`}function $x(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)}function eS(e){return e.startsWith(`-`)&&!e.startsWith(`---`)}function tS(e){return e===`success`?`✓`:e===`error`?`✖`:e===`running`?`●`:`○`}function nS(e){return e===`success`?`done`:e===`error`?`failed`:e===`running`?`running`:`pending`}function rS(e){return typeof e==`object`&&!!e}function iS(e,t){return rS(e)?e[t]:void 0}function aS(e,t){let n=iS(e,t);return typeof n==`string`?n:void 0}var oS=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`medium`}),sS=new Intl.DateTimeFormat(void 0,{timeStyle:`short`});function cS(e){return g`
|
|
2548
2658
|
<svg class=${`notification-icon notification-disclosure-icon${e?``:` expanded`}`} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2549
2659
|
<path d="m9 18 6-6-6-6"></path>
|
|
2550
2660
|
</svg>
|
|
2551
|
-
`}function
|
|
2661
|
+
`}function lS(){return g`
|
|
2552
2662
|
<svg class="notification-icon notification-close-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2553
2663
|
<path d="M6 6l12 12"></path>
|
|
2554
2664
|
<path d="M18 6 6 18"></path>
|
|
2555
2665
|
</svg>
|
|
2556
|
-
`}function
|
|
2557
|
-
`)}function
|
|
2666
|
+
`}function uS(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 dS(e){return fS(e,0,100)}function fS(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function pS(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 mS(e){return{src:`data:${e.mimeType};base64,${e.data}`,alt:`attached image`}}function hS(e){return e===void 0||e===``?`tool output`:`${e} output`}function gS(e){return`m:${String(e)}`}function _S(e){return`g:${String(e)}`}function vS(e){return`e:${String(e)}`}function yS(e){return`g:${String(e)}`}function bS(e){return e?`msg event-group live`:`msg event-group`}function xS(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 wS(e){return e>=50?`generation-rate very-fast`:e>=30?`generation-rate fast`:e>=15?`generation-rate moderate`:`generation-rate slow`}function TS(e){if(e===void 0)return{afterStatus:[],trailing:[]};let t=e.contextUsage,n=t?t.percent==null?`context ${Jy(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Jy(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:`↓ ${Jy(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:wS(r.tokensPerSecond)}]],trailing:[{label:`Input tokens`,text:`↑${Jy(e.tokens.input)}`},{label:`Output tokens`,text:`↓${Jy(e.tokens.output)}`},{label:`Context usage`,text:n},{label:`Session cost`,text:Yy(e.cost)},...e.pendingMessageCount>0?[{label:`Queued messages`,text:`${String(e.pendingMessageCount)} queued`}]:[]]}}function ES(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 DS(e){let t=e.meta?.timestamp,n=[t===void 0?void 0:AS(t),jS(e)].filter(e=>e!==void 0&&e!==``);return n.length===0?`No Pi message metadata available`:n.join(` · `)}function OS(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 kS(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2667
|
+
`)}function AS(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return oS.format(t)}function jS(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 G=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 qv,this.scrollController=new ky,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!uS(e)||t===void 0?e!==t:hd(e)!==hd(t)}render(){let e=this.groupedMessages();return g`
|
|
2558
2668
|
${this.renderTopNotices()}
|
|
2559
2669
|
${this.renderNotificationLiveRegions()}
|
|
2560
|
-
<div class="chat-wrap" style=${this._minimapViewport.visible?`--pi-minimap-right:36px`:``}>
|
|
2670
|
+
<div class="chat-wrap" style=${this._minimapViewport.visible&&this.messages.length>0&&this.messageTotal>0?`--pi-minimap-right:36px`:``}>
|
|
2561
2671
|
${this.renderConversationRail()}
|
|
2562
2672
|
<div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${e=>{this.onWheel(e)}} @touchstart=${e=>{this.onTouchStart(e)}} @touchmove=${e=>{this.onTouchMove(e)}}>
|
|
2563
2673
|
${this.renderHistoryBoundary()}
|
|
2564
|
-
${
|
|
2674
|
+
${F_(e,e=>e.kind===`group`?this.groupRenderKey(e.startIndex):this.messageAnchorKey(e.index),(t,n)=>t.kind===`group`?this.renderMessageGroup(t.messages,t.startIndex,t.endIndex,this.isLiveTailGroup(e,n)):t.kind===`tool-image`?this.renderToolImageOutput(t.message,t.index,t.toolName):this.renderMessage(t.message,t.index))}
|
|
2565
2675
|
${this.renderQueuedMessages()}
|
|
2566
2676
|
${this.renderSessionActivity()}
|
|
2567
2677
|
</div>
|
|
@@ -2589,7 +2699,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2589
2699
|
aria-expanded=${String(!a)}
|
|
2590
2700
|
aria-controls="session-notification-list"
|
|
2591
2701
|
@click=${()=>{this.toggleNotificationTray(e,a)}}
|
|
2592
|
-
>${
|
|
2702
|
+
>${cS(a)}</button>
|
|
2593
2703
|
</div>
|
|
2594
2704
|
</header>
|
|
2595
2705
|
<div class="notification-list" id="session-notification-list" ?hidden=${a}>
|
|
@@ -2601,7 +2711,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2601
2711
|
<div class="notification-metadata">
|
|
2602
2712
|
<strong class="notification-severity">${n}</strong>
|
|
2603
2713
|
<span aria-hidden="true">·</span>
|
|
2604
|
-
<time datetime=${t.receivedAt}>${
|
|
2714
|
+
<time datetime=${t.receivedAt}>${sS.format(new Date(t.receivedAt))}</time>
|
|
2605
2715
|
</div>
|
|
2606
2716
|
<p class="notification-message" dir="auto">${t.message}</p>
|
|
2607
2717
|
${r===void 0?null:g`<p class="notification-truncated">${r}</p>`}
|
|
@@ -2612,15 +2722,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2612
2722
|
title="Dismiss notification"
|
|
2613
2723
|
?disabled=${e.pendingDismissedIds.has(t.id)||e.dismissAllPending||this.onDismissNotification===void 0}
|
|
2614
2724
|
@click=${()=>{this.dismissNotification(t.id)}}
|
|
2615
|
-
>${
|
|
2725
|
+
>${lS()}</button>
|
|
2616
2726
|
</article>
|
|
2617
2727
|
`})}
|
|
2618
2728
|
</div>
|
|
2619
2729
|
</section>
|
|
2620
2730
|
`}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
|
-
<div class="visually-hidden notification-live" aria-live="polite" aria-atomic="false">${
|
|
2622
|
-
<div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${
|
|
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=
|
|
2731
|
+
<div class="visually-hidden notification-live" aria-live="polite" aria-atomic="false">${F_(t,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${ud(e)}</span>`)}</div>
|
|
2732
|
+
<div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${F_(n,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${ud(e)}</span>`)}</div>
|
|
2733
|
+
`}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
2734
|
<aside class="session-warnings" role="alert" aria-live="polite">
|
|
2625
2735
|
${e.map(e=>{let t=e.dismissId;return g`
|
|
2626
2736
|
<div class=${e.severityClass}>
|
|
@@ -2644,7 +2754,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2644
2754
|
</div>
|
|
2645
2755
|
`})}
|
|
2646
2756
|
</aside>
|
|
2647
|
-
`}renderSessionInfoPopover(){if(!this.sessionInfoOpen)return null;let e=this.status;if(e===void 0)return null;let t=this.messages.length>0?
|
|
2757
|
+
`}renderSessionInfoPopover(){if(!this.sessionInfoOpen)return null;let e=this.status;if(e===void 0)return null;let t=this.messages.length>0?eb(this.messages):void 0,n=tb(e,this.sessionInfo,t);return g`
|
|
2648
2758
|
<section
|
|
2649
2759
|
class="session-info-popover"
|
|
2650
2760
|
id=${`session-info-popover-${this.sessionId}`}
|
|
@@ -2694,14 +2804,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2694
2804
|
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
|
|
2695
2805
|
</svg>
|
|
2696
2806
|
</button>
|
|
2697
|
-
`}async copySessionValue(e){await
|
|
2807
|
+
`}async copySessionValue(e){await iy(e)}renderImageZoom(){return g`
|
|
2698
2808
|
<dialog class="image-zoom" @click=${this.onImageZoomDialogClick} @close=${this.closeImageZoom} @cancel=${this.closeImageZoom}>
|
|
2699
2809
|
${this.zoomedImage===void 0?null:g`
|
|
2700
2810
|
<button type="button" class="image-zoom-close" aria-label="Close image" @click=${this.closeImageZoom}>×</button>
|
|
2701
2811
|
<img class="image-zoom-full" src=${this.zoomedImage.src} alt=${this.zoomedImage.alt} />
|
|
2702
2812
|
`}
|
|
2703
2813
|
</dialog>
|
|
2704
|
-
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache
|
|
2814
|
+
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=$v(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=TS(this.status),r=ES(this.warningCount,this.warningsExpanded),i=n.trailing.length>0,a=this.status?$y(this.status):``,o=i?`session-info-popover-${this.sessionId}`:void 0;return g`
|
|
2705
2815
|
<div class=${t?`activity-dock active`:`activity-dock`}>
|
|
2706
2816
|
${r===void 0||this.onToggleWarnings===void 0?null:g`
|
|
2707
2817
|
<button
|
|
@@ -2744,7 +2854,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2744
2854
|
`:null}
|
|
2745
2855
|
${this.renderSessionInfoPopover()}
|
|
2746
2856
|
</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`${
|
|
2857
|
+
`}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`${pS(this.clientQueuedMessages,e).map(e=>this.renderQueuedMessageList(e))}`}renderQueuedMessageList(e){let t=SS(e,this.canClearServerQueue,this.onClearServerQueue!==void 0);return g`
|
|
2748
2858
|
<aside class="queued-messages" aria-live="polite">
|
|
2749
2859
|
<div class="queued-header">
|
|
2750
2860
|
<div class="queued-heading">
|
|
@@ -2768,7 +2878,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2768
2878
|
<span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
|
|
2769
2879
|
${this.pendingMessageCount>0?g`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?`message`:`messages`}</small>`:null}
|
|
2770
2880
|
</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?
|
|
2881
|
+
`: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?dS(this.messages.length/this.conversationDisplayTotal()*100):100,g`
|
|
2772
2882
|
<chat-minimap
|
|
2773
2883
|
.scrollRatio=${this._minimapViewport.scrollRatio}
|
|
2774
2884
|
.viewportRatio=${this._minimapViewport.viewportRatio}
|
|
@@ -2777,7 +2887,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2777
2887
|
.markers=${this._minimapMarkers}
|
|
2778
2888
|
@minimap-scroll-to=${e=>{this._onMinimapScrollTo(e)}}
|
|
2779
2889
|
></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
|
|
2890
|
+
`)}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 dS(fS(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
2891
|
<div class="history-boundary">
|
|
2782
2892
|
<button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>Load earlier messages</button>
|
|
2783
2893
|
<span>Scroll up to load earlier messages</span>
|
|
@@ -2789,7 +2899,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2789
2899
|
${n?null:this.renderMessageHeader(e,String(t))}
|
|
2790
2900
|
${e.parts.map(t=>this.renderPart(t,e))}
|
|
2791
2901
|
</article>
|
|
2792
|
-
`}renderToolImageOutput(e,t,n){let r=
|
|
2902
|
+
`}renderToolImageOutput(e,t,n){let r=hS(n);return g`
|
|
2793
2903
|
${this.renderScrollMarker(this.messageScrollMarkerId(t))}
|
|
2794
2904
|
<article class="msg tool-image-output" data-index=${t} data-scroll-anchor-id=${this.messageAnchorKey(t)}>
|
|
2795
2905
|
${this.renderMessageHeader(e,String(t),r)}
|
|
@@ -2797,10 +2907,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2797
2907
|
</article>
|
|
2798
2908
|
`}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
2909
|
${this.renderScrollMarker(this.groupScrollMarkerId(n))}
|
|
2800
|
-
<details class=${
|
|
2910
|
+
<details class=${bS(r)} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${a} @toggle=${e=>{this.onGroupToggle(i,e,r)}}>
|
|
2801
2911
|
<summary>
|
|
2802
|
-
<b class="label">${
|
|
2803
|
-
<span>${
|
|
2912
|
+
<b class="label">${xS(r)}</b>
|
|
2913
|
+
<span>${ey(e)}</span>
|
|
2804
2914
|
</summary>
|
|
2805
2915
|
${a?this.renderMessageGroupBody(e,t):null}
|
|
2806
2916
|
</details>
|
|
@@ -2821,7 +2931,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2821
2931
|
<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
2932
|
</div>
|
|
2823
2933
|
</div>
|
|
2824
|
-
`}renderMessageActions(e,t){let n=this.isCopyableMessage(e),r=
|
|
2934
|
+
`}renderMessageActions(e,t){let n=this.isCopyableMessage(e),r=OS(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
2935
|
<div class=${`msg-actions${s?` forking`:``}`} aria-label="Message actions">
|
|
2826
2936
|
${n?g`
|
|
2827
2937
|
<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 +2939,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2829
2939
|
</button>
|
|
2830
2940
|
`:null}
|
|
2831
2941
|
${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,
|
|
2942
|
+
<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,kS(e))}}>
|
|
2833
2943
|
<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
2944
|
<polyline points="15 10 20 15 15 20"></polyline>
|
|
2835
2945
|
<path d="M4 4v7a4 4 0 0 0 4 4h12"></path>
|
|
@@ -2851,7 +2961,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2851
2961
|
</div>
|
|
2852
2962
|
`}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
2963
|
|
|
2854
|
-
`);return this.messageCopyTextCache.set(e,n),n}async copyMessage(e,t,n){n.stopPropagation(),await
|
|
2964
|
+
`);return this.messageCopyTextCache.set(e,n),n}async copyMessage(e,t,n){n.stopPropagation(),await iy(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=DS(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
2965
|
<details class="part skill-invocation">
|
|
2856
2966
|
<summary><b>[skill]</b> ${e.name}</summary>
|
|
2857
2967
|
<small>${e.location}</small>
|
|
@@ -2862,58 +2972,58 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2862
2972
|
<strong>Loaded ${e.name}</strong>
|
|
2863
2973
|
<small>read ${e.path}</small>
|
|
2864
2974
|
</div>
|
|
2865
|
-
`;if(e.type===`image`){let{src:t,alt:n}
|
|
2975
|
+
`;if(e.type===`image`){let{src:t,alt:n}=mS(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
2976
|
<details class="part" ?open=${e.isError}>
|
|
2867
2977
|
<summary>${e.isError?`✖`:`✓`} ${e.toolName} result</summary>
|
|
2868
2978
|
<formatted-text .text=${e.text}></formatted-text>
|
|
2869
2979
|
</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&&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 _`
|
|
2980
|
+
`: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&&by({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||Py(e)}isAtBottom(){let e=this.chat;return!e||Ny(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 fy(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(py(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=fS(n,0,Math.max(0,e-1));return}this.currentConversationIndex=fS(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 Ly(e,Array.from(this.renderRoot.querySelectorAll(`article.msg`)))??Ly(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 gS(e)}groupRenderKey(e){return _S(e)}groupAnchorKey(e){return _S(e)}eventAnchorKey(e){return vS(e)}messageScrollMarkerId(e){return gS(e)}groupScrollMarkerId(e){return yS(e)}_updateMinimapViewport(){let e=this.chat;e&&(this._minimapViewport=By({scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,scrollTop:e.scrollTop}),this._minimapLoadedPercent=this.hasMore?dS(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=Uy(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=qy(e.detail);if(t===void 0)return;let n=this.chat;if(!n)return;let r=n.scrollHeight-n.clientHeight;r<=0||(n.scrollTop=Vy(t/(1-this._minimapViewport.viewportRatio))*r,this.pinnedToBottom=Py(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 MS=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function NS(e){return typeof e==`string`&&MS.has(e)}function PS(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 FS=`application/octet-stream`,IS=`Failed to read an attachment.`;async function LS(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(VS(i,e))}catch{r=IS}return{attachments:n,...r===void 0?{}:{error:r}}}function RS(e){return e.kind===`image`&&NS(e.mimeType)}function zS(e){return e.every(e=>RS(e))}function BS(e,t){return zS(t)?e:`folder`}function VS(e,t){return NS(e.type)?{kind:`image`,name:US(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:US(e),mimeType:HS(e),data:t,size:e.size}}function HS(e){let t=e.type.trim();return t===``?FS:t}function US(e){return e.name===``?NS(e.type)?`pasted-image.${PS(e.type)}`:`pasted-file.bin`:e.name}var WS=`pi-webui:attachment-delivery`;function GS(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function KS(e=GS()){try{return e?.getItem(WS)===`folder`?`folder`:`inline`}catch{return`inline`}}function qS(e,t=GS()){try{t?.setItem(WS,e)}catch{}}var JS=`(pointer: coarse), (max-width: 760px)`,YS=`pi-webui.promptEnterPreference`;function XS(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(JS):void 0}function ZS(e){return e===`send`||e===`newline`?e:`auto`}function QS(e=rC()){if(e===void 0)return`auto`;try{return ZS(e.getItem(YS))}catch{return`auto`}}function $S(e,t=rC()){if(t!==void 0)try{t.setItem(YS,e)}catch{}}function eC(e=XS(),t=QS()){return t===`send`||t!==`newline`&&e?.matches!==!0}function tC(e,t,n=XS()){return e?n?.matches!==!0||t:!1}function nC(e,t=XS(),n=QS()){let r=eC(t,n);return e?!r:r}function rC(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function iC(){return _`
|
|
2871
2981
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2872
2982
|
<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
2983
|
</svg>
|
|
2874
|
-
`}function
|
|
2984
|
+
`}function aC(){return _`
|
|
2875
2985
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2876
2986
|
<polyline points="4 14 10 14 10 20"></polyline>
|
|
2877
2987
|
<polyline points="20 10 14 10 14 4"></polyline>
|
|
2878
2988
|
<line x1="10" y1="14" x2="3" y2="21"></line>
|
|
2879
2989
|
<line x1="21" y1="3" x2="14" y2="10"></line>
|
|
2880
2990
|
</svg>
|
|
2881
|
-
`}function
|
|
2991
|
+
`}function oC(){return _`
|
|
2882
2992
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2883
2993
|
<path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
|
|
2884
2994
|
<path d="M21 3 11.5 12.5"></path>
|
|
2885
2995
|
</svg>
|
|
2886
|
-
`}function
|
|
2996
|
+
`}function sC(){return _`
|
|
2887
2997
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2888
2998
|
<path d="M4 7h11"></path>
|
|
2889
2999
|
<path d="M4 12h7"></path>
|
|
2890
3000
|
<path d="M4 17h7"></path>
|
|
2891
3001
|
<path d="m15 14 5 3-5 3z"></path>
|
|
2892
3002
|
</svg>
|
|
2893
|
-
`}function
|
|
3003
|
+
`}function cC(){return oC()}function lC(){return _`
|
|
2894
3004
|
<svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2895
3005
|
<rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
|
|
2896
3006
|
</svg>
|
|
2897
|
-
`}function
|
|
3007
|
+
`}function uC(e){let t=Math.max(e.total,1),n=t>1?1.2:0,r=(18-n*(t-1))/t;return _`
|
|
2898
3008
|
<svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2899
3009
|
${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
3010
|
</svg>
|
|
2901
|
-
`}var
|
|
3011
|
+
`}var dC=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function fC(e){return e===void 0||e===``?`off`:e}function pC(e,t){let n=t.length>=2?t:dC,r=n.length-1,i=fC(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}var mC=C_(class extends w_{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===S_.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){}}),hC=class extends y{constructor(...e){super(...e),this.items=[],this.selectedIndex=0}render(){return this.items.length?g`
|
|
2902
3012
|
<div class="menu">
|
|
2903
3013
|
${this.items.map((e,t)=>g`
|
|
2904
|
-
<button class=${t===this.selectedIndex?`selected`:``} ${
|
|
3014
|
+
<button class=${t===this.selectedIndex?`selected`:``} ${mC(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
|
|
2905
3015
|
<strong>${e.insertText}</strong>
|
|
2906
3016
|
<span>${e.detail}</span>
|
|
2907
3017
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
2908
3018
|
</button>
|
|
2909
3019
|
`)}
|
|
2910
3020
|
</div>
|
|
2911
|
-
`:null}static{this.styles=Xp}};B([x({attribute:!1})],
|
|
3021
|
+
`:null}static{this.styles=Xp}};B([x({attribute:!1})],hC.prototype,`items`,void 0),B([x({type:Number})],hC.prototype,`selectedIndex`,void 0),B([x({attribute:!1})],hC.prototype,`onPick`,void 0),hC=B([b(`autocomplete-menu`)],hC);var K=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=KS(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new s,this.readOnlyCompartment=new s,this.mobilePromptEnterMedia=XS(),this.explicitShiftKeyActive=!1}willUpdate(e){if(!e.has(`sessionId`)&&!e.has(`machineId`))return;let t=e.has(`sessionId`)?e.get(`sessionId`):this.sessionId,n=_C(e.has(`machineId`)?e.get(`machineId`):this.machineId,t);n!==void 0&&Vc(n,this.draft);let r=_C(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?!gC(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
3022
|
<footer class=${t?`shell-mode`:``} @paste=${e=>{this.handlePaste(e)}} @dragover=${e=>{this.handleDragOver(e)}} @drop=${e=>{this.handleDrop(e)}}>
|
|
2913
3023
|
<div class="editor-wrap">
|
|
2914
3024
|
<div class=${`markdown-editor${this.disabled?` markdown-editor-disabled`:``}`} aria-label="Message pi" aria-disabled=${this.disabled?`true`:`false`}></div>
|
|
2915
3025
|
<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()}}>${
|
|
3026
|
+
<button class="editor-attach icon-button" ?disabled=${r} title="Attach files" aria-label="Attach files" @click=${()=>{this.attachmentInput?.click()}}>${iC()}</button>
|
|
2917
3027
|
${t?g`<div class="mode-hint">Shell command${e.excludeFromContext?` · excluded from context`:``}</div>`:null}
|
|
2918
3028
|
${this.isCompacting&&!t?g`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
|
|
2919
3029
|
${this.renderAttachments()}
|
|
@@ -2921,21 +3031,21 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2921
3031
|
</div>
|
|
2922
3032
|
<div class="actions">
|
|
2923
3033
|
${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?.()}>${
|
|
3034
|
+
${this.onCompact===void 0?null:g`<button class="compact-button" ?disabled=${i} title="Compact context" aria-label="Compact context" @click=${()=>this.onCompact?.()}>${aC()}<span>Compact</span></button>`}
|
|
3035
|
+
<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?sC():oC()}</button>
|
|
3036
|
+
${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`)}}>${cC()}</button>`:null}
|
|
3037
|
+
<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?.()}>${lC()}</button>
|
|
2928
3038
|
</div>
|
|
2929
3039
|
</footer>
|
|
2930
|
-
`}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=
|
|
3040
|
+
`}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=_C(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: ${fC(t?.thinkingLevel)}`:`Thinking level: ${fC(t?.thinkingLevel)}`;return g`
|
|
2931
3041
|
<div class="compact-status" aria-label=${e?`Session defaults`:`Session status`}>
|
|
2932
3042
|
<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?.()}>${
|
|
3043
|
+
<button class="select-thinking icon-button" ?disabled=${this.onSelectThinking===void 0} title=${i} aria-label=${i} @click=${()=>this.onSelectThinking?.()}>${uC(pC(t?.thinkingLevel,this.availableThinkingLevels))}</button>
|
|
2934
3044
|
</div>
|
|
2935
|
-
`}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=
|
|
3045
|
+
`}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=zS(this.attachments),t=this.effectiveAttachmentDelivery();return g`
|
|
2936
3046
|
<div class="attachments" aria-label="Pending attachments">
|
|
2937
3047
|
${this.attachments.map(e=>g`
|
|
2938
|
-
<div class=${`attachment-chip ${
|
|
3048
|
+
<div class=${`attachment-chip ${RS(e)?`attachment-chip-image`:`attachment-chip-file`}`} title=${e.name}>
|
|
2939
3049
|
${this.renderAttachmentPreview(e)}
|
|
2940
3050
|
<button type="button" class="attachment-remove" title="Remove attachment" aria-label=${`Remove ${e.name}`} @click=${()=>{this.removeAttachment(e.id)}}>×</button>
|
|
2941
3051
|
</div>
|
|
@@ -2950,10 +3060,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2950
3060
|
`:null}
|
|
2951
3061
|
${this.attachmentError===void 0?null:g`<div class="attachment-error">${this.attachmentError}</div>`}
|
|
2952
3062
|
</div>
|
|
2953
|
-
`}renderAttachmentPreview(e){return
|
|
2954
|
-
<div class="attachment-file-preview" aria-hidden="true">${
|
|
3063
|
+
`}renderAttachmentPreview(e){return RS(e)?g`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:g`
|
|
3064
|
+
<div class="attachment-file-preview" aria-hidden="true">${CC(e.name)}</div>
|
|
2955
3065
|
<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`&&!
|
|
3066
|
+
`}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;if(t===`inline`&&!zS(this.attachments)){e.target.value=`folder`;return}this.attachmentDelivery=t,qS(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){let t=bC(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&xC(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=bC(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 LS(e,wC);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 BS(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=>DC(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=_C(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(vC);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(yC);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=tC(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 nC(t,this.mobilePromptEnterMedia,QS())?(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=_C(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})],K.prototype,`disabled`,void 0),B([x()],K.prototype,`sessionId`,void 0),B([x()],K.prototype,`cwd`,void 0),B([x()],K.prototype,`machineId`,void 0),B([x()],K.prototype,`projectId`,void 0),B([x()],K.prototype,`workspaceId`,void 0),B([x({type:Boolean})],K.prototype,`workspaceScopedFileSuggestions`,void 0),B([x({type:Boolean})],K.prototype,`canSteer`,void 0),B([x({type:Boolean})],K.prototype,`isCompacting`,void 0),B([x({type:Boolean})],K.prototype,`canStop`,void 0),B([x({attribute:!1})],K.prototype,`status`,void 0),B([x({type:Boolean})],K.prototype,`sending`,void 0),B([x({attribute:!1})],K.prototype,`onSend`,void 0),B([x({attribute:!1})],K.prototype,`onStop`,void 0),B([x({attribute:!1})],K.prototype,`onSelectModel`,void 0),B([x({attribute:!1})],K.prototype,`onSelectThinking`,void 0),B([x({attribute:!1})],K.prototype,`onCompact`,void 0),B([x({type:Boolean})],K.prototype,`showSessionConfiguration`,void 0),B([x({attribute:!1})],K.prototype,`sessionConfiguration`,void 0),B([x({attribute:!1})],K.prototype,`availableThinkingLevels`,void 0),B([C(`.markdown-editor`)],K.prototype,`editorHost`,void 0),B([C(`.attachment-input`)],K.prototype,`attachmentInput`,void 0),B([S()],K.prototype,`currentInputMode`,void 0),B([S()],K.prototype,`completions`,void 0),B([S()],K.prototype,`selectedIndex`,void 0),B([S()],K.prototype,`attachments`,void 0),B([S()],K.prototype,`attachmentDelivery`,void 0),B([S()],K.prototype,`attachmentError`,void 0),K=B([b(`prompt-editor`)],K);function gC(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 _C(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return Wo(e,t)}function vC(){return[]}function yC(){return[]}function bC(e){return e===null?[]:Array.from(e.files)}function xC(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 wC(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 TC={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},EC={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function DC(e){return Yl(e).kind===`normal`?TC:EC}var OC=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
3067
|
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
2958
3068
|
<section @mousedown=${e=>{e.stopPropagation()}}>
|
|
2959
3069
|
<header>
|
|
@@ -2969,12 +3079,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2969
3079
|
`}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
3080
|
${t?g`<div class="group-header">${e.group}</div>`:null}
|
|
2971
3081
|
${e.items.map(({option:e,index:n})=>g`
|
|
2972
|
-
<button class="${n===this.selectedIndex?`selected`:``}${t?` grouped`:``}" ${
|
|
3082
|
+
<button class="${n===this.selectedIndex?`selected`:``}${t?` grouped`:``}" ${mC(n===this.selectedIndex,e.value)} @click=${()=>this.onPick?.(e.value)}>
|
|
2973
3083
|
<span>${e.label}</span>
|
|
2974
3084
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
2975
3085
|
</button>
|
|
2976
3086
|
`)}
|
|
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()],
|
|
3087
|
+
`})}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()],OC.prototype,`title`,void 0),B([x({type:Boolean})],OC.prototype,`searchable`,void 0),B([x({attribute:!1})],OC.prototype,`options`,void 0),B([x({attribute:!1})],OC.prototype,`selectedValue`,void 0),B([x({attribute:!1})],OC.prototype,`onPick`,void 0),B([x({attribute:!1})],OC.prototype,`onCancel`,void 0),B([S()],OC.prototype,`selectedIndex`,void 0),B([S()],OC.prototype,`query`,void 0),OC=B([b(`command-picker`)],OC);var kC=class extends y{constructor(...e){super(...e),this.actions=[],this.queryText=``,this.selectedIndex=0}render(){let e=this.filteredActions();return g`
|
|
2978
3088
|
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
2979
3089
|
<section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
2980
3090
|
<header>
|
|
@@ -2987,7 +3097,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2987
3097
|
</header>
|
|
2988
3098
|
<div class="options">
|
|
2989
3099
|
${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} ${
|
|
3100
|
+
<button class=${`${t===this.selectedIndex?`selected`:``} ${e.enabled===!1?`disabled`:``}`} ?disabled=${e.enabled===!1} title=${e.disabledReason??e.title} ${mC(t===this.selectedIndex,e.id)} @click=${()=>{this.run(e)}}>
|
|
2991
3101
|
<span class="main">
|
|
2992
3102
|
<strong>${e.title}</strong>
|
|
2993
3103
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
@@ -3000,7 +3110,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3000
3110
|
</div>
|
|
3001
3111
|
</section>
|
|
3002
3112
|
</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
|
|
3113
|
+
`}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 AC(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})],kC.prototype,`actions`,void 0),B([x({attribute:!1})],kC.prototype,`onRun`,void 0),B([x({attribute:!1})],kC.prototype,`onCancel`,void 0),B([C(`input`)],kC.prototype,`input`,void 0),B([S()],kC.prototype,`queryText`,void 0),B([S()],kC.prototype,`selectedIndex`,void 0),kC=B([b(`action-palette`)],kC);function AC(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 jC=class extends y{render(){let e=this.state;return e===void 0?null:g`
|
|
3004
3114
|
<div class="backdrop" @mousedown=${()=>{this.cancel()}}>
|
|
3005
3115
|
<section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
3006
3116
|
<header>
|
|
@@ -3023,13 +3133,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3023
3133
|
<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
3134
|
</div>
|
|
3025
3135
|
`;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} · ${
|
|
3136
|
+
<button @click=${()=>{this.onLogoutProvider?.(e.id)}}><span>${e.name}</span><small>${e.id} · ${NC(e.authType)}</small></button>
|
|
3027
3137
|
`)}</div>`}}renderProviderButton(e){return g`
|
|
3028
3138
|
<button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
|
|
3029
|
-
<span>${e.name}${e.status.source===void 0?null:g` <em>${
|
|
3030
|
-
<small>${e.id} · ${
|
|
3139
|
+
<span>${e.name}${e.status.source===void 0?null:g` <em>${FC(e)}</em>`}</span>
|
|
3140
|
+
<small>${e.id} · ${NC(e.authType)}</small>
|
|
3031
3141
|
</button>
|
|
3032
|
-
`}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=
|
|
3142
|
+
`}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=MC(n?.promptType);return g`
|
|
3033
3143
|
<div class="form">
|
|
3034
3144
|
${t.auth===void 0?g`<p>Starting login flow…</p>`:g`
|
|
3035
3145
|
<p>Open this authorization link:</p>
|
|
@@ -3062,7 +3172,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3062
3172
|
${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
3173
|
${n===void 0&&r===void 0&&t.status===`running`?g`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
|
|
3064
3174
|
</div>
|
|
3065
|
-
`}focusInputIfNeeded(){let e=
|
|
3175
|
+
`}focusInputIfNeeded(){let e=PC(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
3176
|
.form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
|
|
3067
3177
|
.form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
|
|
3068
3178
|
.form a { color: var(--pi-accent); overflow-wrap: anywhere; }
|
|
@@ -3080,7 +3190,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3080
3190
|
.inline-options button { display: grid; gap: 2px; text-align: left; }
|
|
3081
3191
|
.inline-options small { color: var(--pi-muted); }
|
|
3082
3192
|
em { color: var(--pi-success); font-style: normal; font-size: 12px; }
|
|
3083
|
-
`]}};B([x({attribute:!1})],
|
|
3193
|
+
`]}};B([x({attribute:!1})],jC.prototype,`state`,void 0),B([x({attribute:!1})],jC.prototype,`onChooseMethod`,void 0),B([x({attribute:!1})],jC.prototype,`onSelectProvider`,void 0),B([x({attribute:!1})],jC.prototype,`onApiKeyInput`,void 0),B([x({attribute:!1})],jC.prototype,`onSaveApiKey`,void 0),B([x({attribute:!1})],jC.prototype,`onLogoutProvider`,void 0),B([x({attribute:!1})],jC.prototype,`onOAuthInput`,void 0),B([x({attribute:!1})],jC.prototype,`onOAuthRespond`,void 0),B([x({attribute:!1})],jC.prototype,`onOAuthCancel`,void 0),B([x({attribute:!1})],jC.prototype,`onCancel`,void 0),B([C(`input`)],jC.prototype,`input`,void 0),jC=B([b(`auth-dialog`)],jC);function MC(e){return e===`secret`?`password`:`text`}function NC(e){return e===`oauth`?`subscription`:`credentials`}function PC(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 FC(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 IC=[`openai-completions`,`openai-responses`,`anthropic-messages`,`google-generative-ai`];function LC(e){return IC.map(t=>({api:t,selected:t===e}))}function RC(e,t){return e.map(e=>({candidate:e,selected:e.id===t}))}var zC=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function BC(e){let t=e.providers??{},n=ZC(t);return{config:JC(e,{...t,[n]:{api:`openai-completions`}}),providerName:n}}function VC(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:JC(e,a)}}function HC(e,t,n){let r=e.providers??{};return r[t]===void 0?e:JC(e,{...r,[t]:n})}function UC(e,t){let n=e.providers??{};return n[t]===void 0?e:JC(e,YC(n,t))}function WC(e,t){let n=e.providers?.[t];if(n===void 0)return e;let r=[...n.models??[],{id:``}];return HC(e,t,{...n,models:r})}function GC(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,HC(e,t,{...i,models:o})}function KC(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,HC(e,t,n)}return HC(e,t,{...r,models:a})}function qC(e,t,n,r){let i=n==="default"?XC(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 JC(e,t){return{...e,providers:t}}function YC(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function XC(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function ZC(e){let t=`new-provider`,n=1;for(;e[t]!==void 0;)t=`new-provider-${String(n++)}`;return t}var QC={thinkingFormat:`deepseek`,requiresReasoningContentOnAssistantMessages:!0},$C=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`)&&nw(e.get(`machine`))!==this.machineId()&&(this.resetForMachineChange(),this.isConnected&&this.loadConfig())}render(){return g`
|
|
3084
3194
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
3085
3195
|
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="models-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
3086
3196
|
<header>
|
|
@@ -3091,10 +3201,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3091
3201
|
</div>
|
|
3092
3202
|
<div class="header-actions">
|
|
3093
3203
|
<button class="icon-button" type="button" title="Reload models configuration" aria-label="Reload models configuration" ?disabled=${this.loading} @click=${()=>{this.loadConfig()}}>
|
|
3094
|
-
${
|
|
3204
|
+
${Aw()}
|
|
3095
3205
|
</button>
|
|
3096
3206
|
<button class="icon-button" type="button" title="Close models configuration" aria-label="Close models configuration" @click=${()=>{this.close()}}>
|
|
3097
|
-
${
|
|
3207
|
+
${jw()}
|
|
3098
3208
|
</button>
|
|
3099
3209
|
</div>
|
|
3100
3210
|
</header>
|
|
@@ -3112,7 +3222,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3112
3222
|
${this.savedMessage===``?null:g`<span class="saved-message">${this.savedMessage}</span>`}
|
|
3113
3223
|
</div>
|
|
3114
3224
|
<button type="button" class="secondary" @click=${()=>{this.configureAuth()}}>
|
|
3115
|
-
${
|
|
3225
|
+
${Mw()} Authentication
|
|
3116
3226
|
</button>
|
|
3117
3227
|
<button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
|
|
3118
3228
|
<button type="button" class="primary" ?disabled=${this.saving||this.loading} @click=${()=>{this.saveConfig()}}>
|
|
@@ -3133,28 +3243,28 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3133
3243
|
</div>
|
|
3134
3244
|
<div class="tree-actions">
|
|
3135
3245
|
<button type="button" class="add-provider" @click=${()=>{this.addCustomProvider()}}>
|
|
3136
|
-
${
|
|
3246
|
+
${Ow()} Add provider
|
|
3137
3247
|
</button>
|
|
3138
3248
|
<button type="button" class="auth-link" @click=${()=>{this.configureAuth()}}>
|
|
3139
|
-
${
|
|
3249
|
+
${Mw()} Configure authentication
|
|
3140
3250
|
</button>
|
|
3141
3251
|
</div>
|
|
3142
3252
|
</aside>
|
|
3143
3253
|
`}renderProviderTreeNode(e,t){let n=this.selection?.type===`provider`&&this.selection.providerName===e,r=t.models??[];return g`
|
|
3144
3254
|
<div class="provider-node">
|
|
3145
3255
|
<button class="tree-row provider-row ${n?`selected`:``}" type="button" @click=${()=>{this.selectProvider(e)}}>
|
|
3146
|
-
${
|
|
3256
|
+
${Ew()}
|
|
3147
3257
|
<span class="tree-label">${e}</span>
|
|
3148
3258
|
</button>
|
|
3149
3259
|
${r.map((t,n)=>g`
|
|
3150
3260
|
<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
|
-
${
|
|
3261
|
+
${Dw()}
|
|
3152
3262
|
<span class="tree-label">${t.id.trim()===``?`new model`:t.id}</span>
|
|
3153
3263
|
${t.reasoning===!0?g`<span class="thinking-mark" title="Reasoning enabled">T</span>`:null}
|
|
3154
3264
|
</button>
|
|
3155
3265
|
`)}
|
|
3156
3266
|
<button class="tree-row add-model" type="button" @click=${()=>{this.addModel(e)}}>
|
|
3157
|
-
${
|
|
3267
|
+
${Ow()} <span>Add model</span>
|
|
3158
3268
|
</button>
|
|
3159
3269
|
</div>
|
|
3160
3270
|
`}renderDetail(){let e=this.selection;if(e===void 0)return g`
|
|
@@ -3171,16 +3281,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3171
3281
|
</div>
|
|
3172
3282
|
<div class="provider-actions">
|
|
3173
3283
|
<button type="button" class="secondary" ?disabled=${!r||n?.phase===`discovering`} @click=${()=>{this.discoverModels(e)}}>
|
|
3174
|
-
${n?.phase===`discovering`?
|
|
3284
|
+
${n?.phase===`discovering`?Pw():Aw()} ${n===void 0?`Fetch models`:n.phase===`discovering`?`Fetching models...`:`Refresh models`}
|
|
3175
3285
|
</button>
|
|
3176
|
-
<button type="button" class="danger" @click=${()=>{this.deleteProvider(e)}}>${
|
|
3286
|
+
<button type="button" class="danger" @click=${()=>{this.deleteProvider(e)}}>${kw()} Delete provider</button>
|
|
3177
3287
|
</div>
|
|
3178
3288
|
</div>
|
|
3179
3289
|
|
|
3180
3290
|
<div class="field-stack provider-name-field">
|
|
3181
3291
|
<label for="provider-name">Provider name</label>
|
|
3182
3292
|
<div class="inline-field">
|
|
3183
|
-
<input id="provider-name" class="mono" .value=${this.providerNameDraft} placeholder="provider-name" @input=${e=>{this.providerNameDraft=
|
|
3293
|
+
<input id="provider-name" class="mono" .value=${this.providerNameDraft} placeholder="provider-name" @input=${e=>{this.providerNameDraft=iw(e),this.renameError=``}}>
|
|
3184
3294
|
<button type="button" class="secondary" ?disabled=${this.providerNameDraft.trim()===``||this.providerNameDraft===e} @click=${()=>{this.renameSelectedProvider(e)}}>Rename</button>
|
|
3185
3295
|
</div>
|
|
3186
3296
|
${this.renameError===``?null:g`<span class="field-error">${this.renameError}</span>`}
|
|
@@ -3188,19 +3298,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3188
3298
|
|
|
3189
3299
|
<div class="field-stack">
|
|
3190
3300
|
<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:
|
|
3301
|
+
<input id="provider-base-url" class="mono" .value=${t.baseUrl??``} placeholder="https://api.example.com/v1" @input=${n=>{this.replaceProvider(e,{...t,baseUrl:rw(iw(n))})}}>
|
|
3192
3302
|
</div>
|
|
3193
3303
|
|
|
3194
3304
|
<div class="field-stack">
|
|
3195
3305
|
<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:
|
|
3306
|
+
<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:rw(iw(n))})}}>
|
|
3197
3307
|
<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
3308
|
</div>
|
|
3199
3309
|
|
|
3200
3310
|
<div class="field-stack">
|
|
3201
3311
|
<label for="provider-api">API format</label>
|
|
3202
|
-
<select id="provider-api" .value=${i} @change=${n=>{this.replaceProvider(e,{...t,api:
|
|
3203
|
-
${
|
|
3312
|
+
<select id="provider-api" .value=${i} @change=${n=>{this.replaceProvider(e,{...t,api:iw(n)})}}>
|
|
3313
|
+
${LC(i).map(({api:e,selected:t})=>g`<option value=${e} .selected=${t}>${e}</option>`)}
|
|
3204
3314
|
</select>
|
|
3205
3315
|
</div>
|
|
3206
3316
|
|
|
@@ -3215,7 +3325,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3215
3325
|
</div>
|
|
3216
3326
|
</details>
|
|
3217
3327
|
</div>
|
|
3218
|
-
`}renderModelDetail(e,t,n,r){let i=this.modelTests[
|
|
3328
|
+
`}renderModelDetail(e,t,n,r){let i=this.modelTests[_w(e,r)];return g`
|
|
3219
3329
|
<div class="detail-content">
|
|
3220
3330
|
<div class="detail-heading">
|
|
3221
3331
|
<div>
|
|
@@ -3223,35 +3333,35 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3223
3333
|
<h2>${n.id.trim()===``?`New model`:n.id}</h2>
|
|
3224
3334
|
</div>
|
|
3225
3335
|
<div class="model-actions">
|
|
3226
|
-
${i===void 0?null:g`<span class="connection-state ${i.phase}">${
|
|
3336
|
+
${i===void 0?null:g`<span class="connection-state ${i.phase}">${Sw(i)}</span>`}
|
|
3227
3337
|
<button type="button" class="secondary" ?disabled=${n.id.trim()===``||i?.phase===`testing`} @click=${()=>{this.testModel(e,r)}}>
|
|
3228
|
-
${i?.phase===`testing`?
|
|
3338
|
+
${i?.phase===`testing`?Pw():Nw()} ${i?.phase===`testing`?`Testing...`:`Test`}
|
|
3229
3339
|
</button>
|
|
3230
|
-
<button type="button" class="danger" @click=${()=>{this.deleteModel(e,r)}}>${
|
|
3340
|
+
<button type="button" class="danger" @click=${()=>{this.deleteModel(e,r)}}>${kw()} Remove</button>
|
|
3231
3341
|
</div>
|
|
3232
3342
|
</div>
|
|
3233
3343
|
|
|
3234
|
-
${i===void 0?null:g`<div class="connection-detail ${i.phase}">${
|
|
3344
|
+
${i===void 0?null:g`<div class="connection-detail ${i.phase}">${Cw(i)}</div>`}
|
|
3235
3345
|
|
|
3236
3346
|
<div class="field-grid two-columns">
|
|
3237
3347
|
${this.renderModelIdField(e,n,r)}
|
|
3238
3348
|
<div class="field-stack">
|
|
3239
3349
|
<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:
|
|
3350
|
+
<input id="model-name" .value=${n.name??``} placeholder="Display name" @input=${t=>{this.replaceModel(e,r,{...n,name:rw(iw(t))})}}>
|
|
3241
3351
|
</div>
|
|
3242
3352
|
</div>
|
|
3243
3353
|
|
|
3244
3354
|
<div class="field-stack">
|
|
3245
3355
|
<label for="model-api">API override</label>
|
|
3246
|
-
<select id="model-api" .value=${n.api??``} @change=${t=>{this.replaceModel(e,r,{...n,api:
|
|
3356
|
+
<select id="model-api" .value=${n.api??``} @change=${t=>{this.replaceModel(e,r,{...n,api:rw(iw(t))})}}>
|
|
3247
3357
|
<option value="">Inherit provider API</option>
|
|
3248
|
-
${
|
|
3358
|
+
${LC(n.api).map(({api:e,selected:t})=>g`<option value=${e} .selected=${t}>${e}</option>`)}
|
|
3249
3359
|
</select>
|
|
3250
3360
|
</div>
|
|
3251
3361
|
|
|
3252
3362
|
<div class="switch-row">
|
|
3253
3363
|
${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?
|
|
3364
|
+
${this.renderCheck(`Image input`,n.input?.includes(`image`)===!0,t=>{this.replaceModel(e,r,{...n,input:t?lw(n.input):uw(n.input)})})}
|
|
3255
3365
|
</div>
|
|
3256
3366
|
|
|
3257
3367
|
${n.reasoning===!0?g`
|
|
@@ -3261,10 +3371,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3261
3371
|
<span class="section-label">Thinking configuration</span>
|
|
3262
3372
|
<p>Map Pi thinking levels to values accepted by this model, or disable a level.</p>
|
|
3263
3373
|
</div>
|
|
3264
|
-
${this.renderCheck(`DeepSeek thinking compatibility`,
|
|
3374
|
+
${this.renderCheck(`DeepSeek thinking compatibility`,dw(n),t=>{this.replaceModel(e,r,fw(n,t))})}
|
|
3265
3375
|
</div>
|
|
3266
3376
|
<div class="thinking-map">
|
|
3267
|
-
${
|
|
3377
|
+
${zC.map(t=>this.renderThinkingLevel(e,r,n,t))}
|
|
3268
3378
|
</div>
|
|
3269
3379
|
</section>
|
|
3270
3380
|
`:null}
|
|
@@ -3272,11 +3382,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3272
3382
|
<div class="field-grid two-columns">
|
|
3273
3383
|
<div class="field-stack">
|
|
3274
3384
|
<label for="context-window">Context window (tokens)</label>
|
|
3275
|
-
<input id="context-window" type="number" min="0" inputmode="numeric" .value=${
|
|
3385
|
+
<input id="context-window" type="number" min="0" inputmode="numeric" .value=${ow(n.contextWindow)} placeholder="128000" @input=${t=>{this.replaceModel(e,r,{...n,contextWindow:sw(iw(t))})}}>
|
|
3276
3386
|
</div>
|
|
3277
3387
|
<div class="field-stack">
|
|
3278
3388
|
<label for="max-tokens">Max output tokens</label>
|
|
3279
|
-
<input id="max-tokens" type="number" min="0" inputmode="numeric" .value=${
|
|
3389
|
+
<input id="max-tokens" type="number" min="0" inputmode="numeric" .value=${ow(n.maxTokens)} placeholder="16384" @input=${t=>{this.replaceModel(e,r,{...n,maxTokens:sw(iw(t))})}}>
|
|
3280
3390
|
</div>
|
|
3281
3391
|
</div>
|
|
3282
3392
|
|
|
@@ -3303,14 +3413,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3303
3413
|
`}renderModelIdField(e,t,n){let r=this.discoveredModels[e]?.models;if(r===void 0)return g`
|
|
3304
3414
|
<div class="field-stack">
|
|
3305
3415
|
<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:
|
|
3416
|
+
<input id="model-id" class="mono" .value=${t.id} placeholder="model-id" @input=${r=>{this.replaceModel(e,n,{...t,id:iw(r)})}}>
|
|
3307
3417
|
</div>
|
|
3308
3418
|
`;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
3419
|
<div class="field-stack">
|
|
3310
3420
|
<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,
|
|
3421
|
+
<select id="model-id" class="mono" .value=${t.id} @change=${t=>{this.selectDiscoveredModel(e,n,iw(t))}}>
|
|
3312
3422
|
${t.id.trim()===``?g`<option value="" disabled>Select a model</option>`:null}
|
|
3313
|
-
${
|
|
3423
|
+
${RC(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
3424
|
</select>
|
|
3315
3425
|
</div>
|
|
3316
3426
|
`}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 +3432,26 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3322
3432
|
</div>
|
|
3323
3433
|
<label class="custom-thinking">
|
|
3324
3434
|
<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`,
|
|
3435
|
+
<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`,iw(i))}}>
|
|
3326
3436
|
</label>
|
|
3327
3437
|
</div>
|
|
3328
3438
|
`}renderCostField(e,t,n,r,i){let a=`cost-${t}`;return g`
|
|
3329
3439
|
<div class="field-stack">
|
|
3330
3440
|
<label for=${a}>${e}</label>
|
|
3331
|
-
<input id=${a} type="number" min="0" step="any" inputmode="decimal" .value=${
|
|
3441
|
+
<input id=${a} type="number" min="0" step="any" inputmode="decimal" .value=${ow(i.cost?.[t])} placeholder="0" @input=${e=>{this.setCost(n,r,i,t,cw(iw(e)))}}>
|
|
3332
3442
|
</div>
|
|
3333
3443
|
`}renderCheck(e,t,n){return g`
|
|
3334
3444
|
<label class="check-row">
|
|
3335
|
-
<input type="checkbox" .checked=${t} @change=${e=>{n(
|
|
3445
|
+
<input type="checkbox" .checked=${t} @change=${e=>{n(aw(e))}}>
|
|
3336
3446
|
<span>${e}</span>
|
|
3337
3447
|
</label>
|
|
3338
3448
|
`}renderJsonField(e,t,n,r){let i=`advanced-${t}`,a=this.advancedErrors[t];return g`
|
|
3339
3449
|
<div class="field-stack">
|
|
3340
3450
|
<label for=${i}>${e} (JSON object)</label>
|
|
3341
|
-
<textarea id=${i} class="mono" rows="4" .value=${
|
|
3451
|
+
<textarea id=${i} class="mono" rows="4" .value=${mw(n)} @change=${e=>{r(iw(e))}}></textarea>
|
|
3342
3452
|
${a===void 0?null:g`<span class="field-error">${a}</span>`}
|
|
3343
3453
|
</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=
|
|
3454
|
+
`}async loadConfig(){let e=++this.loadRequestSequence,t=this.machineId();this.modelDiscoveryRequestSequences.clear(),this.discoveredModels={},this.loading=!0,this.error=``,this.savedMessage=``;try{let n=ew(await this.modelsApi.config(t));if(!this.isCurrentLoad(e,t))return;this.config=n,this.selection=tw(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: ${Tw(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: ${Tw(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=_w(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}:xw(t)}}catch(e){a===this.machineId()&&(this.modelTests={...this.modelTests,[i]:{phase:`error`,message:Tw(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?bw(this.discoveredModels,e):{...this.discoveredModels,[e]:i},this.error=`Failed to fetch models for ${e}: ${Tw(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=BC(this.config);this.config=e.config,this.selectProvider(e.providerName)}deleteProvider(e){this.clearProviderDiscovery(e),this.config=UC(this.config,e),this.modelTests=vw(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=VC(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=yw(this.modelTests,e,n),this.selectProvider(n)}replaceProvider(e,t){this.invalidateProviderDiscovery(e),this.config=HC(this.config,e,t),this.modelTests=vw(this.modelTests,e)}addModel(e){let t=this.config.providers?.[e]?.models?.length??0;this.config=WC(this.config,e),this.selectModel(e,t)}deleteModel(e,t){this.config=KC(this.config,e,t),this.modelTests=vw(this.modelTests,e),this.selectProvider(e)}replaceModel(e,t,n){this.config=GC(this.config,e,t,n);let r=_w(e,t);this.modelTests[r]!==void 0&&(this.modelTests=bw(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=bw(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=bw(this.discoveredModels,e))}setThinkingLevel(e,t,n,r,i,a){this.replaceModel(e,t,{...n,thinkingLevelMap:qC(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=pw(n),i=`headers`;if(!r.ok){this.setAdvancedError(i,r.error);return}if(r.value!==void 0&&!hw(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:gw(r.value)})}updateProviderObject(e,t,n,r){let i=pw(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=pw(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=bw(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 nw(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
3455
|
:host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
|
|
3346
3456
|
.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
3457
|
.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 +3559,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3449
3559
|
.thinking-row { grid-template-columns: 58px minmax(0, 1fr); }
|
|
3450
3560
|
.custom-thinking { grid-column: 1 / -1; }
|
|
3451
3561
|
}
|
|
3452
|
-
`}};B([x({attribute:!1})]
|
|
3562
|
+
`}};B([x({attribute:!1})],$C.prototype,`machine`,void 0),B([x({attribute:!1})],$C.prototype,`modelsApi`,void 0),B([x({attribute:!1})],$C.prototype,`onClose`,void 0),B([x({attribute:!1})],$C.prototype,`onConfigureAuth`,void 0),B([x({attribute:!1})],$C.prototype,`onSaved`,void 0),B([S()],$C.prototype,`config`,void 0),B([S()],$C.prototype,`loading`,void 0),B([S()],$C.prototype,`saving`,void 0),B([S()],$C.prototype,`error`,void 0),B([S()],$C.prototype,`savedMessage`,void 0),B([S()],$C.prototype,`selection`,void 0),B([S()],$C.prototype,`providerNameDraft`,void 0),B([S()],$C.prototype,`renameError`,void 0),B([S()],$C.prototype,`advancedErrors`,void 0),B([S()],$C.prototype,`modelTests`,void 0),B([S()],$C.prototype,`discoveredModels`,void 0),$C=B([b(`models-config-dialog`)],$C);function ew(e){return e.providers===void 0?{...e,providers:{}}:e}function tw(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 nw(e){if(!ww(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function rw(e){return e.trim()===``?void 0:e}function iw(e){let t=e.target;return t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement?t.value:``}function aw(e){return e.target instanceof HTMLInputElement&&e.target.checked}function ow(e){return e===void 0?``:String(e)}function sw(e){let t=e.trim();if(t===``)return;let n=Number(t);return Number.isInteger(n)&&n>=0?n:void 0}function cw(e){let t=e.trim();if(t===``)return;let n=Number(t);return Number.isFinite(n)&&n>=0?n:void 0}function lw(e){let t=e??[`text`];return t.includes(`image`)?[...t]:[...t,`image`]}function uw(e){let t=(e??[]).filter(e=>e!==`image`);return t.length===0?void 0:t}function dw(e){return e.compat?.thinkingFormat===`deepseek`}function fw(e,t){if(t)return{...e,compat:{...e.compat??{},...QC}};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 pw(e){if(e.trim()===``)return{ok:!0,value:void 0};try{let t=JSON.parse(e);return ww(t)?{ok:!0,value:t}:{ok:!1,error:`Value must be a JSON object.`}}catch(e){return{ok:!1,error:`Invalid JSON: ${Tw(e)}`}}}function mw(e){return e===void 0?``:JSON.stringify(e,null,2)}function hw(e){return Object.values(e).every(e=>typeof e==`string`)}function gw(e){let t={};for(let[n,r]of Object.entries(e))typeof r==`string`&&(t[n]=r);return t}function _w(e,t){return`${e}\u0000${String(t)}`}function vw(e,t){let n=`${t}\u0000`,r={};for(let[t,i]of Object.entries(e))t.startsWith(n)||(r[t]=i);return r}function yw(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 bw(e,t){let n={};for(let[r,i]of Object.entries(e))r!==t&&(n[r]=i);return n}function xw(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 ww(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Tw(e){return e instanceof Error?e.message:String(e)}function Ew(){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 Dw(){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 Ow(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function kw(){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 Aw(){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 jw(){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 Mw(){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 Nw(){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 Pw(){return _`<svg class="svg-icon spin" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="8" opacity=".25"></circle><path d="M20 12a8 8 0 0 0-8-8"></path></svg>`}var q=class extends y{constructor(...e){super(...e),this.cwd=``,this.skillsApi=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`)&&Fw(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
3563
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
3454
3564
|
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="skills-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
3455
3565
|
<header>
|
|
3456
3566
|
<div class="title-block">
|
|
3457
3567
|
<h1 id="skills-dialog-title">Skills</h1>
|
|
3458
|
-
<span class="target"><code>${
|
|
3568
|
+
<span class="target"><code>${zw(this.cwd)}</code> on ${this.machineLabel()}</span>
|
|
3459
3569
|
</div>
|
|
3460
3570
|
<button class="icon-button" type="button" title="Close skills configuration" aria-label="Close skills configuration" @click=${()=>{this.close()}}>
|
|
3461
|
-
${
|
|
3571
|
+
${eT()}
|
|
3462
3572
|
</button>
|
|
3463
3573
|
</header>
|
|
3464
3574
|
|
|
@@ -3484,21 +3594,21 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3484
3594
|
</div>
|
|
3485
3595
|
<div class="skill-list-actions">
|
|
3486
3596
|
<button class="add-skill" type="button" ?aria-pressed=${this.addMode} @click=${()=>{this.openAddMode()}}>
|
|
3487
|
-
${
|
|
3597
|
+
${$w()} Add skill
|
|
3488
3598
|
</button>
|
|
3489
3599
|
</div>
|
|
3490
3600
|
</aside>
|
|
3491
|
-
`}renderSkillListItem(e){let t=!this.addMode&&e.filePath===this.selectedFilePath,n=
|
|
3601
|
+
`}renderSkillListItem(e){let t=!this.addMode&&e.filePath===this.selectedFilePath,n=Uw(e,this.updateStatuses);return g`
|
|
3492
3602
|
<button class="skill-row ${t?`selected`:``}" type="button" @click=${()=>{this.selectSkill(e)}}>
|
|
3493
3603
|
<span class="skill-indicator ${e.disableModelInvocation?`disabled`:``}" aria-hidden="true"></span>
|
|
3494
3604
|
<span class="skill-name">${e.name}</span>
|
|
3495
3605
|
${n?.state===`update-available`?g`<span class="update-available-mark" title="Update available" aria-label="Update available">↑</span>`:null}
|
|
3496
3606
|
</button>
|
|
3497
|
-
`}renderSkillDetail(e){let t=
|
|
3607
|
+
`}renderSkillDetail(e){let t=Lw(e),n=Hw(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
3608
|
<div class="detail-content">
|
|
3499
3609
|
<div class="skill-meta-row">
|
|
3500
3610
|
<span class="scope-tag ${t}">${t}</span>
|
|
3501
|
-
<code class="skill-path" title=${e.filePath}>${
|
|
3611
|
+
<code class="skill-path" title=${e.filePath}>${Rw(e,this.cwd)}</code>
|
|
3502
3612
|
<button
|
|
3503
3613
|
class="skill-toggle ${o?`enabled`:``}"
|
|
3504
3614
|
type="button"
|
|
@@ -3516,7 +3626,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3516
3626
|
<section class="detail-section">
|
|
3517
3627
|
<h2>Source</h2>
|
|
3518
3628
|
<a class="source-link" href=${e.install.skillsShUrl} target="_blank" rel="noreferrer" title=${e.install.skillsShUrl}>
|
|
3519
|
-
<code>${
|
|
3629
|
+
<code>${Bw(e.install.skillsShUrl)} ↗</code>
|
|
3520
3630
|
</a>
|
|
3521
3631
|
</section>
|
|
3522
3632
|
`}
|
|
@@ -3525,13 +3635,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3525
3635
|
<section class="detail-section">
|
|
3526
3636
|
<h2>Version</h2>
|
|
3527
3637
|
<div class="version-row">
|
|
3528
|
-
<code>${
|
|
3638
|
+
<code>${Vw(r?.currentVersion??e.install.versionHash)}</code>
|
|
3529
3639
|
${e.install.canCheckForUpdates?g`
|
|
3530
3640
|
<button type="button" class="secondary compact-button" ?disabled=${i||a} @click=${()=>{this.checkForUpdates(e)}}>
|
|
3531
3641
|
${i?`Checking...`:`Check`}
|
|
3532
3642
|
</button>
|
|
3533
3643
|
`:null}
|
|
3534
|
-
${r?.state===`update-available`?g`<code class="update-version">${
|
|
3644
|
+
${r?.state===`update-available`?g`<code class="update-version">${Vw(r.latestVersion)}</code>`:null}
|
|
3535
3645
|
${this.renderUpdateStatus(r,i)}
|
|
3536
3646
|
${r?.state===`update-available`?g`
|
|
3537
3647
|
<button type="button" class="primary compact-button" ?disabled=${a||i} @click=${()=>{this.updateInstalledSkill(e)}}>
|
|
@@ -3553,7 +3663,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3553
3663
|
<p>${e.description}</p>
|
|
3554
3664
|
</section>
|
|
3555
3665
|
</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/`:`${
|
|
3666
|
+
`}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/`:`${zw(this.cwd)}/.pi/skills/`;return g`
|
|
3557
3667
|
<div class="detail-content add-panel">
|
|
3558
3668
|
<div class="add-heading">
|
|
3559
3669
|
<h2>Add Skill</h2>
|
|
@@ -3565,7 +3675,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3565
3675
|
id="skill-search"
|
|
3566
3676
|
.value=${this.searchQuery}
|
|
3567
3677
|
placeholder="e.g. react, testing, deploy"
|
|
3568
|
-
@input=${e=>{this.searchQuery=
|
|
3678
|
+
@input=${e=>{this.searchQuery=Xw(e)}}
|
|
3569
3679
|
@keydown=${e=>{e.key===`Enter`&&(e.preventDefault(),this.searchSkills())}}
|
|
3570
3680
|
>
|
|
3571
3681
|
<button type="button" class="primary" ?disabled=${this.searching||this.searchQuery.trim()===``} @click=${()=>{this.searchSkills()}}>
|
|
@@ -3587,7 +3697,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3587
3697
|
|
|
3588
3698
|
${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
3699
|
</div>
|
|
3590
|
-
`}renderSearchResult(e){let t=this.isInstalled(e.package,this.installScope),n=this.installingPackage===e.package,r=
|
|
3700
|
+
`}renderSearchResult(e){let t=this.isInstalled(e.package,this.installScope),n=this.installingPackage===e.package,r=Gw(e.package);return g`
|
|
3591
3701
|
<article class="search-result">
|
|
3592
3702
|
<div class="search-result-copy">
|
|
3593
3703
|
<strong>${r.skill??r.repository}</strong>
|
|
@@ -3616,7 +3726,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3616
3726
|
</div>
|
|
3617
3727
|
<button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
|
|
3618
3728
|
</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=
|
|
3729
|
+
`}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=Iw(this.selectedFilePath,n.skills)}catch(n){this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loadError=`Failed to load skills: ${Zw(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=Kw(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=Zw(e))}finally{this.isCurrentTarget(t)&&(this.togglingPaths=Jw(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=Zw(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=Kw(this.newlyInstalledKeys,Ww(n,e)),await this.loadSkills()}catch(e){this.isCurrentTarget(t)&&(this.installError=Zw(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=Hw(e);return t===void 0?[]:[t]});if(n.length!==0){this.updateError=``,this.checkingUpdateKeys=qw(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=Zw(e))}finally{this.isCurrentTarget(t)&&(this.checkingUpdateKeys=Yw(this.checkingUpdateKeys,n),e===void 0&&(this.checkingAll=!1))}}}async updateInstalledSkill(e){let t=this.target(),n=e.install,r=Hw(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=Zw(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=>Lw(e)===`project`&&e.install?.skillsShUrl!==void 0},{label:`project`,matches:e=>Lw(e)===`project`&&e.install?.skillsShUrl===void 0},{label:`global / skills.sh`,matches:e=>Lw(e)===`global`&&e.install?.skillsShUrl!==void 0},{label:`global`,matches:e=>Lw(e)===`global`&&e.install?.skillsShUrl===void 0},{label:`path`,matches:e=>Lw(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(Ww(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 Fw(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
3730
|
:host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
|
|
3621
3731
|
.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
3732
|
.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 +3827,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3717
3827
|
.scope-row { align-items: flex-start; flex-direction: column; gap: 6px; }
|
|
3718
3828
|
.search-result { align-items: flex-start; }
|
|
3719
3829
|
}
|
|
3720
|
-
`}};B([x({attribute:!1})],
|
|
3830
|
+
`}};B([x({attribute:!1})],q.prototype,`machine`,void 0),B([x({type:String})],q.prototype,`cwd`,void 0),B([x({attribute:!1})],q.prototype,`skillsApi`,void 0),B([x({attribute:!1})],q.prototype,`onClose`,void 0),B([S()],q.prototype,`skills`,void 0),B([S()],q.prototype,`loading`,void 0),B([S()],q.prototype,`loadError`,void 0),B([S()],q.prototype,`selectedFilePath`,void 0),B([S()],q.prototype,`togglingPaths`,void 0),B([S()],q.prototype,`saveError`,void 0),B([S()],q.prototype,`addMode`,void 0),B([S()],q.prototype,`searchQuery`,void 0),B([S()],q.prototype,`searchResults`,void 0),B([S()],q.prototype,`searching`,void 0),B([S()],q.prototype,`searchError`,void 0),B([S()],q.prototype,`installingPackage`,void 0),B([S()],q.prototype,`installError`,void 0),B([S()],q.prototype,`newlyInstalledKeys`,void 0),B([S()],q.prototype,`installScope`,void 0),B([S()],q.prototype,`updateStatuses`,void 0),B([S()],q.prototype,`checkingUpdateKeys`,void 0),B([S()],q.prototype,`checkingAll`,void 0),B([S()],q.prototype,`updatingKey`,void 0),B([S()],q.prototype,`updateError`,void 0),B([C(`#skill-search`)],q.prototype,`searchInput`,void 0),q=B([b(`skills-config-dialog`)],q);function Fw(e){if(!Qw(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function Iw(e,t){return e!==void 0&&t.some(t=>t.filePath===e)?e:t[0]?.filePath}function Lw(e){let t=e.sourceInfo.source,n=e.sourceInfo.scope;return n===`user`||t===`user`?`global`:n===`project`||t===`project`?`project`:`path`}function Rw(e,t){return Lw(e)===`project`&&e.filePath.startsWith(t)?`./${e.filePath.slice(t.length).replace(/^[/\\]/u,``)}`:zw(e.filePath)}function zw(e){return e.replace(/^\/(?:Users|home)\/[^/]+/u,`~`)}function Bw(e){return e.replace(/^https?:\/\//u,``)}function Vw(e){return e===void 0||e===``?`unknown`:e.slice(0,8)}function Hw(e){return e.install===void 0?void 0:`${e.install.scope}\0${e.install.package}`}function Uw(e,t){let n=Hw(e);return n===void 0?void 0:t[n]}function Ww(e,t){return`${e}\0${t}`}function Gw(e){let t=e.lastIndexOf(`@`);return t<0?{repository:e,skill:void 0}:{repository:e.slice(0,t),skill:e.slice(t+1)}}function Kw(e,t){return new Set([...e,t])}function qw(e,t){return new Set([...e,...t])}function Jw(e,t){let n=new Set(e);return n.delete(t),n}function Yw(e,t){let n=new Set(e);for(let e of t)n.delete(e);return n}function Xw(e){let t=e.target;return t instanceof HTMLInputElement?t.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 J=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`)&&cT(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
3831
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
3722
3832
|
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="plugins-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
3723
3833
|
<header>
|
|
3724
3834
|
<div class="title-block">
|
|
3725
3835
|
<h1 id="plugins-dialog-title">Plugins</h1>
|
|
3726
|
-
<span class="target"><code>${
|
|
3836
|
+
<span class="target"><code>${lT(this.cwd)}</code> on ${this.machineLabel()}</span>
|
|
3727
3837
|
</div>
|
|
3728
3838
|
<button class="icon-button" type="button" title="Close Plugins configuration" aria-label="Close Plugins configuration" @click=${()=>{this.close()}}>
|
|
3729
|
-
${
|
|
3839
|
+
${hT()}
|
|
3730
3840
|
</button>
|
|
3731
3841
|
</header>
|
|
3732
3842
|
|
|
@@ -3752,20 +3862,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3752
3862
|
</div>
|
|
3753
3863
|
<div class="package-list-actions">
|
|
3754
3864
|
<button class="add-plugin" type="button" aria-pressed=${String(this.addMode)} @click=${()=>{this.openAddMode()}}>
|
|
3755
|
-
${
|
|
3865
|
+
${mT()} Add plugin
|
|
3756
3866
|
</button>
|
|
3757
3867
|
</div>
|
|
3758
3868
|
</aside>
|
|
3759
|
-
`}renderPackageListItem(e){let t=
|
|
3869
|
+
`}renderPackageListItem(e){let t=tT(e),n=!this.addMode&&t===this.selectedKey;return g`
|
|
3760
3870
|
<button class="package-row ${n?`selected`:``}" type="button" aria-pressed=${String(n)} @click=${()=>{this.selectPackage(e)}}>
|
|
3761
|
-
<span class="package-indicator" style=${`background:${
|
|
3871
|
+
<span class="package-indicator" style=${`background:${oT(e.status)}`} aria-hidden="true"></span>
|
|
3762
3872
|
<span class="package-copy">
|
|
3763
3873
|
<strong>${e.source}</strong>
|
|
3764
|
-
<small>${
|
|
3765
|
-
${e.version===void 0&&e.configuredVersion===void 0?null:g`<small>${
|
|
3874
|
+
<small>${iT(e)}</small>
|
|
3875
|
+
${e.version===void 0&&e.configuredVersion===void 0?null:g`<small>${aT(e)}</small>`}
|
|
3766
3876
|
</span>
|
|
3767
3877
|
</button>
|
|
3768
|
-
`}renderPackageDetail(e){let t=
|
|
3878
|
+
`}renderPackageDetail(e){let t=tT(e),n=this.busyKey?.endsWith(t)??!1,r=this.busyKey===`reload`,i=!e.disabled;return g`
|
|
3769
3879
|
<div class="detail-content">
|
|
3770
3880
|
<div class="detail-heading">
|
|
3771
3881
|
<div class="package-title-row">
|
|
@@ -3797,12 +3907,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3797
3907
|
</div>
|
|
3798
3908
|
|
|
3799
3909
|
<dl class="metadata-grid">
|
|
3800
|
-
<dt>Status</dt><dd style=${`color:${
|
|
3801
|
-
<dt>Version</dt><dd><code>${
|
|
3910
|
+
<dt>Status</dt><dd style=${`color:${oT(e.status)}`}>${e.status}</dd>
|
|
3911
|
+
<dt>Version</dt><dd><code>${aT(e)}</code></dd>
|
|
3802
3912
|
<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>${
|
|
3913
|
+
<dt>Resources</dt><dd>${iT(e)}</dd>
|
|
3914
|
+
<dt>Installed path</dt><dd class=${e.installedPath===void 0?`missing`:``}><code>${e.installedPath===void 0?`Not found`:lT(e.installedPath)}</code></dd>
|
|
3915
|
+
<dt>Workspace</dt><dd><code>${lT(this.cwd)}</code></dd>
|
|
3806
3916
|
</dl>
|
|
3807
3917
|
|
|
3808
3918
|
<section class="resource-section">
|
|
@@ -3831,7 +3941,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3831
3941
|
<div class="detail-content add-panel">
|
|
3832
3942
|
<div class="add-heading">
|
|
3833
3943
|
<h2>Add Plugin</h2>
|
|
3834
|
-
<code>${this.installScope===`project`?`${
|
|
3944
|
+
<code>${this.installScope===`project`?`${lT(this.cwd)}/.pi/agent/{npm,git}`:`~/.pi/agent/{npm,git}`}</code>
|
|
3835
3945
|
</div>
|
|
3836
3946
|
|
|
3837
3947
|
<div class="field-stack">
|
|
@@ -3840,7 +3950,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3840
3950
|
id="plugin-source"
|
|
3841
3951
|
.value=${this.installSource}
|
|
3842
3952
|
placeholder="npm:@scope/package"
|
|
3843
|
-
@input=${e=>{this.installSource=
|
|
3953
|
+
@input=${e=>{this.installSource=dT(e)}}
|
|
3844
3954
|
@keydown=${t=>{t.key!==`Enter`||this.installSource.trim()===``||e||(t.preventDefault(),this.installPlugin())}}
|
|
3845
3955
|
>
|
|
3846
3956
|
</div>
|
|
@@ -3867,7 +3977,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3867
3977
|
`}renderFooter(){let e=this.data,t=e?.diagnostics??[],n=this.busyKey!==void 0;return g`
|
|
3868
3978
|
<footer>
|
|
3869
3979
|
<div class="footer-summary">
|
|
3870
|
-
${t.length>0?g`<span class=${t.some(e=>e.type===`error`)?`error-message`:`warning-message`} title=${t.map(
|
|
3980
|
+
${t.length>0?g`<span class=${t.some(e=>e.type===`error`)?`error-message`:`warning-message`} title=${t.map(uT).join(`
|
|
3871
3981
|
`)}>
|
|
3872
3982
|
${String(t.length)} diagnostic${t.length===1?``:`s`}
|
|
3873
3983
|
</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 +3985,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3875
3985
|
<button type="button" class="secondary" ?disabled=${this.loading||n} @click=${()=>{this.loadPlugins()}}>Refresh</button>
|
|
3876
3986
|
<button type="button" class="secondary" @click=${()=>{this.close()}}>Close</button>
|
|
3877
3987
|
</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=
|
|
3988
|
+
`}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=nT(this.selectedKey,n.packages)}catch(n){this.isCurrentTarget(e)&&t===this.loadRequestSequence&&(this.loadError=`Failed to load plugins: ${fT(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=tT(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=nT(void 0,r.packages),r.packages.length===0&&(this.addMode=!0),this.actionMessage=`Package removed.`):this.actionMessage=sT(e)}catch(e){this.isCurrentTarget(n)&&(this.actionError=fT(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=rT(i.packages,t,n);this.selectedKey=a===void 0?r:tT(a),this.addMode=!1,this.installSource=``,this.actionMessage=`Package installed.`}catch(t){this.isCurrentTarget(e)&&(this.actionError=fT(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=fT(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=>tT(e)===this.selectedKey)}selectPackage(e){this.selectedKey=tT(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 cT(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
3989
|
:host { position: fixed; inset: 0; z-index: 9; display: block; color: var(--pi-text); }
|
|
3880
3990
|
.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
3991
|
.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 +4087,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3977
4087
|
.package-actions { width: 100%; }
|
|
3978
4088
|
.metadata-grid { grid-template-columns: 96px minmax(0, 1fr); }
|
|
3979
4089
|
}
|
|
3980
|
-
`}};B([x({attribute:!1})],
|
|
4090
|
+
`}};B([x({attribute:!1})],J.prototype,`machine`,void 0),B([x({type:String})],J.prototype,`cwd`,void 0),B([x({attribute:!1})],J.prototype,`session`,void 0),B([x({attribute:!1})],J.prototype,`pluginsApi`,void 0),B([x({attribute:!1})],J.prototype,`sessionsApi`,void 0),B([x({attribute:!1})],J.prototype,`onClose`,void 0),B([x({attribute:!1})],J.prototype,`onReloaded`,void 0),B([S()],J.prototype,`data`,void 0),B([S()],J.prototype,`loading`,void 0),B([S()],J.prototype,`loadError`,void 0),B([S()],J.prototype,`selectedKey`,void 0),B([S()],J.prototype,`addMode`,void 0),B([S()],J.prototype,`installSource`,void 0),B([S()],J.prototype,`installScope`,void 0),B([S()],J.prototype,`busyKey`,void 0),B([S()],J.prototype,`actionError`,void 0),B([S()],J.prototype,`actionMessage`,void 0),B([C(`#plugin-source`)],J.prototype,`pluginSourceInput`,void 0),J=B([b(`plugins-config-dialog`)],J);function tT(e){return`${e.scope}\0${e.source}`}function nT(e,t){return e!==void 0&&t.some(t=>tT(t)===e)?e:t[0]===void 0?void 0:tT(t[0])}function rT(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 iT(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 aT(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 oT(e){return e===`loaded`?`var(--pi-accent)`:e===`installed`?`#d97706`:e===`disabled`?`var(--pi-muted)`:`var(--pi-danger)`}function sT(e){switch(e){case`install`:return`Package installed.`;case`update`:return`Package updated.`;case`disable`:return`Package disabled.`;case`enable`:return`Package enabled.`}}function cT(e){if(!pT(e))return`local`;let t=e.id;return typeof t==`string`&&t!==``?t:`local`}function lT(e){return e.replace(/^\/(?:Users|home)\/[^/]+/u,`~`)}function uT(e){return`${e.type}: ${e.source===void 0?``:`${e.source}: `}${e.message}`}function dT(e){return e.target instanceof HTMLInputElement?e.target.value:``}function fT(e){return e instanceof Error?e.message:String(e)}function pT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function mT(){return _`<svg class="svg-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M12 5v14M5 12h14"></path></svg>`}function hT(){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 gT=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
4091
|
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
3982
4092
|
<section @click=${e=>{e.stopPropagation()}}>
|
|
3983
4093
|
<header>
|
|
@@ -4027,7 +4137,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4027
4137
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
4028
4138
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
4029
4139
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
4030
|
-
`}};B([x({attribute:!1})],
|
|
4140
|
+
`}};B([x({attribute:!1})],gT.prototype,`onSubmit`,void 0),B([x({attribute:!1})],gT.prototype,`onCancel`,void 0),B([x()],gT.prototype,`machineId`,void 0),B([S()],gT.prototype,`path`,void 0),B([S()],gT.prototype,`createMissing`,void 0),B([S()],gT.prototype,`suggestions`,void 0),B([S()],gT.prototype,`selected`,void 0),B([S()],gT.prototype,`loading`,void 0),B([C(`input`)],gT.prototype,`pathInput`,void 0),gT=B([b(`project-dialog`)],gT);var _T=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=vT(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`&&yT(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===``||yT(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?yT(this.url):void 0,n=this.validInput()!==void 0&&!this.submitting;return g`
|
|
4031
4141
|
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
4032
4142
|
<section @click=${e=>{e.stopPropagation()}}>
|
|
4033
4143
|
<form @submit=${e=>{this.handleSubmit(e)}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
@@ -4082,7 +4192,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4082
4192
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
4083
4193
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
4084
4194
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
4085
|
-
`}};B([x({attribute:!1})],
|
|
4195
|
+
`}};B([x({attribute:!1})],_T.prototype,`onSubmit`,void 0),B([x({attribute:!1})],_T.prototype,`onCancel`,void 0),B([x()],_T.prototype,`error`,void 0),B([S()],_T.prototype,`url`,void 0),B([S()],_T.prototype,`name`,void 0),B([S()],_T.prototype,`token`,void 0),B([S()],_T.prototype,`submitting`,void 0),B([C(`input[name='baseUrl']`)],_T.prototype,`urlInput`,void 0),B([C(`input[name='name']`)],_T.prototype,`nameInput`,void 0),_T=B([b(`machine-dialog`)],_T);function vT(e){let t=e.trim();if(t===``)return``;let n=bT(t)??bT(`http://${t.replace(/^\/+/u,``)}`);return n!==void 0&&n.hostname!==``?n.hostname.replace(/^\[(.*)\]$/u,`$1`):xT(t)}function yT(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 bT(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:void 0}catch{return}}function xT(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 wT=class extends y{constructor(...e){super(...e),this.heading=``,this.description=``,this.actionLabel=``,this.actionTitle=``,this.actionDisabled=!1,this.notices=[]}render(){return g`
|
|
4086
4196
|
<section class="panel" aria-label=${this.heading||`Settings panel`}>
|
|
4087
4197
|
<header class="section-heading">
|
|
4088
4198
|
<div class="heading-copy">
|
|
@@ -4105,7 +4215,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4105
4215
|
<div class="notice-stack" aria-label="Settings notices">
|
|
4106
4216
|
${this.notices.map(e=>this.renderNotice(e))}
|
|
4107
4217
|
</div>
|
|
4108
|
-
`}renderNotice(e){let t=
|
|
4218
|
+
`}renderNotice(e){let t=CT(e),n=e.role??TT(t),r=e.title;return g`
|
|
4109
4219
|
<article class=${`notice ${t}`} role=${n}>
|
|
4110
4220
|
${r===void 0||r===``?v:g`<strong class="notice-title">${r}</strong>`}
|
|
4111
4221
|
<div class="notice-content">${e.content}</div>
|
|
@@ -4138,13 +4248,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4138
4248
|
.section-heading { display: grid; gap: 12px; }
|
|
4139
4249
|
.heading-actions { justify-self: start; }
|
|
4140
4250
|
}
|
|
4141
|
-
`}};B([x()],
|
|
4142
|
-
`):``}}function
|
|
4143
|
-
`)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function
|
|
4144
|
-
`).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!
|
|
4251
|
+
`}};B([x()],wT.prototype,`heading`,void 0),B([x({attribute:!1})],wT.prototype,`description`,void 0),B([x()],wT.prototype,`actionLabel`,void 0),B([x()],wT.prototype,`actionTitle`,void 0),B([x({type:Boolean})],wT.prototype,`actionDisabled`,void 0),B([x({attribute:!1})],wT.prototype,`notices`,void 0),B([x({attribute:!1})],wT.prototype,`onAction`,void 0),wT=B([b(`settings-panel-frame`)],wT);function TT(e){switch(e){case`error`:return`alert`;case`success`:return`status`;case`warning`:case`info`:return`note`}}function ET(){return{host:``,port:``,allowedHostsMode:`list`,allowedHostsText:``}}function DT(){return{allowedPathsText:``,uploadDefaultFolder:``}}function OT(){return{command:``,dir:``}}function kT(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(`
|
|
4252
|
+
`):``}}function AT(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
|
|
4253
|
+
`)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function jT(e){return{command:e.agent?.command??``,dir:e.agent?.dir??``}}function MT(e){let t=e.command.trim(),n=e.dir.trim();return{agent:{...t===``?{}:{command:t},...n===``?{}:{dir:n}}}}function NT(e,t){let n=MT(e).agent??{},r=t.agent??{};return n.command===r.command&&n.dir===r.dir}function PT(e,t={}){let n=IT(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`||LT(e.allowedHostsText),n}function FT(e){let t=RT(e.allowedPathsText),n=zT(e.uploadDefaultFolder);return{pathAccess:{allowedPaths:t},uploads:n===``?{}:{defaultFolder:n}}}function IT(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 LT(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e!==``)}function RT(e){let t=e.split(`
|
|
4254
|
+
`).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!BT(e));if(n!==void 0)throw Error(`Allowed external paths must be absolute paths or start with ~: ${n}`);return t}function zT(e){let t=e.trim();if(t===``)return``;if(VT(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 BT(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)||e.startsWith(`/`)||e.startsWith(`\\`)||/^[A-Za-z]:[\\/]/u.test(e)}function VT(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function HT(e){return g`Gateway server fields edit this local gateway. File access and upload defaults edit ${e}.`}var Y=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=ET(),this.machineDraft=DT(),this.gatewayLocalError=``,this.machineLocalError=``}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.gatewayDraft=kT(this.configResponse.config),this.gatewayLocalError=``),e.has(`machineConfigResponse`)&&this.machineConfigResponse!==void 0&&(this.machineDraft=AT(this.machineConfigResponse.config),this.machineLocalError=``)}render(){return g`
|
|
4145
4255
|
<settings-panel-frame
|
|
4146
4256
|
heading="General configuration"
|
|
4147
|
-
.description=${
|
|
4257
|
+
.description=${HT(this.targetLabel)}
|
|
4148
4258
|
actionLabel="Reload"
|
|
4149
4259
|
.actionDisabled=${this.loading||this.machineLoading}
|
|
4150
4260
|
.notices=${this.panelNotices()}
|
|
@@ -4173,7 +4283,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4173
4283
|
<span>Host</span>
|
|
4174
4284
|
${this.renderOverrideBadge(`host`)}
|
|
4175
4285
|
</span>
|
|
4176
|
-
<input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:
|
|
4286
|
+
<input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:GT(e)})}}>
|
|
4177
4287
|
<small>Address the web server should bind to. Leave empty to use PI WEBUI's default.</small>
|
|
4178
4288
|
</label>
|
|
4179
4289
|
|
|
@@ -4182,7 +4292,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4182
4292
|
<span>Port</span>
|
|
4183
4293
|
${this.renderOverrideBadge(`port`)}
|
|
4184
4294
|
</span>
|
|
4185
|
-
<input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8808" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:
|
|
4295
|
+
<input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8808" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:GT(e)})}}>
|
|
4186
4296
|
<small>TCP port from 1 to 65535. Leave empty to use PI WEBUI's default.</small>
|
|
4187
4297
|
</label>
|
|
4188
4298
|
|
|
@@ -4191,11 +4301,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4191
4301
|
<span>Allowed hosts</span>
|
|
4192
4302
|
${this.renderOverrideBadge(`allowedHosts`)}
|
|
4193
4303
|
</span>
|
|
4194
|
-
<select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:
|
|
4304
|
+
<select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:KT(e)===`all`?`all`:`list`})}}>
|
|
4195
4305
|
<option value="list">Only listed hosts</option>
|
|
4196
4306
|
<option value="all">Allow every host</option>
|
|
4197
4307
|
</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:
|
|
4308
|
+
<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:qT(e)})}}></textarea>
|
|
4199
4309
|
<small>Enter one host per line, or choose “Allow every host” to write <code>true</code>.</small>
|
|
4200
4310
|
</div>
|
|
4201
4311
|
|
|
@@ -4225,7 +4335,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4225
4335
|
<span class="field-heading">
|
|
4226
4336
|
<span>External filesystem roots</span>
|
|
4227
4337
|
</span>
|
|
4228
|
-
<textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs /opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:
|
|
4338
|
+
<textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs /opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:qT(e)})}}></textarea>
|
|
4229
4339
|
<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
4340
|
</label>
|
|
4231
4341
|
|
|
@@ -4233,7 +4343,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4233
4343
|
<span class="field-heading">
|
|
4234
4344
|
<span>Default upload folder</span>
|
|
4235
4345
|
</span>
|
|
4236
|
-
<input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${_o} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:
|
|
4346
|
+
<input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${_o} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:GT(e)})}}>
|
|
4237
4347
|
<small>Workspace-relative folder for manual file uploads on ${this.targetLabel}. Leave empty to use PI WEBUI's default <code>${_o}</code>.</small>
|
|
4238
4348
|
</label>
|
|
4239
4349
|
|
|
@@ -4251,18 +4361,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4251
4361
|
<dl>
|
|
4252
4362
|
<div><dt>Host</dt><dd>${e.host??g`<span class="muted">127.0.0.1 default</span>`}</dd></div>
|
|
4253
4363
|
<div><dt>Port</dt><dd>${e.port??g`<span class="muted">8808 default</span>`}</dd></div>
|
|
4254
|
-
<div><dt>Allowed hosts</dt><dd>${
|
|
4364
|
+
<div><dt>Allowed hosts</dt><dd>${UT(e.allowedHosts)}</dd></div>
|
|
4255
4365
|
</dl>
|
|
4256
4366
|
</section>
|
|
4257
4367
|
`}renderMachineEffectiveConfig(){let e=this.machineConfigResponse?.effectiveConfig??{};return g`
|
|
4258
4368
|
<section class="effective-card" aria-label="Effective selected machine file access and upload summary">
|
|
4259
4369
|
<h3>Effective selected-machine settings</h3>
|
|
4260
4370
|
<dl>
|
|
4261
|
-
<div><dt>External roots</dt><dd>${
|
|
4371
|
+
<div><dt>External roots</dt><dd>${WT(e.pathAccess?.allowedPaths)}</dd></div>
|
|
4262
4372
|
<div><dt>Upload folder</dt><dd>${e.uploads?.defaultFolder??g`<span class="muted">${`.pi-webui/uploads`} default</span>`}</dd></div>
|
|
4263
4373
|
</dl>
|
|
4264
4374
|
</section>
|
|
4265
|
-
`}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(
|
|
4375
|
+
`}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(PT(this.gatewayDraft,this.configResponse?.config??{}))}catch(e){this.gatewayLocalError=JT(e)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError=``;try{await this.onSaveMachineConfig?.(FT(this.machineDraft))}catch(e){this.machineLocalError=JT(e)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=``}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=``}static{this.styles=h`
|
|
4266
4376
|
:host { display: block; }
|
|
4267
4377
|
.card-heading { display: grid; gap: 6px; min-width: 0; }
|
|
4268
4378
|
h3, p { margin: 0; }
|
|
@@ -4301,10 +4411,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4301
4411
|
@media (max-width: 760px) {
|
|
4302
4412
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
4303
4413
|
}
|
|
4304
|
-
`}};B([x({attribute:!1})],
|
|
4414
|
+
`}};B([x({attribute:!1})],Y.prototype,`configResponse`,void 0),B([x({attribute:!1})],Y.prototype,`machineConfigResponse`,void 0),B([x({type:Boolean})],Y.prototype,`loading`,void 0),B([x({type:Boolean})],Y.prototype,`machineLoading`,void 0),B([x({type:Boolean})],Y.prototype,`saving`,void 0),B([x()],Y.prototype,`error`,void 0),B([x()],Y.prototype,`machineError`,void 0),B([x()],Y.prototype,`savedMessage`,void 0),B([x()],Y.prototype,`targetLabel`,void 0),B([x({attribute:!1})],Y.prototype,`onReload`,void 0),B([x({attribute:!1})],Y.prototype,`onReloadMachine`,void 0),B([x({attribute:!1})],Y.prototype,`onSave`,void 0),B([x({attribute:!1})],Y.prototype,`onSaveMachineConfig`,void 0),B([S()],Y.prototype,`gatewayDraft`,void 0),B([S()],Y.prototype,`machineDraft`,void 0),B([S()],Y.prototype,`gatewayLocalError`,void 0),B([S()],Y.prototype,`machineLocalError`,void 0),Y=B([b(`settings-general-panel`)],Y);function UT(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 WT(e){return e===void 0||e.length===0?g`<span class="muted">External paths denied</span>`:e.join(`, `)}function GT(e){return e.target instanceof HTMLInputElement?e.target.value:``}function KT(e){return e.target instanceof HTMLSelectElement?e.target.value:``}function qT(e){return e.target instanceof HTMLTextAreaElement?e.target.value:``}function JT(e){return e instanceof Error?e.message:String(e)}function YT(e){return{spawnSessions:e}}function XT(e){return{subsessions:e}}function ZT(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&&eE(t.sessionDirEnvKeys,r)?`active`:`restart-required`}function QT(e,t){return e?.agentDirSource===`pi-webui`?!0:e?.agentDirSource===`pi-compatibility`?jt(t.trim()||`pi`):e?.agentDir===!0}function $T(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 eE(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var tE=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=OT(),this.agentDraftDirty=!1,this.agentLocalError=``}willUpdate(e){if(e.has(`configResponse`)){if(this.configResponse===void 0){this.agentDraft=OT(),this.agentDraftDirty=!1,this.agentLocalError=``;return}(!this.agentDraftDirty||NT(this.agentDraft,this.configResponse.config))&&(this.agentDraft=jT(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=QT(e?.envOverrides,s),l=e?.envOverrides.agentDir===!0,u=e?.effectiveConfig.agent,d=ZT(e,this.activeAgentProfile);return g`
|
|
4305
4415
|
<settings-panel-frame
|
|
4306
4416
|
heading="Session daemon"
|
|
4307
|
-
.description=${
|
|
4417
|
+
.description=${aE(this.targetLabel)}
|
|
4308
4418
|
actionLabel="Reload"
|
|
4309
4419
|
.actionDisabled=${this.loading}
|
|
4310
4420
|
.notices=${this.panelNotices(e)}
|
|
@@ -4330,7 +4440,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4330
4440
|
.value=${this.agentDraft.command}
|
|
4331
4441
|
placeholder="pi"
|
|
4332
4442
|
?disabled=${this.loading||this.saving||!o||a}
|
|
4333
|
-
@input=${e=>{this.updateAgentDraft({command:
|
|
4443
|
+
@input=${e=>{this.updateAgentDraft({command:rE(e)})}}
|
|
4334
4444
|
>
|
|
4335
4445
|
<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
4446
|
</label>
|
|
@@ -4347,7 +4457,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4347
4457
|
.value=${this.agentDraft.dir}
|
|
4348
4458
|
placeholder="~/.pi/agent or ~/agent-profiles/work"
|
|
4349
4459
|
?disabled=${this.loading||this.saving||!o||c}
|
|
4350
|
-
@input=${e=>{this.updateAgentDraft({dir:
|
|
4460
|
+
@input=${e=>{this.updateAgentDraft({dir:rE(e)})}}
|
|
4351
4461
|
>
|
|
4352
4462
|
<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
4463
|
</label>
|
|
@@ -4395,14 +4505,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4395
4505
|
<div><dt>Desired state</dt><dd>${u?.dir??g`<span class="muted">Unavailable</span>`}</dd></div>
|
|
4396
4506
|
<div><dt>Active command</dt><dd>${this.activeAgentProfile?.command??g`<span class="muted">Unavailable</span>`}</dd></div>
|
|
4397
4507
|
<div><dt>Active state</dt><dd>${this.activeAgentProfile?.dir??g`<span class="muted">Unavailable</span>`}</dd></div>
|
|
4398
|
-
<div><dt>Profile status</dt><dd>${
|
|
4508
|
+
<div><dt>Profile status</dt><dd>${nE(d)}</dd></div>
|
|
4399
4509
|
<div><dt>Spawn sessions</dt><dd>${n?`Enabled`:g`<span class="muted">Disabled</span>`}</dd></div>
|
|
4400
4510
|
<div><dt>Subsessions</dt><dd>${i?`Enabled`:g`<span class="muted">Disabled</span>`}</dd></div>
|
|
4401
4511
|
</dl>
|
|
4402
4512
|
</section>
|
|
4403
4513
|
`}
|
|
4404
4514
|
</settings-panel-frame>
|
|
4405
|
-
`}panelNotices(e){return
|
|
4515
|
+
`}panelNotices(e){return oE(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?.(MT(this.agentDraft))}catch(e){this.agentLocalError=iE(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?.(YT(t))}async toggleSubsessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(XT(t))}static{this.styles=h`
|
|
4406
4516
|
:host { display: block; }
|
|
4407
4517
|
h3 { margin: 0; font-size: 13px; line-height: 1.3; }
|
|
4408
4518
|
button, input { font: inherit; }
|
|
@@ -4448,10 +4558,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4448
4558
|
@media (max-width: 760px) {
|
|
4449
4559
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
4450
4560
|
}
|
|
4451
|
-
`}};B([x({attribute:!1})],
|
|
4561
|
+
`}};B([x({attribute:!1})],tE.prototype,`configResponse`,void 0),B([x({type:Boolean})],tE.prototype,`loading`,void 0),B([x({type:Boolean})],tE.prototype,`saving`,void 0),B([x()],tE.prototype,`error`,void 0),B([x()],tE.prototype,`savedMessage`,void 0),B([x()],tE.prototype,`targetLabel`,void 0),B([x({attribute:!1})],tE.prototype,`activeAgentProfile`,void 0),B([x({attribute:!1})],tE.prototype,`agentProfileSupport`,void 0),B([x({attribute:!1})],tE.prototype,`onReload`,void 0),B([x({attribute:!1})],tE.prototype,`onSave`,void 0),B([S()],tE.prototype,`agentDraft`,void 0),B([S()],tE.prototype,`agentDraftDirty`,void 0),B([S()],tE.prototype,`agentLocalError`,void 0),tE=B([b(`settings-sessiond-panel`)],tE);function nE(e){return e===`active`?`Active`:e===`restart-required`?`Restart required`:g`<span class="muted">Unavailable</span>`}function rE(e){return e.target instanceof HTMLInputElement?e.target.value:``}function iE(e){return e instanceof Error?e.message:String(e)}function aE(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 oE(e,t){let n=[];t.error!==``&&n.push({type:`error`,content:t.error}),t.savedMessage!==``&&n.push({type:`success`,content:t.savedMessage});let r=ZT(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 sE(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function cE(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function lE(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Gt(t,T.piPackagesManage)?{state:`supported`}:{state:`unsupported`,message:fE(e)}:{state:`unknown`}}function uE(e){return`${e.state}:${e.message??``}`}function dE(e){return e?.state===`unsupported`}function fE(e){return`Pi package management is not available on ${e.name}. Update and restart Pi-Web on that machine, then try again.`}function pE(e){return e.kind===`local`}function mE(e){return e.trim()}function hE(e){if(mE(e)===``)return`Enter a Pi package source accepted by Pi, such as npm:@scope/package, a git/URL source, or a local path.`}function gE(e){return e.scope===`project`?`Project scope`:`User scope`}function _E(e){return e.filtered?`Filtered by current Pi package settings`:`Available in this PI WEBUI process`}function vE(e){return e.installedPath??`Installed path not reported by Pi`}function yE(e){return e.scope===`user`}function bE(e){if(!yE(e))return`Project-scope Pi packages are listed for visibility, but PI WEBUI only updates user-scope Pi packages safely from this view.`}function xE(e){return e.length>0&&e.every(yE)}function SE(e){if(e.length===0)return`No Pi packages are configured yet.`;if(!xE(e))return`Update all is disabled while project-scope Pi packages are listed; update user-scope packages individually.`}function CE(e,t,n){return e?.kind===t?n===void 0||e.source===n:!1}function wE(e,t=sE(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 TE(e,t){let n=e.trim();return t.kind===`remote`?EE(n)?fE(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 EE(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 DE=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=cE(t),r=this.packageManagementUnavailable,i=this.packagesResponse!==void 0&&!r;return g`
|
|
4452
4562
|
<settings-panel-frame
|
|
4453
4563
|
heading="Pi packages"
|
|
4454
|
-
.description=${
|
|
4564
|
+
.description=${OE(n)}
|
|
4455
4565
|
actionLabel="Reload"
|
|
4456
4566
|
actionTitle=${r?this.packageManagementUnavailableMessage(n):`Reload Pi packages from ${n}`}
|
|
4457
4567
|
.actionDisabled=${this.loading||this.isOperating||r}
|
|
@@ -4468,12 +4578,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4468
4578
|
<label for="package-source">Pi package source</label>
|
|
4469
4579
|
<div class="install-row">
|
|
4470
4580
|
<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}>${
|
|
4581
|
+
<button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${CE(this.operation,`install`)?`Installing…`:`Install`}</button>
|
|
4472
4582
|
</div>
|
|
4473
4583
|
${this.validationMessage===``?null:g`<div class="field-error">${this.validationMessage}</div>`}
|
|
4474
4584
|
<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
4585
|
</form>
|
|
4476
|
-
`}renderPackageList(e,t){let n=
|
|
4586
|
+
`}renderPackageList(e,t){let n=cE(t),r=this.packageManagementUnavailable?this.packageManagementUnavailableMessage(n):SE(e),i=r!==void 0&&e.length>0;return g`
|
|
4477
4587
|
<section class="package-section" aria-label="Configured Pi packages">
|
|
4478
4588
|
<div class="package-toolbar">
|
|
4479
4589
|
<div>
|
|
@@ -4481,7 +4591,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4481
4591
|
<p>This list comes from Pi's package manager settings on ${n}.</p>
|
|
4482
4592
|
</div>
|
|
4483
4593
|
<button class="secondary" title=${r??`Update all user-scope Pi packages`} ?disabled=${this.isOperating||r!==void 0} @click=${()=>{this.updatePackage()}}>
|
|
4484
|
-
${
|
|
4594
|
+
${CE(this.operation,`update-all`)?`Updating…`:`Update all`}
|
|
4485
4595
|
</button>
|
|
4486
4596
|
</div>
|
|
4487
4597
|
${i?g`<div class="action-note">${r}</div>`:null}
|
|
@@ -4492,12 +4602,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4492
4602
|
<div class="package-list">
|
|
4493
4603
|
${e.map(e=>this.renderPackage(e))}
|
|
4494
4604
|
</div>
|
|
4495
|
-
`}renderPackage(e){let t=
|
|
4605
|
+
`}renderPackage(e){let t=cE(this.packageTarget),n=this.packageManagementUnavailable,r=n?this.packageManagementUnavailableMessage(t):bE(e),i=n?this.packageManagementUnavailableMessage(t):`Remove this Pi package`,a=CE(this.operation,`update`,e.source),o=CE(this.operation,`remove`,e.source);return g`
|
|
4496
4606
|
<article class=${`package-card${e.filtered?` filtered`:``}`}>
|
|
4497
4607
|
<div class="package-main">
|
|
4498
4608
|
<strong>${e.source}</strong>
|
|
4499
|
-
<small>${
|
|
4500
|
-
<small>Installed path: <code>${
|
|
4609
|
+
<small>${gE(e)} · ${_E(e)}</small>
|
|
4610
|
+
<small>Installed path: <code>${vE(e)}</code></small>
|
|
4501
4611
|
${r===void 0?null:g`<small class="action-note">${r}</small>`}
|
|
4502
4612
|
</div>
|
|
4503
4613
|
<div class="package-actions">
|
|
@@ -4505,7 +4615,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4505
4615
|
<button class="danger" title=${i} ?disabled=${this.isOperating||n} @click=${()=>{this.removePackage(e)}}>${o?`Removing…`:`Remove`}</button>
|
|
4506
4616
|
</div>
|
|
4507
4617
|
</article>
|
|
4508
|
-
`}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=
|
|
4618
|
+
`}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=hE(this.installSource);if(t!==void 0){this.validationMessage=t;return}let n=mE(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??sE(void 0)}get packageManagementUnavailable(){return dE(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
4619
|
:host { display: block; }
|
|
4510
4620
|
.package-toolbar { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
4511
4621
|
.package-toolbar > div, .package-main { display: grid; gap: 6px; min-width: 0; }
|
|
@@ -4540,10 +4650,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4540
4650
|
.package-actions { justify-self: start; flex-wrap: wrap; }
|
|
4541
4651
|
.package-main strong, .package-main small { white-space: normal; }
|
|
4542
4652
|
}
|
|
4543
|
-
`}};B([x({attribute:!1})],
|
|
4653
|
+
`}};B([x({attribute:!1})],DE.prototype,`packagesResponse`,void 0),B([x({type:Boolean})],DE.prototype,`loading`,void 0),B([x({attribute:!1})],DE.prototype,`operation`,void 0),B([x({attribute:!1})],DE.prototype,`targetMachine`,void 0),B([x({attribute:!1})],DE.prototype,`managementSupport`,void 0),B([x()],DE.prototype,`error`,void 0),B([x()],DE.prototype,`operationMessage`,void 0),B([x({attribute:!1})],DE.prototype,`onReload`,void 0),B([x({attribute:!1})],DE.prototype,`onInstallPackage`,void 0),B([x({attribute:!1})],DE.prototype,`onRemovePackage`,void 0),B([x({attribute:!1})],DE.prototype,`onUpdatePackage`,void 0),B([S()],DE.prototype,`installSource`,void 0),B([S()],DE.prototype,`validationMessage`,void 0),DE=B([b(`settings-packages-panel`)],DE);function OE(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 kE=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
4654
|
<settings-panel-frame
|
|
4545
4655
|
heading="PI WEBUI plugins"
|
|
4546
|
-
.description=${
|
|
4656
|
+
.description=${AE(this.targetLabel)}
|
|
4547
4657
|
actionLabel="Reload"
|
|
4548
4658
|
actionTitle=${`Reload PI WEBUI plugins from ${this.targetLabel}`}
|
|
4549
4659
|
.actionDisabled=${this.loading}
|
|
@@ -4589,10 +4699,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4589
4699
|
.plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
4590
4700
|
.toggle { justify-self: start; }
|
|
4591
4701
|
}
|
|
4592
|
-
`}};B([x({attribute:!1})],
|
|
4702
|
+
`}};B([x({attribute:!1})],kE.prototype,`pluginsResponse`,void 0),B([x({attribute:!1})],kE.prototype,`configResponse`,void 0),B([x({type:Boolean})],kE.prototype,`loading`,void 0),B([x({type:Boolean})],kE.prototype,`saving`,void 0),B([x()],kE.prototype,`error`,void 0),B([x()],kE.prototype,`savedMessage`,void 0),B([x()],kE.prototype,`targetLabel`,void 0),B([x({attribute:!1})],kE.prototype,`onReload`,void 0),B([x({attribute:!1})],kE.prototype,`onTogglePlugin`,void 0),kE=B([b(`settings-plugins-panel`)],kE);function AE(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 jE={capture:!0},ME=[{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 NE(){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 PE=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=QS(),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=RE(this.actions),t=this.shortcutResolutions();return g`
|
|
4593
4703
|
<settings-panel-frame
|
|
4594
4704
|
heading="Keyboard shortcuts"
|
|
4595
|
-
.description=${
|
|
4705
|
+
.description=${NE()}
|
|
4596
4706
|
actionLabel="Reload"
|
|
4597
4707
|
.actionDisabled=${this.loading}
|
|
4598
4708
|
.notices=${this.panelNotices()}
|
|
@@ -4623,7 +4733,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4623
4733
|
<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
4734
|
</div>
|
|
4625
4735
|
<div class="prompt-enter-options" role="radiogroup" aria-label="Enter and Shift Enter behavior in the chat composer">
|
|
4626
|
-
${
|
|
4736
|
+
${ME.map(e=>g`
|
|
4627
4737
|
<label class="prompt-enter-option">
|
|
4628
4738
|
<input
|
|
4629
4739
|
type="radio"
|
|
@@ -4640,8 +4750,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4640
4750
|
`)}
|
|
4641
4751
|
</div>
|
|
4642
4752
|
</section>
|
|
4643
|
-
`}updatePromptEnterPreference(e){this.promptEnterPreference=e
|
|
4644
|
-
<article class=${
|
|
4753
|
+
`}updatePromptEnterPreference(e){this.promptEnterPreference=e,$S(e)}renderShortcutRow(e,t){let n=this.configResponse?.config.shortcuts,r=BE(e.id,n),i=UE(e,n),a=this.shortcutInputText(e),o=a.trim()===``?void 0:sf(a),s=o?.ok===!0?o.shortcut:HE(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=LE(t);return g`
|
|
4754
|
+
<article class=${FE(t)}>
|
|
4645
4755
|
<div class="shortcut-main">
|
|
4646
4756
|
<strong>${e.title}</strong>
|
|
4647
4757
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
@@ -4651,8 +4761,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4651
4761
|
<div class="shortcut-editor">
|
|
4652
4762
|
<div class="shortcut-status">
|
|
4653
4763
|
${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=${
|
|
4764
|
+
<small class=${u}>${WE(u)}${l?` · Unsaved`:``}</small>
|
|
4765
|
+
${f===void 0?null:g`<small class=${IE(t)}>${f}</small>`}
|
|
4656
4766
|
</div>
|
|
4657
4767
|
<label class="shortcut-input-label">
|
|
4658
4768
|
<span>Shortcut</span>
|
|
@@ -4665,7 +4775,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4665
4775
|
autocapitalize="off"
|
|
4666
4776
|
spellcheck="false"
|
|
4667
4777
|
?disabled=${this.saving}
|
|
4668
|
-
@input=${t=>{this.updateDraft(e.id,
|
|
4778
|
+
@input=${t=>{this.updateDraft(e.id,GE(t))}}
|
|
4669
4779
|
>
|
|
4670
4780
|
</label>
|
|
4671
4781
|
${d===``?null:g`<small class="recording-hint">${d}</small>`}
|
|
@@ -4677,7 +4787,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4677
4787
|
</div>
|
|
4678
4788
|
</div>
|
|
4679
4789
|
</article>
|
|
4680
|
-
`}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=
|
|
4790
|
+
`}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=BE(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?VE(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,jE),!0)}removeRecordingListener(){this.recordingListenerActive&&=(window.removeEventListener(`keydown`,this.onRecordKeyDown,jE),!1)}static{this.styles=h`
|
|
4681
4791
|
:host { display: block; }
|
|
4682
4792
|
h3, p { margin: 0; }
|
|
4683
4793
|
h3 { font-size: 13px; line-height: 1.3; }
|
|
@@ -4733,7 +4843,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4733
4843
|
.shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
4734
4844
|
.shortcut-status, .shortcut-actions { justify-content: flex-start; }
|
|
4735
4845
|
}
|
|
4736
|
-
`}};B([x({attribute:!1})],
|
|
4846
|
+
`}};B([x({attribute:!1})],PE.prototype,`actions`,void 0),B([x({attribute:!1})],PE.prototype,`configResponse`,void 0),B([x({type:Boolean})],PE.prototype,`loading`,void 0),B([x({type:Boolean})],PE.prototype,`saving`,void 0),B([x()],PE.prototype,`error`,void 0),B([x()],PE.prototype,`savedMessage`,void 0),B([x({attribute:!1})],PE.prototype,`onReload`,void 0),B([x({attribute:!1})],PE.prototype,`onSave`,void 0),B([S()],PE.prototype,`drafts`,void 0),B([S()],PE.prototype,`localError`,void 0),B([S()],PE.prototype,`promptEnterPreference`,void 0),B([S()],PE.prototype,`recording`,void 0),PE=B([b(`settings-shortcuts-panel`)],PE);function FE(e){return e?.active===!1?`shortcut-row shadowed`:e?.active===!0&&e.shadows.length>0?`shortcut-row shadowing`:`shortcut-row`}function IE(e){return e?.active===!1?`conflict shadowed`:`conflict shadowing`}function LE(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 RE(e){let t=new Map;for(let n of[...e].sort(zE)){let e=n.group??`Other`;t.set(e,[...t.get(e)??[],n])}return[...t.entries()].map(([e,t])=>({name:e,actions:t}))}function zE(e,t){return(e.group??`Other`).localeCompare(t.group??`Other`)||e.title.localeCompare(t.title)}function BE(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function VE(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function HE(e,t){let n=BE(e.id,t);if(n!==null)return n??e.shortcut}function UE(e,t){let n=BE(e.id,t);return n===null?`disabled`:n===void 0?e.shortcut===void 0||e.shortcut===``?`unassigned`:`default`:`custom`}function WE(e){switch(e){case`default`:return`Default`;case`custom`:return`Custom`;case`disabled`:return`Disabled`;case`unassigned`:return`No default`}}function GE(e){return e.target instanceof HTMLInputElement?e.target.value:``}async function KE(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: ${JE(t.reason)}`),n.status===`fulfilled`?r.plugins=n.value:i.push(`PI WEBUI plugins: ${JE(n.reason)}`),i.length>0&&(r.error=`Failed to load settings: ${i.join(`; `)}`),r}async function qE(e,t,n){if(dE(n))return{error:n.message??`Pi package management is not available on ${cE(e)}.`,skipped:!0};try{return{packagesResponse:await t(e.id),error:``}}catch(t){return{error:`Failed to load Pi packages from ${cE(e)}: ${TE(JE(t),e)}`}}}function JE(e){return e instanceof Error?e.message:String(e)}function YE(e,t){return{...e,config:XE(e.config,t.config),effectiveConfig:XE(e.effectiveConfig,t.effectiveConfig)}}function XE(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 ZE(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function QE(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function $E(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?Gt(t,T.selectedMachineSettings)?{state:`supported`}:{state:`unsupported`,message:iD(e)}:{state:`unknown`}}function eD(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 tD(e){return`${e.state}:${e.message??``}`}function nD(e){return e?.state===`unsupported`}function rD(e){return e?.state===`supported`}function iD(e){return`Selected-machine settings are not available on ${e.name}. Update and restart PI WEBUI on that machine, then try again.`}function aD(e,t){let n=e.trim();return t.kind===`remote`?oD(n)?iD(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 oD(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 sD(e,t,n){let r=e.plugins??{},i=r[t]??{};return{plugins:{...r,[t]:{...i,enabled:n}}}}function cD(e,t){return{...e,config:lD(e.config,t.config),effectiveConfig:lD(e.effectiveConfig,t.effectiveConfig)}}function lD(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`)&&ZE(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
4847
|
<div class="backdrop" @mousedown=${()=>this.onClose?.()}>
|
|
4738
4848
|
<section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEBUI settings" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
4739
4849
|
<header class="settings-header">
|
|
@@ -4764,7 +4874,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4764
4874
|
.saving=${this.saving}
|
|
4765
4875
|
.error=${this.sessiondError}
|
|
4766
4876
|
.savedMessage=${this.savedMessage}
|
|
4767
|
-
.targetLabel=${
|
|
4877
|
+
.targetLabel=${QE(this.settingsTarget())}
|
|
4768
4878
|
.activeAgentProfile=${this.machineRuntime?.components?.sessiond.activeAgentProfile}
|
|
4769
4879
|
.agentProfileSupport=${this.agentProfileSettingsSupport()}
|
|
4770
4880
|
.onReload=${()=>this.reloadSessiondState()}
|
|
@@ -4803,7 +4913,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4803
4913
|
.saving=${this.saving}
|
|
4804
4914
|
.error=${this.pluginError}
|
|
4805
4915
|
.savedMessage=${this.savedMessage}
|
|
4806
|
-
.targetLabel=${
|
|
4916
|
+
.targetLabel=${QE(this.settingsTarget())}
|
|
4807
4917
|
.onReload=${()=>this.loadPluginsForTarget()}
|
|
4808
4918
|
.onTogglePlugin=${(e,t)=>this.togglePlugin(e,t)}
|
|
4809
4919
|
></settings-plugins-panel>
|
|
@@ -4817,7 +4927,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4817
4927
|
.error=${this.error}
|
|
4818
4928
|
.machineError=${this.accessError}
|
|
4819
4929
|
.savedMessage=${this.savedMessage}
|
|
4820
|
-
.targetLabel=${
|
|
4930
|
+
.targetLabel=${QE(this.settingsTarget())}
|
|
4821
4931
|
.onReload=${()=>this.loadConfig()}
|
|
4822
4932
|
.onReloadMachine=${()=>this.loadAccessConfigForTarget()}
|
|
4823
4933
|
.onSave=${e=>this.saveConfig(e)}
|
|
@@ -4828,7 +4938,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4828
4938
|
<strong>${t}</strong>
|
|
4829
4939
|
<small>${n}</small>
|
|
4830
4940
|
</button>
|
|
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`
|
|
4941
|
+
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await KE({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(nD(n)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=n.message??`Selected-machine settings are not available on ${QE(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 ${QE(e)}: ${aD(uD(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(nD(n)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=n.message??`Selected-machine settings are not available on ${QE(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 ${QE(e)}: ${aD(uD(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(nD(n)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=n.message??`Selected-machine settings are not available on ${QE(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: ${aD(uD(n.reason),e)}`),r.status===`fulfilled`?this.selectedPluginsResponse=r.value:i.push(`PI WEBUI plugins: ${aD(uD(r.reason),e)}`),this.pluginError=i.length===0?``:`Failed to load PI WEBUI plugin settings from ${QE(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 qE(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(nD(r)){this.pluginError=r.message??`Selected-machine settings are not available on ${QE(n)}.`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${QE(n)}. Reload before changing plugin enablement.`;return}let i=sD(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=cD(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 ${QE(n)}: ${aD(uD(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: ${uD(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(nD(n)){this.accessError=n.message??`Selected-machine settings are not available on ${QE(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=YE(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 ${QE(t)}: ${aD(uD(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(nD(n)){this.sessiondError=n.message??`Selected-machine settings are not available on ${QE(t)}.`;return}if(e.agent!==void 0){let e=this.agentProfileSettingsSupport(t);if(!rD(e)){this.sessiondError=e.message??`Pi-compatible agent profile settings are not available on ${QE(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=$T(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${QE(t)}: ${aD(uD(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(dE(i))throw this.packageError=i.message??`Pi package management is not available on ${cE(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=pE(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(a,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=wE(e.action,n)}catch(e){throw this.isCurrentPackageMutation(a,n)&&(this.packageError=`Failed to ${t} on ${cE(n)}: ${TE(uD(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: ${uD(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 ${QE(e)}: ${aD(uD(t),e)}`}}settingsTarget(){return ZE(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return $E(e,this.machineRuntime)}agentProfileSettingsSupport(e=this.settingsTarget()){return eD(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){let n=$E(t,e),r=this.selectedMachineSettingsSupport(t);return tD(n)!==tD(r)}packageManagementSupport(e=this.packageTarget()){return lE(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){let n=lE(t,e),r=this.packageManagementSupport(t);return uE(n)===uE(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
4942
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
4833
4943
|
.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
4944
|
.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 +4965,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4855
4965
|
.settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
|
|
4856
4966
|
.settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
|
|
4857
4967
|
}
|
|
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
|
|
4968
|
+
`}};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 uD(e){return e instanceof Error?e.message:String(e)}var dD=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`)&&pD(e.get(`session`))!==pD(this.session),n=e.has(`machine`)&&fD(e.get(`machine`))!==fD(this.machine);(t||n)&&this.isConnected&&this.loadSystemPrompt()}render(){return g`
|
|
4859
4969
|
<div class="backdrop" @mousedown=${e=>{e.target===e.currentTarget&&this.close()}}>
|
|
4860
4970
|
<section class="dialog" role="dialog" aria-modal="true" aria-labelledby="system-prompt-dialog-title" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
4861
4971
|
<header>
|
|
@@ -4864,7 +4974,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4864
4974
|
<h1 id="system-prompt-dialog-title">System prompt</h1>
|
|
4865
4975
|
</div>
|
|
4866
4976
|
<button class="icon-button" type="button" title="Close system prompt" aria-label="Close system prompt" @click=${()=>{this.close()}}>
|
|
4867
|
-
${
|
|
4977
|
+
${_D()}
|
|
4868
4978
|
</button>
|
|
4869
4979
|
</header>
|
|
4870
4980
|
<div class="prompt-body" aria-live="polite">
|
|
@@ -4875,7 +4985,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4875
4985
|
</footer>
|
|
4876
4986
|
</section>
|
|
4877
4987
|
</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:
|
|
4988
|
+
`}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:hD(fD(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,fD(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: ${gD(e)}`}finally{this.isCurrentLoad(n,t)&&(this.loading=!1)}}isCurrentLoad(e,t){let n=this.session;return e===this.loadRequestSequence&&n!==void 0&&hD(fD(this.machine),n)===t}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),this.close())}close(){this.onClose?.()}static{this.styles=h`
|
|
4879
4989
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
4880
4990
|
* { box-sizing: border-box; }
|
|
4881
4991
|
.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 +5011,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4901
5011
|
header, footer { padding: 12px; }
|
|
4902
5012
|
.system-prompt, .prompt-state { padding: 12px; }
|
|
4903
5013
|
}
|
|
4904
|
-
`}};B([x({attribute:!1})],
|
|
5014
|
+
`}};B([x({attribute:!1})],dD.prototype,`machine`,void 0),B([x({attribute:!1})],dD.prototype,`session`,void 0),B([x({attribute:!1})],dD.prototype,`sessionsApi`,void 0),B([x({attribute:!1})],dD.prototype,`onClose`,void 0),B([S()],dD.prototype,`systemPrompt`,void 0),B([S()],dD.prototype,`loading`,void 0),B([S()],dD.prototype,`error`,void 0),dD=B([b(`system-prompt-dialog`)],dD);function fD(e){return e?.id??`local`}function pD(e){return e===void 0?void 0:mD(e)}function mD(e){return JSON.stringify([e.id,e.cwd])}function hD(e,t){return JSON.stringify([e,t.id,t.cwd])}function gD(e){return e instanceof Error?e.message:String(e)}function _D(){return _`
|
|
4905
5015
|
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
4906
5016
|
<path d="M6 6l12 12M18 6 6 18"></path>
|
|
4907
5017
|
</svg>
|
|
4908
|
-
`}var
|
|
5018
|
+
`}var vD=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
5019
|
${this.hideToolTabs?null:g`
|
|
4910
5020
|
<header>
|
|
4911
5021
|
<div class=${this.workspaceHeaderFrameClass()}>
|
|
@@ -4935,10 +5045,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4935
5045
|
<h2>${e.title}</h2>
|
|
4936
5046
|
${e.body===void 0?null:g`<p>${e.body}</p>`}
|
|
4937
5047
|
</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
|
|
5048
|
+
`}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})],vD.prototype,`workspace`,void 0),B([x({attribute:!1})],vD.prototype,`panelContext`,void 0),B([x({attribute:!1})],vD.prototype,`emptyState`,void 0),B([x()],vD.prototype,`tool`,void 0),B([x({attribute:!1})],vD.prototype,`panels`,void 0),B([x({attribute:!1})],vD.prototype,`hiddenTools`,void 0),B([x({type:Boolean})],vD.prototype,`hideToolTabs`,void 0),B([x({attribute:!1})],vD.prototype,`onSelectTool`,void 0),B([C(`.workspace-header-strip`)],vD.prototype,`workspaceHeaderStrip`,void 0),B([S()],vD.prototype,`workspaceHeaderCanScrollLeft`,void 0),B([S()],vD.prototype,`workspaceHeaderCanScrollRight`,void 0),vD=B([b(`workspace-panel`)],vD);var yD=`important`,bD=` !important`,xD=C_(class extends w_{constructor(e){if(super(e),e.type!==S_.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(bD);e.includes(`-`)||t?n.setProperty(e,t?r.slice(0,-11):r,t?yD:``):n[e]=r}}return Qe}}),SD=`#ffffff`,CD=`#000000`,wD=[`#2e3436`,`#cc0000`,`#4e9a06`,`#c4a000`,`#3465a4`,`#75507b`,`#06989a`,`#d3d7cf`,`#555753`,`#ef2929`,`#8ae234`,`#fce94f`,`#729fcf`,`#ad7fa8`,`#34e2e2`,`#eeeeec`],TD=[`black`,`red`,`green`,`yellow`,`blue`,`magenta`,`cyan`,`white`,`brightBlack`,`brightRed`,`brightGreen`,`brightYellow`,`brightBlue`,`brightMagenta`,`brightCyan`,`brightWhite`],ED={black:wD[0],red:wD[1],green:wD[2],yellow:wD[3],blue:wD[4],magenta:wD[5],cyan:wD[6],white:wD[7],brightBlack:wD[8],brightRed:wD[9],brightGreen:wD[10],brightYellow:wD[11],brightBlue:wD[12],brightMagenta:wD[13],brightCyan:wD[14],brightWhite:wD[15]};function DD(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=FD(n.theme),a=n.theme?.foreground??SD,o=n.theme?.background??CD,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=OD(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,MD(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(`
|
|
5049
|
+
`),lines:p,physicalLineCount:f.length,viewportLine:Math.min(d,Math.max(0,e.viewportY))}}function OD(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:jD(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:kD(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,ND(s,{text:t.text,style:t.style}))}return{text:c,runs:s,wrapped:e.isWrapped}}function kD(e,t){let n=e.isInverse()!==0,r=AD(e,`foreground`,t),i=AD(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 AD(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?ID(a):i?n.palette[a]??(t===`foreground`?n.foreground:n.background):t===`foreground`?n.foreground:n.background}function jD(e){return{foreground:e.foreground,background:e.background,bold:!1,italic:!1,dim:!1,underline:!1,invisible:!1,strikethrough:!1,overline:!1}}function MD(e,t){for(let n of t)ND(e,n)}function ND(e,t){if(t.text===``)return;let n=e.at(-1);if(n!==void 0&&PD(n.style,t.style)){n.text+=t.text;return}e.push({text:t.text,style:t.style})}function PD(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 FD(e){let t=[...wD];for(let n=0;n<TD.length;n+=1){let r=TD[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(LD(r,i,a))}for(let e=0;e<24;e+=1){let n=8+e*10;t.push(LD(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 ID(e){return`#${(e&16777215).toString(16).padStart(6,`0`)}`}function LD(e,t,n){return`#${e.toString(16).padStart(2,`0`)}${t.toString(16).padStart(2,`0`)}${n.toString(16).padStart(2,`0`)}`}var RD=`pi-webui.terminal.softKeys`,zD=`(pointer: coarse), (max-width: 760px)`;function BD(e,t){return e??t}function VD(e){if(e===`true`)return!0;if(e===`false`)return!1}function HD(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(zD):void 0}function UD(e){return e?.matches===!0}function WD(e=HD()){return BD(KD(),UD(e))}function GD(){return KD()!==void 0}function KD(e=JD()){if(e!==void 0)try{return VD(e.getItem(RD))}catch{return}}function qD(e,t=JD()){if(t!==void 0)try{t.setItem(RD,String(e))}catch{}}function JD(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var YD=[{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`}],XD=`\x1B`,ZD=``;function QD(e,t){switch(e){case`escape`:return XD;case`tab`:return` `;case`ctrl-c`:return $D(`c`);case`ctrl-d`:return $D(`d`);case`ctrl-z`:return $D(`z`);case`ctrl-l`:return $D(`l`);case`ctrl-r`:return $D(`r`);case`ctrl-u`:return $D(`u`);case`ctrl-w`:return $D(`w`);case`arrow-left`:return eO(`D`,t);case`arrow-up`:return eO(`A`,t);case`arrow-down`:return eO(`B`,t);case`arrow-right`:return eO(`C`,t);case`home`:return tO(`H`,t);case`end`:return tO(`F`,t);case`page-up`:return`${XD}[5~`;case`page-down`:return`${XD}[6~`;case`delete`:return`${XD}[3~`;case`backspace`:return ZD;case`meta-backward-word`:return`${XD}b`;case`meta-forward-word`:return`${XD}f`}}function $D(e){return String.fromCharCode(e.toUpperCase().charCodeAt(0)-64)}function eO(e,t){return t?.applicationCursorKeysMode===!0?`${XD}O${e}`:`${XD}[${e}`}function tO(e,t){return t?.applicationCursorKeysMode===!0?`${XD}O${e}`:`${XD}[${e}`}var nO=8,rO=500,iO=class extends y{constructor(...e){super(...e),this.refocusOnClick=!0,this.onInput=()=>void 0,this.lastPointerFinishedAt=0}sendSoftKey(e,t){this.onInput(QD(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&&aO(t,e)&&this.finishSoftKeyPointer()}onSoftKeyPointerUp(e,t){let n=this.pointerStart;n?.pointerId===e.pointerId&&(e.preventDefault(),this.finishSoftKeyPointer(),!(n.key.id!==t.id||aO(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<rO){e.preventDefault();return}this.sendSoftKey(t,{refocus:this.refocusOnClick})}render(){return g`
|
|
4940
5050
|
<div class="terminal-soft-keys" role="toolbar" aria-label="Terminal soft keys">
|
|
4941
|
-
${
|
|
5051
|
+
${YD.map(e=>g`
|
|
4942
5052
|
<button
|
|
4943
5053
|
type="button"
|
|
4944
5054
|
class="soft-key"
|
|
@@ -4958,7 +5068,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4958
5068
|
.terminal-soft-keys::-webkit-scrollbar { display: none; }
|
|
4959
5069
|
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
5070
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
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`
|
|
5071
|
+
`}};B([x({attribute:!1})],iO.prototype,`modes`,void 0),B([x({type:Boolean})],iO.prototype,`refocusOnClick`,void 0),B([x({attribute:!1})],iO.prototype,`onInput`,void 0),iO=B([b(`terminal-soft-keys`)],iO);function aO(e,t){return Math.hypot(t.clientX-e.clientX,t.clientY-e.clientY)>nO}var oO=oe({TerminalPanel:()=>Z,filterTerminalInput:()=>vO,terminalBackgroundWithOpacity:()=>wO}),sO={allowTransparency:!0,cursorBlink:!0,convertEol:!0,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,fontSize:13},cO={cols:100,rows:30},lO=1e3,uO=`--pi-terminal-effective-bg`,dO=`--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=WD(),this.suppressTerminalInput=!1,this.softKeysDefaultEnvironmentMedia=HD(),this.softKeysPreferenceStored=GD(),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=UD(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()??cO,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&&hO(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()},lO);return}!e&&this.commandRunPollTimer!==void 0&&(window.clearInterval(this.commandRunPollTimer),this.commandRunPollTimer=void 0)}hasPendingCommandRuns(e=this.commandRuns){return e.some(hO)}async cancelCommandRun(e){if(!(!hO(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(bO(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=_O(await yO(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=TO(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(bO(this)),r=new ie;n.loadAddon(r),n.open(t);let i=TO(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=xO(this))}syncTerminalBackground(){let e=CO(this.bgOpacity),t=wO(SO(this,`--pi-terminal-bg`,`#05070a`),e);this.style.setProperty(uO,t),this.style.setProperty(dO,`${String(e)}%`)}sendTerminalInput(e){let t=vO(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(hO(e)){let t=this.cancellingRunIds.includes(e.id);return g`
|
|
4962
5072
|
<section class="command-run-notice running">
|
|
4963
5073
|
<div>
|
|
4964
5074
|
<strong>${e.title}</strong>
|
|
@@ -4970,13 +5080,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4970
5080
|
`}if(t?.exited===!0){let n=this.continuingTerminalIds.includes(t.id);return g`
|
|
4971
5081
|
<section class=${`command-run-notice ${e.status}`}>
|
|
4972
5082
|
<div>
|
|
4973
|
-
<strong>${
|
|
5083
|
+
<strong>${gO(e)}</strong>
|
|
4974
5084
|
<p>Output is preserved. Continue in a shell to inspect or run follow-up commands.</p>
|
|
4975
5085
|
<code>${e.command}</code>
|
|
4976
5086
|
</div>
|
|
4977
5087
|
<button ?disabled=${n} @click=${()=>{this.continueTerminal(t.id)}}>${n?`Starting shell…`:`Continue in shell`}</button>
|
|
4978
5088
|
</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=
|
|
5089
|
+
`}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=DD(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=fO(e.scrollTop,n,r),t.scrollLeft=fO(e.scrollLeft,i,a)}async copyAllSnapshotText(){let e=this.copySnapshot?.text??``;if(e===``){this.copyStatus=`No terminal output to copy.`;return}this.copyStatus=await iy(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
5090
|
<button
|
|
4981
5091
|
type="button"
|
|
4982
5092
|
class=${e?`copy-mode-toggle selected`:`copy-mode-toggle`}
|
|
@@ -4999,7 +5109,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4999
5109
|
${this.copyToolbarReplacesSoftKeys()?null:this.renderCopyModeToolbar()}
|
|
5000
5110
|
<div class="terminal-copy-layers">
|
|
5001
5111
|
<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=${
|
|
5112
|
+
`}${e.runs.map(e=>g`<span style=${xD(mO(e.style))}>${e.text}</span>`)}`)}</pre>
|
|
5003
5113
|
<textarea
|
|
5004
5114
|
class="terminal-copy-selector"
|
|
5005
5115
|
readonly
|
|
@@ -5014,7 +5124,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5014
5124
|
></textarea>
|
|
5015
5125
|
</div>
|
|
5016
5126
|
</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,
|
|
5127
|
+
`}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,qD(this.softKeysEnabled),this.scheduleFitAndNotify())}renderSoftKeysToggle(){return this.shouldShowSoftKeysToggle()?g`
|
|
5018
5128
|
<button
|
|
5019
5129
|
type="button"
|
|
5020
5130
|
class=${this.softKeysEnabled?`soft-keys-toggle selected`:`soft-keys-toggle`}
|
|
@@ -5135,32 +5245,32 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5135
5245
|
.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
5246
|
.muted { margin: 10px; color: var(--pi-muted); }
|
|
5137
5247
|
.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
|
|
5248
|
+
`}};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 fO(e,t,n){return t<=0||n<=0?0:Math.min(1,Math.max(0,e/t))*n}function pO(e){return/^#[\da-f]{6}$/i.test(e)?`${e}80`:`color-mix(in srgb, ${e} 50%, transparent)`}function mO(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?pO(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 hO(e){return e.status===`queued`||e.status===`running`}function gO(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 _O(e){let t=JSON.parse(e);if(!DO(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 vO(e){return e.replaceAll(`\x1B[I`,``).replaceAll(`\x1B[O`,``)}async function yO(e){return typeof e==`string`?e:e instanceof ArrayBuffer?new TextDecoder().decode(e):e instanceof Blob?await e.text():String(e)}function bO(e){let t=sO;return e instanceof Z?{...t,fontSize:e.fontSize,theme:xO(e)}:{...t,theme:xO(e)}}function xO(e){let t=wO(SO(e,`--pi-terminal-bg`,`#05070a`),e instanceof Z?e.bgOpacity:100);return{...ED,background:t,foreground:SO(e,`--pi-terminal-text`,`#e6edf3`),cursor:SO(e,`--pi-accent`,`#58a6ff`),selectionBackground:SO(e,`--pi-terminal-selection`,`#264f78`)}}function SO(e,t,n){let r=getComputedStyle(e).getPropertyValue(t).trim();return r===``?n:r}function CO(e){return Math.max(0,Math.min(100,e))}function wO(e,t){let n=CO(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 TO(e){if(!(e===void 0||!EO(e.cols,e.rows)))return{cols:Math.floor(e.cols),rows:Math.floor(e.rows)}}function EO(e,t){return Number.isFinite(e)&&Number.isFinite(t)&&e>0&&t>0}function DO(e){return typeof e==`object`&&!!e}var OO=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=kO(this.machines),t=AO(this.machine),n=MO(this.project),r=PO(this.workspace),i=IO(this.session);return g`
|
|
5139
5249
|
<nav class=${this.contextBarClass()} aria-label="Current location">
|
|
5140
5250
|
<span class="context-bar-label">Location</span>
|
|
5141
5251
|
<ol class="context-items" @scroll=${this.onContextScroll}>
|
|
5142
5252
|
${e?g`
|
|
5143
5253
|
<li class="context-item">
|
|
5144
|
-
<button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${
|
|
5254
|
+
<button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${jO(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.(`machines`)}}>
|
|
5145
5255
|
<span class="context-kind">Machine</span>
|
|
5146
5256
|
<span class="context-value">${t}</span>
|
|
5147
5257
|
</button>
|
|
5148
5258
|
</li>
|
|
5149
5259
|
`:null}
|
|
5150
5260
|
<li class="context-item">
|
|
5151
|
-
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${
|
|
5261
|
+
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${NO(this.project)} aria-label=${`Project: ${n}. Open project selection.`} @click=${()=>{this.onOpenSection?.(`projects`)}}>
|
|
5152
5262
|
<span class="context-kind">Project</span>
|
|
5153
5263
|
<span class="context-value">${n}</span>
|
|
5154
5264
|
</button>
|
|
5155
5265
|
</li>
|
|
5156
5266
|
<li class="context-item">
|
|
5157
|
-
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${
|
|
5267
|
+
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${FO(this.workspace)} aria-label=${`Workspace: ${r}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
|
|
5158
5268
|
<span class="context-kind">Workspace</span>
|
|
5159
5269
|
<span class="context-value">${r}</span>
|
|
5160
5270
|
</button>
|
|
5161
5271
|
</li>
|
|
5162
5272
|
<li class="context-item">
|
|
5163
|
-
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${
|
|
5273
|
+
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${LO(this.session)} aria-label=${`Session: ${i}. Open session selection.`} @click=${()=>{this.onOpenSection?.(`sessions`)}}>
|
|
5164
5274
|
<span class="context-kind">Session</span>
|
|
5165
5275
|
<span class="context-value">${i}</span>
|
|
5166
5276
|
</button>
|
|
@@ -5200,7 +5310,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5200
5310
|
.context-kind { display: none; }
|
|
5201
5311
|
.context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
|
|
5202
5312
|
button { cursor: pointer; }
|
|
5203
|
-
`}};B([x({attribute:!1})],
|
|
5313
|
+
`}};B([x({attribute:!1})],OO.prototype,`machines`,void 0),B([x({attribute:!1})],OO.prototype,`machine`,void 0),B([x({attribute:!1})],OO.prototype,`project`,void 0),B([x({attribute:!1})],OO.prototype,`workspace`,void 0),B([x({attribute:!1})],OO.prototype,`session`,void 0),B([x({attribute:!1})],OO.prototype,`refreshControl`,void 0),B([x({attribute:!1})],OO.prototype,`onOpenSection`,void 0),B([x({attribute:!1})],OO.prototype,`onShowActions`,void 0),B([C(`.context-items`)],OO.prototype,`contextItems`,void 0),B([S()],OO.prototype,`canScrollLeft`,void 0),B([S()],OO.prototype,`canScrollRight`,void 0),OO=B([b(`app-context-bar`)],OO);function kO(e){return e.length>1}function AO(e){return e===void 0?`No machine`:`${e.name}${e.kind===`remote`?` · remote`:``}`}function jO(e){return e===void 0?`No machine selected`:e.baseUrl??e.name}function MO(e){return e?.name??`No project`}function NO(e){return e===void 0?`No project selected`:`${e.name} — ${e.path}`}function PO(e){return e===void 0?`No workspace`:`${e.label}${e.isMain?` · main`:``} · ${e.path}`}function FO(e){return e===void 0?`No workspace selected`:`${e.label}${e.isMain?` · main`:``} — ${e.path}`}function IO(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`:X_(e.id)}function LO(e){return e===void 0?`No session selected`:e.path}var RO=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
5314
|
<div class=${this.frameClass()}>
|
|
5205
5315
|
<div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
|
|
5206
5316
|
${this.tabs.map(t=>{let n=this.selectedView===t.id;return g`
|
|
@@ -5239,12 +5349,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5239
5349
|
.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
5350
|
.tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
|
|
5241
5351
|
}
|
|
5242
|
-
`}};B([x({attribute:!1})],
|
|
5352
|
+
`}};B([x({attribute:!1})],RO.prototype,`tabs`,void 0),B([x({attribute:!1})],RO.prototype,`selectedView`,void 0),B([x({attribute:!1})],RO.prototype,`onSelect`,void 0),B([C(`.mobile-tabs`)],RO.prototype,`mobileTabs`,void 0),B([S()],RO.prototype,`canScrollLeft`,void 0),B([S()],RO.prototype,`canScrollRight`,void 0),RO=B([b(`app-mobile-main-tabs`)],RO);var zO=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=BO(e,this.statuses),n=e.name;return g`
|
|
5243
5353
|
<div class="machine-switcher">
|
|
5244
5354
|
<button
|
|
5245
5355
|
type="button"
|
|
5246
5356
|
class="machine-switcher-button"
|
|
5247
|
-
title=${
|
|
5357
|
+
title=${HO(e)}
|
|
5248
5358
|
aria-label=${this.machineSwitcherAriaLabel(e)}
|
|
5249
5359
|
aria-expanded=${String(this.open)}
|
|
5250
5360
|
@click=${e=>{this.toggleMenu(e.currentTarget)}}
|
|
@@ -5255,7 +5365,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5255
5365
|
<span class="machine-switcher-kicker">Machine</span>
|
|
5256
5366
|
<span class="machine-switcher-label">${n}</span>
|
|
5257
5367
|
</span>
|
|
5258
|
-
<span class=${`machine-status ${t}`}>${
|
|
5368
|
+
<span class=${`machine-status ${t}`}>${VO(t)}</span>
|
|
5259
5369
|
<span class="machine-chevron" aria-hidden="true">▾</span>
|
|
5260
5370
|
</button>
|
|
5261
5371
|
${this.open?g`
|
|
@@ -5264,18 +5374,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5264
5374
|
</div>
|
|
5265
5375
|
`:null}
|
|
5266
5376
|
</div>
|
|
5267
|
-
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=
|
|
5377
|
+
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=BO(e,this.statuses),r=b_(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return g`
|
|
5268
5378
|
<div class=${`machine-option ${t?`selected`:``} ${r?``:`no-actions`}`}>
|
|
5269
5379
|
<button
|
|
5270
5380
|
type="button"
|
|
5271
5381
|
class="machine-option-main"
|
|
5272
|
-
title=${
|
|
5382
|
+
title=${HO(e)}
|
|
5273
5383
|
data-machine-id=${e.id}
|
|
5274
5384
|
@click=${()=>{this.select(e)}}
|
|
5275
5385
|
@keydown=${e=>{this.handleMachineOptionKeydown(e)}}
|
|
5276
5386
|
>
|
|
5277
5387
|
<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`} · ${
|
|
5388
|
+
<small>${e.kind===`local`?`Local Pi WebUI`:e.baseUrl??`Remote Pi WebUI`} · ${VO(n)}</small>
|
|
5279
5389
|
</button>
|
|
5280
5390
|
${r?g`
|
|
5281
5391
|
<div class="machine-option-actions">
|
|
@@ -5295,7 +5405,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5295
5405
|
</div>
|
|
5296
5406
|
`:null}
|
|
5297
5407
|
</div>
|
|
5298
|
-
`}renderActivity(e){let t=
|
|
5408
|
+
`}renderActivity(e){let t=BO(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=UO(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=UO(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
5409
|
:host { min-width: 0; display: block; }
|
|
5300
5410
|
.machine-switcher { min-width: 0; }
|
|
5301
5411
|
.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 +5438,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5328
5438
|
.machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
|
|
5329
5439
|
.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
5440
|
@keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
|
|
5331
|
-
`}};B([x({attribute:!1})],
|
|
5441
|
+
`}};B([x({attribute:!1})],zO.prototype,`machines`,void 0),B([x({attribute:!1})],zO.prototype,`selected`,void 0),B([x({attribute:!1})],zO.prototype,`statuses`,void 0),B([x({attribute:!1})],zO.prototype,`activities`,void 0),B([x({attribute:!1})],zO.prototype,`onSelect`,void 0),B([x({attribute:!1})],zO.prototype,`onRemove`,void 0),B([x({attribute:!1})],zO.prototype,`onFocusNextSection`,void 0),B([x({attribute:!1})],zO.prototype,`onCancelKeyboardNavigation`,void 0),B([S()],zO.prototype,`open`,void 0),B([S()],zO.prototype,`menuStyle`,void 0),B([S()],zO.prototype,`openActionsMachineId`,void 0),B([S()],zO.prototype,`actionMenuStyle`,void 0),zO=B([b(`machine-switcher`)],zO);function BO(e,t){return t[e.id]?.status??e.status??`unknown`}function VO(e){return e===`online`?`online`:e===`offline`?`offline`:e===`error`?`error`:`unknown`}function HO(e){return e.baseUrl??e.name}function UO(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: ${WO(t.bottom)};`,`left: ${WO(r)};`,`width: ${WO(n)};`,`max-height: ${WO(i)};`].join(` `)}function WO(e){return`${String(Math.round(e))}px`}var GO=[{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
5442
|
<header>
|
|
5333
5443
|
<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
|
-
${
|
|
5444
|
+
${YO(this.machines)?g`
|
|
5335
5445
|
<machine-switcher
|
|
5336
5446
|
.machines=${this.machines}
|
|
5337
5447
|
.selected=${this.selectedMachine}
|
|
@@ -5348,7 +5458,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5348
5458
|
<button title="Show Actions" aria-label="Show Actions" @click=${()=>{this.onShowActions?.()}}>Actions</button>
|
|
5349
5459
|
</div>
|
|
5350
5460
|
</header>
|
|
5351
|
-
${this.compact&&
|
|
5461
|
+
${this.compact&&YO(this.machines)?g`
|
|
5352
5462
|
<machine-list
|
|
5353
5463
|
.machines=${this.machines}
|
|
5354
5464
|
.selected=${this.selectedMachine}
|
|
@@ -5415,6 +5525,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5415
5525
|
.collapsible=${this.collapsible}
|
|
5416
5526
|
.collapsed=${this.sessionsCollapsed}
|
|
5417
5527
|
.onToggleCollapsed=${()=>{this.onToggleSessions?.()}}
|
|
5528
|
+
.onOpenExpanded=${this.onOpenSessionBrowser===void 0?void 0:e=>this.onOpenSessionBrowser?.(e)}
|
|
5418
5529
|
.onArchivedCollapsed=${()=>this.onArchivedCollapsed?.()}
|
|
5419
5530
|
.onStart=${()=>this.onStartSession?.()}
|
|
5420
5531
|
.onSelect=${e=>this.onSelectSession?.(e)}
|
|
@@ -5437,9 +5548,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5437
5548
|
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
5438
5549
|
></session-list>
|
|
5439
5550
|
<footer class="resource-underbar" aria-label="Resources">
|
|
5440
|
-
${
|
|
5551
|
+
${GO.map(e=>KO(e,e.id===`models`?()=>{this.onOpenModels?.()}:e.id===`skills`?()=>{this.onOpenSkills?.()}:()=>{this.onOpenPlugins?.()},this.skillsEnabled,this.pluginsEnabled))}
|
|
5441
5552
|
</footer>
|
|
5442
|
-
`}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=
|
|
5553
|
+
`}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=XO(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(ZO(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
|
|
5443
5554
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
|
|
5444
5555
|
:host([compact]) { flex: 1 1 auto; }
|
|
5445
5556
|
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 +5582,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5471
5582
|
:host([compact]) workspace-list[collapsed],
|
|
5472
5583
|
:host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
5473
5584
|
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
|
-
${
|
|
5585
|
+
`}};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,`onOpenSessionBrowser`,void 0),B([x({attribute:!1})],Q.prototype,`onSelectProject`,void 0),B([x({attribute:!1})],Q.prototype,`onCloseProject`,void 0),B([x({attribute:!1})],Q.prototype,`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 KO(e,t,n,r){return g`
|
|
5586
|
+
<button type="button" ?disabled=${!qO(e.id,n,r)} title=${e.label} aria-label=${e.label} @click=${t}>
|
|
5587
|
+
${JO(e.id)}
|
|
5477
5588
|
<span>${e.label}</span>
|
|
5478
5589
|
</button>
|
|
5479
|
-
`}function
|
|
5590
|
+
`}function qO(e,t=!1,n=t){return e===`models`||e===`skills`&&t||e===`plugins`&&n}function JO(e){switch(e){case`models`:return _`
|
|
5480
5591
|
<svg class="resource-underbar-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
5481
5592
|
<rect x="4" y="4" width="16" height="16" rx="2"></rect>
|
|
5482
5593
|
<rect x="9" y="9" width="6" height="6"></rect>
|
|
@@ -5494,7 +5605,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5494
5605
|
<path d="M6 13V8a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v5a6 6 0 0 1-12 0Z"></path>
|
|
5495
5606
|
<path d="M12 19v3"></path>
|
|
5496
5607
|
</svg>
|
|
5497
|
-
`}}function
|
|
5608
|
+
`}}function YO(e){return e.length>1}function XO(e,t){let n=QO(t);return n[n.indexOf(e)-1]}function ZO(e,t){let n=QO(t);return n[n.indexOf(e)+1]??`chat`}function QO(e){return Fh.filter(t=>t!==`machines`||YO(e))}var $O=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),ek=420,tk=4,nk=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
5609
|
${this.renderResizeHandle()}
|
|
5499
5610
|
<button
|
|
5500
5611
|
type="button"
|
|
@@ -5524,7 +5635,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5524
5635
|
@dblclick=${e=>{this.onResizeDoubleClick(e)}}
|
|
5525
5636
|
@keydown=${e=>{this.onResizeKeyDown(e)}}
|
|
5526
5637
|
></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)<=
|
|
5638
|
+
`}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)<=tk)&&(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||!$O.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<=ek){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
5639
|
: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
5640
|
:host([side="navigation"]) { grid-column: 2; }
|
|
5530
5641
|
:host([side="workspace"]) { grid-column: 4; }
|
|
@@ -5543,7 +5654,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5543
5654
|
@media (max-width: 760px) {
|
|
5544
5655
|
:host([side="navigation"]) { display: none; }
|
|
5545
5656
|
}
|
|
5546
|
-
`}};B([x({reflect:!0})],
|
|
5657
|
+
`}};B([x({reflect:!0})],nk.prototype,`side`,void 0),B([x({type:Boolean,reflect:!0})],nk.prototype,`collapsed`,void 0),B([x({type:Boolean})],nk.prototype,`resizable`,void 0),B([x({type:Number})],nk.prototype,`panelWidth`,void 0),B([x({type:Number})],nk.prototype,`minWidth`,void 0),B([x({type:Number})],nk.prototype,`maxWidth`,void 0),B([x()],nk.prototype,`controls`,void 0),B([x()],nk.prototype,`resizeLabel`,void 0),B([x()],nk.prototype,`expandLabel`,void 0),B([x()],nk.prototype,`collapseLabel`,void 0),B([x({attribute:!1})],nk.prototype,`onToggle`,void 0),B([x({attribute:!1})],nk.prototype,`onResizeStart`,void 0),B([x({attribute:!1})],nk.prototype,`onResize`,void 0),B([x({attribute:!1})],nk.prototype,`onResizeEnd`,void 0),B([x({attribute:!1})],nk.prototype,`onReset`,void 0),nk=B([b(`app-panel-edge-control`)],nk);var rk=class extends y{constructor(...e){super(...e),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){let e=`Full page reload`;return g`
|
|
5547
5658
|
<button
|
|
5548
5659
|
class="app-refresh-button"
|
|
5549
5660
|
title=${e}
|
|
@@ -5562,7 +5673,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5562
5673
|
:host, :host * { -webkit-user-select: none; user-select: none; }
|
|
5563
5674
|
.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
5675
|
.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})],
|
|
5676
|
+
`}};B([x({attribute:!1})],rk.prototype,`onReload`,void 0),rk=B([b(`app-refresh-control`)],rk);var ik=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`],ak=`file-manager`,ok=`browser`,sk=[...ik],ck=new Set(ik),lk=`pi-webui:activity-rail-order`;function uk(){return typeof localStorage>`u`?void 0:localStorage}function dk(e){return ck.has(e)}function fk(e){if(!Array.isArray(e))return;let t=[],n=new Set;for(let r of e){if(typeof r!=`string`)return;let e=r===ak?`git-update-manager`:r;if(e!==ok){if(!dk(e)||n.has(e))return;n.add(e),t.push(e)}}if(t.length===ik.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===ik.length?r:void 0}function pk(){try{let e=uk();if(e===void 0)return;let t=e.getItem(lk);return t===null?void 0:fk(JSON.parse(t))}catch{return}}function mk(e){try{let t=uk();if(t===void 0)return;t.setItem(lk,JSON.stringify(e))}catch{}}var hk=`(min-width: 1181px)`,gk=[`terminal`,`git-update-manager`,`theme`,`system-prompt`,`history`,`info`];function _k(e){return gk.includes(e)}var vk=class extends y{constructor(){super(),this.terminalCount=0,this.gitUpdateManagerCount=0,this.systemPromptEnabled=!1,this.historyEnabled=!1,this.railOrder=[...sk],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||!_k(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(hk))}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
5677
|
<button
|
|
5567
5678
|
type="button"
|
|
5568
5679
|
class="icon-button terminal-button"
|
|
@@ -5702,7 +5813,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5702
5813
|
<circle cx="12" cy="12" r="3"/>
|
|
5703
5814
|
</svg>
|
|
5704
5815
|
</button>
|
|
5705
|
-
`}render(){if(!(this.desktopMedia?.matches??!0))return g``;let e=this.railOrder.length===0?[...
|
|
5816
|
+
`}render(){if(!(this.desktopMedia?.matches??!0))return g``;let e=this.railOrder.length===0?[...sk]:this.railOrder;return g`
|
|
5706
5817
|
<nav
|
|
5707
5818
|
class="rail"
|
|
5708
5819
|
aria-label="Activity rail"
|
|
@@ -5776,7 +5887,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5776
5887
|
}
|
|
5777
5888
|
.rail-spacer { flex: 1 1 auto; min-height: 0; }
|
|
5778
5889
|
.settings-button { margin-bottom: 12px; }
|
|
5779
|
-
`}};B([x({attribute:!1})],
|
|
5890
|
+
`}};B([x({attribute:!1})],vk.prototype,`onOpenTerminal`,void 0),B([x({attribute:!1})],vk.prototype,`onOpenGitUpdateManager`,void 0),B([x({attribute:!1})],vk.prototype,`onOpenTheme`,void 0),B([x({attribute:!1})],vk.prototype,`onOpenSystemPrompt`,void 0),B([x({attribute:!1})],vk.prototype,`onOpenHistory`,void 0),B([x({attribute:!1})],vk.prototype,`onOpenInfo`,void 0),B([x({attribute:!1})],vk.prototype,`onOpenSettings`,void 0),B([x({type:Number})],vk.prototype,`terminalCount`,void 0),B([x({type:Number})],vk.prototype,`gitUpdateManagerCount`,void 0),B([x({type:Boolean})],vk.prototype,`systemPromptEnabled`,void 0),B([x({type:Boolean})],vk.prototype,`historyEnabled`,void 0),B([x({attribute:!1})],vk.prototype,`railOrder`,void 0),B([x({attribute:!1})],vk.prototype,`onRailOrderChange`,void 0),vk=B([b(`activity-rail`)],vk);var yk=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:xk(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=wk(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
5891
|
<div class="git-update-manager-backdrop" role="dialog" aria-modal="true" aria-label="Git Update Manager">
|
|
5781
5892
|
<section class=${this.bounds===void 0?`git-update-manager-frame`:`git-update-manager-frame git-update-manager-frame-positioned`} style=${this.frameStyle()}>
|
|
5782
5893
|
<header class="git-update-manager-header">
|
|
@@ -5810,15 +5921,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5810
5921
|
></div>
|
|
5811
5922
|
</section>
|
|
5812
5923
|
</div>
|
|
5813
|
-
`}ensureWorkspaceScope(){let e=
|
|
5924
|
+
`}ensureWorkspaceScope(){let e=Ck(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
5925
|
${this.renderChangeGroup(`staged`,t.staged)}
|
|
5815
5926
|
${this.renderChangeGroup(`unstaged`,t.unstaged)}
|
|
5816
|
-
`}renderChangeGroup(e,t){if(t.length===0)return null;let n=
|
|
5927
|
+
`}renderChangeGroup(e,t){if(t.length===0)return null;let n=Sk(e);return g`
|
|
5817
5928
|
<section class="git-update-manager-change-group" aria-label=${`${n} changes`}>
|
|
5818
5929
|
<h2>${n} (${String(t.length)})</h2>
|
|
5819
5930
|
${t.map(e=>this.renderChange(e))}
|
|
5820
5931
|
</section>
|
|
5821
|
-
`}renderChange(e){let t=this.selectedChange?.id===e.id,n=Ss(e),r=xs(e.state),i=
|
|
5932
|
+
`}renderChange(e){let t=this.selectedChange?.id===e.id,n=Ss(e),r=xs(e.state),i=Sk(e.scope);return g`
|
|
5822
5933
|
<button
|
|
5823
5934
|
type="button"
|
|
5824
5935
|
class=${`git-update-manager-entry ${t?`selected`:``}`}
|
|
@@ -5830,13 +5941,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5830
5941
|
<span class="git-update-manager-path">${n}</span>
|
|
5831
5942
|
<span class="git-update-manager-scope">${i}</span>
|
|
5832
5943
|
</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
|
|
5944
|
+
`}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 bk(),g`
|
|
5834
5945
|
<header class="git-update-manager-diff-header">
|
|
5835
5946
|
<strong>${Ss(e)}</strong>
|
|
5836
|
-
<small>${
|
|
5947
|
+
<small>${Sk(e.scope)} · ${xs(e.state)}${t.truncated?` · truncated`:``}</small>
|
|
5837
5948
|
</header>
|
|
5838
5949
|
<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=
|
|
5950
|
+
`}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=wk(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
5951
|
:host { position: fixed; inset: 0; z-index: 80; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
5841
5952
|
.git-update-manager-backdrop { width: 100%; height: 100dvh; display: grid; place-items: center; padding: 16px; background: rgba(0, 0, 0, .48); }
|
|
5842
5953
|
.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 +5986,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5875
5986
|
.git-update-manager-workspace { grid-template-columns: 1fr; grid-template-rows: minmax(190px, 40%) minmax(0, 1fr); }
|
|
5876
5987
|
.git-update-manager-entries { border-right: 0; border-bottom: 1px solid var(--pi-border); }
|
|
5877
5988
|
}
|
|
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`
|
|
5989
|
+
`}};B([x({attribute:!1})],yk.prototype,`onClose`,void 0),B([x({attribute:!1})],yk.prototype,`onStatusChange`,void 0),B([x({attribute:!1})],yk.prototype,`workspace`,void 0),B([x()],yk.prototype,`machineId`,void 0),B([x({attribute:!1})],yk.prototype,`api`,void 0),B([S()],yk.prototype,`status`,void 0),B([S()],yk.prototype,`selectedChange`,void 0),B([S()],yk.prototype,`selectedDiff`,void 0),B([S()],yk.prototype,`loadingStatus`,void 0),B([S()],yk.prototype,`loadingDiff`,void 0),B([S()],yk.prototype,`error`,void 0),B([S()],yk.prototype,`bounds`,void 0),yk=B([b(`git-update-manager-panel`)],yk);function bk(){rm(()=>import(`./UnifiedDiffViewer-DDlEJGJ4.js`),[],import.meta.url)}function xk(e,t){let n=vs(e.files);return[...n.staged,...n.unstaged].find(e=>e.id===t)}function Sk(e){return e===`staged`?`Staged`:`Unstaged`}function Ck(e,t){return e===void 0?void 0:JSON.stringify([t,e.projectId,e.id])}function wk(e){return e instanceof Error?e.message:String(e)}var Tk=900*1e3,Ek=750,Dk=[1e3,3e3,8e3,15e3,3e4],Ok={capture:!0},kk=`auto:on`,Ak=`auto:off`,jk=`theme:`,Mk=Qo(`core:workspace.files`),Nk=Qo(`core:workspace.git`),Pk=Qo(`core:workspace.terminal`),Fk=320,Ik=2,Lk=`(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=Rk(),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.sessionBrowserOpen=!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=rA(),this.infoTabHidden=oA(),this.railOrder=pk()??[...sk],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,mk(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=Vk(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=Bk(e,t);await this.updateComplete,!(!this.unreadConnected||Vk(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(R(this.state),this.state.sessions);qk(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=Bk(e,t);return Vk(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.sessionBrowserOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.treeDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.state.authDialog!==void 0||this.gitUpdateManagerPanelOpen||this.terminalModalOpen}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,Ok),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebUiStatusTimer=window.setInterval(()=>{this.schedulePiWebUiStatusRefresh()},Tk),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,Ok),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(!Kk(this.state,e))return;let t=this.state;this.state={...this.state,...e},Vk(t)!==Vk(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),Hk(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),Uk(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=Ek){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=>Gk(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===``?Xk():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===``?Xk():{selectedFilePath:es(Mk,`file`),selectedDiffPath:es(Nk,`diff`),selectedTerminalId:es(Pk,`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(Mk,`file`,void 0,{replace:!0}),ts(Nk,`diff`,void 0,{replace:!0}),ts(Pk,`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=Qk(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 tA(),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(Mk,`file`,e.selectedFilePath,{replace:!0}),ts(Nk,`diff`,e.selectedDiffPath,{replace:!0}),ts(Pk,`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=Zk(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(Pk,`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=>Wk(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):Yk(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=Jk(e),r=Jk(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
5990
|
<workspace-panel
|
|
5880
5991
|
id="workspace-panel"
|
|
5881
5992
|
.workspace=${e}
|
|
@@ -5922,7 +6033,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5922
6033
|
.onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
|
|
5923
6034
|
.onReset=${()=>{this.resetResizablePanel(`workspace`)}}
|
|
5924
6035
|
></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-
|
|
6036
|
+
`}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-Ik-Fk);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(Lk).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: ${$k(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: ${$k(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: ${$k(e)}`})}}renderNavigationPanel(){return g`
|
|
5926
6037
|
<app-navigation-panel
|
|
5927
6038
|
.machines=${this.state.machines}
|
|
5928
6039
|
.selectedMachine=${this.state.selectedMachine}
|
|
@@ -5971,6 +6082,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5971
6082
|
.onToggleProjects=${()=>{this.navigationSections.toggle(`projects`)}}
|
|
5972
6083
|
.onAddProject=${()=>{this.openProjectDialog()}}
|
|
5973
6084
|
.onOpenProjectBrowser=${e=>{this.openProjectBrowser(e)}}
|
|
6085
|
+
.onOpenSessionBrowser=${this.state.selectedProject===void 0?void 0:e=>{this.openSessionBrowser(e)}}
|
|
5974
6086
|
.onToggleWorkspaces=${()=>{this.navigationSections.toggle(`workspaces`)}}
|
|
5975
6087
|
.onToggleSessions=${()=>{this.navigationSections.toggle(`sessions`)}}
|
|
5976
6088
|
.onSelectProject=${e=>this.selectNavigationItem(`projects`,`workspaces`,()=>this.workspaces.selectProject(e))}
|
|
@@ -5997,7 +6109,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5997
6109
|
.onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
|
|
5998
6110
|
.onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
|
|
5999
6111
|
></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`&&!
|
|
6112
|
+
`}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`&&!YO(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 tA(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!==`chat`&&this.selectMainView(`chat`),await this.updateComplete,await tA(),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
6113
|
<session-tree-navigator
|
|
6002
6114
|
.tree=${e.treeDialog}
|
|
6003
6115
|
.onNavigate=${(e,t)=>this.navigateSessionTree(e,t)}
|
|
@@ -6016,7 +6128,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6016
6128
|
<p class="session-start-hint">Describe a goal, paste a task, or attach a file to begin.</p>
|
|
6017
6129
|
</div>
|
|
6018
6130
|
</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=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`
|
|
6131
|
+
`}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=zk(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=zk(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: ${$k(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=Zk(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:eA(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()}openSessionBrowser(e){this.state.selectedProject!==void 0&&(this.sessionBrowserRestoreFocus=e,this.sessionBrowserOpen=!0)}closeSessionBrowser(e={}){let t=e.restoreFocus===!0?this.sessionBrowserRestoreFocus:void 0;this.sessionBrowserRestoreFocus=void 0,this.sessionBrowserOpen=!1,t!==void 0&&this.updateComplete.then(()=>{t()})}selectSessionFromBrowser(e){this.closeSessionBrowser(),this.selectNavigationItem(`sessions`,`chat`,()=>this.selectSessionFromNavigation(e))}openProjectDialog(){this.setState({projectDialogOpen:!0})}openMachineDialog(){this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebUiStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(`Remove ${e.name}?\n\nThis only removes it from this PI WEBUI gateway.`))return;let t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();let n=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(t=>t.id===e.id)||this.machineNavigation.forget(e.id),t&&n!==void 0&&await this.selectMachineWithMemory(n,{rememberCurrent:!1})}openSelectedMachine(){let e=this.state.selectedMachine;e?.kind!==`remote`||e.baseUrl===void 0||window.open(e.baseUrl,`_blank`,`noopener,noreferrer`)}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{let n=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`Action failed: ${n}`})})}async openModelDialog(){let e=await this.sessions.listModels(),t=this.state.status?.model?.provider,n=this.state.status?.model?.id,r=[...e].sort((e,t)=>{let n=e.provider??``,r=t.provider??``;return n===r?(e.id??``).localeCompare(t.id??``):n.localeCompare(r)});this.setState({modelDialog:{title:`Select Model`,...t!==void 0&&n!==void 0?{selectedValue:`${t}/${n}`}:{},options:r.map(e=>{let r=e.provider??``,i=e.id??``,a=r===t&&i===n;return{value:`${r}/${i}`,label:i+(a?` ✓ current`:``),...r===``?{}:{group:r}}})}})}async pickModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);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?Ak:kk;this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${jk}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${jk}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===kk||e===Ak){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===kk},this.applyPreferredTheme(!0);return}if(!e.startsWith(jk))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=cA(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=cA(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,iA(this.terminalTabHidden)}toggleInfoTab(){this.infoTabHidden=!this.infoTabHidden,sA(this.infoTabHidden)}renderChatView(e,t){return g`
|
|
6020
6132
|
<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
6133
|
`}renderContextBar(){return this.appShell.isMobileNavigationLayout?g`
|
|
6022
6134
|
<app-context-bar
|
|
@@ -6035,7 +6147,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6035
6147
|
.selectedView=${this.state.mainView}
|
|
6036
6148
|
.onSelect=${e=>{this.selectMainView(e)}}
|
|
6037
6149
|
></app-mobile-main-tabs>
|
|
6038
|
-
`}mobileMainTabs(){let e=
|
|
6150
|
+
`}mobileMainTabs(){let e=iv(this.state.sessions,this.unreadSessionIds,{statuses:this.state.sessionStatuses,activities:this.state.sessionActivities,sending:this.state.sendingPrompts});return[{id:`navigation`,label:`Sessions`,icon:`navigation`,className:`navigation-tab`,...e===0?{}:{badge:e,badgeLabel:`${String(e)} unread`,badgeTone:`unread`}},{id:`chat`,label:`Chat`,icon:`chat`},...this.visibleWorkspacePanels().map(e=>{let t=e.icon??this.mobilePanelIcon(e);return{id:e.id,label:e.title,...t===void 0?{}:{icon:t},badge:this.mobilePanelBadge(e)}})]}renderAppRefresh(){return g`<app-refresh-control .onReload=${()=>{this.hardReloadApp()}}></app-refresh-control>`}renderTerminalModal(){let e=this.state,t=R(e);return g`
|
|
6039
6151
|
<div
|
|
6040
6152
|
class="terminal-modal-backdrop"
|
|
6041
6153
|
role="dialog"
|
|
@@ -6159,6 +6271,17 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6159
6271
|
.onAdd=${()=>{this.addProjectFromBrowser()}}
|
|
6160
6272
|
.onCloseProject=${e=>this.projects.closeProject(e.id)}
|
|
6161
6273
|
></project-browser-dialog>`:null}
|
|
6274
|
+
${this.sessionBrowserOpen&&e.selectedProject!==void 0?g`<session-browser-dialog
|
|
6275
|
+
.projectName=${e.selectedProject.name}
|
|
6276
|
+
.sessions=${e.projectSessions}
|
|
6277
|
+
.statuses=${e.sessionStatuses}
|
|
6278
|
+
.activities=${e.sessionActivities}
|
|
6279
|
+
.sending=${e.sendingPrompts}
|
|
6280
|
+
.unreadSessionIds=${this.unreadSessionIds}
|
|
6281
|
+
.selected=${e.selectedSession}
|
|
6282
|
+
.onSelect=${e=>{this.selectSessionFromBrowser(e)}}
|
|
6283
|
+
.onClose=${()=>{this.closeSessionBrowser({restoreFocus:!0})}}
|
|
6284
|
+
></session-browser-dialog>`:null}
|
|
6162
6285
|
${this.historyWindow===void 0?null:g`<session-history-window .machineId=${this.historyWindow.machineId} .session=${this.historyWindow.session} .onClose=${()=>{this.historyWindow=void 0}}></session-history-window>`}
|
|
6163
6286
|
${e.projectDialogOpen?g`<project-dialog .machineId=${R(e)} .onSubmit=${(e,t)=>this.projects.addProject(e,t)} .onCancel=${()=>{this.setState({projectDialogOpen:!1})}}></project-dialog>`:null}
|
|
6164
6287
|
${e.machineDialogOpen?g`<machine-dialog .error=${e.error} .onSubmit=${e=>this.submitMachineDialog(e)} .onCancel=${()=>{this.setState({machineDialogOpen:!1})}}></machine-dialog>`:null}
|
|
@@ -6173,4 +6296,4 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6173
6296
|
${this.terminalModalOpen?this.renderTerminalModal():null}
|
|
6174
6297
|
${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
6298
|
</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
|
|
6299
|
+
`}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,`sessionBrowserOpen`,void 0),B([S()],$.prototype,`skillsConfigDialogOpen`,void 0),B([S()],$.prototype,`pluginsConfigDialogOpen`,void 0),B([S()],$.prototype,`systemPromptDialogOpen`,void 0),B([S()],$.prototype,`gitUpdateManagerPanelOpen`,void 0),B([S()],$.prototype,`terminalModalOpen`,void 0),B([S()],$.prototype,`terminalModalBounds`,void 0),B([S()],$.prototype,`terminalModalMaximized`,void 0),B([S()],$.prototype,`terminalModalFontSize`,void 0),B([S()],$.prototype,`terminalModalOpacity`,void 0),B([S()],$.prototype,`terminalTabHidden`,void 0),B([S()],$.prototype,`infoTabHidden`,void 0),B([S()],$.prototype,`railOrder`,void 0),B([S()],$.prototype,`settingsSection`,void 0),B([S()],$.prototype,`shortcutConfig`,void 0),B([S()],$.prototype,`workspaceUploadDefaultFolder`,void 0),$=B([b(`pi-webui-app`)],$);function Rk(){let e=new fh;return e.register({id:`core`,plugin:Um}),e.register({id:`themes`,plugin:qm}),e}function zk(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 Bk(e,t){return JSON.stringify([e,t.id,t.cwd])}function Vk(e){let t=e.selectedSession;return t===void 0?void 0:Bk(R(e),t)}function Hk(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function Uk(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function Wk(e,t){return Gk(e,t)}function Gk(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function Kk(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function qk(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function Jk(e){return Vo(e.status,e.activity)}function Yk(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function Xk(){return{}}function Zk(e,t){return JSON.stringify([e,t])}function Qk(e){return Dk[Math.min(e,Dk.length-1)]??3e4}function $k(e){return e instanceof Error?e.message:String(e)}function eA(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function tA(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}var nA=`pi-webui:terminal-tab-hidden`;function rA(){try{let e=typeof localStorage>`u`?void 0:localStorage;return e!==void 0&&e.getItem(nA)===`true`}catch{return!1}}function iA(e){try{let t=typeof localStorage>`u`?void 0:localStorage;if(t===void 0)return;e?t.setItem(nA,`true`):t.removeItem(nA)}catch{}}var aA=`pi-webui:info-tab-hidden`;function oA(){try{let e=typeof localStorage>`u`?void 0:localStorage;return e!==void 0&&e.getItem(aA)===`true`}catch{return!1}}function sA(e){try{let t=typeof localStorage>`u`?void 0:localStorage;if(t===void 0)return;e?t.setItem(aA,`true`):t.removeItem(aA)}catch{}}function cA(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};
|