@vincenthanxiaodu/pi-web 1.202608.38 → 1.202608.39
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-BFdRFved.js → CodeViewer-DWMYXHbj.js} +1 -1
- package/dist/client/assets/{TerminalPanel-DDLb8OAR.js → TerminalPanel-FojQLt0o.js} +1 -1
- package/dist/client/assets/{index-bUMfm16g.js → index-CCOS1IF6.js} +308 -291
- package/dist/client/index.html +1 -1
- package/dist/pi-web-plugins/git/browser/git-panel.js +6 -1
- package/dist/pi-web-plugins/git/browser/gitSplitLayout.js +12 -0
- 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-DWMYXHbj.js","./vendor-editor-core-CXO8gGab.js","./vendor-editor-languages-CpW4sJsX.js","./vendor-editor-legacy-CYBnW6ZU.js","./TerminalPanel-FojQLt0o.js","./vendor-terminal-D8k4UKM2.js","./vendor-terminal-BrP-ENHg.css"])))=>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,Y as o,Z as s,d as c,et as l,f as u,j as d,l as f,p,q as m,u as ee}from"./vendor-editor-core-CXO8gGab.js";import{a as te,o as ne,s as re}from"./vendor-editor-languages-CpW4sJsX.js";(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 ie=globalThis,ae=ie.ShadowRoot&&(ie.ShadyCSS===void 0||ie.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,oe=Symbol(),se=new WeakMap,ce=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==oe)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(ae&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=se.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&se.set(t,e))}return e}toString(){return this.cssText}},le=e=>new ce(typeof e==`string`?e:e+``,void 0,oe),h=(e,...t)=>new ce(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,oe),ue=(e,t)=>{if(ae)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=ie.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},de=ae?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return le(t)})(e):e,{is:fe,defineProperty:pe,getOwnPropertyDescriptor:me,getOwnPropertyNames:he,getOwnPropertySymbols:ge,getPrototypeOf:_e}=Object,ve=globalThis,ye=ve.trustedTypes,be=ye?ye.emptyScript:``,xe=ve.reactiveElementPolyfillSupport,Se=(e,t)=>e,Ce={toAttribute(e,t){switch(t){case Boolean:e=e?be: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}},we=(e,t)=>!fe(e,t),Te={attribute:!0,type:String,converter:Ce,reflect:!1,useDefault:!1,hasChanged:we};Symbol.metadata??=Symbol(`metadata`),ve.litPropertyMetadata??=new WeakMap;var Ee=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=Te){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&&pe(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=me(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)??Te}static _$Ei(){if(this.hasOwnProperty(Se(`elementProperties`)))return;let e=_e(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Se(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Se(`properties`))){let e=this.properties,t=[...he(e),...ge(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(de(e))}else e!==void 0&&t.push(de(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 ue(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?Ce: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?Ce: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??we)(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){}};Ee.elementStyles=[],Ee.shadowRootOptions={mode:`open`},Ee[Se(`elementProperties`)]=new Map,Ee[Se(`finalized`)]=new Map,xe?.({ReactiveElement:Ee}),(ve.reactiveElementVersions??=[]).push(`2.1.2`);var De=globalThis,Oe=e=>e,ke=De.trustedTypes,Ae=ke?ke.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,je=`$lit$`,Me=`lit$${Math.random().toFixed(9).slice(2)}$`,Ne=`?`+Me,Pe=`<${Ne}>`,Fe=document,Ie=()=>Fe.createComment(``),Le=e=>e===null||typeof e!=`object`&&typeof e!=`function`,Re=Array.isArray,ze=e=>Re(e)||typeof e?.[Symbol.iterator]==`function`,Be=`[
|
|
3
3
|
\f\r]`,Ve=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,He=/-->/g,Ue=/>/g,We=RegExp(`>|${Be}(?:([^\\s"'>=/]+)(${Be}*=${Be}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),Ge=/'/g,Ke=/"/g,qe=/^(?:script|style|textarea|title)$/i,Je=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),g=Je(1),Ye=Je(2),Xe=Symbol.for(`lit-noChange`),_=Symbol.for(`lit-nothing`),Ze=new WeakMap,Qe=Fe.createTreeWalker(Fe,129);function $e(e,t){if(!Re(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return Ae===void 0?t:Ae.createHTML(t)}var et=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=Ve;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===Ve?c[1]===`!--`?o=He:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=We):(qe.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=We):o=Ue:o===We?c[0]===`>`?(o=i??Ve,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?We:c[3]===`"`?Ke:Ge):o===Ke||o===Ge?o=We:o===He||o===Ue?o=Ve:(o=We,i=void 0);let d=o===We&&e[t+1].startsWith(`/>`)?` `:``;a+=o===Ve?n+Pe:l>=0?(r.push(s),n.slice(0,l)+je+n.slice(l)+Me+d):n+Me+(l===-2?t:d)}return[$e(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},tt=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]=et(t,n);if(this.el=e.createElement(l,r),Qe.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=Qe.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(je)){let t=u[o++],n=i.getAttribute(e).split(Me),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?ot:r[1]===`?`?st:r[1]===`@`?ct:at}),i.removeAttribute(e)}else e.startsWith(Me)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(qe.test(i.tagName)){let e=i.textContent.split(Me),t=e.length-1;if(t>0){i.textContent=ke?ke.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],Ie()),Qe.nextNode(),c.push({type:2,index:++a});i.append(e[t],Ie())}}}else if(i.nodeType===8)if(i.data===Ne)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(Me,e+1))!==-1;)c.push({type:7,index:a}),e+=Me.length-1}a++}}static createElement(e,t){let n=Fe.createElement(`template`);return n.innerHTML=e,n}};function nt(e,t,n=e,r){if(t===Xe)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=Le(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=nt(e,i._$AS(e,t.values),i,r)),t}var rt=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??Fe).importNode(t,!0);Qe.currentNode=r;let i=Qe.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new it(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new lt(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=Qe.nextNode(),a++)}return Qe.currentNode=Fe,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++}},it=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=_,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=nt(this,e,t),Le(e)?e===_||e==null||e===``?(this._$AH!==_&&this._$AR(),this._$AH=_):e!==this._$AH&&e!==Xe&&this._(e):e._$litType$===void 0?e.nodeType===void 0?ze(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!==_&&Le(this._$AH)?this._$AA.nextSibling.data=e:this.T(Fe.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=tt.createElement($e(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new rt(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=Ze.get(e.strings);return t===void 0&&Ze.set(e.strings,t=new tt(e)),t}k(t){Re(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(Ie()),this.O(Ie()),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=Oe(e).nextSibling;Oe(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},at=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=_,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=_}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=nt(this,e,t,0),a=!Le(e)||e!==this._$AH&&e!==Xe,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=nt(this,r[n+o],t,o),s===Xe&&(s=this._$AH[o]),a||=!Le(s)||s!==this._$AH[o],s===_?e=_:e!==_&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===_?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},ot=class extends at{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===_?void 0:e}},st=class extends at{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==_)}},ct=class extends at{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=nt(this,e,t,0)??_)===Xe)return;let n=this._$AH,r=e===_&&n!==_||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==_&&(n===_||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)}},lt=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){nt(this,e)}},ut={M:je,P:Me,A:Ne,C:1,L:et,R:rt,D:ze,V:nt,I:it,H:at,N:st,U:ct,B:ot,F:lt},dt=De.litHtmlPolyfillSupport;dt?.(tt,it),(De.litHtmlVersions??=[]).push(`3.3.3`);var ft=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new it(t.insertBefore(Ie(),e),e,void 0,n??{})}return i._$AI(e),i},pt=globalThis,v=class extends Ee{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=ft(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Xe}};v._$litElement$=!0,v.finalized=!0,pt.litElementHydrateSupport?.({LitElement:v});var mt=pt.litElementPolyfillSupport;mt?.({LitElement:v}),(pt.litElementVersions??=[]).push(`4.2.2`);var y=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},ht={attribute:!0,type:String,converter:Ce,reflect:!1,hasChanged:we},gt=(e=ht,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 b(e){return(t,n)=>typeof n==`object`?gt(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 x(e){return b({...e,state:!0,attribute:!1})}var _t=(e,t,n)=>(n.configurable=!0,n.enumerable=!0,Reflect.decorate&&typeof t!=`object`&&Object.defineProperty(e,t,n),n);function S(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 _t(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 _t(n,r,{get(){return a(this)}})}}function vt(e,t=bt()){let n=new URL(t.viteBaseUrl,t.documentBaseUrl);return new URL(xt(e),n).toString()}function yt(e,t=bt()){let n=new URL(vt(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 bt(){return{viteBaseUrl:`./`,documentBaseUrl:document.baseURI}}function xt(e){return e.startsWith(`/`)?`.${e}`:e}var St;function Ct(e){St=e}function wt(){let e=St;if(e!==void 0)try{e()}catch{}}var Tt=class extends Error{constructor(e,t){super(e),this.status=t,this.name=`HttpError`}};function Et(e){return e instanceof Tt&&e.status===404}async function C(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(vt(e),{...n,headers:r});if(!i.ok)throw new Tt(Dt(await i.json().catch(()=>({})))??i.statusText,i.status);let a=await i.json();return wt(),t(a)}function Dt(e){if(Ot(e))return typeof e.error==`string`?e.error:void 0}function Ot(e){return typeof e==`object`&&!!e}var kt={pluginLifecycle:`plugins.lifecycle`},At=1e3,jt=32*1024,Mt=8*1024,Nt=1e3,Pt=4e3,Ft=1e3,It=8e3,Lt=4e3,Rt=1e4,zt={working:`core:working`,terminal:`core:terminal`,unread:`core:unread`};function Bt(e){if(!Ut(e))return;let t=e.epochId,n=e.revision,r=e.generatedAt,i=Vt(e.machine),a=Vt(e.unattributed),o=Ht(e.projects),s=Ht(e.workspaces);if(!(typeof t!=`string`||t===``)&&!(typeof n!=`number`||!Number.isFinite(n))&&!(typeof r!=`string`||r===``)&&!(i===void 0||a===void 0)&&!(o===void 0||s===void 0))return{epochId:t,revision:n,machine:i,projects:o,workspaces:s,unattributed:a,generatedAt:r}}function Vt(e){if(!Ut(e))return;let t=new Map;for(let[n,r]of Object.entries(e))typeof r==`boolean`&&t.set(n,r);return Object.fromEntries(t)}function Ht(e){if(!Ut(e))return;let t=new Map;for(let[n,r]of Object.entries(e)){let e=Vt(r);e!==void 0&&t.set(n,e)}return Object.fromEntries(t)}function Ut(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Wt=Object.values(kt),Gt=new Set(Wt);kt.pluginLifecycle,kt.pluginLifecycle;function Kt(e){return typeof e==`string`&&Gt.has(e)}function qt(e,t){return e?.capabilities?.includes(t)===!0}function Jt(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(Kt)}function Yt(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(!Xt(n))continue;let e=n.source,r=n.name,i=n.replacement;e!==`environment`&&e!==`config`||typeof r!=`string`||r===``||i!==void 0&&(typeof i!=`string`||i===``)||t.push({source:e,name:r,...i===void 0?{}:{replacement:i}})}return t}function Xt(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Zt=/^[a-z][a-z0-9.-]*$/u,Qt=new Set([`core`,`themes`]),$t=`machine.`;function en(e){return Zt.test(e)}function tn(e){return Qt.has(e)||e.startsWith($t)}var nn=Object.freeze({showSafeStart:`pi-web plugins safe-start show`,bundledOnly:`pi-web plugins safe-start set bundled-only --restart`,noServerPlugins:`pi-web plugins safe-start set none --restart`,clearSafeStart:`pi-web plugins safe-start clear --restart`});function rn(e){if(!en(e))throw Error(`Invalid PI WEB plugin id: ${e}`);return`pi-web plugins disable ${e} --restart`}function w(e){return typeof e==`object`&&!!e}function T(e){if(!w(e))throw Error(`Expected object response`);return e}function E(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Expected string field: ${t}`);return n}function D(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw Error(`Expected optional string field: ${t}`);return n}}function O(e,t){let n=e[t];if(typeof n!=`number`)throw Error(`Expected number field: ${t}`);return n}function k(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Expected boolean field: ${t}`);return n}function A(e){return t=>{if(!Array.isArray(t))throw Error(`Expected array response`);return t.map(e)}}function an(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function on(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function sn(e){let t=T(e);return{messages:an(t.messages),start:O(t,`start`),total:O(t,`total`)}}function cn(e){let t=T(e);return A(ln)(t.machines)}function ln(e){let t=T(e),n=pn(t,`kind`),r=D(t,`baseUrl`),i=mn(t,`status`),a=D(t,`statusMessage`);return{id:E(t,`id`),name:E(t,`name`),kind:n,...r===void 0?{}:{baseUrl:r},createdAt:E(t,`createdAt`),updatedAt:E(t,`updatedAt`),...i===void 0?{}:{status:i},...a===void 0?{}:{statusMessage:a}}}function un(e){let t=T(e),n=mn(t,`status`),r=D(t,`error`);return{machineId:E(t,`machineId`),ok:k(t,`ok`),checkedAt:E(t,`checkedAt`),...n===void 0?{}:{status:n},...t.web===void 0?{}:{web:va(t.web)},...t.sessiond===void 0?{}:{sessiond:va(t.sessiond)},...r===void 0?{}:{error:r}}}function dn(e){let t=T(e),n=D(t,`error`);return{machineId:E(t,`machineId`),ok:k(t,`ok`),checkedAt:E(t,`checkedAt`),...M(`packageName`,D(t,`packageName`)),...M(`generatedAt`,D(t,`generatedAt`)),...t.components===void 0?{}:{components:ga(t.components)},...t.capabilities===void 0?{}:{capabilities:wa(t.capabilities)},...t.deprecatedAgentInputs===void 0?{}:{deprecatedAgentInputs:fn(t.deprecatedAgentInputs)},...n===void 0?{}:{error:n}}}function fn(e){let t=Yt(e);if(t===void 0)throw Error(`Invalid PI WEB deprecated agent inputs`);return t}function pn(e,t){let n=E(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function mn(e,t){let n=D(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 hn(e){let t=T(e);return{id:E(t,`id`),name:E(t,`name`),path:E(t,`path`),createdAt:E(t,`createdAt`)}}function gn(e){let t=T(e);return Object.freeze({id:E(t,`id`),projectId:E(t,`projectId`),path:E(t,`path`),label:E(t,`label`),isMain:k(t,`isMain`),...M(`provider`,Sn(t.provider)),...M(`removal`,Cn(t.removal)),effectiveConfig:En(t.effectiveConfig)})}function _n(e){let t=T(e),n=vn(t.status),r=E(t,`projectId`),i=D(t,`ownerPluginId`);if(n===`provider`&&i===void 0)throw Error(`Provider workspace resolution is missing ownerPluginId`);if(n===`folder`&&i!==void 0)throw Error(`Folder workspace resolution must not include ownerPluginId`);let a=A(gn)(t.workspaces);if(a.length===0||a.some(e=>e.projectId!==r))throw Error(`Workspace resolution contains invalid project workspaces`);let o=A(yn)(t.diagnostics);return Object.freeze({status:n,projectId:r,...i===void 0?{}:{ownerPluginId:i},workspaces:Object.freeze(a),diagnostics:Object.freeze(o)})}function vn(e){if(e===`provider`||e===`folder`||e===`degraded`)return e;throw Error(`Invalid workspace provider resolution status`)}function yn(e){let t=T(e),n=D(t,`pluginId`),r=t.pluginIds===void 0?void 0:on(t.pluginIds,`pluginIds`);return Object.freeze({code:bn(t.code),message:E(t,`message`),tier:xn(t.tier),...n===void 0?{}:{pluginId:n},...r===void 0?{}:{pluginIds:Object.freeze(r)}})}function bn(e){if(e===`probe-failed`||e===`claim-conflict`||e===`list-failed`)return e;throw Error(`Invalid workspace provider diagnostic code`)}function xn(e){if(e===`primary`||e===`fallback`)return e;throw Error(`Invalid workspace provider diagnostic tier`)}function Sn(e){if(e===void 0)return;if(!w(e)||Array.isArray(e))throw Error(`Invalid workspace provider field`);let t=e.capabilities;if(!w(t)||Array.isArray(t))throw Error(`Invalid workspace provider capabilities field`);let n=e.metadata;return Object.freeze({pluginId:E(e,`pluginId`),capabilities:Object.freeze({request:k(t,`request`),remove:k(t,`remove`)}),...M(`metadata`,n===void 0?void 0:wn(n,`workspace provider metadata`))})}function Cn(e){if(e!==void 0){if(!w(e)||Array.isArray(e))throw Error(`Invalid workspace removal field`);return Object.freeze({actionLabel:j(e,`actionLabel`),confirmation:j(e,`confirmation`),precondition:j(e,`precondition`)})}}function wn(e,t){if(!w(e)||Array.isArray(e))throw Error(`Invalid ${t} field`);return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Tn(n,t)])))}function Tn(e,t){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(Array.isArray(e))return Object.freeze(e.map(e=>Tn(e,t)));if(w(e))return wn(e,t);throw Error(`Invalid ${t} field`)}function En(e){if(!w(e)||Array.isArray(e))throw Error(`Expected workspace effectiveConfig field`);let t=Ki(e.uploads);return Object.freeze({...M(`uploads`,t===void 0?void 0:Object.freeze({...t}))})}function Dn(e){let t=T(e),n=D(t,`name`),r=fa(t.persisted,`persisted`),i=D(t,`parentSessionPath`),a=D(t,`archivedAt`);return{id:E(t,`id`),path:E(t,`path`),cwd:E(t,`cwd`),...r===void 0?{}:{persisted:r},...n===void 0?{}:{name:n},created:E(t,`created`),modified:E(t,`modified`),messageCount:O(t,`messageCount`),firstMessage:E(t,`firstMessage`),...i===void 0?{}:{parentSessionPath:i},...t.archived===!0?{archived:!0}:{},...a===void 0?{}:{archivedAt:a}}}function On(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function kn(e){if(e!==void 0)return{id:E(T(e),`id`)}}function An(e){let t=T(e),n=kn(t.dismiss);return{severity:On(t.severity),message:E(t,`message`),...M(`source`,D(t,`source`)),...M(`path`,D(t,`path`)),...n===void 0?{}:{dismiss:n}}}function jn(e){return e===void 0?{}:{warnings:A(An)(e)}}function Mn(e){let t=T(e);return{value:xr(t,`value`,128),label:xr(t,`label`,Nt),...M(`detail`,Sr(t,`detail`,Nt))}}function Nn(e){let t=T(e),n=Nr(t.options,Mn,12,`options`);Un(n.map(e=>e.value),`ask option value`);let r=fa(t.multiple,`multiple`);return{id:xr(t,`id`,128),question:xr(t,`question`,Nt),...M(`detail`,Sr(t,`detail`,Nt)),options:n,...r===void 0?{}:{multiple:r}}}function Pn(e){let t=T(e),n=Nr(t.questions,Nn,20,`questions`);if(n.length===0)throw Error(`Pending ask has no questions`);return Un(n.map(e=>e.id),`ask question id`),{askId:xr(t,`askId`,128),askedAt:j(t,`askedAt`),questions:n}}function Fn(e){return e===void 0?{}:{pendingAsk:Pn(e)}}function In(e){let t=T(e);if(t.type!==`ask.opened`)throw Error(`Invalid ask opened event type`);return{type:`ask.opened`,ask:Pn(t.ask)}}function Ln(e){let t=T(e);if(t.type!==`ask.closed`)throw Error(`Invalid ask closed event type`);return{type:`ask.closed`,askId:xr(t,`askId`,128),reason:Rn(t.reason)}}function Rn(e){if(e!==`submitted`&&e!==`superseded`&&e!==`cancelled`)throw Error(`Invalid ask close reason`);return e}function zn(e){let t=T(e),n=Nn(t.question),r=Nr(t.values,Pr,12,`values`),i=new Set(n.options.map(e=>e.value));if(r.some(e=>!i.has(e)))throw Error(`Ask answer selected an option the question never offered`);let a=Sr(t,`otherText`,Pt),o=k(t,`answered`);if(o!==(r.length>0||a!==void 0))throw Error(`Ask answer contradicts its answered flag`);return{question:n,answered:o,values:r,...a===void 0?{}:{otherText:a}}}function Bn(e){let t=T(e),n=Nr(t.questions,zn,20,`questions`),r=Fr(t,`answeredCount`),i=on(t.unansweredIds,`unansweredIds`),a=n.filter(e=>!e.answered).map(e=>e.question.id);if(r!==n.length-a.length)throw Error(`Ask outcome answered count mismatch`);if(i.length!==a.length||i.some((e,t)=>e!==a[t]))throw Error(`Ask outcome unanswered ids mismatch`);return{askId:xr(t,`askId`,128),reason:Rn(t.reason),askedAt:j(t,`askedAt`),closedAt:j(t,`closedAt`),questions:n,answeredCount:r,unansweredIds:i,summary:j(t,`summary`)}}function Vn(e){let t=T(e),n=t.result;if(n!==`closed`&&n!==`stale`)throw Error(`Invalid ask close result`);let r=t.outcome===void 0?void 0:Bn(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Ask close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:er(t.sessionStatus)}}function Hn(e){let t=T(e),n=t.result;if(n!==`closed`&&n!==`stale`)throw Error(`Invalid dialog close result`);let r=t.outcome===void 0?void 0:Qn(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Dialog close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:er(t.sessionStatus)}}function Un(e,t){if(new Set(e).size!==e.length)throw Error(`Duplicate ${t}`)}function Wn(e){if(e!==`confirm`&&e!==`select`&&e!==`input`)throw Error(`Invalid extension dialog kind`);return e}function Gn(e){if(e!==`answered`&&e!==`cancelled`&&e!==`timeout`&&e!==`aborted`&&e!==`session-ended`)throw Error(`Invalid extension dialog close reason`);return e}function Kn(e){if(typeof e==`boolean`||typeof e==`string`&&e.length<=4e3)return e;throw Error(`Invalid extension dialog answer`)}function qn(e){let t=Pr(e);if(t.length>1e3)throw Error(`String field exceeds limit: option`);return t}function Jn(e){let t=T(e),n=Wn(t.kind),r=t.options===void 0?void 0:Nr(t.options,qn,24,`options`);if(r!==void 0&&Un(r,`dialog option`),n===`select`&&(r===void 0||r.length===0))throw Error(`Select dialog has no options`);return{dialogId:xr(t,`dialogId`,128),kind:n,title:xr(t,`title`,It),...M(`message`,Sr(t,`message`,It)),...r===void 0?{}:{options:r},...M(`placeholder`,Sr(t,`placeholder`,Ft)),askedAt:j(t,`askedAt`),...M(`timeoutAt`,$n(t,`timeoutAt`)),runScoped:k(t,`runScoped`)}}function Yn(e){if(e===void 0)return{};let t=A(Jn)(e);return Un(t.map(e=>e.dialogId),`dialog id`),{pendingDialogs:t}}function Xn(e){let t=T(e);if(t.type!==`dialog.opened`)throw Error(`Invalid dialog opened event type`);return{type:`dialog.opened`,dialog:Jn(t.dialog)}}function Zn(e){let t=T(e);if(t.type!==`dialog.closed`)throw Error(`Invalid dialog closed event type`);let n=Gn(t.reason),r=t.answer===void 0?void 0:Kn(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog closed event answer mismatch`);return{type:`dialog.closed`,dialogId:xr(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r}}}function Qn(e){let t=T(e),n=Gn(t.reason),r=t.answer===void 0?void 0:Kn(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog outcome answer mismatch`);return{dialogId:xr(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r},askedAt:j(t,`askedAt`),closedAt:j(t,`closedAt`)}}function $n(e,t){let n=D(e,t);if(n!==void 0){if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}}function er(e){let t=T(e);return{sessionId:E(t,`sessionId`),...M(`persisted`,fa(t.persisted,`persisted`)),isStreaming:k(t,`isStreaming`),isCompacting:k(t,`isCompacting`),isBashRunning:k(t,`isBashRunning`),pendingMessageCount:O(t,`pendingMessageCount`),queuedMessages:t.queuedMessages===void 0?[]:A(Jr)(t.queuedMessages),...M(`messageCount`,Ya(t,`messageCount`)),tokens:Yr(t.tokens),cost:O(t,`cost`),...Zr(t.model),..._i(t.contextUsage),...M(`thinkingLevel`,D(t,`thinkingLevel`)),...jn(t.warnings),...Fn(t.pendingAsk),...Yn(t.pendingDialogs)}}function tr(e){let t=T(e);return{seq:O(t,`seq`),partial:t.partial??null}}function nr(e){let t=T(e),n=t.subtasks===void 0?[]:A(nr)(t.subtasks);return{id:E(t,`id`),title:E(t,`title`),status:E(t,`status`),...M(`verificationContract`,D(t,`verificationContract`)),...n.length===0?{}:{subtasks:n}}}function rr(e){let t=T(e);return{id:E(t,`id`),objective:E(t,`objective`),status:E(t,`status`),path:E(t,`path`),sisyphus:k(t,`sisyphus`),autoContinue:k(t,`autoContinue`),...M(`createdAt`,D(t,`createdAt`)),...M(`updatedAt`,D(t,`updatedAt`)),...M(`currentTaskId`,D(t,`currentTaskId`)),...M(`stopReason`,D(t,`stopReason`)),...M(`pauseReason`,D(t,`pauseReason`)),...M(`verificationContract`,D(t,`verificationContract`)),...M(`tokensUsed`,Ya(t,`tokensUsed`)),...M(`activeSeconds`,Ya(t,`activeSeconds`)),tasks:A(nr)(t.tasks),completedTaskCount:O(t,`completedTaskCount`),totalTaskCount:O(t,`totalTaskCount`)}}function ir(e){let t=T(e);return{goals:A(rr)(t.goals),directory:E(t,`directory`),generatedAt:E(t,`generatedAt`)}}function ar(e){let t=T(e),n=A(er)(t.statuses),r=new Set;for(let e of n){if(r.has(e.sessionId))throw Error(`Duplicate session status in catalog`);r.add(e.sessionId)}return{statuses:n,generatedAt:E(t,`generatedAt`)}}function or(e){let t=T(e),n=Fr(t,`catalogRevision`),r=Nr(t.sessions,vr,At,`sessions`);if(yr(r),br(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:xr(t,`catalogId`,512),catalogRevision:n,sessions:r}}function sr(e){let t=T(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=xr(t,`sessionId`,512),r=xr(t,`cwd`,jt),i=Cr(t,`catalogRevision`),a=t.unread===null?null:vr(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:xr(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function cr(e){let t=T(e);if(t.type!==`session.startup`)throw Error(`Invalid session startup event type`);let n=D(t,`startupToken`);if(n===``)throw Error(`Expected non-empty string field: startupToken`);return{type:`session.startup`,...M(`startupToken`,n),activity:lr(t.activity)}}function lr(e){let t=T(e);return{sessionId:j(t,`sessionId`),phase:dr(t,`phase`),label:j(t,`label`),...M(`detail`,D(t,`detail`)),at:j(t,`at`),...M(`startup`,ur(t))}}function ur(e){let t=e.startup;if(t!==void 0){if(typeof t!=`boolean`)throw Error(`Expected optional boolean field: startup`);return t}}function dr(e,t){let n=E(e,t);if(n!==`active`&&n!==`idle`&&n!==`error`)throw Error(`Expected session activity phase field: ${t}`);return n}function fr(e){let t=T(e);switch(t.type){case`message.append`:return{type:`message.append`,message:mr(t,`message`),...M(`clientMessageId`,D(t,`clientMessageId`)),...t.echo===!0?{echo:!0}:{}};case`assistant.delta`:return{type:`assistant.delta`,text:E(t,`text`)};case`assistant.thinking.delta`:return{type:`assistant.thinking.delta`,text:E(t,`text`)};case`tool.start`:return{type:`tool.start`,toolName:E(t,`toolName`),toolCallId:E(t,`toolCallId`),summary:E(t,`summary`),...M(`args`,t.args)};case`tool.update`:return{type:`tool.update`,toolName:E(t,`toolName`),toolCallId:E(t,`toolCallId`),text:E(t,`text`),...M(`content`,t.content),...M(`details`,t.details)};case`tool.end`:return{type:`tool.end`,toolName:E(t,`toolName`),toolCallId:E(t,`toolCallId`),text:E(t,`text`),isError:k(t,`isError`),...M(`content`,t.content),...M(`details`,t.details)};case`shell.start`:return{type:`shell.start`,command:E(t,`command`),...M(`excludeFromContext`,fa(t.excludeFromContext,`excludeFromContext`))};case`shell.chunk`:return{type:`shell.chunk`,chunk:E(t,`chunk`)};case`shell.end`:return{type:`shell.end`,...M(`output`,D(t,`output`)),...M(`exitCode`,hr(t,`exitCode`)),...M(`cancelled`,fa(t.cancelled,`cancelled`)),...M(`truncated`,fa(t.truncated,`truncated`)),...M(`fullOutputPath`,D(t,`fullOutputPath`)),...M(`isError`,fa(t.isError,`isError`))};case`agent.start`:return{type:`agent.start`};case`agent.end`:return{type:`agent.end`};case`message.end`:return{type:`message.end`,...M(`message`,t.message)};case`status.update`:return{type:`status.update`,status:er(t.status)};case`activity.update`:return{type:`activity.update`,activity:lr(t.activity)};case`command.output`:return gr(t);case`session.error`:return{type:`session.error`,message:E(t,`message`)};case`session.name`:return _r(t);case`session.created`:return{type:`session.created`,session:Dn(t.session)};case`pi.event`:return{type:`pi.event`,eventType:E(t,`eventType`)};default:throw Error(`Unsupported session stream event type`)}}function pr(e){let t=T(e);switch(t.type){case`status.update`:return{type:`status.update`,status:er(t.status)};case`activity.update`:return{type:`activity.update`,activity:lr(t.activity)};case`session.name`:return _r(t);case`session.created`:return{type:`session.created`,session:Dn(t.session)};case`terminal.created`:return{type:`terminal.created`,terminal:Oi(t.terminal)};case`terminal.exited`:return{type:`terminal.exited`,terminal:Oi(t.terminal)};case`terminal.closed`:return{type:`terminal.closed`,terminalId:j(t,`terminalId`),cwd:j(t,`cwd`)};case`machine.status`:return{type:`machine.status`,status:Mi(t.status)};default:throw Error(`Unsupported realtime stream event type`)}}function mr(e,t){let n=e[t];if(n===void 0)throw Error(`Expected field: ${t}`);return n}function hr(e,t){let n=e[t];if(n!==void 0){if(n===null)return null;if(typeof n!=`number`)throw Error(`Expected optional number|null field: ${t}`);return n}}function gr(e){let t=E(e,`level`);if(t!==`info`&&t!==`success`&&t!==`error`)throw Error(`Invalid command output level`);return{type:`command.output`,level:t,message:E(e,`message`)}}function _r(e){return{type:`session.name`,sessionId:j(e,`sessionId`),...M(`name`,D(e,`name`))}}function vr(e){let t=T(e),n=xr(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:xr(t,`sessionId`,512),cwd:xr(t,`cwd`,jt),completionOrder:Cr(t,`completionOrder`),completedAt:n}}function yr(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 br(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 xr(e,t,n){let r=j(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function Sr(e,t,n){let r=D(e,t);if(r!==void 0){if(r===``)throw Error(`Expected non-empty string field: ${t}`);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}}function Cr(e,t){let n=Fr(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function wr(e){let t=T(e),n=Er(t.summary),r=Nr(t.notifications,Dr,100,`notifications`);if(Ir(r),Lr(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==zr(r))throw Error(`Notification snapshot severity mismatch`);let i=Or(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:j(t,`daemonInstanceId`),catalogRevision:Fr(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function Tr(e){let t=T(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=Er(t.summary),r=Or(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=kr(t.delta);if(i.kind===`cleared`&&!Rr(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:j(t,`daemonInstanceId`),catalogRevision:Fr(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function Er(e){let t=T(e),n=Fr(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=Fr(t,`discardedCount`),i=jr(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:j(t,`sessionId`),cwd:j(t,`cwd`),inboxRevision:Fr(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function Dr(e){let t=T(e),n=E(t,`message`);if(new TextEncoder().encode(n).byteLength>8192)throw Error(`Notification message exceeds byte limit`);let r=E(t,`receivedAt`);if(!Number.isFinite(Date.parse(r)))throw Error(`Invalid notification receive time`);let i=Fr(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:j(t,`id`),message:n,truncated:k(t,`truncated`),severity:Ar(t.severity),receivedAt:r,order:i}}function Or(e){let t=T(e);return{order:Fr(t,`order`),overflowWatermark:Fr(t,`overflowWatermark`)}}function kr(e){let t=T(e);switch(t.kind){case`added`:{let e=D(t,`evictedNotificationId`);return{kind:`added`,notification:Dr(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=Nr(t.notificationIds,Pr,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:Mr(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function Ar(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function jr(e){return e===void 0?void 0:Ar(e)}function Mr(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 Nr(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 Pr(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function j(e,t){let n=E(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function Fr(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 Ir(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 Lr(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 Rr(e){return e.retainedCount===0&&e.discardedCount===0}function zr(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function Br(e){let t=T(e),n=t.skippedBusySessionIds===void 0?void 0:on(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:E(t,`generatedAt`),thresholds:Gr(t.thresholds),projects:A(Kr)(t.projects),totals:qr(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function Vr(e){let t=T(e);return{...Br(t),archivedSessionIds:on(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:on(t.deletedSessionIds,`deletedSessionIds`)}}function Hr(e){let t=T(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:on(t.archivedSessionIds,`archivedSessionIds`),failures:A(Wr)(t.failures),generatedAt:E(t,`generatedAt`)}}function Ur(e){let t=T(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:on(t.deletedSessionIds,`deletedSessionIds`),failures:A(Wr)(t.failures),generatedAt:E(t,`generatedAt`)}}function Wr(e){let t=T(e);return{sessionId:E(t,`sessionId`),error:E(t,`error`)}}function Gr(e){let t=T(e);return{...M(`archiveIdleDays`,Ya(t,`archiveIdleDays`)),...M(`deleteArchivedDays`,Ya(t,`deleteArchivedDays`))}}function Kr(e){let t=T(e);return{cwd:E(t,`cwd`),archiveCount:O(t,`archiveCount`),deleteCount:O(t,`deleteCount`)}}function qr(e){let t=T(e);return{archiveCount:O(t,`archiveCount`),deleteCount:O(t,`deleteCount`)}}function Jr(e){let t=T(e),n=E(t,`kind`);if(n!==`steer`&&n!==`followUp`)throw Error(`Invalid queued message kind`);return{kind:n,text:E(t,`text`),...M(`clientMessageId`,D(t,`clientMessageId`))}}function Yr(e){let t=T(e);return{input:O(t,`input`),output:O(t,`output`),cacheRead:O(t,`cacheRead`),cacheWrite:O(t,`cacheWrite`),total:O(t,`total`)}}function Xr(e){let t=T(e);return{...M(`provider`,D(t,`provider`)),...M(`id`,D(t,`id`)),...M(`name`,D(t,`name`)),...M(`contextWindow`,Ya(t,`contextWindow`)),...M(`reasoning`,t.reasoning)}}function Zr(e){return e===void 0?{}:{model:Xr(e)}}function Qr(e){let t=T(e);return{models:A(Xr)(t.models)}}function $r(e){let t=T(e);return{provider:E(t,`provider`),id:E(t,`id`),...M(`name`,D(t,`name`)),...M(`contextWindow`,Ya(t,`contextWindow`)),...M(`reasoning`,t.reasoning),enabled:k(t,`enabled`)}}function ei(e){let t=T(e);return{models:A($r)(t.models)}}function ti(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function ni(e){let t=T(e);return{levels:A(ti)(t.levels)}}function ri(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function ii(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 ai(e){let t=T(e),n=t.source===void 0?void 0:ii(t.source);return{configured:k(t,`configured`),...M(`source`,n),...M(`label`,D(t,`label`))}}function oi(e){let t=T(e),n=t.loginFlow;if(n!==void 0&&n!==`interactive`)throw Error(`Invalid auth provider login flow`);return{id:E(t,`id`),name:E(t,`name`),authType:ri(t.authType),status:ai(t.status),...n===void 0?{}:{loginFlow:n}}}function si(e){let t=T(e);return{providers:A(oi)(t.providers)}}function ci(e){let t=T(e);return{flowId:E(t,`flowId`),providerId:E(t,`providerId`),providerName:E(t,`providerName`),status:li(t.status),progress:A(e=>{if(typeof e!=`string`)throw Error(`Expected progress item string`);return e})(t.progress),...M(`error`,D(t,`error`)),...M(`auth`,ui(t.auth)),...M(`prompt`,fi(t.prompt)),...M(`select`,mi(t.select)),...M(`info`,hi(t.info))}}function li(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function ui(e){if(e===void 0)return;let t=T(e);return{url:E(t,`url`),...M(`instructions`,D(t,`instructions`)),...M(`deviceCode`,di(t.deviceCode))}}function di(e){if(e===void 0)return;let t=T(e);return{userCode:E(t,`userCode`),...M(`intervalSeconds`,Ya(t,`intervalSeconds`)),...M(`expiresInSeconds`,Ya(t,`expiresInSeconds`))}}function fi(e){if(e===void 0)return;let t=T(e);return{requestId:E(t,`requestId`),message:E(t,`message`),promptType:pi(t.promptType),...M(`placeholder`,D(t,`placeholder`)),...M(`allowEmpty`,Ja(t,`allowEmpty`))}}function pi(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function mi(e){if(e===void 0)return;let t=T(e);return{requestId:E(t,`requestId`),message:E(t,`message`),options:A(Ia)(t.options)}}function hi(e){if(e!==void 0)return A(e=>{let t=T(e);return{message:E(t,`message`),...M(`links`,t.links===void 0?void 0:A(gi)(t.links))}})(e)}function gi(e){let t=T(e);return{url:E(t,`url`),...M(`label`,D(t,`label`))}}function _i(e){if(e===void 0)return{};let t=T(e);return{contextUsage:{tokens:Xa(t,`tokens`),contextWindow:O(t,`contextWindow`),percent:Xa(t,`percent`)}}}function vi(e){let t=T(e),n=E(t,`source`);if(n!==`extension`&&n!==`prompt`&&n!==`skill`&&n!==`builtin`)throw Error(`Invalid command source`);return{name:E(t,`name`),source:n,...M(`description`,D(t,`description`))}}function yi(e){let t=T(e),n=E(t,`kind`);if(n!==`tracked`&&n!==`untracked`&&n!==`other`)throw Error(`Invalid file kind`);return{path:E(t,`path`),kind:n}}function bi(e){let t=T(e);return{path:E(t,`path`),entries:A(xi)(t.entries),scannedAt:E(t,`scannedAt`),truncated:k(t,`truncated`)}}function xi(e){let t=T(e),n=E(t,`type`);if(n!==`file`&&n!==`directory`&&n!==`symlink`)throw Error(`Invalid file tree entry type`);return{name:E(t,`name`),path:E(t,`path`),type:n,...M(`size`,Ya(t,`size`)),...M(`modifiedAt`,D(t,`modifiedAt`))}}function Si(e){let t=T(e),n=E(t,`encoding`);if(n!==`utf8`)throw Error(`Invalid file encoding`);return{path:E(t,`path`),...M(`language`,D(t,`language`)),...M(`mediaType`,Ei(t.mediaType)),...M(`mimeType`,D(t,`mimeType`)),encoding:n,size:O(t,`size`),modifiedAt:E(t,`modifiedAt`),content:E(t,`content`),truncated:k(t,`truncated`),binary:k(t,`binary`)}}function Ci(e){let t=T(e);return{path:E(t,`path`),size:O(t,`size`),modifiedAt:E(t,`modifiedAt`),created:k(t,`created`)}}function wi(e){let t=T(e);return{path:E(t,`path`),existed:k(t,`existed`)}}function Ti(e){let t=T(e);return{fromPath:E(t,`fromPath`),toPath:E(t,`toPath`),size:O(t,`size`),modifiedAt:E(t,`modifiedAt`)}}function Ei(e){if(e!==void 0){if(e!==`image`&&e!==`html`&&e!==`pdf`&&e!==`markdown`)throw Error(`Invalid file media type`);return e}}function Di(e){let t=T(e),n=t.decision;if(n!==!0&&n!==!1&&n!==null)throw Error(`Invalid workspace trust decision`);return{path:E(t,`path`),decision:n,trusted:k(t,`trusted`)}}function Oi(e){let t=T(e);return{id:E(t,`id`),cwd:E(t,`cwd`),name:E(t,`name`),createdAt:E(t,`createdAt`),exited:k(t,`exited`),...M(`exitCode`,Ya(t,`exitCode`)),...M(`commandRunId`,D(t,`commandRunId`))}}function ki(e){let t=T(e);return{id:E(t,`id`),origin:E(t,`origin`),projectId:E(t,`projectId`),workspaceId:E(t,`workspaceId`),terminalId:E(t,`terminalId`),title:E(t,`title`),command:E(t,`command`),status:Ai(t.status),...M(`exitCode`,Ya(t,`exitCode`)),createdAt:E(t,`createdAt`),...M(`startedAt`,D(t,`startedAt`)),...M(`completedAt`,D(t,`completedAt`)),metadata:ji(t.metadata,`metadata`)}}function Ai(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function ji(e,t){let n=T(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 Mi(e){let t=Bt(e);if(t===void 0)throw Error(`Expected machine status snapshot`);return t}function Ni(e){let t=T(e),n=t.enabled===!0,r=typeof t.disabledReason==`string`?t.disabledReason:void 0,i=typeof t.latest==`string`?t.latest:void 0,a=typeof t.branch==`string`?t.branch:void 0;return n?{enabled:!0,current:E(t,`current`),latest:i,available:t.available===!0,branch:a,checkedAt:E(t,`checkedAt`)}:{enabled:!1,current:``,latest:i,available:!1,branch:a,checkedAt:E(t,`checkedAt`),...r===void 0?{}:{disabledReason:r}}}function Pi(e){let t=T(e);return{goalId:E(t,`goalId`),archivedPath:typeof t.archivedPath==`string`?t.archivedPath:``,alreadyArchived:t.alreadyArchived===!0,agentMayRecreate:t.agentMayRecreate===!0}}function Fi(e){let t=T(e);return{hub:Li(t.hub),machines:A(Ri)(t.machines)}}function Ii(e){let t=T(e),n=E(t,`operation`);if(n!==`restart`&&n!==`update`)throw Error(`Invalid fleet operation`);return{operation:n,hub:Li(t.hub),outcomes:A(zi)(t.outcomes)}}function Li(e){let t=T(e);return{machineId:E(t,`machineId`),name:E(t,`name`)}}function Ri(e){let t=T(e),n=E(t,`kind`);if(n!==`local`&&n!==`remote`)throw Error(`Invalid machine kind`);return{...Li(e),kind:n,online:t.online===!0,...M(`version`,D(t,`version`)),...M(`piVersion`,D(t,`piVersion`)),...M(`error`,D(t,`error`))}}function zi(e){let t=T(e);return{...Li(e),started:t.started===!0,...M(`error`,D(t,`error`))}}function Bi(e){let t=T(e);return{path:E(t,`path`),exists:k(t,`exists`),config:Vi(t.config),effectiveConfig:Vi(t.effectiveConfig),envOverrides:Zi(t.envOverrides)}}function Vi(e){let t=T(e);return{...M(`host`,D(t,`host`)),...M(`port`,Ya(t,`port`)),...M(`allowedHosts`,Ui(t.allowedHosts)),...M(`shortcuts`,Yi(t.shortcuts)),...M(`plugins`,Xi(t.plugins)),...M(`pathAccess`,Wi(t.pathAccess)),...M(`uploads`,Ki(t.uploads)),...M(`maxUploadBytes`,Ya(t,`maxUploadBytes`)),...M(`agent`,Hi(t.agent)),...M(`spawnSessions`,Ja(t,`spawnSessions`)),...M(`subsessions`,Ja(t,`subsessions`)),...M(`askUser`,Ja(t,`askUser`))}}function Hi(e){if(e!==void 0){if(!w(e)||Array.isArray(e))throw Error(`Invalid PI WEB agent field`);return{...M(`command`,D(e,`command`)),...M(`dir`,D(e,`dir`))}}}function Ui(e){if(e!==void 0){if(e===!0)return!0;if(qi(e))return e;throw Error(`Invalid PI WEB allowedHosts field`)}}function Wi(e){if(e===void 0)return;if(!w(e))throw Error(`Invalid PI WEB pathAccess field`);let t=e.allowedPaths;return{...M(`allowedPaths`,Gi(t,`pathAccess.allowedPaths`))}}function Gi(e,t){if(e!==void 0){if(Ji(e))return e;throw Error(`Invalid PI WEB ${t} field`)}}function Ki(e){if(e!==void 0){if(!w(e)||Array.isArray(e))throw Error(`Invalid PI WEB uploads field`);return{...M(`defaultFolder`,D(e,`defaultFolder`))}}}function qi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function Ji(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function Yi(e){if(e!==void 0){if(!w(e)||Array.isArray(e))throw Error(`Invalid PI WEB shortcuts field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(t!==null&&(typeof t!=`string`||t===``))throw Error(`Invalid PI WEB shortcut field`);return[e,t]}))}}function Xi(e){if(e!==void 0){if(!w(e)||Array.isArray(e))throw Error(`Invalid PI WEB plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!w(t)||Array.isArray(t))throw Error(`Invalid PI WEB plugin config field`);let n=t.enabled;if(n!==void 0&&typeof n!=`boolean`)throw Error(`Invalid PI WEB plugin enabled field`);let r=t.settings;if(r!==void 0&&(!w(r)||Array.isArray(r)))throw Error(`Invalid PI WEB plugin settings field`);return[e,t]}))}}function Zi(e){let t=T(e);return{host:k(t,`host`),port:k(t,`port`),allowedHosts:k(t,`allowedHosts`),spawnSessions:k(t,`spawnSessions`),subsessions:k(t,`subsessions`),askUser:k(t,`askUser`)}}function Qi(e){let t=T(e);return{packages:A(ea)(t.packages)}}function $i(e){let t=T(e),n=D(t,`source`),r=t.scope===void 0?void 0:ta(t.scope),i=fa(t.removed,`removed`);return{action:na(t.action),...M(`source`,n),...M(`scope`,r),...M(`removed`,i),packages:A(ea)(t.packages)}}function ea(e){let t=T(e);return{source:E(t,`source`),scope:ta(t.scope),filtered:k(t,`filtered`),...M(`installedPath`,D(t,`installedPath`))}}function ta(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function na(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function ra(e){let t=T(e),n=A(ia)(t.plugins);if(t.lifecycleVersion===void 0)return{lifecycleVersion:1,plugins:n,diagnostics:[],serverRuntime:{status:`incompatible`,restartRequired:!1,message:`PI WEB does not support plugin lifecycle diagnostics. Update and restart PI WEB, then try again.`,recovery:ua()}};if(t.lifecycleVersion!==1)throw Error(`Unsupported PI WEB plugin lifecycle version`);return{lifecycleVersion:1,plugins:n,diagnostics:A(sa)(t.diagnostics),serverRuntime:ca(t.serverRuntime)}}function ia(e){let t=T(e),n=E(t,`id`),r=t.server===void 0?void 0:aa(t.server,n);return{id:n,...M(`module`,D(t,`module`)),source:E(t,`source`),scope:da(t.scope),machineSpecific:fa(t.machineSpecific,`machineSpecific`)??!1,enabled:k(t,`enabled`),discovered:fa(t.discovered,`discovered`)??!0,conflict:fa(t.conflict,`conflict`)??!1,...r===void 0?{}:{server:r}}}function aa(e,t){let n=T(e),r=n.state,i=n.phase;if(r!==`active`&&r!==`failed`&&r!==`incompatible`&&r!==`disabled`&&r!==`missing`&&r!==`unknown`)throw Error(`Invalid PI WEB server plugin state`);if(i!==void 0&&i!==`import`&&i!==`activate`&&i!==`validate`&&i!==`start`&&i!==`health`&&i!==`stop`)throw Error(`Invalid PI WEB server plugin phase`);let a=n.health===void 0?void 0:oa(n.health),o=E(n,`disableCommand`);if(o!==rn(t))throw Error(`Invalid PI WEB server plugin recovery command`);return{state:r,...M(`desiredRevision`,D(n,`desiredRevision`)),...M(`activeRevision`,D(n,`activeRevision`)),...i===void 0?{}:{phase:i},...M(`message`,D(n,`message`)),...a===void 0?{}:{health:a},staleRevision:k(n,`staleRevision`),restartRequired:k(n,`restartRequired`),disableCommand:o}}function oa(e){let t=T(e),n=t.status;if(n!==`healthy`&&n!==`degraded`&&n!==`unhealthy`)throw Error(`Invalid PI WEB server plugin health status`);return{status:n,...M(`message`,D(t,`message`))}}function sa(e){let t=T(e),n=t.kind,r=t.snapshot;if(n!==`conflict`&&n!==`discovery`)throw Error(`Invalid PI WEB plugin diagnostic kind`);if(r!==`desired`&&r!==`active`)throw Error(`Invalid PI WEB plugin diagnostic snapshot`);return{kind:n,snapshot:r,source:E(t,`source`),message:E(t,`message`),...M(`pluginId`,D(t,`pluginId`))}}function ca(e){let t=T(e),n=t.status,r=t.safeStart,i=t.desiredSafeStart;if(n!==`available`&&n!==`unavailable`&&n!==`incompatible`)throw Error(`Invalid PI WEB server-plugin runtime status`);if(r!==void 0&&r!==`bundled-only`&&r!==`none`)throw Error(`Invalid PI WEB server-plugin safe-start state`);if(i!==void 0&&i!==`off`&&i!==`bundled-only`&&i!==`none`)throw Error(`Invalid desired PI WEB server-plugin safe-start state`);return{status:n,...r===void 0?{}:{safeStart:r},...i===void 0?{}:{desiredSafeStart:i},restartRequired:k(t,`restartRequired`),...M(`message`,D(t,`message`)),recovery:la(t.recovery)}}function la(e){let t=T(e),n={showSafeStart:E(t,`showSafeStart`),bundledOnly:E(t,`bundledOnly`),noServerPlugins:E(t,`noServerPlugins`),clearSafeStart:E(t,`clearSafeStart`)};if(n.showSafeStart!==nn.showSafeStart||n.bundledOnly!==nn.bundledOnly||n.noServerPlugins!==nn.noServerPlugins||n.clearSafeStart!==nn.clearSafeStart)throw Error(`Invalid PI WEB server plugin recovery commands`);return n}function ua(){return{...nn}}function da(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEB plugin scope`);return e}function fa(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function pa(e){let t=T(e);return{packageName:E(t,`packageName`),generatedAt:E(t,`generatedAt`),components:ha(t.components),release:ba(t.release),commands:xa(t.commands),messages:A(Sa)(t.messages)}}function ma(e){let t=T(e);return{packageName:E(t,`packageName`),generatedAt:E(t,`generatedAt`),components:ga(t.components),capabilities:wa(t.capabilities)}}function ha(e){let t=T(e);return{web:va(t.web),sessiond:va(t.sessiond)}}function ga(e){let t=T(e);return{web:_a(t.web),sessiond:_a(t.sessiond)}}function _a(e){let t=T(e);return{component:Ca(t.component),label:E(t,`label`),...M(`runtimeVersion`,D(t,`runtimeVersion`)),...M(`piVersion`,D(t,`piVersion`)),available:k(t,`available`),capabilities:wa(t.capabilities),...M(`error`,D(t,`error`))}}function va(e){let t=T(e);return{component:Ca(t.component),label:E(t,`label`),...M(`runtimeVersion`,D(t,`runtimeVersion`)),...M(`installedVersion`,D(t,`installedVersion`)),...M(`piVersion`,D(t,`piVersion`)),stale:k(t,`stale`),available:k(t,`available`),...M(`installation`,ya(t.installation)),...M(`error`,D(t,`error`))}}function ya(e){if(e===void 0)return;let t=T(e),n=E(t,`kind`);if(n!==`pi-package`&&n!==`npm-global`&&n!==`local`&&n!==`docker`&&n!==`unknown`)throw Error(`Invalid PI WEB installation kind`);let r=t.scope;if(r!==void 0&&r!==`user`&&r!==`project`)throw Error(`Invalid PI WEB installation scope`);let i=t.dockerMode;if(i!==void 0&&i!==`runtime`&&i!==`dev`)throw Error(`Invalid PI WEB Docker mode`);return{kind:n,...M(`path`,D(t,`path`)),...M(`source`,D(t,`source`)),...r===void 0?{}:{scope:r},...M(`npmRoot`,D(t,`npmRoot`)),...i===void 0?{}:{dockerMode:i}}}function ba(e){let t=T(e);return{packageName:E(t,`packageName`),...M(`latestVersion`,D(t,`latestVersion`)),updateAvailable:k(t,`updateAvailable`),...M(`checkedAt`,D(t,`checkedAt`)),...t.skipped===!0?{skipped:!0}:{},...M(`error`,D(t,`error`))}}function xa(e){let t=T(e);return{...M(`update`,D(t,`update`)),...M(`restart`,D(t,`restart`)),...M(`restartWeb`,D(t,`restartWeb`)),...M(`restartSessiond`,D(t,`restartSessiond`)),...M(`status`,D(t,`status`))}}function Sa(e){let t=T(e);return{id:E(t,`id`),severity:Ta(t.severity),title:E(t,`title`),body:E(t,`body`),...M(`command`,D(t,`command`))}}function Ca(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEB service component`);return e}function wa(e){let t=Jt(e);if(t===void 0)throw Error(`Invalid PI WEB capabilities`);return t}function Ta(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEB status severity`);return e}function Ea(e){let t=T(e),n=E(t,`type`);if(n===`unsupported`)return{type:n,message:E(t,`message`)};if(n===`select`)return{type:n,requestId:E(t,`requestId`),title:E(t,`title`),options:A(Ia)(t.options)};if(n===`tree`)return{type:n,tree:Da(t.tree)};if(n===`done`)return{type:n,...M(`message`,D(t,`message`)),...La(t.session),...M(`promptDraft`,D(t,`promptDraft`))};throw Error(`Invalid command result type`)}function Da(e){let t=T(e),n=A(Oa)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=Na(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:Fa(t.activePathIds,`activePathIds`)}}function Oa(e){let t=T(e);return{id:Pa(t,`id`),parentId:Na(t,`parentId`),kind:ka(t.kind),summary:E(t,`summary`),...M(`timestamp`,D(t,`timestamp`)),...M(`label`,D(t,`label`))}}function ka(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 Aa(e){let t=T(e),n=k(t,`cancelled`);if(Object.hasOwn(t,`summaryEntry`))throw Error(`Invalid session tree navigation result field: summaryEntry`);if(n){Ma(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 Ma(t,`aborted`,`session tree navigation result`),{cancelled:n,...M(`editorText`,D(t,`editorText`))}}function ja(e){let t=T(e),n=k(t,`cancelled`);return n?(Ma(t,`session`,`session tree fork cancellation result`),Ma(t,`promptDraft`,`session tree fork cancellation result`),{cancelled:n}):{cancelled:n,session:Dn(t.session),...M(`promptDraft`,D(t,`promptDraft`))}}function Ma(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function Na(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 Pa(e,t){let n=E(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function Fa(e,t){let n=on(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function Ia(e){let t=T(e);return{value:E(t,`value`),label:E(t,`label`),...M(`description`,D(t,`description`))}}function La(e){return e===void 0?{}:{session:Dn(e)}}function Ra(e){if(T(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function za(e){let t=T(e);return A(Ba)(t.attachments)}function Ba(e){let t=T(e);return{path:E(t,`path`),mimeType:E(t,`mimeType`),size:O(t,`size`)}}function Va(e){if(T(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function Ha(e){let t=T(e);if(t.aborted!==!0)throw Error(`Expected aborted response`);let n=t.discarded;return{aborted:!0,discarded:Array.isArray(n)?A(Jr)(n):[]}}function Ua(e){if(T(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function Wa(e){let t=T(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:on(t.sessionIds,`sessionIds`),r=Ya(t,`archivedCount`),i=Ya(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function Ga(e){if(T(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function Ka(e){if(T(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function qa(e){if(T(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function Ja(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEB ${t} field`);return n}}function Ya(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function Xa(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 M(e,t){return t===void 0?{}:{[e]:t}}function Za(e){if(!w(e))return{runs:[]};let t=e.runs;if(!Array.isArray(t))return{runs:[]};let n=[];for(let e of t){if(!w(e))continue;let t=e.sessionId,r=e.cwd,i=e.interruptedAt;typeof t!=`string`||t===``||typeof r!=`string`||typeof i!=`string`||n.push({sessionId:t,cwd:r,interruptedAt:i})}return{runs:n}}function Qa(e){if(!w(e))return{subsessions:[],toolRuns:[]};let t=[],n=e.subsessions;if(Array.isArray(n))for(let e of n){if(!w(e))continue;let n=e.sessionId,r=e.cwd,i=e.status;typeof n!=`string`||n===``||typeof r==`string`&&(i!==`working`&&i!==`idle`&&i!==`error`&&i!==`unknown`||t.push({sessionId:n,cwd:r,status:i}))}return{subsessions:t,toolRuns:ro(e.toolRuns)}}function $a(e){let t=er(e);return{recalled:w(e)&&e.recalled===!0,status:t}}function eo(e){if(!w(e)||!Array.isArray(e.tasks))return[];let t=[];for(let n of e.tasks){if(!w(n))continue;let e=n.id,r=n.name,i=n.status;typeof e!=`string`||e===``||t.push({id:e,name:typeof r==`string`&&r!==``?r:e,command:typeof n.command==`string`?n.command:``,status:typeof i==`string`?i:`unknown`,...typeof n.startedAt==`string`?{startedAt:n.startedAt}:{},...typeof n.endedAt==`string`?{endedAt:n.endedAt}:{},...typeof n.durationMs==`number`?{durationMs:n.durationMs}:{},...typeof n.exitCode==`number`?{exitCode:n.exitCode}:{},bytesWritten:typeof n.bytesWritten==`number`?n.bytesWritten:0,hasOutput:n.hasOutput===!0})}return t}function to(e){if(!w(e))return``;let t=e.output;return typeof t==`string`?t:``}function no(e){if(!w(e))return``;let t=e.output;return typeof t==`string`?t:``}function ro(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!w(n))continue;let e=n.runId,r=n.agent,i=n.status,a=n.elapsedMs,o=n.startedAt;if(typeof e!=`string`||e===``||typeof r!=`string`||r===``||i!==`running`&&i!==`done`&&i!==`failed`&&i!==`lost`&&i!==`unknown`||typeof a!=`number`||typeof o!=`string`)continue;let s=n.lastActivity,c=n.task,l=n.model,u=n.toolCount;t.push({runId:e,agent:r,status:i,elapsedMs:a,startedAt:o,...typeof s==`string`&&s!==``?{lastActivity:s}:{},...typeof c==`string`&&c!==``?{task:c}:{},...typeof l==`string`&&l!==``?{model:l}:{},...typeof u==`number`?{toolCount:u}:{},hasOutput:n.hasOutput===!0})}return t}function io(e){return typeof e==`string`?e:e.id}function ao(e){return typeof e==`string`?void 0:e.cwd}function oo(e,t,n=`local`){let r=new URLSearchParams,i=ao(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(io(e))}/messages${a===``?``:`?${a}`}`}function so(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`),vt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`)}function co(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),r?.download===!0&&i.set(`download`,`1`),`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`}function lo(e,t,n,r){return vt(co(e,t,n,r))}var N=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`;function uo(e,t=`local`){return`${N(t)}/sessions/${encodeURIComponent(e.id)}`}function P(e,t,n=`local`){return`${uo(e,n)}/${t}`}function fo(e,t,n=`local`){return`${P(e,t,n)}${po(e)}`}function po(e){return`?${new URLSearchParams({cwd:e.cwd}).toString()}`}function F(e,t={}){return JSON.stringify({cwd:e.cwd,...t})}function mo(e){return JSON.stringify({sessions:e.map(ho)})}function ho(e){return{id:e.id,cwd:e.cwd}}function go(e){return e===`local`?`api/pi-web/status`:`${N(e)}/pi-web/status`}var _o={piWebStatus:(e=`local`)=>C(go(e),pa),checkForUpdates:(e=`local`)=>C(`${go(e)}?refresh=1`,pa,{cache:`no-store`}),piWebRuntime:()=>C(`api/pi-web/runtime`,ma)},vo={machines:()=>C(`api/machines`,cn),addMachine:e=>C(`api/machines`,ln,{method:`POST`,body:JSON.stringify(e)}),deleteMachine:e=>C(`api/machines/${encodeURIComponent(e)}`,e=>e,{method:`DELETE`}),updateMachine:(e,t)=>C(`api/machines/${encodeURIComponent(e)}`,ln,{method:`PATCH`,body:JSON.stringify(t)}),health:e=>C(`api/machines/${encodeURIComponent(e)}/health`,un),runtime:(e,t=!1)=>C(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,dn,t?{cache:`no-store`}:{})};function yo(e){return e===void 0?`api/config`:`${N(e)}/config`}function bo(e){return e===void 0?`api/plugins`:`${N(e)}/plugins`}var xo={config:e=>C(yo(e),Bi),saveConfig:(e,t)=>C(yo(t),Bi,{method:`PUT`,body:JSON.stringify({config:e})})};function So(e){let t=Bo(e)?e:{},n=t.started===!0,r=typeof t.error==`string`?t.error:void 0;return r===void 0?{started:n}:{started:n,error:r}}var Co={plugins:e=>C(bo(e),ra)},wo={status:()=>C(`api/pi-web/update/status`,Ni,{cache:`no-store`}),apply:()=>C(`api/pi-web/update/apply`,So,{method:`POST`,body:JSON.stringify({})})},To={report:()=>C(`api/pi-web/fleet`,Fi,{cache:`no-store`}),run:(e,t)=>C(`api/pi-web/fleet/run`,Ii,{method:`POST`,body:JSON.stringify({operation:e,...t===void 0?{}:{machineIds:t}})})};function Eo(e=``,t){let n=t===void 0?`api/pi-packages`:`${N(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var Do={packages:e=>C(Eo(``,e),Qi),install:(e,t)=>{let n={source:e};return C(Eo(`install`,t),$i,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return C(Eo(`remove`,n),$i,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return C(Eo(`update`,t),$i,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}},Oo={machineStatus:(e=`local`)=>C(`${N(e)}/status`,Mi)},ko={projects:(e=`local`)=>C(`${N(e)}/projects`,A(hn)),addProject:(e,t,n,r=`local`)=>C(`${N(r)}/projects`,hn,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>C(`${N(t)}/projects/${encodeURIComponent(e)}`,Va,{method:`DELETE`}),projectDirectories:(e,t=`local`)=>C(`${N(t)}/project-directories?q=${encodeURIComponent(e)}`,A(yi))};function Ao(e,t=`local`){return C(`${N(t)}/projects/${encodeURIComponent(e)}/workspaces`,t=>{let n=_n(t);if(n.projectId!==e)throw Error(`Workspace resolution did not match the requested project`);return n})}var jo={workspaceResolution:Ao,workspaces:async(e,t=`local`)=>[...(await Ao(e,t)).workspaces],deleteWorkspace:(e,t,n,r=`local`)=>{let i={precondition:n};return C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,ki,{method:`DELETE`,body:JSON.stringify(i)})},archiveWorkspaceGoal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/goals/${encodeURIComponent(n)}/archive`,Pi,{method:`POST`,body:JSON.stringify({})}),workspaceGoals:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/goals`,ir,{cache:`no-store`}),workspaceTree:(e,t,n=``,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,bi),workspaceFile:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,Si),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 C(`${N(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,Ci,{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 C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`,wi,{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`),C(`${N(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${o.toString()}`,Ti,{method:`POST`})}},Mo={sessions:(e,t=`local`)=>C(`${N(t)}/sessions?cwd=${encodeURIComponent(e)}`,A(Dn)),unreadCatalog:(e=`local`)=>C(`${N(e)}/sessions/unread`,or,{cache:`no-store`}),statusCatalog:(e=`local`)=>C(`${N(e)}/sessions/statuses`,ar,{cache:`no-store`}),interruptedRuns:(e=`local`)=>C(`${N(e)}/sessions/interrupted`,Za,{cache:`no-store`}),subsessions:(e,t=`local`)=>C(`${P(e,`subsessions`,t)}?cwd=${encodeURIComponent(e.cwd)}`,Qa,{cache:`no-store`}),acknowledgeUnread:(e,t,n,r=`local`)=>{let i={cwd:e.cwd,catalogId:t,throughCompletionOrder:n};return C(P(e,`unread/acknowledge`,r),or,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>C(fo(e,`notifications`,t),wr),dismissNotification:(e,t,n,r=`local`)=>C(P(e,`notifications/dismiss`,r),wr,{method:`POST`,body:F(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>C(P(e,`notifications/dismiss-all`,r),wr,{method:`POST`,body:F(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`,n)=>C(`${N(t)}/sessions`,Dn,{method:`POST`,body:JSON.stringify(n===void 0?{cwd:e}:{cwd:e,startupToken:n})}),cleanupPreview:(e,t=`local`)=>C(`${N(t)}/sessions/cleanup/preview`,Br,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>C(`${N(t)}/sessions/cleanup`,Vr,{method:`POST`,body:JSON.stringify(e)}),archiveMany:(e,t=`local`)=>C(`${N(t)}/sessions/bulk/archive`,Hr,{method:`POST`,body:mo(e)}),deleteArchivedMany:(e,t=`local`)=>C(`${N(t)}/sessions/bulk/delete-archived`,Ur,{method:`POST`,body:mo(e)}),messages:(e,t,n=`local`)=>C(oo(e,t,n),sn),status:(e,t=`local`)=>C(fo(e,`status`,t),er),streamSnapshot:(e,t=`local`)=>C(fo(e,`stream-snapshot`,t),tr),backgroundTasks:(e,t=`local`)=>C(`${P(e,`background-tasks`,t)}?cwd=${encodeURIComponent(e.cwd)}`,eo,{cache:`no-store`}),backgroundTaskOutput:(e,t,n=`local`)=>C(`${P(e,`background-tasks/${encodeURIComponent(t)}/output`,n)}?cwd=${encodeURIComponent(e.cwd)}`,to,{cache:`no-store`}),subagentRunOutput:(e,t,n=`local`)=>C(`${P(e,`subagent-runs/${encodeURIComponent(t)}/output`,n)}?cwd=${encodeURIComponent(e.cwd)}`,no,{cache:`no-store`}),clearQueue:(e,t=`local`)=>C(P(e,`queue/clear`,t),er,{method:`POST`,body:F(e)}),recallQueuedMessage:(e,t,n=`local`)=>C(P(e,`queue/clear`,n),$a,{method:`POST`,body:F(e,{text:t.text,kind:t.kind,...t.clientMessageId===void 0?{}:{clientMessageId:t.clientMessageId}})}),dismissWarning:(e,t,n=`local`)=>C(P(e,`warnings/dismiss`,n),er,{method:`POST`,body:F(e,{dismissId:t})}),submitAsk:(e,t,n,r=`local`)=>C(P(e,`ask/submit`,r),Vn,{method:`POST`,body:F(e,{askId:t,answers:n.answers})}),cancelAsk:(e,t,n=`local`)=>C(P(e,`ask/cancel`,n),Vn,{method:`POST`,body:F(e,{askId:t})}),answerDialog:(e,t,n,r=`local`)=>C(P(e,`dialogs/answer`,r),Hn,{method:`POST`,body:F(e,{dialogId:t,value:n})}),cancelDialog:(e,t,n=`local`)=>C(P(e,`dialogs/cancel`,n),Hn,{method:`POST`,body:F(e,{dialogId:t})}),models:(e,t=`local`)=>C(fo(e,`models`,t),Qr),modelCatalog:(e,t=`local`)=>C(fo(e,`models/catalog`,t),ei),setModelEnabled:(e,t,n,r,i=`local`)=>C(P(e,`models/enabled`,i),ei,{method:`POST`,body:F(e,{provider:t,modelId:n,enabled:r})}),setModel:(e,t,n,r=`local`)=>C(P(e,`model`,r),er,{method:`POST`,body:F(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>C(P(e,`model/cycle`,n),er,{method:`POST`,body:F(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>C(fo(e,`thinking-levels`,t),ni),setThinkingLevel:(e,t,n=`local`)=>C(P(e,`thinking-level`,n),er,{method:`POST`,body:F(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>C(P(e,`thinking-level/cycle`,t),er,{method:`POST`,body:F(e)}),commands:(e,t=`local`)=>C(fo(e,`commands`,t),A(vi)),prompt:(e,t,n,r=`local`,i,a)=>C(P(e,`prompt`,r),Ra,{method:`POST`,body:F(e,{text:t,...n===void 0?{}:{streamingBehavior:n},...i!==void 0&&i.length>0?{attachments:i}:{},...a===void 0?{}:{clientMessageId:a}})}),saveAttachments:(e,t,n=`local`,r)=>C(P(e,`attachments`,n),za,{method:`POST`,body:F(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>C(P(e,`shell`,n),Ra,{method:`POST`,body:F(e,{text:t})}),runCommand:(e,t,n=`local`)=>C(P(e,`commands/run`,n),Ea,{method:`POST`,body:F(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>C(P(e,`commands/respond`,r),Ea,{method:`POST`,body:F(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>C(P(e,`tree/navigate`,n),Aa,{method:`POST`,body:F(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary})}),forkTree:(e,t,n=`local`)=>Fo(e,t,n),abort:(e,t=`local`)=>C(P(e,`abort`,t),Ha,{method:`POST`,body:F(e)}),stop:(e,t=`local`)=>C(P(e,`stop`,t),Ua,{method:`POST`,body:F(e)}),archive:(e,t=`local`)=>C(P(e,`archive`,t),Wa,{method:`POST`,body:F(e)}),archiveWithDescendants:(e,t=`local`)=>C(P(e,`archive-tree`,t),Wa,{method:`POST`,body:F(e)}),restore:(e,t=`local`)=>C(P(e,`restore`,t),Ga,{method:`POST`,body:F(e)}),detachParent:(e,t=`local`)=>C(P(e,`detach-parent`,t),Ka,{method:`POST`,body:F(e)}),reloadSession:(e,t=`local`)=>C(P(e,`reload`,t),qa,{method:`POST`,body:F(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 C(`${N(e?.machineId)}/auth/providers${n===``?``:`?${n}`}`,si)},startInteractiveApiKeyLogin:(e,t=`local`)=>C(`${N(t)}/auth/api-key/interactive`,ci,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t=`local`)=>C(`${N(t)}/auth/logout`,Ra,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t=`local`)=>C(`${N(t)}/auth/oauth`,ci,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t=`local`)=>C(`${N(t)}/auth/oauth/${encodeURIComponent(e)}`,ci),respondOAuthFlow:(e,t,n,r=`local`)=>C(`${N(r)}/auth/oauth/${encodeURIComponent(e)}/respond`,ci,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t=`local`)=>C(`${N(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,ci,{method:`POST`})},No={terminals:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,A(Oi)),startTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Oi,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Va,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,Va,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,Oi,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,ki,{method:`POST`,body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t=`local`)=>C(`${N(t)}/terminal-command-runs${Ro(e)}`,A(ki)),getCommandRun:(e,t=`local`)=>Lo(e,t),cancelCommandRun:(e,t=`local`)=>C(`${N(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,ki,{method:`POST`})},Po=class extends Error{constructor(){super(`Fork from the session tree is unavailable. Restart the session daemon to enable it.`),this.name=`SessionTreeForkUnavailableError`}};async function Fo(e,t,n){let r=await fetch(vt(P(e,`tree/fork`,n)),{method:`POST`,headers:{"content-type":`application/json`},body:F(e,{entryId:t.entryId,expectedLeafId:t.expectedLeafId})});if(!r.ok){let e=await r.json().catch(()=>({}));throw Io(r.status,e)?new Po:Error(zo(e)??r.statusText)}return ja(await r.json())}function Io(e,t){if(e!==404||!Bo(t)||t.statusCode!==404||t.error!==`Not Found`)return!1;let n=t.message;return typeof n==`string`&&/^Route POST:.*\/tree\/fork not found$/i.test(n)}async function Lo(e,t){let n=await fetch(vt(`${N(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(n.status!==404){if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(zo(e)??n.statusText)}return ki(await n.json())}}function Ro(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 zo(e){if(!Bo(e))return;let t=e.error;return typeof t==`string`?t:void 0}function Bo(e){return typeof e==`object`&&!!e}var Vo={files:(e,t)=>{let n=new URLSearchParams({q:e});return t.kind!==void 0&&n.set(`kind`,t.kind),t.mode!==void 0&&n.set(`mode`,t.mode),t.scope!==void 0&&n.set(`scope`,t.scope),C(`${N(t.machineId)}/projects/${encodeURIComponent(t.projectId)}/workspaces/${encodeURIComponent(t.workspaceId)}/files?${n.toString()}`,A(yi))}},Ho=(e,t,n)=>`${N(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(n)}/trust`,Uo=(e,t)=>{let n=new URLSearchParams({path:t});return`${N(e)}/projects/trust?${n.toString()}`},Wo={projectTrust:(e,t=`local`)=>C(Uo(t,e),Di),workspaceTrust:(e,t,n=`local`)=>C(Ho(n,e,t),Di),setWorkspaceTrust:(e,t,n,r=`local`)=>C(Ho(r,e,t),Di,{method:`PUT`,body:JSON.stringify({trusted:n})})},I={..._o,...vo,...xo,...Co,...Do,...ko,...jo,...Mo,...No,...Vo,...Wo},Go=256*1024,Ko=8*1024*1024,qo=266240,Jo=8392704,Yo=/^[a-z][a-z0-9.-]*$/u,Xo=64;function Zo(e){return e.length<=128&&Yo.test(e)}function Qo(e){if(!Zo(e))throw Error(`Plugin backend operation must match ${String(Yo)} and be at most 128 characters`);return e}function $o(e){if(typeof e!=`string`||e===``||e.length>512)throw Error(`Plugin backend revision must be a non-empty string of at most 512 characters`);return e}function es(e,t,n=Go){let r=rs(e,new Set,t,0);if(ns(JSON.stringify(r))>n)throw Error(`${t} exceeds the ${String(n)} byte limit`);return r}function ts(e,t,n=Go){if(ns(e)>n)throw Error(`${t} exceeds the ${String(n)} byte limit`);let r;try{r=JSON.parse(e)}catch(e){throw Error(`${t} must be valid JSON`,{cause:e})}return es(r,t,n)}function ns(e){return new TextEncoder().encode(e).byteLength}function rs(e,t,n,r){if(r>Xo)throw Error(`${n} exceeds the maximum JSON depth of ${String(Xo)}`);if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`){if(!Number.isFinite(e))throw Error(`${n} must contain only finite JSON numbers`);return e}if(Array.isArray(e)){if(t.has(e))throw Error(`${n} must not contain cycles`);t.add(e);let i=e.map(e=>rs(e,t,n,r+1));return t.delete(e),Object.freeze(i),i}if(!as(e))throw Error(`${n} must contain only JSON values`);if(t.has(e))throw Error(`${n} must not contain cycles`);t.add(e);let i={};for(let[a,o]of Object.entries(e))is(i,a,rs(o,t,n,r+1));return t.delete(e),Object.freeze(i)}function is(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})}function as(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function os(e,t){if(!en(e.pluginId))throw Error(`Invalid PI WEB plugin id: ${e.pluginId}`);if(e.machineId===``)throw Error(`Machine id is required`);if(e.projectId===``)throw Error(`Project id is required`);if(e.workspaceId===``)throw Error(`Workspace id is required`);let n=Qo(t);return`${e.machineId===`local`?`api`:`api/machines/${encodeURIComponent(e.machineId)}`}/plugin-backends/${encodeURIComponent(e.pluginId)}/projects/${encodeURIComponent(e.projectId)}/workspaces/${encodeURIComponent(e.workspaceId)}/${encodeURIComponent(n)}`}function ss(e,t,n){let r=os(e,t);return n===void 0?vt(r):vt(r,n)}async function cs(e,t,n){let r=$o(e.backendRevision),i=es(n,`Plugin backend request input`),a=JSON.stringify({revision:r,input:i});if(ns(a)>266240)throw Error(`Plugin backend request exceeds the ${String(qo)} byte wire limit`);let o;try{o=await fetch(ss(e,t),{method:`POST`,headers:{"content-type":`application/json`},body:a})}catch(e){throw Error(`Plugin backend request unavailable: ${fs(e)}`,{cause:e})}let s=await ls(o);if(!o.ok)throw Error(ds(s)??`Plugin backend request returned HTTP ${String(o.status)}`);return ts(s,`Plugin backend response`,Ko)}async function ls(e){let t=e.headers.get(`content-length`);if(t!==null&&/^\d+$/u.test(t)&&Number(t)>8392704)throw await e.body?.cancel(),Error(`Plugin backend response exceeds the ${String(Jo)} byte wire limit`);if(e.body===null){let t=await e.text();if(ns(t)>8392704)throw us();return t}let n=e.body.getReader(),r=new TextDecoder,i=0,a=``;try{let e=await n.read();for(;!e.done;){if(i+=e.value.byteLength,i>8392704)throw await n.cancel(),us();a+=r.decode(e.value,{stream:!0}),e=await n.read()}return a+r.decode()}finally{n.releaseLock()}}function us(){return Error(`Plugin backend response exceeds the ${String(Jo)} byte wire limit`)}function ds(e){try{let t=JSON.parse(e);return ps(t)&&typeof t.error==`string`?t.error:void 0}catch{return}}function fs(e){return e instanceof Error?e.message:String(e)}function ps(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ms(e,t=`local`){let n=`?${new URLSearchParams({cwd:e.cwd}).toString()}`;return new WebSocket(yt(`${_s(t)}/sessions/${encodeURIComponent(e.id)}/events${n}`))}function hs(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(yt(`${_s(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function gs(e=`local`){return new WebSocket(yt(`${_s(e)}/events`))}function _s(e){return`api/machines/${encodeURIComponent(e)}`}var vs=`.pi-web/uploads`,ys=class extends Error{constructor(e=`Workspace upload cancelled`){super(e),this.name=`WorkspaceUploadCancelledError`}},bs=class extends Error{constructor(e,t){super(js(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function xs(e){return e?.uploads?.defaultFolder??`.pi-web/uploads`}function Ss(e,t){return e.uploads?.defaultFolder??t}function Cs(e,t){let n=Ps(e,`upload destination`,{allowEmpty:!0}),r=Ps(t,`upload file name`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function ws(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`,so(e,t,n.path,Ds(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(Os(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(Ci(Is(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(Ls(i)))},i.onerror=()=>{l(Error(`Workspace upload failed`))},i.onabort=()=>{l(new ys(o?void 0:`Workspace upload aborted`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function Ts(e,t,n,r={}){let i=r.destinationFolder??`.pi-web/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:Cs(i,e.name),loaded:0,total:e.size,percent:As(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(ks(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 ys;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=ws(e,t,{path:p.path,file:f},{...Es(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(Ns(e,c))throw e;let t=Ms(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 bs(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function Es(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 Ds(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Os(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:As(e.loaded,n),lengthComputable:e.lengthComputable}}function ks(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:As(i,r),done:n}}function As(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function js(e){return e.length===1?e[0]?.error??`Workspace upload failed`:`${String(e.length)} files failed to upload`}function Ms(e){return e instanceof Error?e.message:String(e)}function Ns(e,t){return t.requested||e instanceof ys}function Ps(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t} must not be empty`)}if(Fs(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 Fs(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function Is(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function Ls(e){let t=Rs(e);return zs(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function Rs(e){try{return Is(e)}catch{return}}function zs(e){return typeof e==`object`&&!!e}function Bs(e,t){return{title:e,text:t,empty:t.trim()===``}}function Vs(){return{sessions:[],workspaceGoals:[],workspaceGoalsLoading:!1,clientQueuedSessionMessages:{},startingSessionCount:0,selectedNotificationInbox:void 0,treeDialog:void 0,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,selectedFileLoadError:void 0,fileTreeStale:!1,selectedTerminalId:void 0,error:``}}function Hs(){return{machines:[],selfUpdate:void 0,selfUpdateApplying:!1,selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},machineStatusSnapshots:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,subagents:[],backgroundTasks:[],subagentRuns:[],activityOutput:void 0,status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],workspaceGoals:[],workspaceGoalsLoading:!1,sessionStatuses:{},sessionActivities:{},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,selectedFileLoadError:void 0,fileTreeStale:!1,workspaceUploadBatches:{},activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:``}}function Us(e,t){return t?.phase===`active`&&t.startup!==!0||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}var Ws=`machine.`;function Gs(e,t){if(e===``)throw Error(`Machine id is required`);if(!en(t))throw Error(`Invalid PI WEB plugin id: ${t}`);if(tn(t))throw Error(`Reserved PI WEB plugin id: ${t}`);return`${Ws}${Ks(e)}.${t}`}function Ks(e){return[...new TextEncoder().encode(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function qs(e,t){return`${e}:${t}`}function Js(e,t){return`${e}:${t}`}function L(e){return e.selectedMachine?.id??`local`}var Ys=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.applyStatus=n,this.authOperationGeneration=0,this.pollGeneration=0,this.api=r.api??I,this.pollIntervalMs=r.pollIntervalMs??1e3}dispose(){this.advanceAuthOperation()}handleSlashCommand(e){let t=Qs(e);return t===void 0?!1:(t.command===`login`?this.openLogin(t.providerId):this.openLogout(t.providerId),!0)}async openLogin(e){let t=this.advanceAuthOperation(),n=L(this.getState());if(e!==void 0&&e!==``){await this.openLoginProvider(e,n,t);return}this.setState({authDialog:{step:`method`,machineId:n}})}async chooseLoginMethod(e){let t=this.getState().authDialog;if(t?.step!==`method`)return;let n=this.authOperationGeneration,{machineId:r}=t;try{let{providers:i}=await this.api.authProviders({mode:`login`,authType:e,machineId:r});if(!this.isCurrentAuthOperation(n)||this.getState().authDialog!==t)return;this.setState({authDialog:{step:`providers`,mode:`login`,machineId:r,authType:e,providers:i}})}catch(e){this.isCurrentAuthOperation(n)&&this.getState().authDialog===t&&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));if(r!==void 0&&(r.authType===`oauth`||r.loginFlow===`interactive`)){let e=this.advanceAuthOperation();await this.startLoginFlow(r,n.machineId,e)}}async openLogout(e){let t=this.advanceAuthOperation(),n=L(this.getState());try{let{providers:r}=await this.api.authProviders({mode:`logout`,machineId:n});if(!this.isCurrentAuthOperation(t))return;if(e!==void 0&&e!==``){let i=r.find(t=>t.id===e);i===void 0?this.setState({error:`No stored credentials for ${e}`}):await this.logoutProviderOnMachine(i.id,n,t);return}this.setState({authDialog:{step:`logout`,machineId:n,providers:r}})}catch(e){this.isCurrentAuthOperation(t)&&this.setState({error:String(e)})}}async logoutProvider(e){let t=this.getState().authDialog;if(t?.step!==`logout`)return;let n=this.advanceAuthOperation();await this.logoutProviderOnMachine(e,t.machineId,n)}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.authOperationGeneration,i=t.flow.flowId,a=n.requestId,o={flowId:i,requestId:a};if(Xs(this.inFlightResponse,o))return;let s=e??t.inputValue??``,c={...t};delete c.error,this.inFlightResponse=o,this.setState({authDialog:{...c,responding:!0}});try{let e=await this.api.respondOAuthFlow(i,a,s,t.machineId),n=this.currentOAuthDialog(r,i);if(e.flowId!==i||n===void 0||Zs(n.flow)!==a)return;this.updateOAuthFlow(e,n.machineId)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||Zs(t.flow)!==a)return;this.setState({authDialog:{...t,responding:!1,error:String(e)}})}finally{Xs(this.inFlightResponse,o)&&(this.inFlightResponse=void 0)}}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.advanceAuthOperation(),this.setState({authDialog:void 0})}async openLoginProvider(e,t,n){try{let{providers:r}=await this.api.authProviders({mode:`login`,machineId:t});if(!this.isCurrentAuthOperation(n))return;let i=r.filter(t=>t.id===e);if(i.length===0){this.setState({error:`Auth provider not found: ${e}`});return}if(i.length>1){this.setState({authDialog:{step:`providers`,mode:`login`,machineId:t,providers:i}});return}let a=i[0];if(a===void 0)return;(a.authType===`oauth`||a.loginFlow===`interactive`)&&await this.startLoginFlow(a,t,n)}catch(e){this.isCurrentAuthOperation(n)&&this.setState({error:String(e)})}}async logoutProviderOnMachine(e,t,n){if(this.isCurrentAuthOperation(n))try{if(await this.api.logoutProvider(e,t),!this.isCurrentAuthOperation(n))return;this.closeDialog(),this.refreshStatus(t)}catch(e){this.isCurrentAuthOperation(n)&&this.setState({error:String(e)})}}async startLoginFlow(e,t,n){if(this.isCurrentAuthOperation(n))try{let r=e.authType===`oauth`?await this.api.startOAuthLogin(e.id,t):await this.api.startInteractiveApiKeyLogin(e.id,t);if(!this.isCurrentAuthOperation(n)){if(r.status===`running`)try{await this.api.cancelOAuthFlow(r.flowId,t)}catch{}return}this.updateOAuthFlow(r,t),r.status===`running`&&this.startPolling(r.flowId,t)}catch(e){this.isCurrentAuthOperation(n)&&this.setState({error:String(e)})}}updateOAuthFlow(e,t){if(e.status===`complete`){this.stopPolling(),this.closeDialog(),this.refreshStatus(t);return}(e.status===`error`||e.status===`cancelled`)&&this.advanceAuthOperation();let n=this.getState().authDialog,r=n?.step===`oauth`&&n.flow.flowId===e.flowId?n.inputValue??``:``,i=n?.step===`oauth`?Zs(n.flow):void 0,a=Zs(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.authOperationGeneration,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=Zs(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||Zs(o.flow)!==a)return;this.updateOAuthFlow(i,t)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o?.machineId!==t||Zs(o.flow)!==a)return;this.stopPolling(),this.setState({authDialog:{...o,error:String(i)}})}}advanceAuthOperation(){return this.authOperationGeneration+=1,this.stopPolling(),this.authOperationGeneration}isCurrentAuthOperation(e){return e===this.authOperationGeneration}currentOAuthDialog(e,t){if(!this.isCurrentAuthOperation(e))return;let n=this.getState().authDialog;return n?.step===`oauth`&&n.flow.flowId===t?n:void 0}async refreshStatus(e=L(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(L(t)!==e)return;let n=t.selectedSession;if(!(n===void 0||n.archived===!0))return n}};function Xs(e,t){return e?.flowId===t.flowId&&e.requestId===t.requestId}function Zs(e){return e.prompt?.requestId??e.select?.requestId}function Qs(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 $s(e){return e.replaceAll(`:`,`.`)}function ec(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 tc(e,t){let n=ec(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function nc(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));rc(i,r)}function rc(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 ic(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:Cs(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:uc(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:uc(0,n),status:`uploading`,startedAt:e.startedAt}}function ac(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 oc(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=lc(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function sc(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,...lc(r),status:`error`,error:t,completedAt:n}}function cc(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,...lc(r),status:`cancelled`,error:n,completedAt:t}}function lc(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function uc(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var dc=class{constructor(e,t){this.getState=e,this.setState=t}report(e){this.reported=e,this.setState({error:e})}clear(){let e=this.reported;this.reported=void 0,!(e===void 0||this.getState().error!==e)&&this.setState({error:``})}},fc=$s(`core:workspace.files`),pc=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.updateUrl=n,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.fileRequestGeneration=0,this.reportedError=new dc(e,t),this.api=r.api??I,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??Ts,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=L(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}),this.reportedError.clear()}catch(e){this.reportedError.report(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:gc(this.getState().expandedDirs,e)});return}try{let r=await this.api.workspaceTree(t.id,n.id,e,L(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[e]:r.entries}}),this.reportedError.clear()}catch(e){this.reportedError.report(String(e))}}}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,selectedFileLoadError:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),nc(fc,`file`,e),this.updateUrl({replace:!0}),await this.restoreFile(e)}async restoreFile(e){let t=++this.fileRequestGeneration,n=this.getState(),r=n.selectedProject,i=n.selectedWorkspace;if(r===void 0||i===void 0)return;let a={generation:t,machineId:L(n),projectId:r.id,workspaceId:i.id,path:e};this.setState({selectedFilePath:e,selectedFileContent:void 0,selectedFileLoadError:void 0});try{let e=await this.api.workspaceFile(a.projectId,a.workspaceId,a.path,a.machineId);if(!this.isCurrentFileRequest(a))return;this.setState({selectedFileContent:e,selectedFileLoadError:void 0}),this.reportedError.clear()}catch(e){if(!this.isCurrentFileRequest(a))return;this.setState({selectedFileContent:void 0,selectedFileLoadError:hc(e)})}}isCurrentFileRequest(e){let t=this.getState();return e.generation===this.fileRequestGeneration&&t.selectedFilePath===e.path&&t.selectedProject?.id===e.projectId&&t.selectedWorkspace?.id===e.workspaceId&&L(t)===e.machineId}startWorkspaceUpload(e,t){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0){this.reportedError.report(`Select a workspace before uploading files.`);return}if(e.length===0)return;let i=L(this.getState()),a=t.overwrite??!1,o=t.createDirs??!0,s;try{s=ic({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.reportedError.report(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(cc(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:gc(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(ac(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(oc(r,t,this.now())),this.reportedError.clear(),!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 bs)||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(mc(t)){let e=cc(n,this.now());return this.setUploadBatch(e),e}let r=hc(t),i=sc(n,r,this.now());return this.setUploadBatch(i),this.reportedError.report(r),i}getUploadBatch(e){return this.getState().workspaceUploadBatches[e]}setUploadBatch(e){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[e.id]:e}})}isCurrentWorkspaceBatch(e){let t=this.getState();return t.selectedProject?.id===e.projectId&&t.selectedWorkspace?.id===e.workspaceId&&L(t)===e.machineId}};function mc(e){return e instanceof ys}function hc(e){return e instanceof Error?e.message:String(e)}function gc(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}var _c=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 I.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));this.setState({machines:t,selectedMachine:n,machineRuntimes:yc(this.getState().machineRuntimes,r),machineStatusSnapshots:yc(this.getState().machineStatusSnapshots,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:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...Vs()}),t.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(e.id),this.refreshMachineRuntime(e.id))}async updateMachine(e,t){this.setState({error:``});try{let n=await I.updateMachine(e.id,t);return this.setState({machines:this.getState().machines.map(e=>e.id===n.id?n:e)}),n}catch(e){this.setState({error:String(e)});return}}async addMachine(e){this.setState({error:``});try{let t=await I.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 I.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:vc(this.getState().machineStatuses,e.id),machineRuntimes:vc(this.getState().machineRuntimes,e.id),machineStatusSnapshots:vc(this.getState().machineStatusSnapshots,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 I.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 I.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 I.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=>I.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=>I.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 vc(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function yc(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var bc=class{constructor(e=0){if(this.debounceMs=e,this.pendingByKey=new Map,!Number.isInteger(e)||e<0)throw Error(`debounceMs must be a non-negative integer`)}request(e,t){let n=this.pendingByKey.get(e);if(n!==void 0)return n.latestRefresh=t,n.phase===`running`?n.trailing=!0:this.rescheduleDebounce(n),n.promise;let r={promise:Promise.resolve(),latestRefresh:t,phase:`debouncing`,trailing:!1,debounceTimer:void 0,finishDebounce:void 0};return r.promise=Promise.resolve().then(async()=>{let e,t;do{r.trailing=!1,r.phase=`debouncing`,this.debounceMs>0&&await this.waitForDebounce(r),r.phase=`running`;let n=r.latestRefresh;t=!1;try{await n()}catch(n){e=n,t=!0}}while(this.hasTrailingRequest(r));if(t)throw e}).finally(()=>{this.cancelDebounce(r),this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e)}),this.pendingByKey.set(e,r),r.promise}hasTrailingRequest(e){return e.trailing}waitForDebounce(e){return new Promise(t=>{e.finishDebounce=t,this.rescheduleDebounce(e)})}rescheduleDebounce(e){e.finishDebounce!==void 0&&(e.debounceTimer!==void 0&&globalThis.clearTimeout(e.debounceTimer),e.debounceTimer=globalThis.setTimeout(()=>{let t=e.finishDebounce;e.debounceTimer=void 0,e.finishDebounce=void 0,e.phase=`running`,t?.()},this.debounceMs))}cancelDebounce(e){e.debounceTimer!==void 0&&globalThis.clearTimeout(e.debounceTimer),e.debounceTimer=void 0,e.finishDebounce=void 0}},xc=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new bc,this.api=n.api??Oo}refresh(e){return this.refreshes.request(e,async()=>{this.apply(e,await this.api.machineStatus(e))})}apply(e,t){let n=this.getState().machineStatusSnapshots;Sc(n[e],t)&&this.setState({machineStatusSnapshots:{...n,[e]:t}})}};function Sc(e,t){return e===void 0||e.epochId!==t.epochId||t.revision>e.revision}var Cc=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.api=r.api??I}async loadProjects(){let e=L(this.getState());this.setState({error:``,isLoadingProjects:!0});try{let t=await this.api.projects(e);if(L(this.getState())!==e)return;let n=new Set(t.map(e=>e.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([e])=>n.has(e)));this.setState({projects:t,workspacesByProjectId:r})}catch(t){L(this.getState())===e&&this.setState({error:String(t)})}finally{L(this.getState())===e&&this.setState({isLoadingProjects:!1})}}async addProject(e,t,n){if(e.trim()===``)return;let r=L(this.getState());try{let i=await this.api.addProject(e.trim(),void 0,t,r);if(L(this.getState())!==r)return;let a=this.getState().projects;this.setState({projects:[...a.filter(e=>e.id!==i.id),i],projectDialogOpen:!1}),await this.workspaces.selectProject(i),n?.changed===!0&&await this.applyTrustChoice(i,n.trusted,r);return}catch(e){return wc(e)}}async applyTrustChoice(e,t,n){let r=this.getState().workspaces.find(e=>e.isMain);r!==void 0&&await this.api.setWorkspaceTrust(e.id,r.id,t,n)}async closeProject(e){let t=L(this.getState());try{if(await this.api.closeProject(e,t),L(this.getState())!==t)return;this.workspaces.forgetProject(e);let n=this.getState();this.setState({projects:n.projects.filter(t=>t.id!==e)}),n.selectedProject?.id===e&&this.workspaces.clearSelection()}catch(e){L(this.getState())===t&&this.setState({error:String(e)})}}};function wc(e){let t=e instanceof Error?e.message:String(e);return/ENOENT|no such file or directory/u.test(t)?`That folder does not exist. Tick “Create the folder if it does not exist” to make it, or correct the path.`:t.includes(`ENOTDIR`)?`That path is a file, not a folder.`:/EACCES|EPERM/u.test(t)?`That folder cannot be read with this account's permissions.`:t.replace(/^Error:\s*/u,``)}var Tc=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??_o,this.onRefreshError=n.onRefreshError??(()=>void 0)}async refresh(){let e=L(this.getState());if(this.pendingUpdateCheck?.machineId===e)return;let t=++this.requestSequence;try{let n=await this.api.piWebStatus(e);this.isCurrent(e,t)&&this.setState({piWebStatus:n})}catch(n){if(!this.isCurrent(e,t))return;this.setState({piWebStatus:void 0}),this.onRefreshError(e,n)}}checkForUpdates(){let e=L(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({piWebStatus:t}),Ec(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 L(this.getState())===e&&t===this.requestSequence}};function Ec(e){if(e.release.error!==void 0)throw Error(`PI WEB update check failed: ${e.release.error}`);if(e.release.skipped===!0)throw Error(`PI WEB update check was skipped because remote version checks are disabled by offline/version-check settings`)}var Dc=`pi-web:cached-new-sessions:v1`,Oc=`browserCachedNew`,kc=`local`;function Ac(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function jc(e,t=kc,n=Ac()){if(e.messageCount!==0||e.archived===!0)return;let r=Lc(n).filter(n=>n.id!==e.id||n.machineId!==t);Rc([Mc(e,t),...r],n)}function Mc(e,t=kc){return{...e,browserCachedNew:!0,machineId:t}}function Nc(e,t=kc,n=Ac()){Rc(Lc(n).filter(n=>n.id!==e||n.machineId!==t),n)}function Pc(e,t,n=kc,r=Ac()){let i=new Set(t.map(e=>e.id)),a=Lc(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&Rc(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function Fc(e){return e!==void 0&&Bc(e)&&e.browserCachedNew===!0}function Ic(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:kc},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Lc(e=Ac()){try{let t=e?.getItem(Dc);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>zc(e)):[]}catch{return[]}}function Rc(e,t=Ac()){try{e.length===0?t?.removeItem(Dc):t?.setItem(Dc,JSON.stringify(e))}catch{}}function zc(e){if(!Vc(e))return[];let t=Hc(e,`id`),n=Hc(e,`path`),r=Hc(e,`cwd`),i=Hc(e,`created`),a=Hc(e,`modified`),o=Hc(e,`firstMessage`),s=Wc(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=Uc(e,`name`),l=Uc(e,`parentSessionPath`),u=Uc(e,`machineId`)??kc;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 Bc(e){return Oc in e}function Vc(e){return typeof e==`object`&&!!e}function Hc(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Uc(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function Wc(e,t){let n=e[t];return typeof n==`number`?n:void 0}function Gc(e){return hl(e.flatMap(Xc)).filter(e=>e.parts.length>0)}function Kc(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function qc(e,t){let n=il(t);return n===void 0?e:{...e,meta:n}}function Jc(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,Kc(t,n)]}function Yc(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 Xc(e){if(el(e))return[e];if(R(e,`role`)===`bashExecution`)return[qc(sl(e),e)];let t=R(e,`role`),n=cl(t),r=ll(Cl(e,`content`),e),i=t===`toolResult`?dl(R(e,`toolName`)??``,Cl(e,`details`)):void 0,a=i===void 0?r:[...r,i],o=n===`user`?tl(a):void 0;if(o!==void 0)return o.map(t=>qc(t,e));let s=rl(e);if(n===`tool`)return[qc({role:n,parts:a,...s===void 0?{}:{source:s}},e)];let c=a.filter(e=>e.type!==`empty`),l=n===`assistant`&&c.length>0&&c.every(e=>e.type===`skillRead`)?`skill`:n,u=c.length>0?[qc({role:l,parts:c,...s===void 0?{}:{source:s}},e)]:[],d=Zc(e);return d===void 0?u:[...u,qc(d,e)]}function Zc(e){if(R(e,`role`)!==`assistant`||R(e,`stopReason`)!==`error`)return;let t=R(e,`errorMessage`)?.trim();return Kc(`system`,`Model response failed: ${Qc(t===void 0||t===``?`The model returned an error.`:t,e)}`)}function Qc(e,t){if(!/aborted/iu.test(e))return e;let n=$c(t);return n===void 0?`${e} (the turn was stopped before it finished)`:`${e} (stopped while running ${n})`}function $c(e){let t=Cl(e,`content`);if(Array.isArray(t))for(let e=t.length-1;e>=0;--e){let n=t[e],r=R(n,`type`);if(r!==`toolCall`&&r!==`toolExecution`)continue;let i=R(n,`name`)??R(n,`toolName`);if(i!==void 0&&i!==``)return i}}function el(e){let t=R(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(Cl(e,`parts`))}function tl(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=nl(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 nl(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 rl(e){let t=R(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function il(e){let t=al(Cl(e,`timestamp`)),n=ol(e),r=R(e,`thinkingLevel`);if(!(t===void 0&&n===void 0&&(r===void 0||r===``)))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n},...r===void 0||r===``?{}:{thinkingLevel:r}}}function al(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 ol(e){if(R(e,`role`)!==`assistant`)return;let t=R(e,`provider`),n=R(e,`model`),r=R(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 sl(e){let t=R(e,`command`)??``,n=wl(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=Cl(e,`output`);r!=null&&n.push(``,El(r));let i=Cl(e,`exitCode`);i!=null&&n.push(``,`exit ${El(i)}`),wl(e,`cancelled`)===!0&&n.push(``,`cancelled`),wl(e,`truncated`)===!0&&n.push(``,`output truncated`);let a=R(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`full output: ${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
|
|
4
4
|
`)}]}}function cl(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function ll(e,t){let n=ul(t);return n===void 0?typeof e==`string`?e===``?[]:[{type:`text`,text:e}]:Array.isArray(e)?e.flatMap(e=>{let t=R(e,`type`),n=R(e,`text`);if(t===`text`)return n!==void 0&&n!==``?[{type:`text`,text:n}]:[];if(t===`thinking`){let t=R(e,`thinking`)??n;return t!==void 0&&t!==``?[{type:`thinking`,text:t}]:[]}if(t===`toolCall`){let t=R(e,`name`)??`tool`,n=Cl(e,`arguments`),r=R(e,`id`),i=t===`read`?ml(R(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:bl(n),...n===void 0?{}:{args:n}}]:[{type:`skillRead`,...i,...r===void 0?{}:{toolCallId:r}}]}if(t===`image`){let t=R(e,`data`),n=R(e,`mimeType`);return t!==void 0&&t!==``&&n!==void 0&&n!==``?[{type:`image`,mimeType:n,data:t}]:[{type:`text`,text:`[image]`}]}return yl(e)}).map(e=>e.type===`text`&&R(t,`role`)===`toolResult`?pl(e.text,t):e):yl(e):[n]}function ul(e){if(!(R(e,`role`)!==`custom`||R(e,`customType`)!==`pi-web.ask.answers`))return fl(Cl(e,`details`))}function dl(e,t){if(e===`ask_user`)return fl(Cl(t,`superseded`))}function fl(e){try{return{type:`askUserRecord`,outcome:Bn(e)}}catch{return}}function pl(e,t){let n=R(t,`toolCallId`),r=Cl(t,`content`),i=Cl(t,`details`);return{type:`toolResult`,...n===void 0?{}:{toolCallId:n},toolName:R(t,`toolName`)??`tool`,text:e,...r===void 0?{}:{content:r},...i===void 0?{}:{details:i},isError:wl(t,`isError`)===!0}}function ml(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 hl(e){let t=[],n=new Map;for(let r of e){let e=[],i={...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=gl(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&&_l(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function gl(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 _l(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=vl(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 vl(e){let t=Cl(e,`preview`);if(!Sl(t))return;let n=R(t,`diff`),r=R(t,`error`),i=Tl(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 yl(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:bl(e)}]:[{type:`text`,text:El(e)}]}function bl(e){if(!Sl(e))return El(e);let t=R(e,`command`);if(t!==void 0)return t;let n=R(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}: ${xl(t)}`).join(` · `)}function xl(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 Sl(e){return typeof e==`object`&&!!e}function Cl(e,t){return Sl(e)?e[t]:void 0}function R(e,t){let n=Cl(e,t);return typeof n==`string`?n:void 0}function wl(e,t){let n=Cl(e,t);return typeof n==`boolean`?n:void 0}function Tl(e,t){let n=Cl(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function El(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var Dl=`pi-web:prompt-draft:`;function Ol(e){return`${Dl}${e}`}function kl(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Al(e,t=kl()){try{return t?.getItem(Ol(e))??``}catch{return``}}function jl(e,t,n=kl()){try{t?n?.setItem(Ol(e),t):n?.removeItem(Ol(e))}catch{}}function Ml(e,t=kl()){try{t?.removeItem(Ol(e))}catch{}}function Nl(e,t,n=kl()){let r=Al(e,n);r!==``&&(jl(t,r,n),Ml(e,n))}var Pl=`pi-web:ask-draft:`;function Fl(e,t){return`${Pl}${e}:${t}`}function Il(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Ll(e,t,n=Il()){try{let r=n?.getItem(Fl(e,t));return r==null?{}:Bl(r)}catch{return{}}}function Rl(e,t,n,r=Il()){try{let i=Object.entries(n).filter(([,e])=>e.values.length>0||(e.otherText??``)!==``);i.length===0?r?.removeItem(Fl(e,t)):r?.setItem(Fl(e,t),JSON.stringify(Object.fromEntries(i)))}catch{}}function zl(e,t,n=Il()){try{n?.removeItem(Fl(e,t))}catch{}}function Bl(e){let t=JSON.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))return{};let n={};for(let[e,r]of Object.entries(t)){let t=Vl(r);t!==void 0&&(n[e]=t)}return n}function Vl(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t={...e},n=t.values,r=t.otherText;if(!(!Array.isArray(n)||!n.every(e=>typeof e==`string`))&&!(r!==void 0&&typeof r!=`string`))return{values:[...n],...r===void 0?{}:{otherText:r}}}function Hl(e,t){return e.filter(e=>Gl(e,t[e.id])!==void 0).length}function Ul(e,t){return e.filter(e=>Gl(e,t[e.id])===void 0)}function Wl(e,t){let n=[];for(let r of e){let e=Gl(r,t[r.id]);e!==void 0&&n.push(e)}return{answers:n}}function Gl(e,t){if(t===void 0)return;let n=new Set(e.options.map(e=>e.value)),r=[...new Set(t.values)].filter(e=>n.has(e)),i=Kl(t.otherText);if(e.multiple!==!0&&r.length+(i===void 0?0:1)>1){let t=r[0];return t===void 0?i===void 0?void 0:{id:e.id,values:[],otherText:i}:{id:e.id,values:[t]}}if(!(r.length===0&&i===void 0))return{id:e.id,values:r,...i===void 0?{}:{otherText:i}}}function Kl(e){if(e===void 0)return;let t=e.trim().slice(0,Pt);return t===``?void 0:t}function ql(e,t){let n=Jl(t);if(n===void 0)return[...e,t];let r=e.length;for(;r>0;){let t=e[r-1],i=t===void 0?void 0:Jl(t);if(i===void 0||i<=n)break;--r}return r===e.length?[...e,t]:[...e.slice(0,r),t,...e.slice(r)]}function Jl(e){let t=e.meta?.timestamp;if(t===void 0||t===``)return;let n=Date.parse(t);return Number.isNaN(n)?void 0:n}function Yl(){let e=globalThis.crypto.randomUUID?.();return e===void 0?`cm-${String(Date.now())}-${Math.random().toString(36).slice(2,10)}`:e}function Xl(e,t,n=[]){let r=n.filter(e=>e.kind===`image`).map(e=>({type:`image`,mimeType:e.mimeType,data:e.data}));return{role:`user`,parts:e===``?[...r]:[{type:`text`,text:e},...r],meta:{delivery:{clientMessageId:t,state:`sending`}}}}function Zl(e,t){if(t.length===0)return[...e];let n=new Map;for(let t of e){let e=t.meta?.delivery;e?.state===`queued`&&n.set(e.clientMessageId,t)}let r=[];for(let e of t){let t=e.clientMessageId===void 0?void 0:n.get(e.clientMessageId);r.push(t??Ql(e))}let i=new Set(r);return[...e.filter(e=>!i.has(e)),...r]}function Ql(e){let t=e.clientMessageId??`queued:${e.kind}:${e.text}`;return{role:`user`,parts:[{type:`text`,text:e.text}],meta:{delivery:{clientMessageId:t,state:`queued`,kind:e.kind}}}}function $l(e,t){return e.findIndex(e=>e.meta?.delivery?.clientMessageId===t)}function eu(e,t,n,r){let i=$l(e,t);if(i===-1)return e;let a=e[i],o=a?.meta?.delivery;if(a===void 0||o===void 0||!ru(o.state,n)&&!tu(o.kind,r,o.state,n))return e;let s=[...e],c=ru(o.state,n)?n:o.state,l=r??o.kind;return s[i]={...a,meta:{...a.meta,delivery:{clientMessageId:t,state:c,...l===void 0?{}:{kind:l}}}},s}function tu(e,t,n,r){return t!==void 0&&t!==e&&n===`queued`&&r===`queued`}var nu={failed:-1,sending:0,received:1,queued:2,delivered:3};function ru(e,t){return e===t?!1:t===`failed`?e!==`delivered`:e!==`failed`&&nu[t]>nu[e]}function iu(e,t){let n=$l(e,t);if(n===-1)return[...e];let r=e[n];if(r?.meta?.delivery?.state!==`failed`)return[...e];let i=r.meta.delivery,a=[...e];return a[n]={...r,meta:{...r.meta,delivery:{clientMessageId:t,state:`sending`,...i.kind===void 0?{}:{kind:i.kind}}}},a}function au(e,t){let n=$l(e,t);return n===-1?[...e]:[...e.slice(0,n),...e.slice(n+1)]}function ou(e,t){let n=e,r=new Map;for(let e of t)e.clientMessageId!==void 0&&r.set(e.clientMessageId,e.kind);for(let t of e){let e=t.meta?.delivery;if(e===void 0)continue;let i=r.get(e.clientMessageId);if(i!==void 0){n=eu(n,e.clientMessageId,`queued`,i);continue}(e.state===`received`||e.state===`queued`)&&(n=eu(n,e.clientMessageId,`delivered`))}return n}function su(e,t){return t!==void 0&&$l(e,t)!==-1}function cu(e,t){let n=e.meta?.delivery;return n===void 0?t:{...t,meta:{...t.meta,delivery:{...n,state:n.state===`failed`?n.state:`delivered`}}}}function lu(e,t){return t===``?-1:e.findIndex(e=>e.role===`user`&&e.meta?.delivery!==void 0&&uu(e)===t)}function uu(e){return e.parts.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
@@ -43,7 +43,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,Y as o,Z as s,d as c,et as l,f
|
|
|
43
43
|
<path d="m7 10 3 3-3 3"></path>
|
|
44
44
|
<path d="M12 16h5"></path>
|
|
45
45
|
</svg>
|
|
46
|
-
`}}function jh(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
|
|
46
|
+
`}}function jh(e){return e===void 0||e===``?`split list-only`:`split`}function Mh(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 Nh(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`${Ph(t)} KB`;let n=t/1024;return n<1024?`${Ph(n)} MB`:`${Ph(n/1024)} GB`}function Ph(e){return e>=10?String(Math.round(e)):e.toFixed(1)}function Fh(e){return!Number.isFinite(e)||e===0?`$0`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var Ih=new Set,Lh=0;function Rh(e){let t=e.element.ownerDocument,n=Xh(t),r=n instanceof HTMLElement?Wh(t,n):void 0,i={layer:e,order:++Lh,restorationPath:n instanceof HTMLElement?[n,...r?.restorationPath??[]]:[]},a=!0;return Ih.add(i),Vh(t),{get isTop(){return a&&Hh(t)===i},focus:()=>a&&qh(i),unregister:()=>{a&&(a=!1,Ih.delete(i),Vh(t),Bh(i))}}}function zh(e){return e!==void 0&&Hh(e)!==void 0}function Bh(e){let{element:t}=e.layer,n=t.ownerDocument,r=Xh(n);if(!(r===null||r===n.body||r===n.documentElement)&&!$h(t,r))return;let i=Hh(n);if(i!==void 0){if(Jh(e.restorationPath.filter(e=>$h(i.layer.element,e))))return;qh(i);return}Jh(e.restorationPath)}function Vh(e){let t=Hh(e);for(let n of[...Ih])n.layer.element.ownerDocument===e&&n.layer.onTopChange?.(n===t)}function Hh(e){let t;for(let n of Ih)Uh(e,n)&&(t===void 0||Gh(n,t)>0)&&(t=n);return t}function Uh(e,t){let{element:n,nativeTopLayer:r}=t.layer;return!n.isConnected||n.ownerDocument!==e?!1:r===!0||!Zh(n)}function Wh(e,t){let n;for(let r of Ih)!Uh(e,r)||!$h(r.layer.element,t)||(n===void 0||Gh(r,n)>0)&&(n=r);return n}function Gh(e,t){let n=Number(e.layer.nativeTopLayer===!0)-Number(t.layer.nativeTopLayer===!0);if(n!==0)return n;let r=e.layer.paintElement??e.layer.element,i=t.layer.paintElement??t.layer.element,a=Kh(r)-Kh(i);if(a!==0)return a;if(r!==i){let e=r.compareDocumentPosition(i);if((e&Node.DOCUMENT_POSITION_DISCONNECTED)===0){if((e&Node.DOCUMENT_POSITION_FOLLOWING)!==0)return-1;if((e&Node.DOCUMENT_POSITION_PRECEDING)!==0)return 1}}return e.order-t.order}function Kh(e){let t=e.ownerDocument.defaultView?.getComputedStyle(e).zIndex??``,n=Number.parseFloat(t);return Number.isFinite(n)?n:0}function qh(e){if(Hh(e.layer.element.ownerDocument)!==e)return!1;e.layer.focus();let t=Xh(e.layer.element.ownerDocument);return t!==null&&$h(e.layer.element,t)}function Jh(e){for(let t of e)if(Yh(t))return!0;return!1}function Yh(e){if(!e.isConnected||e.matches(`:disabled`)||Zh(e))return!1;e.focus();let t=Xh(e.ownerDocument);return t===e||t!==null&&$h(e,t)}function Xh(e){let t=e.activeElement;for(;t instanceof HTMLElement;){let e=t.shadowRoot?.activeElement??null;if(e===null)return t;t=e}return t??null}function Zh(e){let t=e.ownerDocument.defaultView,n=t?.getComputedStyle(e);if(n?.visibility===`hidden`||n?.visibility===`collapse`)return!0;let r=e;for(;r!==null;){if(r.hasAttribute(`hidden`)||r.hasAttribute(`inert`))return!0;let e=t?.getComputedStyle(r);if(e?.display===`none`||e?.getPropertyValue(`content-visibility`)===`hidden`)return!0;r=Qh(r)}return!1}function Qh(e){let t=e.assignedSlot;if(t instanceof HTMLSlotElement)return t;let n=e.parentElement;if(n instanceof Element)return n;let r=e.getRootNode();return r instanceof ShadowRoot&&r.host instanceof Element?r.host:null}function $h(e,t){let n=t;for(;;){if(n===e)return!0;let t=n.parentNode;if(t!=null&&t!==n){n=t;continue}let r=n instanceof ShadowRoot?n:n.getRootNode();if(!(r instanceof ShadowRoot))return!1;n=r.host}}var eg=h`
|
|
47
47
|
.session-state { box-sizing: border-box; display: inline-grid; place-items: center; width: 9px; height: 9px; flex: 0 0 auto; border-radius: 50%; vertical-align: 1px; }
|
|
48
48
|
.session-state.idle { background: var(--pi-dim); animation: none; }
|
|
49
49
|
.session-state.idle.unread { background: var(--pi-success); }
|
|
@@ -56,7 +56,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,Y as o,Z as s,d as c,et as l,f
|
|
|
56
56
|
@media (prefers-reduced-motion: reduce) {
|
|
57
57
|
.state-dot { animation: none; }
|
|
58
58
|
}
|
|
59
|
-
`;function
|
|
59
|
+
`;function tg(e,t){return e===`error`?Ye`
|
|
60
60
|
<svg class=${t} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
61
61
|
<circle cx="12" cy="12" r="10"></circle>
|
|
62
62
|
<path d="m15 9-6 6"></path>
|
|
@@ -74,7 +74,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,Y as o,Z as s,d as c,et as l,f
|
|
|
74
74
|
<path d="M12 9v4"></path>
|
|
75
75
|
<path d="M12 17h.01"></path>
|
|
76
76
|
</svg>
|
|
77
|
-
`}var
|
|
77
|
+
`}var ng=h`
|
|
78
78
|
/* Motion is decoration here: scroll shadows, hover fades, pulsing dots. A
|
|
79
79
|
reader who asked the system for less motion gets none of it. */
|
|
80
80
|
@media (prefers-reduced-motion: reduce) {
|
|
@@ -190,7 +190,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,Y as o,Z as s,d as c,et as l,f
|
|
|
190
190
|
.self-update-banner button:hover { border-color: var(--pi-accent); }
|
|
191
191
|
.self-update-banner button.skip { color: var(--pi-muted); background: transparent; }
|
|
192
192
|
.self-update-banner .state-dot { background: currentColor; }
|
|
193
|
-
`,
|
|
193
|
+
`,rg=h`
|
|
194
194
|
/* Motion is decoration here: scroll shadows, hover fades, pulsing dots. A
|
|
195
195
|
reader who asked the system for less motion gets none of it. */
|
|
196
196
|
@media (prefers-reduced-motion: reduce) {
|
|
@@ -243,6 +243,10 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,Y as o,Z as s,d as c,et as l,f
|
|
|
243
243
|
.toolbar button { margin-left: auto; }
|
|
244
244
|
.stale { border: 1px solid var(--pi-warning-border); border-radius: var(--pi-radius-pill); color: var(--pi-warning); padding: 1px var(--pi-space-3); font-size: var(--pi-text-xs); }
|
|
245
245
|
.split { flex: 1 1 auto; min-height: 0; display: grid; grid-template-rows: minmax(160px, 34%) minmax(0, 1fr); }
|
|
246
|
+
/* With nothing selected there is no second pane to show, so the list takes
|
|
247
|
+
the panel rather than sitting above an empty one. */
|
|
248
|
+
.split.list-only { grid-template-rows: minmax(0, 1fr) 0; }
|
|
249
|
+
.split.list-only > :nth-child(2) { display: none; }
|
|
246
250
|
.list { min-height: 0; overflow: auto; border-bottom: 1px solid var(--pi-border); padding: var(--pi-space-3); }
|
|
247
251
|
.row { display: grid; grid-template-columns: 18px minmax(0, 1fr); gap: var(--pi-space-2); width: 100%; border: 0; border-radius: var(--pi-radius-sm); background: transparent; text-align: left; padding: 4px 6px 4px calc(6px + var(--depth, 0) * 14px); }
|
|
248
252
|
.row:hover, .row.selected { background: var(--pi-selection-bg); }
|
|
@@ -252,7 +256,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,Y as o,Z as s,d as c,et as l,f
|
|
|
252
256
|
.viewer { min-height: 0; overflow: auto; display: flex; flex-direction: column; }
|
|
253
257
|
pre { margin: 0; padding: var(--pi-space-5); overflow: auto; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
254
258
|
p { margin: var(--pi-space-5); }
|
|
255
|
-
`,
|
|
259
|
+
`,ig=h`
|
|
256
260
|
/* Mobile browsers paint a rectangular highlight on tap, which looks pasted-on
|
|
257
261
|
over a round or rounded control. Suppressed in favour of the app's own
|
|
258
262
|
pressed and focus styling; :focus-visible still shows keyboard focus, so
|
|
@@ -431,8 +435,8 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,Y as o,Z as s,d as c,et as l,f
|
|
|
431
435
|
.workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
|
|
432
436
|
.workspace-detail-row .workspace-label-base, .workspace-detail-row .workspace-label-item, .workspace-detail-row .workspace-label-render { overflow: visible; text-overflow: clip; overflow-wrap: anywhere; white-space: normal; }
|
|
433
437
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
434
|
-
`,
|
|
435
|
-
${
|
|
438
|
+
`,ag=h`
|
|
439
|
+
${eg}
|
|
436
440
|
/* Mobile browsers paint a rectangular highlight on tap, which looks pasted-on
|
|
437
441
|
over a round or rounded control. Suppressed in favour of the app's own
|
|
438
442
|
pressed and focus styling; :focus-visible still shows keyboard focus, so
|
|
@@ -795,7 +799,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,Y as o,Z as s,d as c,et as l,f
|
|
|
795
799
|
pre { margin: var(--pi-space-3) 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; direction: ltr; text-align: left; unicode-bidi: isolate; }
|
|
796
800
|
.shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; direction: ltr; text-align: left; unicode-bidi: isolate; }
|
|
797
801
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
798
|
-
`,
|
|
802
|
+
`,og=h`
|
|
799
803
|
:host { display: block; }
|
|
800
804
|
.formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; text-align: start; unicode-bidi: plaintext; }
|
|
801
805
|
p, ul, ol, pre, blockquote, .table-scroll, .code-block-wrapper { margin: 0 0 var(--pi-space-5); }
|
|
@@ -822,7 +826,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,Y as o,Z as s,d as c,et as l,f
|
|
|
822
826
|
table { border-collapse: collapse; width: max-content; min-width: 100%; max-width: none; }
|
|
823
827
|
th, td { border: 1px solid var(--pi-border); padding: var(--pi-space-2) var(--pi-space-4); max-width: 48ch; overflow-wrap: anywhere; }
|
|
824
828
|
th { background: var(--pi-surface); }
|
|
825
|
-
`,
|
|
829
|
+
`,sg=h`
|
|
826
830
|
:host { display: block; color: var(--pi-muted); font: var(--pi-text-xs) var(--pi-font-ui); }
|
|
827
831
|
.bar { display: flex; justify-content: flex-end; gap: var(--pi-space-6); align-items: center; min-width: 0; padding: var(--pi-space-4) var(--pi-space-6); border-top: 1px solid var(--pi-border); background: var(--pi-bg); white-space: nowrap; overflow: hidden; }
|
|
828
832
|
span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
@@ -835,7 +839,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,Y as o,Z as s,d as c,et as l,f
|
|
|
835
839
|
.activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
|
|
836
840
|
.muted { color: var(--pi-dim); }
|
|
837
841
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
838
|
-
`,
|
|
842
|
+
`,cg=h`
|
|
839
843
|
:host { display: block; }
|
|
840
844
|
.menu { position: absolute; left: 0; right: 0; bottom: calc(100% + 6px); z-index: 10; max-height: 260px; overflow: auto; border: 1px solid var(--pi-border); border-radius: var(--pi-radius-md); background: var(--pi-surface); box-shadow: 0 10px 30px var(--pi-shadow); }
|
|
841
845
|
button { font: var(--pi-text-xs) var(--pi-font-ui); display: grid; grid-template-columns: minmax(120px, 1fr) auto; gap: var(--pi-space-2) var(--pi-space-5); width: 100%; border: 0; border-bottom: 1px solid var(--pi-border); border-radius: 0; background: transparent; color: var(--pi-text); padding: var(--pi-space-4) var(--pi-space-5); text-align: left; cursor: pointer; }
|
|
@@ -843,7 +847,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,Y as o,Z as s,d as c,et as l,f
|
|
|
843
847
|
button.selected, button:hover { background: var(--pi-selection-bg); }
|
|
844
848
|
span { color: var(--pi-muted); font-size: var(--pi-text-xs); }
|
|
845
849
|
small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
846
|
-
`,
|
|
850
|
+
`,lg=h`
|
|
847
851
|
/* Mobile browsers paint a rectangular highlight on tap, which looks pasted-on
|
|
848
852
|
over a round or rounded control. Suppressed in favour of the app's own
|
|
849
853
|
pressed and focus styling; :focus-visible still shows keyboard focus, so
|
|
@@ -1015,14 +1019,14 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,Y as o,Z as s,d as c,et as l,f
|
|
|
1015
1019
|
.list-search-clear { width: 30px; height: 30px; }
|
|
1016
1020
|
.list-body.tiles { gap: var(--pi-space-3); grid-template-columns: 1fr; }
|
|
1017
1021
|
.list-body.tiles .action-main { min-height: 48px; padding: var(--pi-space-4) 28px var(--pi-space-4) var(--pi-space-4); }
|
|
1018
|
-
}`,
|
|
1019
|
-
]`).replace(`lheading`,
|
|
1020
|
-
`),n=t.length-1;for(;n>=0&&
|
|
1021
|
-
`)}function
|
|
1022
|
+
}`,ug=e=>e??_,dg={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},fg=e=>(...t)=>({_$litDirective$:e,values:t}),pg=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)}},mg=class extends pg{constructor(e){if(super(e),this.it=_,e.type!==dg.CHILD)throw Error(this.constructor.directiveName+`() can only be used in child bindings`)}render(e){if(e===_||e==null)return this._t=void 0,this.it=e;if(e===Xe)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:[]}}};mg.directiveName=`unsafeHTML`,mg.resultType=1;var hg=fg(mg);function gg(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var _g=gg();function vg(e){_g=e}var yg={exec:()=>null};function bg(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 z(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(Sg.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var xg=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),Sg={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:bg(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:bg(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:bg(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:bg(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:bg(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:bg(e=>RegExp(`^ {0,${e}}>`))},Cg=/^(?:[ \t]*(?:\n|$))+/,wg=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Tg=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,Eg=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Dg=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Og=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,kg=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Ag=z(kg).replace(/bull/g,Og).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(),jg=z(kg).replace(/bull/g,Og).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(),Mg=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Ng=/^[^\n]+/,Pg=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Fg=z(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,Pg).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Ig=z(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Og).getRegex(),Lg=`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`,Rg=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,zg=z(`^ {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`,Rg).replace(`tag`,Lg).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Bg=e=>z(Mg).replace(`hr`,Eg).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`,Lg).getRegex(),Vg=Bg(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Hg=Bg(/ {0,3}(?:[*+-]|\d{1,9}[.)])[ \t]+[^ \t\n]/),Ug={blockquote:z(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,Hg).getRegex(),code:wg,def:Fg,fences:Tg,heading:Dg,hr:Eg,html:zg,lheading:Ag,list:Ig,newline:Cg,paragraph:Vg,table:yg,text:Ng},Wg=z(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,Eg).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`,Lg).getRegex(),Gg={...Ug,lheading:jg,table:Wg,paragraph:z(Mg).replace(`hr`,Eg).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,Wg).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`,Lg).getRegex()},Kg={...Ug,html:z(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,Rg).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:yg,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:z(Mg).replace(`hr`,Eg).replace(`heading`,` *#{1,6} *[^
|
|
1023
|
+
]`).replace(`lheading`,Ag).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},qg=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Jg=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Yg=/^( {2,}|\\)\n(?!\s*$)/,Xg=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Zg=/[\p{P}\p{S}]/u,Qg=/[\s\p{P}\p{S}]/u,$g=/[^\s\p{P}\p{S}]/u,e_=z(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,Qg).getRegex(),t_=/(?!~)[\p{P}\p{S}]/u,n_=/(?!~)[\s\p{P}\p{S}]/u,r_=/(?:[^\s\p{P}\p{S}]|~)/u,i_=z(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,xg?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),a_=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,o_=z(a_,`u`).replace(/punct/g,Zg).getRegex(),s_=z(a_,`u`).replace(/punct/g,t_).getRegex(),c_=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,l_=z(c_,`gu`).replace(/notPunctSpace/g,$g).replace(/punctSpace/g,Qg).replace(/punct/g,Zg).getRegex(),u_=z(c_,`gu`).replace(/notPunctSpace/g,r_).replace(/punctSpace/g,n_).replace(/punct/g,t_).getRegex(),d_=z(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,$g).replace(/punctSpace/g,Qg).replace(/punct/g,Zg).getRegex(),f_=z(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,Zg).getRegex(),p_=z(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,$g).replace(/punctSpace/g,Qg).replace(/punct/g,Zg).getRegex(),m_=z(/\\(punct)/,`gu`).replace(/punct/g,Zg).getRegex(),h_=z(/^<(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(),g_=z(Rg).replace(`(?:-->|$)`,`-->`).getRegex(),__=z(`^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`,g_).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),v_=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,y_=z(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,v_).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),b_=z(/^!?\[(label)\]\[(ref)\]/).replace(`label`,v_).replace(`ref`,Pg).getRegex(),x_=z(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,Pg).getRegex(),S_=z(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,b_).replace(`nolink`,x_).getRegex(),C_=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,w_={_backpedal:yg,anyPunctuation:m_,autolink:h_,blockSkip:i_,br:Yg,code:Jg,del:yg,delLDelim:yg,delRDelim:yg,emStrongLDelim:o_,emStrongRDelimAst:l_,emStrongRDelimUnd:d_,escape:qg,link:y_,nolink:x_,punctuation:e_,reflink:b_,reflinkSearch:S_,tag:__,text:Xg,url:yg},T_={...w_,link:z(/^!?\[(label)\]\((.*?)\)/).replace(`label`,v_).getRegex(),reflink:z(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,v_).getRegex()},E_={...w_,emStrongRDelimAst:u_,emStrongLDelim:s_,delLDelim:f_,delRDelim:p_,url:z(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,C_).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:z(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,C_).getRegex()},D_={...E_,br:z(Yg).replace(`{2,}`,`*`).getRegex(),text:z(E_.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},O_={normal:Ug,gfm:Gg,pedantic:Kg},k_={normal:w_,gfm:E_,breaks:D_,pedantic:T_},A_={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},j_=e=>A_[e];function M_(e,t){if(t){if(Sg.escapeTest.test(e))return e.replace(Sg.escapeReplace,j_)}else if(Sg.escapeTestNoEncode.test(e))return e.replace(Sg.escapeReplaceNoEncode,j_);return e}function N_(e){try{e=encodeURI(e).replace(Sg.percentDecode,`%`)}catch{return null}return e}function P_(e,t){let n=e.replace(Sg.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(Sg.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(Sg.slashPipe,`|`);return n}function F_(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 I_(e){let t=e.split(`
|
|
1024
|
+
`),n=t.length-1;for(;n>=0&&Sg.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
|
|
1025
|
+
`)}function L_(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 R_(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 z_(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 B_(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
1022
1026
|
`).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(`
|
|
1023
|
-
`)}var
|
|
1024
|
-
`),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:
|
|
1025
|
-
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=
|
|
1027
|
+
`)}var V_=class{options;rules;lexer;constructor(e){this.options=e||_g}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]:I_(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=B_(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=F_(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:F_(t[0],`
|
|
1028
|
+
`),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:F_(t[0],`
|
|
1029
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=F_(t[0],`
|
|
1026
1030
|
`).split(`
|
|
1027
1031
|
`),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(`
|
|
1028
1032
|
`),c=s.replace(this.rules.other.blockquoteSetextReplace,`
|
|
@@ -1033,20 +1037,20 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
1033
1037
|
`),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+`
|
|
1034
1038
|
`+e.join(`
|
|
1035
1039
|
`),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(`
|
|
1036
|
-
`);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=
|
|
1040
|
+
`);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=R_(t[2].split(`
|
|
1037
1041
|
`,1)[0],t[1].length),l=e.split(`
|
|
1038
1042
|
`,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+`
|
|
1039
1043
|
`,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(`
|
|
1040
1044
|
`,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+=`
|
|
1041
1045
|
`+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+=`
|
|
1042
1046
|
`+l}u=!l.trim(),r+=p+`
|
|
1043
|
-
`,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=
|
|
1044
|
-
`),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=
|
|
1045
|
-
`):[],a={type:`table`,raw:
|
|
1046
|
-
`),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(
|
|
1047
|
+
`,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=I_(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:F_(t[0],`
|
|
1048
|
+
`),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=P_(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
|
|
1049
|
+
`):[],a={type:`table`,raw:F_(t[0],`
|
|
1050
|
+
`),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(P_(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:F_(t[0],`
|
|
1047
1051
|
`),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)===`
|
|
1048
|
-
`?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=
|
|
1049
|
-
`),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(
|
|
1052
|
+
`?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=F_(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=L_(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)),z_(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 z_(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}}}},H_=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||_g,this.options.tokenizer=this.options.tokenizer||new V_,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:Sg,block:O_.normal,inline:k_.normal};this.options.pedantic?(t.block=O_.pedantic,t.inline=k_.pedantic):this.options.gfm&&(t.block=O_.gfm,this.options.breaks?t.inline=k_.breaks:t.inline=k_.gfm),this.tokenizer.rules=t}static get rules(){return{block:O_,inline:k_}}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(Sg.carriageReturn,`
|
|
1053
|
+
`),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(Sg.tabCharGlobal,` `).replace(Sg.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+=`
|
|
1050
1054
|
`: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(`
|
|
1051
1055
|
`)?``:`
|
|
1052
1056
|
`)+i.raw,n.text+=`
|
|
@@ -1059,9 +1063,9 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
1059
1063
|
`+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(`
|
|
1060
1064
|
`)?``:`
|
|
1061
1065
|
`)+i.raw,n.text+=`
|
|
1062
|
-
`+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)}},
|
|
1063
|
-
`;return r?`<pre><code class="language-`+
|
|
1064
|
-
`:`<pre><code>`+(n?i:
|
|
1066
|
+
`+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)}},U_=class{options;parser;constructor(e){this.options=e||_g}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(Sg.notSpaceStart)?.[0],i=e.replace(Sg.endingNewline,``)+`
|
|
1067
|
+
`;return r?`<pre><code class="language-`+M_(r)+`">`+(n?i:M_(i,!0))+`</code></pre>
|
|
1068
|
+
`:`<pre><code>`+(n?i:M_(i,!0))+`</code></pre>
|
|
1065
1069
|
`}blockquote({tokens:e}){return`<blockquote>
|
|
1066
1070
|
${this.parser.parse(e)}</blockquote>
|
|
1067
1071
|
`}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
@@ -1077,12 +1081,12 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
1077
1081
|
`}tablerow({text:e}){return`<tr>
|
|
1078
1082
|
${e}</tr>
|
|
1079
1083
|
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
1080
|
-
`}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>${
|
|
1081
|
-
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+
|
|
1082
|
-
${this.renderViewerHeader(t,
|
|
1083
|
-
${
|
|
1084
|
+
`}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>${M_(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=N_(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+M_(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=N_(e);if(i===null)return M_(n);e=i;let a=`<img src="${e}" alt="${M_(n)}"`;return t&&(a+=` title="${M_(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:M_(e.text)}},W_=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}},G_=class e{options;renderer;textRenderer;constructor(e){this.options=e||_g,this.options.renderer=this.options.renderer||new U_,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new W_}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}},K_=class{options;block;constructor(e){this.options=e||_g}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?H_.lex:H_.lexInline}provideParser(e=this.block){return e?G_.parse:G_.parseInline}},q_=new class{defaults=gg();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=G_;Renderer=U_;TextRenderer=W_;Lexer=H_;Tokenizer=V_;Hooks=K_;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 U_(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 V_(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 K_;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];K_.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&K_.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 H_.lex(e,t??this.defaults)}parser(e,t){return G_.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?H_.lex:H_.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?G_.parse:G_.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?H_.lex:H_.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?G_.parse:G_.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+=`
|
|
1085
|
+
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+M_(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function B(e,t){return q_.parse(e,t)}B.options=B.setOptions=function(e){return q_.setOptions(e),B.defaults=q_.defaults,vg(B.defaults),B},B.getDefaults=gg,B.defaults=_g,B.use=function(...e){return q_.use(...e),B.defaults=q_.defaults,vg(B.defaults),B},B.walkTokens=function(e,t){return q_.walkTokens(e,t)},B.parseInline=q_.parseInline,B.Parser=G_,B.parser=G_.parse,B.Renderer=U_,B.TextRenderer=W_,B.Lexer=H_,B.lexer=H_.lex,B.Tokenizer=V_,B.Hooks=K_,B.parse=B,B.options,B.setOptions,B.use,B.walkTokens,B.parseInline,G_.parse,H_.lex;var J_=new B.Renderer;J_.html=({text:e})=>ov(e),J_.image=({text:e})=>ov(e===``?`[Image omitted]`:`[Image omitted: ${e}]`),J_.checkbox=({checked:e})=>e?`[x] `:`[ ] `;var V=new Set,Y_={a:new Set([`href`,`title`]),blockquote:V,br:V,code:V,del:V,em:V,h1:V,h2:V,h3:V,h4:V,h5:V,h6:V,hr:V,li:V,ol:new Set([`start`]),p:V,pre:V,strong:V,table:V,tbody:V,td:new Set([`align`]),th:new Set([`align`]),thead:V,tr:V,ul:V},X_=new Set([`http:`,`https:`,`mailto:`]),Z_=new Set([`left`,`center`,`right`]),Q_=`table-scroll`;function $_(e){return ev(B.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:J_}))}function ev(e){let t=document.createElement(`template`);t.innerHTML=e;for(let e of[...t.content.querySelectorAll(`*`)]){let t=e.tagName.toLowerCase(),n=Y_[t];if(n===void 0){e.remove();continue}for(let r of[...e.attributes]){let i=r.name.toLowerCase();(!n.has(i)||!nv(t,i,r.value))&&e.removeAttribute(r.name)}t===`a`&&tv(e)}return av(t.content),t.innerHTML}function tv(e){if(!e.hasAttribute(`href`)){e.removeAttribute(`target`),e.removeAttribute(`rel`),e.removeAttribute(`referrerpolicy`);return}e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noopener noreferrer`),e.setAttribute(`referrerpolicy`,`no-referrer`)}function nv(e,t,n){return e===`a`&&t===`href`?rv(n):e===`ol`&&t===`start`?/^-?\d+$/.test(n):(e===`td`||e===`th`)&&t===`align`?Z_.has(n.toLowerCase()):!0}function rv(e){if(e===``||iv(e))return!1;try{return X_.has(new URL(e).protocol)}catch{return!1}}function iv(e){for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n<=31||n===127)return!0}return!1}function av(e){e.querySelectorAll(`table`).forEach(e=>{let t=document.createElement(`div`);t.className=Q_,t.setAttribute(`role`,`region`),t.setAttribute(`aria-label`,`Table`),t.setAttribute(`tabindex`,`0`),e.before(t),t.append(e)})}function ov(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}var sv=`10 MB`;function cv(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return e.slice(t+1)}var lv=`pi-web.workspace.files.viewMode`,uv=`mode`,dv=$s(`core:workspace.files`);function fv(e){return e===`preview`||e===`raw`?e:void 0}function pv(e,t){let n=fv(e.read());return n===void 0?hv(t)??`raw`:(gv(n,t),n)}function mv(e,t,n){gv(e,n),t.write(e)}function hv(e){if(e!==void 0)try{return fv(e.getItem(lv))}catch{return}}function gv(e,t){if(t!==void 0)try{t.setItem(lv,e)}catch{}}var _v={adopt:()=>pv(vv(),yv()),publish:e=>{mv(e,vv(),yv())}};function vv(){return{read:()=>typeof window>`u`?void 0:tc(dv,uv),write:e=>{typeof window>`u`||nc(dv,uv,e,{replace:!0})}}}function yv(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function H(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}var bv=`modulepreload`,xv=function(e,t){return new URL(e,t).href},Sv={},Cv=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=xv(t,n),t=s(t),t in Sv)return;Sv[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:bv,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},wv=class extends v{constructor(...e){super(...e),this.machineId=``,this.projectId=``,this.workspaceId=``,this.previewUrlBuilder=lo,this.modeStore=_v,this.selectionToken=0,this.restoreModeFromHistory=()=>{this.mode=this.modeStore.adopt(),this.publishedMode=void 0,this.failedPreviewToken=void 0,this.requestUpdate()}}connectedCallback(){super.connectedCallback(),window.addEventListener(`popstate`,this.restoreModeFromHistory)}disconnectedCallback(){window.removeEventListener(`popstate`,this.restoreModeFromHistory),super.disconnectedCallback()}willUpdate(){this.mode??=this.modeStore.adopt();let e=this.currentFileKey();e!==this.activeFileKey&&(this.activeFileKey=e,this.selectionToken+=1,this.failedPreviewToken=void 0)}updated(){let e=this.mode;e===void 0||e===this.publishedMode||this.selectionHasRawAndPreviewModes()&&(this.publishedMode=e,this.modeStore.publish(e))}render(){let e=this.selectedPath;if(e===void 0||e===``)return this.renderStatus(`Select a file.`);if(this.loadError!==void 0)return this.renderStatus(`Unable to load ${e}: ${this.loadError}`,!0);let t=this.file;if(t===void 0)return this.renderStatus(`Loading ${e}…`);if(t.path!==e)return this.renderStatus(`Unable to preview ${e}: loaded content belongs to ${t.path}.`,!0);let n=this.selectionToken,r=Ev(t),i=kv(r)&&t.size>0&&t.size<=10485760;return g`
|
|
1086
|
+
${this.renderViewerHeader(t,Av(t,r),i)}
|
|
1087
|
+
${Dv(t,r)?this.renderModeControls(t,n):null}
|
|
1084
1088
|
${this.renderLoadedFile(t,r,n)}
|
|
1085
|
-
`}renderLoadedFile(e,t,n){if(
|
|
1089
|
+
`}renderLoadedFile(e,t,n){if(Dv(e,t)&&this.mode===`raw`)return this.renderRawSource(e);if(e.size===0)return this.renderStatus(`This file is empty.`);switch(t){case`image`:return this.renderImagePreview(e,n);case`html`:return this.renderFramePreview(e,`html`,n);case`pdf`:return this.renderFramePreview(e,`pdf`,n);case`markdown`:return this.renderMarkdownPreview(e);case`download`:return this.renderUnsupportedFile(e);case`code`:return this.renderRawSource(e)}}renderViewerHeader(e,t,n){let r=cv(e.path),i={modifiedAt:e.modifiedAt,machineId:this.machineId},a=this.previewUrlBuilder(this.projectId,this.workspaceId,e.path,i),o=this.previewUrlBuilder(this.projectId,this.workspaceId,e.path,{...i,download:!0});return g`
|
|
1086
1090
|
<div class="viewer-header">
|
|
1087
1091
|
<strong title=${e.path}>${e.path}</strong>
|
|
1088
1092
|
<div class="viewer-actions">
|
|
@@ -1113,12 +1117,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1113
1117
|
@click=${()=>{this.setMode(`raw`,t)}}
|
|
1114
1118
|
>Raw</button>
|
|
1115
1119
|
</div>
|
|
1116
|
-
`}renderRawSource(e){return e.size===0?this.renderStatus(`This file is empty.`):(
|
|
1120
|
+
`}renderRawSource(e){return e.size===0?this.renderStatus(`This file is empty.`):(jv(),g`
|
|
1117
1121
|
${e.truncated?g`<p class="preview-note" role="status">Raw source is truncated. Use Download for the complete file.</p>`:null}
|
|
1118
1122
|
<code-viewer .content=${e.content} .language=${e.language}></code-viewer>
|
|
1119
|
-
`)}renderMarkdownPreview(e){if(e.size>10485760)return this.renderPreviewTooLarge(e);try{let t
|
|
1123
|
+
`)}renderMarkdownPreview(e){if(e.size>10485760)return this.renderPreviewTooLarge(e);try{let t=$_(e.content);return g`
|
|
1120
1124
|
${e.truncated?g`<p class="preview-note" role="status">Preview is rendered from truncated source. Use Download for the complete file.</p>`:null}
|
|
1121
|
-
<div class="formatted markdown-preview" dir="auto">${
|
|
1125
|
+
<div class="formatted markdown-preview" dir="auto">${hg(t)}</div>
|
|
1122
1126
|
`}catch{return this.renderStatus(`Markdown preview failed. Use Raw or Download instead.`,!0)}}renderImagePreview(e,t){return e.size>10485760?this.renderPreviewTooLarge(e):this.failedPreviewToken===t?this.renderPreviewFailure(e,t):g`
|
|
1123
1127
|
<div class="image-preview">
|
|
1124
1128
|
<img
|
|
@@ -1134,7 +1138,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1134
1138
|
<iframe
|
|
1135
1139
|
class="file-frame-preview"
|
|
1136
1140
|
src=${r}
|
|
1137
|
-
sandbox=${
|
|
1141
|
+
sandbox=${ug(Ov(t))}
|
|
1138
1142
|
allow=""
|
|
1139
1143
|
referrerpolicy="no-referrer"
|
|
1140
1144
|
title=${`Preview of ${e.path}`}
|
|
@@ -1146,12 +1150,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1146
1150
|
<span>Open it in a new window or use Download above.</span>
|
|
1147
1151
|
<button type="button" @click=${()=>{this.retryPreview(t)}}>Retry preview</button>
|
|
1148
1152
|
</div>
|
|
1149
|
-
`}renderUnsupportedFile(e){let t=
|
|
1153
|
+
`}renderUnsupportedFile(e){let t=cv(e.path);return g`
|
|
1150
1154
|
<div class="preview-state">
|
|
1151
1155
|
<p>Preview isn't available for this file type.</p>
|
|
1152
|
-
<a class="download-link" href=${this.previewUrlBuilder(this.projectId,this.workspaceId,e.path,{modifiedAt:e.modifiedAt,machineId:this.machineId,download:!0})} download=${t}>Download ${t} · ${
|
|
1156
|
+
<a class="download-link" href=${this.previewUrlBuilder(this.projectId,this.workspaceId,e.path,{modifiedAt:e.modifiedAt,machineId:this.machineId,download:!0})} download=${t}>Download ${t} · ${Nh(e.size)}</a>
|
|
1153
1157
|
</div>
|
|
1154
|
-
`}renderPreviewTooLarge(e){return this.renderStatus(`File too large to preview: ${
|
|
1158
|
+
`}renderPreviewTooLarge(e){return this.renderStatus(`File too large to preview: ${Nh(e.size)} · limit ${sv}. Use Download above.`)}renderStatus(e,t=!1){return t?g`<p class="viewer-status" role="alert">${e}</p>`:g`<p class="viewer-status" role="status" aria-live="polite">${e}</p>`}previewUrl(e){return this.previewUrlBuilder(this.projectId,this.workspaceId,e.path,{modifiedAt:e.modifiedAt,machineId:this.machineId})}setMode(e,t){t===this.selectionToken&&(this.mode=e,this.failedPreviewToken=void 0,this.requestUpdate())}recordPreviewFailure(e){e!==this.selectionToken||this.showsRawSource()||(this.failedPreviewToken=e,this.requestUpdate())}retryPreview(e){e===this.selectionToken&&(this.failedPreviewToken=void 0,this.requestUpdate())}currentFileKey(){return Tv(this)}showsRawSource(){return this.mode===`raw`&&this.selectionHasRawAndPreviewModes()}selectionHasRawAndPreviewModes(){let e=this.file;return e===void 0||this.loadError!==void 0||this.selectedPath===void 0||e.path!==this.selectedPath?!1:Dv(e,Ev(e))}static{this.styles=[og,h`
|
|
1155
1159
|
:host { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: auto; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
1156
1160
|
.viewer-header { position: sticky; top: 0; z-index: 1; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
|
|
1157
1161
|
.viewer-header strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
@@ -1180,7 +1184,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1180
1184
|
.viewer-header { align-items: flex-start; flex-direction: column; }
|
|
1181
1185
|
.viewer-actions { width: 100%; flex-wrap: wrap; }
|
|
1182
1186
|
}
|
|
1183
|
-
`]}};H([b({attribute:!1})],
|
|
1187
|
+
`]}};H([b({attribute:!1})],wv.prototype,`machineId`,void 0),H([b({attribute:!1})],wv.prototype,`projectId`,void 0),H([b({attribute:!1})],wv.prototype,`workspaceId`,void 0),H([b({attribute:!1})],wv.prototype,`selectedPath`,void 0),H([b({attribute:!1})],wv.prototype,`file`,void 0),H([b({attribute:!1})],wv.prototype,`loadError`,void 0),H([b({attribute:!1})],wv.prototype,`previewUrlBuilder`,void 0),H([b({attribute:!1})],wv.prototype,`modeStore`,void 0),wv=H([y(`workspace-file-viewer`)],wv);function Tv(e){return JSON.stringify([e.machineId,e.projectId,e.workspaceId,e.selectedPath??null,e.file?.path??null,e.file?.modifiedAt??null,e.file?.mediaType??null])}function Ev(e){return e.mediaType===`image`?`image`:e.mediaType===`html`?`html`:e.mediaType===`pdf`?`pdf`:e.mediaType===`markdown`?`markdown`:e.binary?`download`:`code`}function Dv(e,t){return t!==`code`&&t!==`download`&&!e.binary}function Ov(e){return e===`html`?``:void 0}function kv(e){return e===`image`||e===`html`||e===`pdf`}function Av(e,t){return`${t===`code`?e.language??`text`:t===`download`?e.mimeType??`binary`:t===`markdown`?`markdown`:e.mimeType??t} · ${Nh(e.size)}${e.truncated?` · truncated`:``}`}function jv(){Cv(()=>import(`./CodeViewer-DWMYXHbj.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}var Mv=class extends v{constructor(...e){super(...e),this.destinationFolder=``,this.overwrite=!1,this.createDirs=!0,this.formError=``,this.dragActive=!1,this.dragDepth=0,this.openFilePicker=()=>{this.uploadInput?.click()},this.handleFileInputChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0,n=Rv(t?.files);t!==void 0&&(t.value=``),n.length>0&&this.openUploadReview(n)},this.handleDragEnter=e=>{zv(e)&&(e.preventDefault(),this.dragDepth+=1,this.dragActive=!0)},this.handleDragOver=e=>{zv(e)&&(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect=`copy`),this.dragActive=!0)},this.handleDragLeave=e=>{zv(e)&&(e.preventDefault(),this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&(this.dragActive=!1))},this.handleDrop=e=>{if(!zv(e))return;e.preventDefault(),this.dragDepth=0,this.dragActive=!1;let t=Rv(e.dataTransfer?.files),n=this.context;t.length>0&&n!==void 0&&Iv(n,t)},this.handleDestinationInput=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.destinationFolder=t?.value??``,this.formError=``},this.handleCreateDirsChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.createDirs=t?.checked??!0},this.handleOverwriteChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.overwrite=t?.checked??!1},this.handleDialogKeyDown=e=>{e.key===`Escape`&&(e.preventDefault(),this.closeUploadDialog())}}willUpdate(e){if(!e.has(`context`))return;let t=e.get(`context`);t!==void 0&&this.context!==void 0&&Lv(t)!==Lv(this.context)&&this.resetPendingUpload()}updated(){this.syncUploadModal()}disconnectedCallback(){this.releaseUploadModal(),super.disconnectedCallback()}render(){let e=this.context;return e===void 0?g`<p class="muted">Files unavailable.</p>`:g`
|
|
1184
1188
|
<section
|
|
1185
1189
|
class=${this.dragActive?`files-panel dragging`:`files-panel`}
|
|
1186
1190
|
@dragenter=${this.handleDragEnter}
|
|
@@ -1198,7 +1202,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1198
1202
|
<input id="workspace-upload-input" class="visually-hidden" type="file" multiple @change=${this.handleFileInputChange} />
|
|
1199
1203
|
</section>
|
|
1200
1204
|
${this.renderUploadProgress(e)}
|
|
1201
|
-
<section class
|
|
1205
|
+
<section class=${jh(e.selectedFilePath)}>
|
|
1202
1206
|
<div class="list tree">
|
|
1203
1207
|
${e.fileTree.length===0?g`<p class="muted">No files loaded.</p>`:e.fileTree.map(t=>this.renderTreeEntry(e,t,0))}
|
|
1204
1208
|
</div>
|
|
@@ -1227,11 +1231,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1227
1231
|
<span>${t.name}</span>
|
|
1228
1232
|
</button>
|
|
1229
1233
|
${i?r.map(t=>this.renderTreeEntry(e,t,n+1)):null}
|
|
1230
|
-
`}selectTreeEntry(e,t){t.type===`directory`?e.onExpandDir(t.path):e.onSelectFile(t.path)}renderUploadProgress(e){let t=
|
|
1234
|
+
`}selectTreeEntry(e,t){t.type===`directory`?e.onExpandDir(t.path):e.onSelectFile(t.path)}renderUploadProgress(e){let t=Nv(e.state.workspaceUploadBatches,{projectId:e.workspace.projectId,workspaceId:e.workspace.id,machineId:e.machine.id});return t.length===0?null:g`
|
|
1231
1235
|
<section class="upload-progress" aria-label="Workspace uploads">
|
|
1232
1236
|
<div class="upload-progress-header">
|
|
1233
1237
|
<strong>Uploads</strong>
|
|
1234
|
-
<small>${
|
|
1238
|
+
<small>${Vv(t)}</small>
|
|
1235
1239
|
</div>
|
|
1236
1240
|
${t.map(t=>this.renderUploadBatch(e,t))}
|
|
1237
1241
|
</section>
|
|
@@ -1239,12 +1243,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1239
1243
|
<article class=${`upload-batch ${t.status}`}>
|
|
1240
1244
|
<div class="upload-batch-heading">
|
|
1241
1245
|
<div>
|
|
1242
|
-
<strong>${
|
|
1246
|
+
<strong>${Hv(t)}</strong>
|
|
1243
1247
|
<small>${t.destinationFolder===``?`workspace root`:t.destinationFolder}</small>
|
|
1244
1248
|
</div>
|
|
1245
|
-
<span>${
|
|
1249
|
+
<span>${Uv(t)}</span>
|
|
1246
1250
|
</div>
|
|
1247
|
-
<progress max="1" .value=${
|
|
1251
|
+
<progress max="1" .value=${Wv(t)}></progress>
|
|
1248
1252
|
<div class="upload-file-list">
|
|
1249
1253
|
${t.files.map(e=>this.renderUploadFile(e))}
|
|
1250
1254
|
</div>
|
|
@@ -1252,13 +1256,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1252
1256
|
${t.status===`uploading`?g`<button @click=${()=>{e.onCancelWorkspaceUpload(t.id)}}>Cancel</button>`:g`<button @click=${()=>{e.onClearWorkspaceUpload(t.id)}}>Dismiss</button>`}
|
|
1253
1257
|
</div>
|
|
1254
1258
|
</article>
|
|
1255
|
-
`}renderUploadFile(e){let t=
|
|
1259
|
+
`}renderUploadFile(e){let t=Kv(e);return g`
|
|
1256
1260
|
<div class=${`upload-file ${e.status}`}>
|
|
1257
1261
|
<div class="upload-file-main">
|
|
1258
1262
|
<span>${e.name}</span>
|
|
1259
1263
|
<small>${t}</small>
|
|
1260
1264
|
</div>
|
|
1261
|
-
<span class="upload-file-status">${
|
|
1265
|
+
<span class="upload-file-status">${Gv(e)}</span>
|
|
1262
1266
|
</div>
|
|
1263
1267
|
`}renderUploadDialog(e,t){let n=t.files.length;return g`
|
|
1264
1268
|
<div class="dialog-backdrop" @mousedown=${()=>{this.closeUploadDialog()}}>
|
|
@@ -1291,7 +1295,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1291
1295
|
${t.files.map(e=>g`
|
|
1292
1296
|
<div class="review-file">
|
|
1293
1297
|
<span>${e.name}</span>
|
|
1294
|
-
<small>${
|
|
1298
|
+
<small>${Nh(e.size)}</small>
|
|
1295
1299
|
</div>
|
|
1296
1300
|
`)}
|
|
1297
1301
|
</section>
|
|
@@ -1303,7 +1307,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1303
1307
|
</form>
|
|
1304
1308
|
</section>
|
|
1305
1309
|
</div>
|
|
1306
|
-
`}openUploadReview(e){let t=this.context,n=
|
|
1310
|
+
`}openUploadReview(e){let t=this.context,n=Fv(t?.workspaceUploadDefaultFolder??``);this.pendingUpload={files:e},this.destinationFolder=n.destinationFolder,this.overwrite=n.overwrite,this.createDirs=n.createDirs,this.formError=``}submitUploadReview(e,t,n){e.preventDefault();let r=Pv(n.files,this.destinationFolder);if(r!==void 0){this.formError=r;return}t.onStartWorkspaceUpload(n.files,{destinationFolder:this.destinationFolder,createDirs:this.createDirs,overwrite:this.overwrite,selectUploadedFile:!0})!==void 0&&this.closeUploadDialog()}closeUploadDialog(){this.pendingUpload=void 0,this.formError=``}syncUploadModal(){let e=this.uploadDialogBackdrop,t=this.uploadDialog;if(!(e instanceof HTMLElement)||!(t instanceof HTMLElement)){this.releaseUploadModal();return}if(this.uploadModalRegistration!==void 0){this.applyUploadModalAccessibility(t,this.uploadModalRegistration.isTop);return}let n=Rh({element:e,paintElement:Bv(this),focus:()=>{(this.renderRoot.querySelector(`#workspace-upload-destination`)??t).focus()},onTopChange:e=>{this.applyUploadModalAccessibility(t,e)}});this.uploadModalRegistration=n,n.focus()}applyUploadModalAccessibility(e,t){e.setAttribute(`aria-modal`,t?`true`:`false`),t?e.removeAttribute(`aria-hidden`):e.setAttribute(`aria-hidden`,`true`)}releaseUploadModal(){let e=this.uploadModalRegistration;this.uploadModalRegistration=void 0,e?.unregister()}resetPendingUpload(){this.closeUploadDialog(),this.dragDepth=0,this.dragActive=!1}static{this.styles=[rg,h`
|
|
1307
1311
|
:host { flex: 1 1 auto; }
|
|
1308
1312
|
workspace-file-viewer { flex: 1 1 auto; min-height: 0; }
|
|
1309
1313
|
.files-panel { position: relative; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
|
|
@@ -1350,7 +1354,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1350
1354
|
.review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1351
1355
|
.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; }
|
|
1352
1356
|
footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
|
|
1353
|
-
`]}};H([b({attribute:!1})],jv.prototype,`context`,void 0),H([S(`#workspace-upload-input`)],jv.prototype,`uploadInput`,void 0),H([S(`.dialog-backdrop`)],jv.prototype,`uploadDialogBackdrop`,void 0),H([S(`.upload-dialog`)],jv.prototype,`uploadDialog`,void 0),H([x()],jv.prototype,`pendingUpload`,void 0),H([x()],jv.prototype,`destinationFolder`,void 0),H([x()],jv.prototype,`overwrite`,void 0),H([x()],jv.prototype,`createDirs`,void 0),H([x()],jv.prototype,`formError`,void 0),H([x()],jv.prototype,`dragActive`,void 0),jv=H([y(`workspace-files-panel`)],jv);function Mv(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 Nv(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{Cs(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function Pv(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function Fv(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function Iv(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Lv(e){return e==null?[]:Array.from(e)}function Rv(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function zv(e){let t=e.getRootNode();return t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host:e}function Bv(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function Vv(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 Hv(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return Kv(e.percent)}}function Uv(e){return e.status===`uploading`?e.percent:1}function Wv(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return Kv(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function Gv(e){return e.error===void 0?e.response===void 0?`${e.path} · ${Mh(e.loaded)} / ${Mh(e.total)}`:`Wrote ${e.response.path}`:e.error}function Kv(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function qv(){return[{id:`workspace.files`,title:`Files`,icon:Ah(`files`),order:10,routeAliases:[`files`],render:Jv},{id:`workspace.terminal`,title:`Terminal`,icon:Ah(`terminal`),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Yv}]}function Jv(e){return g`<workspace-files-panel .context=${e}></workspace-files-panel>`}function Yv(e){return Xv(),g`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Xv(){Sv(()=>import(`./TerminalPanel-DDLb8OAR.js`),__vite__mapDeps([4,5,6]),import.meta.url)}var Zv={apiVersion:2,name:`PI WEB Core`,activate:()=>({contributions:{actions:Sh(),workspacePanels:qv()}})},Qv={"--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`},$v={"--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`},ey={"--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`},ty={"--pi-bg":`#000000`,"--pi-surface":`#0d0d0d`,"--pi-surface-hover":`#1a1a1a`,"--pi-terminal-bg":`#000000`,"--pi-terminal-text":`#ffffff`,"--pi-border":`#5c5c5c`,"--pi-border-muted":`#3d3d3d`,"--pi-text":`#ffffff`,"--pi-text-secondary":`#e6e6e6`,"--pi-text-bright":`#ffffff`,"--pi-muted":`#b3b3b3`,"--pi-dim":`#8f8f8f`,"--pi-accent":`#4dc3ff`,"--pi-accent-border":`#4dc3ff`,"--pi-selection-bg":`#00263a`,"--pi-success":`#3ff05a`,"--pi-success-border":`#3ff05a`,"--pi-success-bg":`#001a06`,"--pi-success-surface":`#00280b`,"--pi-success-ring":`#3ff05a66`,"--pi-warning":`#ffcc33`,"--pi-warning-border":`#ffcc33`,"--pi-warning-surface":`#251c00`,"--pi-danger":`#ff6b6b`,"--pi-purple":`#c9a3ff`,"--pi-purple-border":`#c9a3ff`,"--pi-purple-surface":`#180d29`,"--pi-overlay":`#000000cc`,"--pi-shadow-soft":`#00000099`,"--pi-shadow":`#000000bb`,"--pi-shadow-strong":`#000000e6`,"--pi-bg-overlay-soft":`#000000dd`,"--pi-bg-overlay":`#000000f2`,"--pi-success-bg-overlay":`#001a06ee`,"--pi-terminal-selection":`#00456b`},ny={"--pi-bg":`#14110e`,"--pi-surface":`#1d1915`,"--pi-surface-hover":`#26211b`,"--pi-terminal-bg":`#100d0b`,"--pi-terminal-text":`#e8ddcc`,"--pi-border":`#3a3229`,"--pi-border-muted":`#2b2520`,"--pi-text":`#e8ddcc`,"--pi-text-secondary":`#cbbfad`,"--pi-text-bright":`#fff4e0`,"--pi-muted":`#9c9081`,"--pi-dim":`#7a6f62`,"--pi-accent":`#e0a35c`,"--pi-accent-border":`#b8813f`,"--pi-selection-bg":`#2e2415`,"--pi-success":`#8fbf6f`,"--pi-success-border":`#6d9954`,"--pi-success-bg":`#161c12`,"--pi-success-surface":`#1e2718`,"--pi-success-ring":`#8fbf6f55`,"--pi-warning":`#d9a441`,"--pi-warning-border":`#9c7429`,"--pi-warning-surface":`#241c0f`,"--pi-danger":`#d97b6c`,"--pi-purple":`#b79ad1`,"--pi-purple-border":`#8d74a8`,"--pi-purple-surface":`#221a2b`,"--pi-overlay":`#0a0806cc`,"--pi-shadow-soft":`#00000055`,"--pi-shadow":`#00000077`,"--pi-shadow-strong":`#000000aa`,"--pi-bg-overlay-soft":`#14110edd`,"--pi-bg-overlay":`#14110ee6`,"--pi-success-bg-overlay":`#161c12ee`,"--pi-terminal-selection":`#3d3121`},ry={"--pi-bg":`#fbfbf9`,"--pi-surface":`#ffffff`,"--pi-surface-hover":`#f1f1ee`,"--pi-terminal-bg":`#1c1c1a`,"--pi-terminal-text":`#fbfbf9`,"--pi-border":`#c7c7c1`,"--pi-border-muted":`#e0e0da`,"--pi-text":`#1c1c1a`,"--pi-text-secondary":`#33332f`,"--pi-text-bright":`#000000`,"--pi-muted":`#5e5e58`,"--pi-dim":`#7c7c75`,"--pi-accent":`#1f5fd0`,"--pi-accent-border":`#1f5fd0`,"--pi-selection-bg":`#e2ecfb`,"--pi-success":`#0f7a4a`,"--pi-success-border":`#0f7a4a`,"--pi-success-bg":`#e6f5ed`,"--pi-success-surface":`#d9efe3`,"--pi-success-ring":`#0f7a4a55`,"--pi-warning":`#8a5a00`,"--pi-warning-border":`#8a5a00`,"--pi-warning-surface":`#fdf0d5`,"--pi-danger":`#b02020`,"--pi-purple":`#5b3fc7`,"--pi-purple-border":`#5b3fc7`,"--pi-purple-surface":`#ece7fb`,"--pi-overlay":`#1c1c1a66`,"--pi-shadow-soft":`#1c1c1a1a`,"--pi-shadow":`#1c1c1a2b`,"--pi-shadow-strong":`#1c1c1a40`,"--pi-bg-overlay-soft":`#fbfbf9dd`,"--pi-bg-overlay":`#fbfbf9e6`,"--pi-success-bg-overlay":`#e6f5edee`,"--pi-terminal-selection":`#9ab4d8`},iy={apiVersion:2,name:`PI WEB Themes`,activate:()=>({contributions:{themes:[{id:`pi-web-dark`,name:`PI WEB Dark`,description:`Dark PI WEB palette.`,order:10,colorScheme:`dark`,tokens:$v},{id:`pi-web-light`,name:`PI WEB Light`,description:`Light PI WEB palette.`,order:20,colorScheme:`light`,tokens:ey},{id:`classic`,name:`PI WEB Classic`,description:`The original PI WEB dark palette.`,order:30,colorScheme:`dark`,tokens:Qv},{id:`high-contrast`,name:`High Contrast`,description:`Near-black behind near-white, for bright rooms and tired eyes.`,order:40,colorScheme:`dark`,tokens:ty},{id:`night`,name:`Night`,description:`Warm and dim, with an amber accent instead of blue light.`,order:50,colorScheme:`dark`,tokens:ny},{id:`paper`,name:`Paper`,description:`Untinted ink on paper, for daylight and for screenshots.`,order:60,colorScheme:`light`,tokens:ry}],themePairs:[{id:`pi-web`,name:`PI WEB`,description:`Follow the system light/dark preference with PI WEB themes.`,order:10,light:`pi-web-light`,dark:`pi-web-dark`}]}})};async function ay(e=`pi-web-plugins/manifest.json`,t={}){let n=vt(e),r=await cy(n);if(r===void 0)return{registrations:[],failures:[]};let i=[],a=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=oy(e.module,n),a=py(await(t.moduleLoader??sy)(r),r);i.push({id:t.machineId===void 0?e.id:Gs(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...e.backendRevision===void 0?{}:{backendRevision:e.backendRevision},...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){a.push({entry:e,error:t})}return{registrations:i,failures:a}}function oy(e,t,n){return e.startsWith(`/`)?n===void 0?vt(e):vt(e,n):new URL(e,t).toString()}async function sy(e){return Sv(()=>import(e),[],import.meta.url)}async function cy(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(await uy(t));return ly(await t.json())}}function ly(e){if(!hy(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);let t=e.plugins.map(e=>{if(!hy(e)||typeof e.id!=`string`||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);let t=e.id;if(!en(t))throw Error(`Invalid plugin manifest id: ${t}`);if(tn(t))throw Error(`Reserved plugin manifest id: ${t}`);return{id:t,module:e.module,...dy(e.backendRevision),machineSpecific:fy(e.machineSpecific)}}),n=new Set;for(let e of t){if(n.has(e.id))throw Error(`Duplicate plugin manifest id: ${e.id}`);n.add(e.id)}return{plugins:t}}async function uy(e){let t;try{let n=await e.json();if(hy(n)){let e=n.error,r=n.detail;t=typeof r==`string`?`${typeof e==`string`?`${e}: `:``}${r}`:typeof e==`string`?e:void 0}}catch{}return`Failed to load plugin manifest (${`${String(e.status)}${e.statusText===``?``:` ${e.statusText}`}`})${t===void 0?``:`: ${t}`}`}function dy(e){if(e===void 0)return{};try{return{backendRevision:$o(e)}}catch{throw Error(`Invalid plugin manifest entry`)}}function fy(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function py(e,t){if(!hy(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(hy(n)&&n.apiVersion!==2)throw Error(`Unsupported browser plugin API version for ${t}: ${String(n.apiVersion)} (expected 2)`);if(!my(n))throw Error(`Plugin module ${t} default export is not a PiWebPlugin`);return n}function my(e){return hy(e)&&e.apiVersion===2&&typeof e.name==`string`&&typeof e.activate==`function`}function hy(e){return typeof e==`object`&&!!e}var gy=/^[a-z][a-z0-9.-]*$/u,_y=/^[a-z][a-z0-9.-]*$/u,vy=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u,yy=/^[a-z][a-z0-9.-]*(?::[a-z][a-z0-9.-]*)?$/u,by=new WeakMap,xy=new WeakMap,Sy=new WeakMap,Cy=class{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.registeringPluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{plugin:t}=e,n=e.id,r=e.sourcePluginId??n;this.validatePluginId(n),this.validatePluginId(r);let i=this.parseMachineSpecific(n,e.machineSpecific),a=this.parseBackendRevision(n,e.backendRevision);if(this.pluginIds.has(n)||this.registeringPluginIds.has(n))throw Error(`Duplicate plugin id: ${n}`);if(!this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,i)){this.registeringPluginIds.add(n);try{let o=t.apiVersion;if(o!==2)throw Error(`Unsupported browser plugin API version for ${r}: ${String(o)} (expected 2)`);let s=t.activate(Object.freeze({apiVersion:2,pluginId:r,runtimePluginId:n,html:g,svg:Ye})).contributions,c=new Set,l=(s.actions??[]).map(t=>this.qualifyAction(n,t,e.machineId,e.sourcePluginId,c)),u=(s.workspacePanels??[]).map(t=>this.qualifyWorkspacePanel(n,t,e.machineId,e.sourcePluginId,a,c)),d=(s.workspaceLabels??[]).map(t=>this.qualifyWorkspaceLabelContribution(n,t,e.machineId,e.sourcePluginId,a,c)),f=e.machineId===void 0?(s.themes??[]).map(e=>this.qualifyTheme(n,e,c)):[],p=e.machineId===void 0?(s.themePairs??[]).map(e=>this.qualifyThemePair(n,e,c)):[];this.pluginIds.add(n);for(let e of c)this.contributionIds.add(e);this.actions.push(...l),this.workspacePanels.push(...u),this.workspaceLabels.push(...d),this.themes.push(...f),this.themePairs.push(...p),e.machineId===void 0?(this.gatewayPluginIds.add(n),i&&this.gatewayMachineSpecificPluginIds.add(n)):e.sourcePluginId!==void 0&&i&&jy(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}finally{this.registeringPluginIds.delete(n)}}}hasPlugin(e){return this.pluginIds.has(e)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=Py(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=wy(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.shortcutAliases!==void 0&&(a.shortcutAliases=[...t.shortcutAliases]),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))}resolveWorkspacePanelRouteId(e,t){let n=this.workspacePanels.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)),r=n.find(t=>t.id===e);if(r!==void 0)return r.id;let i=n.filter(t=>t.routeAliases?.includes(e)===!0);if(i.length===1)return i[0]?.id;i.length>1&&console.warn(`Ambiguous PI WEB workspace panel route: ${e}`)}async invalidateWorkspacePanels(e,t){await Promise.all(this.workspacePanels.map(async n=>{if(!(n.onInvalidate===void 0||t!==void 0&&n.id!==t))try{await n.onInvalidate(e)}catch(e){console.warn(`Failed to invalidate PI WEB plugin panel ${n.id}`,e)}}))}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,i){let a=this.qualify(e,t.id,i),o=`${r??e}:${t.id}`,s=this.parseShortcutAliases(a,t.shortcutAliases,o);return{...t,id:a,pluginId:e,localId:t.id,...s.length===0?{}:{shortcutAliases:s},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.badge,c=t.visible,l=t.onInvalidate,u=Ay(e,r,i),d=`${r??e}:${t.id}`,f=this.parseRouteAliases(o,t.routeAliases,d);return{...t,id:o,pluginId:e,localId:t.id,...f.length===0?{}:{routeAliases:f},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(c?.(Ty(t,u))??!0),...s===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?s(Ty(t,u)):void 0},...l===void 0?{}:{onInvalidate:t=>this.isContributionActive(e,n,t.machine.id,r)?l(Ty(t,u)):void 0},render:e=>t.render(Ty(e,u))}}qualifyWorkspaceLabelContribution(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.visible,c=t.items,l=Ay(e,r,i);return{...t,id:o,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(s?.(Ey(t,l))??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?c(Ey(t,l)):[]}}qualifyTheme(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id}}qualifyThemePair(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t,n){this.validateLocalId(t);let r=`${e}:${t}`;if(this.contributionIds.has(r)||n.has(r))throw Error(`Duplicate contribution id: ${r}`);return n.add(r),r}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)}parseShortcutAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e),i=r.find(e=>!My(e));if(i!==void 0)throw Error(`Invalid shortcut alias for ${e}: ${i}`);return r.filter(My)}parseRouteAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e);for(let t of r)if(!yy.test(t))throw Error(`Invalid workspace panel route alias for ${e}: ${t}`);return r}validatePluginId(e){if(!gy.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!_y.test(e))throw Error(`Invalid contribution id: ${e}`)}parseBackendRevision(e,t){if(t!==void 0)try{return $o(t)}catch{throw Error(`Invalid plugin backend revision for ${e}`)}}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${Ny(t)}`);return t}};function wy(e,t){return by.get(e)?.(t)??e}function Ty(e,t){return xy.get(e)?.(t)??e}function Ey(e,t){return Sy.get(e)?.(t)??e}function Dy(e,t){return by.set(e,t),e}function Oy(e,t){return xy.set(e,t),e}function ky(e,t){return Sy.set(e,t),e}function Ay(e,t,n){return Object.freeze({registrationPluginId:e,sourcePluginId:t??e,...n===void 0?{}:{backendRevision:n}})}function jy(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function My(e){return vy.test(e)}function Ny(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 Py(e){return e.state.selectedMachine?.id??`local`}function Fy(e,t,n,r=cs){let i=e.backendRevision;if(i!==void 0)return{request:(a,o)=>r({pluginId:e.sourcePluginId,backendRevision:i,machineId:n,projectId:t.projectId,workspaceId:t.id},a,o)}}function Iy(e,t,n,r){return{readFile:r=>e.workspaceFile(t.projectId,t.id,r,n),listFiles:r=>e.workspaceTree(t.projectId,t.id,r,n),writeFile:async(i,a,o)=>{let s=await e.writeWorkspaceFile(t.projectId,t.id,i,a,o,n);return r?.(),s},deleteFile:async i=>{let a=await e.deleteWorkspaceFile(t.projectId,t.id,i,n);return r?.(),a},moveFile:async(i,a,o)=>{let s=await e.moveWorkspaceFile(t.projectId,t.id,i,a,o,n);return r?.(),s}}}var Ly=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function Ry(){return typeof window>`u`||!(`matchMedia`in window)?[]:Ly.map(e=>window.matchMedia(e))}function zy(e,t=By()){return e.some(e=>e.matches)||Vy(t)}function By(){return typeof navigator>`u`?void 0:navigator}function Vy(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var Hy=class{constructor(e=Uy()){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 Uy(){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 Wy=`(max-width: 760px)`,Gy=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=zy(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??Ky(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??Ry(),this.viewportPositionRepairer=t.viewportPositionRepairer??new Hy,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=zy(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(e={}){return qy(this.isMobileNavigationLayout,e)}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function Ky(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(Wy)}function qy(e,t){return e&&(t.sessionId??``)===``?`navigation`:`chat`}var Jy=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new bc,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??Yy(),this.documentTarget=t.documentTarget??Xy(),this.isDocumentVisible=t.isDocumentVisible??Zy,this.scheduleFrame=t.scheduleFrame??Qy}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 Yy(){return typeof window>`u`?void 0:window}function Xy(){return typeof document>`u`?void 0:document}function Zy(){return typeof document>`u`||document.visibilityState===`visible`}function Qy(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 $y=[`machines`,`projects`,`workspaces`,`sessions`];function eb(e){return e.selectedWorkspace===void 0?e.selectedProject===void 0?`projects`:`workspaces`:`sessions`}function tb(e,t){if(e!==`none`)return e??eb(t)}function nb(e,t){return tb(t.expanded,t.state)!==e}function rb(e,t,n){return tb(e,n.state)===t?`none`:t}function ib(e){return e.workspaceCount===1?`sessions`:`workspaces`}function ab(e){return $y[$y.indexOf(e)+1]}var ob=class{hostConnected(){}constructor(e,t){this.host=e,this.getState=t,e.addController(this)}expandedSection(){return tb(this.expanded,this.getState())}isCollapsed(e){return nb(e,{expanded:this.expanded,state:this.getState()})}toggle(e){this.setExpanded(rb(this.expanded,e,{state:this.getState()}))}expand(e){this.setExpanded(e)}advanceAfterSelection(e,t){let n=e===`projects`?ib({workspaceCount:t?.workspaceCount}):ab(e);n!==void 0&&this.expand(n)}open(e,t){this.expand(e),t()}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}},sb=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,t=!0){return[`shell`,lb(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...cb(this.workspacePanelCollapsed,t)?[]:[`workspace-panel-collapsed`]].join(` `)}};function cb(e,t){return!e&&t}function lb(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var ub=`pi-web:panel-sizes:v1`,db={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},fb=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??Eb(),this.panelSizes=vb(this.storage)}hostConnected(){}constraints(e){return pb(e)}panelWidth(e,t){return _b(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=_b(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=Sb(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=Cb(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(){yb(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${Tb(_b(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${Tb(_b(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function pb(e){return db[e]}function mb(e,t,n){return e===`navigation`?n-t:t-n}function hb(e,t,n,r,i=pb(e)){return _b(e,t+mb(e,n,r),i)}function gb(e,t,n,r={}){let i=r.constraints??pb(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=wb(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return _b(e,t+a,i)}function _b(e,t,n=pb(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function vb(e=Eb()){try{let t=e?.getItem(ub);return t==null||t===``?{}:bb(JSON.parse(t))}catch{return{}}}function yb(e,t=Eb()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(ub);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=_b(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=_b(`workspace`,e.workspacePanelWidth)),t.setItem(ub,JSON.stringify(n))}catch{}}function bb(e){if(!Db(e)||e.version!==1)return{};let t={},n=xb(e.navigationPanelWidth),r=xb(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=_b(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=_b(`workspace`,r)),t}function xb(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Sb(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function Cb(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function wb(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 Tb(e){return`${String(Math.round(e))}px`}function Eb(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function Db(e){return typeof e==`object`&&!!e}function Ob(){let e=new URLSearchParams(window.location.search);return{machineId:Mb(e.get(`machine`)),projectId:Mb(e.get(`project`)),workspaceId:Mb(e.get(`workspace`)),sessionId:Mb(e.get(`session`)),tool:Mb(e.get(`tool`)),view:Mb(e.get(`view`))}}function kb(e,t){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool===void 0?void 0:Ab(e.tool,t),view:e.view===`chat`?`chat`:e.view===void 0?void 0:Ab(e.view,t)}}function Ab(e,t){return t(e)??(Nb(e)?e:void 0)}function jb(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&&e.tool!==``&&n.searchParams.set(`tool`,e.tool),e.view!==void 0&&e.view!==``&&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 Mb(e){return e===null||e===``?void 0:e}function Nb(e){return/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Pb(){return Ib(new URLSearchParams(window.location.search).get(`settings`))}function Fb(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 Ib(e){if(e===`general`)return`general`;if(e===`appearance`||e===`theme`||e===`themes`)return`appearance`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`machines`)return`machines`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`}function Lb(e,t){return t===void 0?e:e.map(e=>zb(e,t))}function Rb(e,t){let n=new Set(Wp(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return Lb(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?Bb(e):e)}function zb(e,t){let n=Zp(e,t);return n===void 0?e:n===null?Bb(e):{...e,shortcut:n}}function Bb(e){let t={...e};return delete t.shortcut,t}function Vb(e,t){let n=t.api??No,r=t.pollIntervalMs??1e3,i=t.setTimeout??Wb(),a=t.clearTimeout??Gb();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:Hb(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function Hb(e,t,n,r,i){return Ub(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&&Ub(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function Ub(e){return e.status===`succeeded`||e.status===`failed`}function Wb(){return(e,t)=>globalThis.setTimeout(e,t)}function Gb(){return e=>{globalThis.clearTimeout(e)}}var Kb=class{constructor(e){this.callbacks=e,this.fired=!1}start(e){this.cancel(),this.origin=e,this.fired=!1,this.handle=this.callbacks.setTimer(()=>{this.handle=void 0,this.fired=!0,this.callbacks.onLongPress()},500)}move(e){if(this.origin===void 0)return;let t=Math.abs(e.clientX-this.origin.clientX),n=Math.abs(e.clientY-this.origin.clientY);(t>10||n>10)&&this.cancel()}cancel(){this.handle!==void 0&&this.callbacks.clearTimer(this.handle),this.handle=void 0,this.origin=void 0}consumeSuppressedClick(){let e=this.fired;return this.fired=!1,e}},qb=class{constructor(e){this.open=e,this.longPress=new Kb({onLongPress:()=>{this.heldId!==void 0&&this.open(this.heldId,this.heldAnchor??null)},setTimer:(e,t)=>window.setTimeout(e,t),clearTimer:e=>{window.clearTimeout(e)}})}pointerDown(e,t){t.pointerType!==`mouse`&&(this.heldId=e,this.heldAnchor=t.currentTarget,this.longPress.start(t))}pointerMove(e){this.longPress.move(e)}cancel(){this.longPress.cancel(),this.heldId=void 0,this.heldAnchor=void 0}consumeSuppressedClick(){return this.longPress.consumeSuppressedClick()}contextMenu(e,t){t.preventDefault(),this.open(e,t.currentTarget)}},Jb=0,Yb=120;function Xb(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?Qb():Zb(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-Jb,f=n.top-c-Jb;return[...d<Yb&&f>d?[`bottom: ${$b(a-n.top+Jb)};`,`max-height: ${$b(Math.max(0,f))};`]:[`top: ${$b(n.bottom+Jb)};`,`max-height: ${$b(Math.max(0,d))};`],`right: ${$b(Math.max(0,i-u))};`,`max-width: ${$b(Math.max(0,u-o))};`].join(` `)}function Zb(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Qb()}function Qb(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function $b(e){return`${String(Math.round(e))}px`}function ex(e,t=`Active`,n){if(e===void 0)return n===void 0?void 0:g`<span class="activity-indicator unread" role="img" aria-label=${n} title=${n}></span>`;if(n===void 0)return g`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`;let r=`${n} · ${t}`;return g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`activity-indicator ${e}`} aria-hidden="true"></span></span>`}function tx(e){if(e!==void 0)return e[zt.working]===!0?`session`:e[zt.terminal]===!0?`terminal`:Object.entries(e).some(([e,t])=>t&&e!==zt.unread)?`session`:void 0}function nx(e){return e?.[zt.unread]===!0}var rx={working:`Session is working`,idle:`Session is done`,asking:`Waiting for your answer`,error:`Session hit an error`};function ix(e,t){if(e===void 0)return t===void 0?void 0:g`<span class="session-state unread" role="img" aria-label=${t} title=${t}></span>`;let n=e===`sending`?`Sending message`:rx[e],r=t===void 0?n:`${t} · ${n}`;if(e===`idle`)return g`<span class=${t===void 0?`session-state idle`:`session-state idle unread`} role="img" aria-label=${r} title=${r}></span>`;if(e===`working`||e===`sending`){let i=e===`working`?[0,1,2].map(e=>g`<span class="state-dot working-dot" style=${`animation-delay:${(e*.14).toFixed(2)}s`}></span>`):null;return t===void 0?g`<span class="session-state working" role="img" aria-label=${n} title=${n}><span class="state-dots">${i}</span></span>`:g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class="session-state working" aria-hidden="true"><span class="state-dots">${i}</span></span></span>`}return t===void 0?g`<span class=${`session-state ${e}`} role="img" aria-label=${n} title=${n}></span>`:g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`session-state ${e}`} aria-hidden="true"></span></span>`}function ax(e,t=`Active`,n){let r=ex(e,t,n);if(r!==void 0)return g`<span class="action-activity">${r}</span>`}var ox=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function sx(e){return e.composedPath().some(e=>cx(e,ox))}function cx(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 lx(e,t){return sx(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?dx(e,()=>{fx(e.currentTarget,-1)}):e.key===`ArrowDown`?dx(e,()=>{fx(e.currentTarget,1)}):e.key===`Home`?dx(e,()=>{px(e.currentTarget,0)}):e.key===`End`?dx(e,()=>{px(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?dx(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?dx(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&dx(e,t.cancel)}function ux(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 dx(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function fx(e,t){let n=hx(e),r=_x(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||mx(n,i+t)}function px(e,t){let n=hx(e);n.length!==0&&mx(n,t<0?n.length-1:t)}function mx(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function hx(e){let t=_x(e)?.getRootNode();return t===void 0||!gx(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function gx(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function _x(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var U=class extends v{constructor(...e){super(...e),this.machines=[],this.statuses={},this.statusSnapshots={},this.collapsible=!1,this.collapsed=!1,this.gestures=new qb((e,t)=>{this.openMenu(e,t)}),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,ux(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
|
|
1357
|
+
`]}};H([b({attribute:!1})],Mv.prototype,`context`,void 0),H([S(`#workspace-upload-input`)],Mv.prototype,`uploadInput`,void 0),H([S(`.dialog-backdrop`)],Mv.prototype,`uploadDialogBackdrop`,void 0),H([S(`.upload-dialog`)],Mv.prototype,`uploadDialog`,void 0),H([x()],Mv.prototype,`pendingUpload`,void 0),H([x()],Mv.prototype,`destinationFolder`,void 0),H([x()],Mv.prototype,`overwrite`,void 0),H([x()],Mv.prototype,`createDirs`,void 0),H([x()],Mv.prototype,`formError`,void 0),H([x()],Mv.prototype,`dragActive`,void 0),Mv=H([y(`workspace-files-panel`)],Mv);function Nv(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 Pv(e,t){if(e.length===0)return`Choose at least one file to upload.`;for(let n of e)try{Cs(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function Fv(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function Iv(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function Lv(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Rv(e){return e==null?[]:Array.from(e)}function zv(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function Bv(e){let t=e.getRootNode();return t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host:e}function Vv(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`${String(e.length)} recent`:`${String(t)} uploading`}function Hv(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 Uv(e){switch(e.status){case`completed`:return`Done`;case`error`:return`Failed`;case`cancelled`:return`Cancelled`;case`uploading`:return qv(e.percent)}}function Wv(e){return e.status===`uploading`?e.percent:1}function Gv(e){switch(e.status){case`pending`:return`Pending`;case`uploading`:return qv(e.percent);case`completed`:return`Done`;case`error`:return`Error`;case`cancelled`:return`Cancelled`}}function Kv(e){return e.error===void 0?e.response===void 0?`${e.path} · ${Nh(e.loaded)} / ${Nh(e.total)}`:`Wrote ${e.response.path}`:e.error}function qv(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function Jv(){return[{id:`workspace.files`,title:`Files`,icon:Ah(`files`),order:10,routeAliases:[`files`],render:Yv},{id:`workspace.terminal`,title:`Terminal`,icon:Ah(`terminal`),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Xv}]}function Yv(e){return g`<workspace-files-panel .context=${e}></workspace-files-panel>`}function Xv(e){return Zv(),g`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Zv(){Cv(()=>import(`./TerminalPanel-FojQLt0o.js`),__vite__mapDeps([4,5,6]),import.meta.url)}var Qv={apiVersion:2,name:`PI WEB Core`,activate:()=>({contributions:{actions:Sh(),workspacePanels:Jv()}})},$v={"--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`},ey={"--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`},ty={"--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`},ny={"--pi-bg":`#000000`,"--pi-surface":`#0d0d0d`,"--pi-surface-hover":`#1a1a1a`,"--pi-terminal-bg":`#000000`,"--pi-terminal-text":`#ffffff`,"--pi-border":`#5c5c5c`,"--pi-border-muted":`#3d3d3d`,"--pi-text":`#ffffff`,"--pi-text-secondary":`#e6e6e6`,"--pi-text-bright":`#ffffff`,"--pi-muted":`#b3b3b3`,"--pi-dim":`#8f8f8f`,"--pi-accent":`#4dc3ff`,"--pi-accent-border":`#4dc3ff`,"--pi-selection-bg":`#00263a`,"--pi-success":`#3ff05a`,"--pi-success-border":`#3ff05a`,"--pi-success-bg":`#001a06`,"--pi-success-surface":`#00280b`,"--pi-success-ring":`#3ff05a66`,"--pi-warning":`#ffcc33`,"--pi-warning-border":`#ffcc33`,"--pi-warning-surface":`#251c00`,"--pi-danger":`#ff6b6b`,"--pi-purple":`#c9a3ff`,"--pi-purple-border":`#c9a3ff`,"--pi-purple-surface":`#180d29`,"--pi-overlay":`#000000cc`,"--pi-shadow-soft":`#00000099`,"--pi-shadow":`#000000bb`,"--pi-shadow-strong":`#000000e6`,"--pi-bg-overlay-soft":`#000000dd`,"--pi-bg-overlay":`#000000f2`,"--pi-success-bg-overlay":`#001a06ee`,"--pi-terminal-selection":`#00456b`},ry={"--pi-bg":`#14110e`,"--pi-surface":`#1d1915`,"--pi-surface-hover":`#26211b`,"--pi-terminal-bg":`#100d0b`,"--pi-terminal-text":`#e8ddcc`,"--pi-border":`#3a3229`,"--pi-border-muted":`#2b2520`,"--pi-text":`#e8ddcc`,"--pi-text-secondary":`#cbbfad`,"--pi-text-bright":`#fff4e0`,"--pi-muted":`#9c9081`,"--pi-dim":`#7a6f62`,"--pi-accent":`#e0a35c`,"--pi-accent-border":`#b8813f`,"--pi-selection-bg":`#2e2415`,"--pi-success":`#8fbf6f`,"--pi-success-border":`#6d9954`,"--pi-success-bg":`#161c12`,"--pi-success-surface":`#1e2718`,"--pi-success-ring":`#8fbf6f55`,"--pi-warning":`#d9a441`,"--pi-warning-border":`#9c7429`,"--pi-warning-surface":`#241c0f`,"--pi-danger":`#d97b6c`,"--pi-purple":`#b79ad1`,"--pi-purple-border":`#8d74a8`,"--pi-purple-surface":`#221a2b`,"--pi-overlay":`#0a0806cc`,"--pi-shadow-soft":`#00000055`,"--pi-shadow":`#00000077`,"--pi-shadow-strong":`#000000aa`,"--pi-bg-overlay-soft":`#14110edd`,"--pi-bg-overlay":`#14110ee6`,"--pi-success-bg-overlay":`#161c12ee`,"--pi-terminal-selection":`#3d3121`},iy={"--pi-bg":`#fbfbf9`,"--pi-surface":`#ffffff`,"--pi-surface-hover":`#f1f1ee`,"--pi-terminal-bg":`#1c1c1a`,"--pi-terminal-text":`#fbfbf9`,"--pi-border":`#c7c7c1`,"--pi-border-muted":`#e0e0da`,"--pi-text":`#1c1c1a`,"--pi-text-secondary":`#33332f`,"--pi-text-bright":`#000000`,"--pi-muted":`#5e5e58`,"--pi-dim":`#7c7c75`,"--pi-accent":`#1f5fd0`,"--pi-accent-border":`#1f5fd0`,"--pi-selection-bg":`#e2ecfb`,"--pi-success":`#0f7a4a`,"--pi-success-border":`#0f7a4a`,"--pi-success-bg":`#e6f5ed`,"--pi-success-surface":`#d9efe3`,"--pi-success-ring":`#0f7a4a55`,"--pi-warning":`#8a5a00`,"--pi-warning-border":`#8a5a00`,"--pi-warning-surface":`#fdf0d5`,"--pi-danger":`#b02020`,"--pi-purple":`#5b3fc7`,"--pi-purple-border":`#5b3fc7`,"--pi-purple-surface":`#ece7fb`,"--pi-overlay":`#1c1c1a66`,"--pi-shadow-soft":`#1c1c1a1a`,"--pi-shadow":`#1c1c1a2b`,"--pi-shadow-strong":`#1c1c1a40`,"--pi-bg-overlay-soft":`#fbfbf9dd`,"--pi-bg-overlay":`#fbfbf9e6`,"--pi-success-bg-overlay":`#e6f5edee`,"--pi-terminal-selection":`#9ab4d8`},ay={apiVersion:2,name:`PI WEB Themes`,activate:()=>({contributions:{themes:[{id:`pi-web-dark`,name:`PI WEB Dark`,description:`Dark PI WEB palette.`,order:10,colorScheme:`dark`,tokens:ey},{id:`pi-web-light`,name:`PI WEB Light`,description:`Light PI WEB palette.`,order:20,colorScheme:`light`,tokens:ty},{id:`classic`,name:`PI WEB Classic`,description:`The original PI WEB dark palette.`,order:30,colorScheme:`dark`,tokens:$v},{id:`high-contrast`,name:`High Contrast`,description:`Near-black behind near-white, for bright rooms and tired eyes.`,order:40,colorScheme:`dark`,tokens:ny},{id:`night`,name:`Night`,description:`Warm and dim, with an amber accent instead of blue light.`,order:50,colorScheme:`dark`,tokens:ry},{id:`paper`,name:`Paper`,description:`Untinted ink on paper, for daylight and for screenshots.`,order:60,colorScheme:`light`,tokens:iy}],themePairs:[{id:`pi-web`,name:`PI WEB`,description:`Follow the system light/dark preference with PI WEB themes.`,order:10,light:`pi-web-light`,dark:`pi-web-dark`}]}})};async function oy(e=`pi-web-plugins/manifest.json`,t={}){let n=vt(e),r=await ly(n);if(r===void 0)return{registrations:[],failures:[]};let i=[],a=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=sy(e.module,n),a=my(await(t.moduleLoader??cy)(r),r);i.push({id:t.machineId===void 0?e.id:Gs(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...e.backendRevision===void 0?{}:{backendRevision:e.backendRevision},...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){a.push({entry:e,error:t})}return{registrations:i,failures:a}}function sy(e,t,n){return e.startsWith(`/`)?n===void 0?vt(e):vt(e,n):new URL(e,t).toString()}async function cy(e){return Cv(()=>import(e),[],import.meta.url)}async function ly(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(await dy(t));return uy(await t.json())}}function uy(e){if(!gy(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);let t=e.plugins.map(e=>{if(!gy(e)||typeof e.id!=`string`||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);let t=e.id;if(!en(t))throw Error(`Invalid plugin manifest id: ${t}`);if(tn(t))throw Error(`Reserved plugin manifest id: ${t}`);return{id:t,module:e.module,...fy(e.backendRevision),machineSpecific:py(e.machineSpecific)}}),n=new Set;for(let e of t){if(n.has(e.id))throw Error(`Duplicate plugin manifest id: ${e.id}`);n.add(e.id)}return{plugins:t}}async function dy(e){let t;try{let n=await e.json();if(gy(n)){let e=n.error,r=n.detail;t=typeof r==`string`?`${typeof e==`string`?`${e}: `:``}${r}`:typeof e==`string`?e:void 0}}catch{}return`Failed to load plugin manifest (${`${String(e.status)}${e.statusText===``?``:` ${e.statusText}`}`})${t===void 0?``:`: ${t}`}`}function fy(e){if(e===void 0)return{};try{return{backendRevision:$o(e)}}catch{throw Error(`Invalid plugin manifest entry`)}}function py(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function my(e,t){if(!gy(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(gy(n)&&n.apiVersion!==2)throw Error(`Unsupported browser plugin API version for ${t}: ${String(n.apiVersion)} (expected 2)`);if(!hy(n))throw Error(`Plugin module ${t} default export is not a PiWebPlugin`);return n}function hy(e){return gy(e)&&e.apiVersion===2&&typeof e.name==`string`&&typeof e.activate==`function`}function gy(e){return typeof e==`object`&&!!e}var _y=/^[a-z][a-z0-9.-]*$/u,vy=/^[a-z][a-z0-9.-]*$/u,yy=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u,by=/^[a-z][a-z0-9.-]*(?::[a-z][a-z0-9.-]*)?$/u,xy=new WeakMap,Sy=new WeakMap,Cy=new WeakMap,wy=class{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.registeringPluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{plugin:t}=e,n=e.id,r=e.sourcePluginId??n;this.validatePluginId(n),this.validatePluginId(r);let i=this.parseMachineSpecific(n,e.machineSpecific),a=this.parseBackendRevision(n,e.backendRevision);if(this.pluginIds.has(n)||this.registeringPluginIds.has(n))throw Error(`Duplicate plugin id: ${n}`);if(!this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,i)){this.registeringPluginIds.add(n);try{let o=t.apiVersion;if(o!==2)throw Error(`Unsupported browser plugin API version for ${r}: ${String(o)} (expected 2)`);let s=t.activate(Object.freeze({apiVersion:2,pluginId:r,runtimePluginId:n,html:g,svg:Ye})).contributions,c=new Set,l=(s.actions??[]).map(t=>this.qualifyAction(n,t,e.machineId,e.sourcePluginId,c)),u=(s.workspacePanels??[]).map(t=>this.qualifyWorkspacePanel(n,t,e.machineId,e.sourcePluginId,a,c)),d=(s.workspaceLabels??[]).map(t=>this.qualifyWorkspaceLabelContribution(n,t,e.machineId,e.sourcePluginId,a,c)),f=e.machineId===void 0?(s.themes??[]).map(e=>this.qualifyTheme(n,e,c)):[],p=e.machineId===void 0?(s.themePairs??[]).map(e=>this.qualifyThemePair(n,e,c)):[];this.pluginIds.add(n);for(let e of c)this.contributionIds.add(e);this.actions.push(...l),this.workspacePanels.push(...u),this.workspaceLabels.push(...d),this.themes.push(...f),this.themePairs.push(...p),e.machineId===void 0?(this.gatewayPluginIds.add(n),i&&this.gatewayMachineSpecificPluginIds.add(n)):e.sourcePluginId!==void 0&&i&&My(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}finally{this.registeringPluginIds.delete(n)}}}hasPlugin(e){return this.pluginIds.has(e)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=Fy(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=Ty(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.shortcutAliases!==void 0&&(a.shortcutAliases=[...t.shortcutAliases]),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))}resolveWorkspacePanelRouteId(e,t){let n=this.workspacePanels.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)),r=n.find(t=>t.id===e);if(r!==void 0)return r.id;let i=n.filter(t=>t.routeAliases?.includes(e)===!0);if(i.length===1)return i[0]?.id;i.length>1&&console.warn(`Ambiguous PI WEB workspace panel route: ${e}`)}async invalidateWorkspacePanels(e,t){await Promise.all(this.workspacePanels.map(async n=>{if(!(n.onInvalidate===void 0||t!==void 0&&n.id!==t))try{await n.onInvalidate(e)}catch(e){console.warn(`Failed to invalidate PI WEB plugin panel ${n.id}`,e)}}))}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,i){let a=this.qualify(e,t.id,i),o=`${r??e}:${t.id}`,s=this.parseShortcutAliases(a,t.shortcutAliases,o);return{...t,id:a,pluginId:e,localId:t.id,...s.length===0?{}:{shortcutAliases:s},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.badge,c=t.visible,l=t.onInvalidate,u=jy(e,r,i),d=`${r??e}:${t.id}`,f=this.parseRouteAliases(o,t.routeAliases,d);return{...t,id:o,pluginId:e,localId:t.id,...f.length===0?{}:{routeAliases:f},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(c?.(Ey(t,u))??!0),...s===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?s(Ey(t,u)):void 0},...l===void 0?{}:{onInvalidate:t=>this.isContributionActive(e,n,t.machine.id,r)?l(Ey(t,u)):void 0},render:e=>t.render(Ey(e,u))}}qualifyWorkspaceLabelContribution(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.visible,c=t.items,l=jy(e,r,i);return{...t,id:o,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(s?.(Dy(t,l))??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?c(Dy(t,l)):[]}}qualifyTheme(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id}}qualifyThemePair(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t,n){this.validateLocalId(t);let r=`${e}:${t}`;if(this.contributionIds.has(r)||n.has(r))throw Error(`Duplicate contribution id: ${r}`);return n.add(r),r}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)}parseShortcutAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e),i=r.find(e=>!Ny(e));if(i!==void 0)throw Error(`Invalid shortcut alias for ${e}: ${i}`);return r.filter(Ny)}parseRouteAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e);for(let t of r)if(!by.test(t))throw Error(`Invalid workspace panel route alias for ${e}: ${t}`);return r}validatePluginId(e){if(!_y.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!vy.test(e))throw Error(`Invalid contribution id: ${e}`)}parseBackendRevision(e,t){if(t!==void 0)try{return $o(t)}catch{throw Error(`Invalid plugin backend revision for ${e}`)}}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${Py(t)}`);return t}};function Ty(e,t){return xy.get(e)?.(t)??e}function Ey(e,t){return Sy.get(e)?.(t)??e}function Dy(e,t){return Cy.get(e)?.(t)??e}function Oy(e,t){return xy.set(e,t),e}function ky(e,t){return Sy.set(e,t),e}function Ay(e,t){return Cy.set(e,t),e}function jy(e,t,n){return Object.freeze({registrationPluginId:e,sourcePluginId:t??e,...n===void 0?{}:{backendRevision:n}})}function My(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function Ny(e){return yy.test(e)}function Py(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 Fy(e){return e.state.selectedMachine?.id??`local`}function Iy(e,t,n,r=cs){let i=e.backendRevision;if(i!==void 0)return{request:(a,o)=>r({pluginId:e.sourcePluginId,backendRevision:i,machineId:n,projectId:t.projectId,workspaceId:t.id},a,o)}}function Ly(e,t,n,r){return{readFile:r=>e.workspaceFile(t.projectId,t.id,r,n),listFiles:r=>e.workspaceTree(t.projectId,t.id,r,n),writeFile:async(i,a,o)=>{let s=await e.writeWorkspaceFile(t.projectId,t.id,i,a,o,n);return r?.(),s},deleteFile:async i=>{let a=await e.deleteWorkspaceFile(t.projectId,t.id,i,n);return r?.(),a},moveFile:async(i,a,o)=>{let s=await e.moveWorkspaceFile(t.projectId,t.id,i,a,o,n);return r?.(),s}}}var Ry=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function zy(){return typeof window>`u`||!(`matchMedia`in window)?[]:Ry.map(e=>window.matchMedia(e))}function By(e,t=Vy()){return e.some(e=>e.matches)||Hy(t)}function Vy(){return typeof navigator>`u`?void 0:navigator}function Hy(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var Uy=class{constructor(e=Wy()){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 Wy(){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 Gy=`(max-width: 760px)`,Ky=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=By(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??qy(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??zy(),this.viewportPositionRepairer=t.viewportPositionRepairer??new Uy,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=By(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(e={}){return Jy(this.isMobileNavigationLayout,e)}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function qy(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(Gy)}function Jy(e,t){return e&&(t.sessionId??``)===``?`navigation`:`chat`}var Yy=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new bc,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??Xy(),this.documentTarget=t.documentTarget??Zy(),this.isDocumentVisible=t.isDocumentVisible??Qy,this.scheduleFrame=t.scheduleFrame??$y}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 Xy(){return typeof window>`u`?void 0:window}function Zy(){return typeof document>`u`?void 0:document}function Qy(){return typeof document>`u`||document.visibilityState===`visible`}function $y(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 eb=[`machines`,`projects`,`workspaces`,`sessions`];function tb(e){return e.selectedWorkspace===void 0?e.selectedProject===void 0?`projects`:`workspaces`:`sessions`}function nb(e,t){if(e!==`none`)return e??tb(t)}function rb(e,t){return nb(t.expanded,t.state)!==e}function ib(e,t,n){return nb(e,n.state)===t?`none`:t}function ab(e){return e.workspaceCount===1?`sessions`:`workspaces`}function ob(e){return eb[eb.indexOf(e)+1]}var sb=class{hostConnected(){}constructor(e,t){this.host=e,this.getState=t,e.addController(this)}expandedSection(){return nb(this.expanded,this.getState())}isCollapsed(e){return rb(e,{expanded:this.expanded,state:this.getState()})}toggle(e){this.setExpanded(ib(this.expanded,e,{state:this.getState()}))}expand(e){this.setExpanded(e)}advanceAfterSelection(e,t){let n=e===`projects`?ab({workspaceCount:t?.workspaceCount}):ob(e);n!==void 0&&this.expand(n)}open(e,t){this.expand(e),t()}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}},cb=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,t=!0){return[`shell`,ub(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...lb(this.workspacePanelCollapsed,t)?[]:[`workspace-panel-collapsed`]].join(` `)}};function lb(e,t){return!e&&t}function ub(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var db=`pi-web:panel-sizes:v1`,fb={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},pb=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??Db(),this.panelSizes=yb(this.storage)}hostConnected(){}constraints(e){return mb(e)}panelWidth(e,t){return vb(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=vb(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=Cb(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=wb(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(){bb(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${Eb(vb(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${Eb(vb(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function mb(e){return fb[e]}function hb(e,t,n){return e===`navigation`?n-t:t-n}function gb(e,t,n,r,i=mb(e)){return vb(e,t+hb(e,n,r),i)}function _b(e,t,n,r={}){let i=r.constraints??mb(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=Tb(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return vb(e,t+a,i)}function vb(e,t,n=mb(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function yb(e=Db()){try{let t=e?.getItem(db);return t==null||t===``?{}:xb(JSON.parse(t))}catch{return{}}}function bb(e,t=Db()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(db);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=vb(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=vb(`workspace`,e.workspacePanelWidth)),t.setItem(db,JSON.stringify(n))}catch{}}function xb(e){if(!Ob(e)||e.version!==1)return{};let t={},n=Sb(e.navigationPanelWidth),r=Sb(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=vb(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=vb(`workspace`,r)),t}function Sb(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Cb(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function wb(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Tb(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 Eb(e){return`${String(Math.round(e))}px`}function Db(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function Ob(e){return typeof e==`object`&&!!e}function kb(){let e=new URLSearchParams(window.location.search);return{machineId:Nb(e.get(`machine`)),projectId:Nb(e.get(`project`)),workspaceId:Nb(e.get(`workspace`)),sessionId:Nb(e.get(`session`)),tool:Nb(e.get(`tool`)),view:Nb(e.get(`view`))}}function Ab(e,t){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool===void 0?void 0:jb(e.tool,t),view:e.view===`chat`?`chat`:e.view===void 0?void 0:jb(e.view,t)}}function jb(e,t){return t(e)??(Pb(e)?e:void 0)}function Mb(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&&e.tool!==``&&n.searchParams.set(`tool`,e.tool),e.view!==void 0&&e.view!==``&&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 Nb(e){return e===null||e===``?void 0:e}function Pb(e){return/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Fb(){return Lb(new URLSearchParams(window.location.search).get(`settings`))}function Ib(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 Lb(e){if(e===`general`)return`general`;if(e===`appearance`||e===`theme`||e===`themes`)return`appearance`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`machines`)return`machines`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`}function Rb(e,t){return t===void 0?e:e.map(e=>Bb(e,t))}function zb(e,t){let n=new Set(Wp(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return Rb(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?Vb(e):e)}function Bb(e,t){let n=Zp(e,t);return n===void 0?e:n===null?Vb(e):{...e,shortcut:n}}function Vb(e){let t={...e};return delete t.shortcut,t}function Hb(e,t){let n=t.api??No,r=t.pollIntervalMs??1e3,i=t.setTimeout??Gb(),a=t.clearTimeout??Kb();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:Ub(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function Ub(e,t,n,r,i){return Wb(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&&Wb(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function Wb(e){return e.status===`succeeded`||e.status===`failed`}function Gb(){return(e,t)=>globalThis.setTimeout(e,t)}function Kb(){return e=>{globalThis.clearTimeout(e)}}var qb=class{constructor(e){this.callbacks=e,this.fired=!1}start(e){this.cancel(),this.origin=e,this.fired=!1,this.handle=this.callbacks.setTimer(()=>{this.handle=void 0,this.fired=!0,this.callbacks.onLongPress()},500)}move(e){if(this.origin===void 0)return;let t=Math.abs(e.clientX-this.origin.clientX),n=Math.abs(e.clientY-this.origin.clientY);(t>10||n>10)&&this.cancel()}cancel(){this.handle!==void 0&&this.callbacks.clearTimer(this.handle),this.handle=void 0,this.origin=void 0}consumeSuppressedClick(){let e=this.fired;return this.fired=!1,e}},Jb=class{constructor(e){this.open=e,this.longPress=new qb({onLongPress:()=>{this.heldId!==void 0&&this.open(this.heldId,this.heldAnchor??null)},setTimer:(e,t)=>window.setTimeout(e,t),clearTimer:e=>{window.clearTimeout(e)}})}pointerDown(e,t){t.pointerType!==`mouse`&&(this.heldId=e,this.heldAnchor=t.currentTarget,this.longPress.start(t))}pointerMove(e){this.longPress.move(e)}cancel(){this.longPress.cancel(),this.heldId=void 0,this.heldAnchor=void 0}consumeSuppressedClick(){return this.longPress.consumeSuppressedClick()}contextMenu(e,t){t.preventDefault(),this.open(e,t.currentTarget)}},Yb=0,Xb=120;function Zb(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?$b():Qb(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-Yb,f=n.top-c-Yb;return[...d<Xb&&f>d?[`bottom: ${ex(a-n.top+Yb)};`,`max-height: ${ex(Math.max(0,f))};`]:[`top: ${ex(n.bottom+Yb)};`,`max-height: ${ex(Math.max(0,d))};`],`right: ${ex(Math.max(0,i-u))};`,`max-width: ${ex(Math.max(0,u-o))};`].join(` `)}function Qb(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():$b()}function $b(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function ex(e){return`${String(Math.round(e))}px`}function tx(e,t=`Active`,n){if(e===void 0)return n===void 0?void 0:g`<span class="activity-indicator unread" role="img" aria-label=${n} title=${n}></span>`;if(n===void 0)return g`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`;let r=`${n} · ${t}`;return g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`activity-indicator ${e}`} aria-hidden="true"></span></span>`}function nx(e){if(e!==void 0)return e[zt.working]===!0?`session`:e[zt.terminal]===!0?`terminal`:Object.entries(e).some(([e,t])=>t&&e!==zt.unread)?`session`:void 0}function rx(e){return e?.[zt.unread]===!0}var ix={working:`Session is working`,idle:`Session is done`,asking:`Waiting for your answer`,error:`Session hit an error`};function ax(e,t){if(e===void 0)return t===void 0?void 0:g`<span class="session-state unread" role="img" aria-label=${t} title=${t}></span>`;let n=e===`sending`?`Sending message`:ix[e],r=t===void 0?n:`${t} · ${n}`;if(e===`idle`)return g`<span class=${t===void 0?`session-state idle`:`session-state idle unread`} role="img" aria-label=${r} title=${r}></span>`;if(e===`working`||e===`sending`){let i=e===`working`?[0,1,2].map(e=>g`<span class="state-dot working-dot" style=${`animation-delay:${(e*.14).toFixed(2)}s`}></span>`):null;return t===void 0?g`<span class="session-state working" role="img" aria-label=${n} title=${n}><span class="state-dots">${i}</span></span>`:g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class="session-state working" aria-hidden="true"><span class="state-dots">${i}</span></span></span>`}return t===void 0?g`<span class=${`session-state ${e}`} role="img" aria-label=${n} title=${n}></span>`:g`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`session-state ${e}`} aria-hidden="true"></span></span>`}function ox(e,t=`Active`,n){let r=tx(e,t,n);if(r!==void 0)return g`<span class="action-activity">${r}</span>`}var sx=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function cx(e){return e.composedPath().some(e=>lx(e,sx))}function lx(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 ux(e,t){return cx(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?fx(e,()=>{px(e.currentTarget,-1)}):e.key===`ArrowDown`?fx(e,()=>{px(e.currentTarget,1)}):e.key===`Home`?fx(e,()=>{mx(e.currentTarget,0)}):e.key===`End`?fx(e,()=>{mx(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?fx(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?fx(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&fx(e,t.cancel)}function dx(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 fx(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function px(e,t){let n=gx(e),r=vx(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||hx(n,i+t)}function mx(e,t){let n=gx(e);n.length!==0&&hx(n,t<0?n.length-1:t)}function hx(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function gx(e){let t=vx(e)?.getRootNode();return t===void 0||!_x(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function _x(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function vx(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var U=class extends v{constructor(...e){super(...e),this.machines=[],this.statuses={},this.statusSnapshots={},this.collapsible=!1,this.collapsed=!1,this.gestures=new Jb((e,t)=>{this.openMenu(e,t)}),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,dx(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
|
|
1354
1358
|
<section>
|
|
1355
1359
|
<h2>${this.renderHeading()}${this.renderAdd()}</h2>
|
|
1356
1360
|
${this.collapsed?null:g`
|
|
@@ -1359,7 +1363,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1359
1363
|
</div>
|
|
1360
1364
|
`}
|
|
1361
1365
|
</section>
|
|
1362
|
-
`}renderMachine(e){let t=this.statuses[e.id]?.status??e.status??`unknown`,n=t===`online`?`online`:t===`offline`?`offline`:t===`error`?`error`:`unknown`,r=
|
|
1366
|
+
`}renderMachine(e){let t=this.statuses[e.id]?.status??e.status??`unknown`,n=t===`online`?`online`:t===`offline`?`offline`:t===`error`?`error`:`unknown`,r=bx(e,{remove:this.onRemove!==void 0,rename:this.onRename!==void 0,refresh:this.onRefresh!==void 0,open:this.onOpen!==void 0}).length>0;return g`
|
|
1363
1367
|
<div
|
|
1364
1368
|
class=${`action-row machine-row ${this.selected?.id===e.id?`selected`:``} ${r?``:`no-actions`}`}
|
|
1365
1369
|
title=${e.baseUrl??e.name}
|
|
@@ -1381,7 +1385,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1381
1385
|
</button>
|
|
1382
1386
|
${r?this.renderMachineMenu(e):null}
|
|
1383
1387
|
</div>
|
|
1384
|
-
`}renderActivity(e){let t=this.statusSnapshots[e.id]?.machine,n=this.statuses[e.id]?.status??e.status,r=n===`offline`||n===`error`?void 0:
|
|
1388
|
+
`}renderActivity(e){let t=this.statusSnapshots[e.id]?.machine,n=this.statuses[e.id]?.status??e.status,r=n===`offline`||n===`error`?void 0:nx(t),i=rx(t)?`Unread sessions on this machine`:void 0;return ox(r,r===`terminal`?`Machine terminal active`:`Machine active`,i)}renderMachineMenu(e){let t=this.openMenuMachineId===e.id,n=xx(e.id);return g`
|
|
1385
1389
|
<div class="action-menu">
|
|
1386
1390
|
<button
|
|
1387
1391
|
class="action-menu-toggle"
|
|
@@ -1396,11 +1400,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1396
1400
|
${this.onRefresh===void 0?null:g`<button title=${`Check ${e.name} again`} @click=${()=>{this.openMenuMachineId=void 0,this.onRefresh?.(e)}}>Check again</button>`}
|
|
1397
1401
|
${this.onRename===void 0?null:g`<button title=${e.kind===`local`?`Rename this device (display name only)`:`Rename ${e.name}`} @click=${()=>{this.promptRename(e)}}>Rename…</button>`}
|
|
1398
1402
|
${this.onOpen===void 0||e.kind!==`remote`?null:g`<button title=${`Open ${e.name} in a new tab`} @click=${()=>{this.openMenuMachineId=void 0,this.onOpen?.(e)}}>Open PI WEB</button>`}
|
|
1399
|
-
${
|
|
1403
|
+
${yx(e)&&this.onRemove!==void 0?g`<button class="danger" title=${`Remove ${e.name}`} @click=${()=>{this.removeMachine(e)}}>Remove</button>`:null}
|
|
1400
1404
|
</div>
|
|
1401
1405
|
`:null}
|
|
1402
1406
|
</div>
|
|
1403
|
-
`}renderAdd(){return this.onAdd===void 0?null:g`<button class="section-add" title="Add machine" aria-label="Add machine" @click=${e=>{e.stopPropagation(),this.onAdd?.()}}><span aria-hidden="true">+</span><span class="section-add-label">Add machine</span></button>`}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>`}openMenu(e,t){this.menuStyle=
|
|
1407
|
+
`}renderAdd(){return this.onAdd===void 0?null:g`<button class="section-add" title="Add machine" aria-label="Add machine" @click=${e=>{e.stopPropagation(),this.onAdd?.()}}><span aria-hidden="true">+</span><span class="section-add-label">Add machine</span></button>`}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>`}openMenu(e,t){this.menuStyle=Zb(t,{constrainTo:`viewport`}),this.openMenuMachineId=e}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=Zb(t,{constrainTo:`viewport`}),this.openMenuMachineId=e}promptRename(e){this.openMenuMachineId=void 0;let t=prompt(e.kind===`local`?`Name for this device:`:`Name for ${e.name}:`,e.name);if(t===null)return;let n=t.trim();n===``||n===e.name||this.onRename?.(e,n)}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}ux(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=[ig,h`
|
|
1404
1408
|
.machine-row { border-radius: var(--pi-radius-lg); }
|
|
1405
1409
|
.machine-row.no-actions .action-main { border-radius: var(--pi-radius-lg); }
|
|
1406
1410
|
.machine-row .action-main { min-height: 58px; align-content: center; }
|
|
@@ -1408,7 +1412,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1408
1412
|
.machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
1409
1413
|
.machine-menu-panel button.danger { color: var(--pi-danger); }
|
|
1410
1414
|
.machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
|
|
1411
|
-
`]}};H([b({attribute:!1})],U.prototype,`machines`,void 0),H([b({attribute:!1})],U.prototype,`selected`,void 0),H([b({attribute:!1})],U.prototype,`statuses`,void 0),H([b({attribute:!1})],U.prototype,`statusSnapshots`,void 0),H([b({type:Boolean,reflect:!0})],U.prototype,`collapsible`,void 0),H([b({type:Boolean,reflect:!0})],U.prototype,`collapsed`,void 0),H([b({attribute:!1})],U.prototype,`onSelect`,void 0),H([b({attribute:!1})],U.prototype,`onRemove`,void 0),H([b({attribute:!1})],U.prototype,`onRename`,void 0),H([b({attribute:!1})],U.prototype,`onRefresh`,void 0),H([b({attribute:!1})],U.prototype,`onOpen`,void 0),H([b({attribute:!1})],U.prototype,`onToggleCollapsed`,void 0),H([b({attribute:!1})],U.prototype,`onAdd`,void 0),H([b({attribute:!1})],U.prototype,`onFocusNextSection`,void 0),H([b({attribute:!1})],U.prototype,`onCancelKeyboardNavigation`,void 0),H([x()],U.prototype,`openMenuMachineId`,void 0),H([x()],U.prototype,`menuStyle`,void 0),U=H([y(`machine-list`)],U);function
|
|
1415
|
+
`]}};H([b({attribute:!1})],U.prototype,`machines`,void 0),H([b({attribute:!1})],U.prototype,`selected`,void 0),H([b({attribute:!1})],U.prototype,`statuses`,void 0),H([b({attribute:!1})],U.prototype,`statusSnapshots`,void 0),H([b({type:Boolean,reflect:!0})],U.prototype,`collapsible`,void 0),H([b({type:Boolean,reflect:!0})],U.prototype,`collapsed`,void 0),H([b({attribute:!1})],U.prototype,`onSelect`,void 0),H([b({attribute:!1})],U.prototype,`onRemove`,void 0),H([b({attribute:!1})],U.prototype,`onRename`,void 0),H([b({attribute:!1})],U.prototype,`onRefresh`,void 0),H([b({attribute:!1})],U.prototype,`onOpen`,void 0),H([b({attribute:!1})],U.prototype,`onToggleCollapsed`,void 0),H([b({attribute:!1})],U.prototype,`onAdd`,void 0),H([b({attribute:!1})],U.prototype,`onFocusNextSection`,void 0),H([b({attribute:!1})],U.prototype,`onCancelKeyboardNavigation`,void 0),H([x()],U.prototype,`openMenuMachineId`,void 0),H([x()],U.prototype,`menuStyle`,void 0),U=H([y(`machine-list`)],U);function yx(e){return e.kind===`remote`}function bx(e,t){let n=[];return t.refresh&&n.push(`refresh`),t.rename&&n.push(`rename`),t.open&&e.kind===`remote`&&n.push(`open`),t.remove&&yx(e)&&n.push(`remove`),n}function xx(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}function Sx(e){return`${e.name} ${e.path}`}function Cx(e,t){return Ed(e,t,Sx)}function wx(e,t){return e>=6||wd(t).length>0}var Tx=class extends v{constructor(...e){super(...e),this.projects=[],this.searchQuery=``,this.collapsible=!1,this.collapsed=!1,this.tiles=!1,this.gestures=new Jb((e,t)=>{this.openMenu(e,t)}),this.menuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuProjectId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has(`projects`)&&this.openMenuProjectId!==void 0&&!this.projects.some(e=>e.id===this.openMenuProjectId)&&(this.openMenuProjectId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuProjectId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,dx(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){let e=Cx(this.projects,this.searchQuery);return g`
|
|
1412
1416
|
<section>
|
|
1413
1417
|
<h2>${this.renderHeading()}${this.renderAdd()}</h2>
|
|
1414
1418
|
${this.collapsed?null:g`
|
|
@@ -1453,7 +1457,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1453
1457
|
</div>
|
|
1454
1458
|
`}
|
|
1455
1459
|
</section>
|
|
1456
|
-
`}handleProjectKeydown(e,t){
|
|
1460
|
+
`}handleProjectKeydown(e,t){ux(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?.()}})}renderSearch(){if(!wx(this.projects.length,this.searchQuery))return null;let e=this.searchQuery!==``;return g`
|
|
1457
1461
|
<div class="list-search">
|
|
1458
1462
|
<input
|
|
1459
1463
|
class="list-search-input"
|
|
@@ -1470,12 +1474,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1470
1474
|
>
|
|
1471
1475
|
${e?g`<button class="list-search-clear" title="Clear search" aria-label="Clear search" @click=${()=>{this.searchQuery=``}}>×</button>`:null}
|
|
1472
1476
|
</div>
|
|
1473
|
-
`}renderAdd(){return this.onAdd===void 0?null:g`<button class="section-add" title="Add project" aria-label="Add project" @click=${e=>{e.stopPropagation(),this.onAdd?.()}}><span aria-hidden="true">+</span><span class="section-add-label">Add project</span></button>`}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>`}renderActivity(e){let t=this.statusSnapshot?.projects[e.id],n=
|
|
1477
|
+
`}renderAdd(){return this.onAdd===void 0?null:g`<button class="section-add" title="Add project" aria-label="Add project" @click=${e=>{e.stopPropagation(),this.onAdd?.()}}><span aria-hidden="true">+</span><span class="section-add-label">Add project</span></button>`}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>`}renderActivity(e){let t=this.statusSnapshot?.projects[e.id],n=nx(t),r=rx(t)?`Unread sessions in this project`:void 0;return ox(n,n===`terminal`?`Project terminal active`:`Project active`,r)}openMenu(e,t){this.menuStyle=Zb(t,{constrainTo:`viewport`}),this.openMenuProjectId=e}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=Zb(t,{constrainTo:`viewport`}),this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`Close ${e.name}?\n\nThis only removes it from PI WEB; it will not change the project folder.`)&&this.onClose?.(e)}static{this.styles=ig}};H([b({attribute:!1})],Tx.prototype,`projects`,void 0),H([x()],Tx.prototype,`searchQuery`,void 0),H([b({attribute:!1})],Tx.prototype,`selected`,void 0),H([b({attribute:!1})],Tx.prototype,`statusSnapshot`,void 0),H([b({type:Boolean,reflect:!0})],Tx.prototype,`collapsible`,void 0),H([b({type:Boolean,reflect:!0})],Tx.prototype,`collapsed`,void 0),H([b({type:Boolean})],Tx.prototype,`tiles`,void 0),H([b({attribute:!1})],Tx.prototype,`onAdd`,void 0),H([b({attribute:!1})],Tx.prototype,`onSelect`,void 0),H([b({attribute:!1})],Tx.prototype,`onClose`,void 0),H([b({attribute:!1})],Tx.prototype,`onToggleCollapsed`,void 0),H([b({attribute:!1})],Tx.prototype,`onFocusPreviousSection`,void 0),H([b({attribute:!1})],Tx.prototype,`onFocusNextSection`,void 0),H([b({attribute:!1})],Tx.prototype,`onCancelKeyboardNavigation`,void 0),H([x()],Tx.prototype,`openMenuProjectId`,void 0),H([x()],Tx.prototype,`menuStyle`,void 0),Tx=H([y(`project-list`)],Tx);async function Ex(e,t=Dx()){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 Dx(){let e=e=>Ax(e),t=kx();return t===void 0?{isSecureContext:Ox(),fallbackWriteText:e}:{isSecureContext:Ox(),writeText:t,fallbackWriteText:e}}function Ox(){return typeof window<`u`&&window.isSecureContext}function kx(){if(!(typeof navigator>`u`||!(`clipboard`in navigator)))return navigator.clipboard.writeText.bind(navigator.clipboard)}function Ax(e){if(typeof document>`u`)return!1;let t=document.activeElement,n=document.getSelection(),r=n===null?[]:jx(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(),Mx(n,r),Nx(t)}}function jx(e){let t=[];for(let n=0;n<e.rangeCount;n+=1)t.push(e.getRangeAt(n));return t}function Mx(e,t){if(e!==null)try{e.removeAllRanges();for(let n of t)e.addRange(n)}catch{}}function Nx(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))try{e.focus({preventScroll:!0})}catch{e.focus()}}function Px(e=[]){return e.map((e,t)=>g`${t===0?null:g`<span class="workspace-label-separator">·</span>`}${Fx(e)}`)}function Fx(e){if(e.type===`render`)return g`<span class="workspace-label-render">${e.render()}</span>`;if(e.type===`link`&&Ix(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 Ix(e){let t=e.trim().toLowerCase();return t!==``&&!t.startsWith(`javascript:`)&&!t.startsWith(`data:`)}var W=class extends v{constructor(...e){super(...e),this.workspaces=[],this.machineId=`local`,this.collapsible=!1,this.collapsed=!1,this.tiles=!1,this.workspaceLabelItems=()=>[],this.deletingWorkspaceIds=[],this.gestures=new Jb((e,t)=>{this.openMenu(e,t)}),this.menuStyle=``,this.trustByWorkspaceId={},this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuWorkspaceId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),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),this.shouldRevealSelectedRow(e)&&this.scrollSelectedIntoView()}shouldRevealSelectedRow(e){return this.collapsed?!1:e.has(`collapsed`)?!0:e.has(`selected`)&&e.get(`selected`)?.id!==this.selected?.id}async focusSelectedOrFirst(){return await this.updateComplete,dx(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
|
|
1474
1478
|
<section>
|
|
1475
1479
|
<h2>${this.renderHeading()}</h2>
|
|
1476
1480
|
${this.collapsed?null:g`
|
|
1477
1481
|
<div class="list-body ${this.tiles?`tiles`:``}">
|
|
1478
|
-
${this.workspaces.map(e=>{let t=
|
|
1482
|
+
${this.workspaces.map(e=>{let t=Lx(e),n=this.workspaceLabelItems(e);return g`
|
|
1479
1483
|
<div
|
|
1480
1484
|
class=${`action-row workspace-row ${this.selected?.id===e.id?`selected`:``}`}
|
|
1481
1485
|
title=${t}
|
|
@@ -1500,18 +1504,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1500
1504
|
</div>
|
|
1501
1505
|
`}
|
|
1502
1506
|
</section>
|
|
1503
|
-
`}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=this.statusSnapshot?.workspaces[e.id],n=
|
|
1507
|
+
`}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=this.statusSnapshot?.workspaces[e.id],n=nx(t),r=rx(t)?`Unread sessions in this workspace`:void 0;return ox(n,n===`terminal`?`Workspace terminal active`:`Workspace active`,r)}renderWorkspaceMain(e,t,n){return g`
|
|
1504
1508
|
<span class="workspace-primary">
|
|
1505
1509
|
<span class="workspace-primary-label">${e}</span>
|
|
1506
1510
|
${this.isDeleting(n)?g`<span class="workspace-status">Deleting…</span>`:null}
|
|
1507
1511
|
</span>
|
|
1508
1512
|
${t.length===0?null:g`
|
|
1509
1513
|
<small class="workspace-secondary">
|
|
1510
|
-
<span class="workspace-label">${
|
|
1514
|
+
<span class="workspace-label">${Px(t)}</span>
|
|
1511
1515
|
</small>
|
|
1512
1516
|
`}
|
|
1513
1517
|
${this.renderActivity(n)}
|
|
1514
|
-
`}renderWorkspaceMenu(e,t,n){let r=this.openMenuWorkspaceId===n.id,i=
|
|
1518
|
+
`}renderWorkspaceMenu(e,t,n){let r=this.openMenuWorkspaceId===n.id,i=Rx(n.id);return g`
|
|
1515
1519
|
<div class="action-menu">
|
|
1516
1520
|
<button
|
|
1517
1521
|
class="action-menu-toggle"
|
|
@@ -1535,7 +1539,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1535
1539
|
<button class="danger" title=${t?`Workspace removal in progress`:n} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?`Removing…`:n}</button>
|
|
1536
1540
|
`:null}
|
|
1537
1541
|
</div>
|
|
1538
|
-
`}renderTrustToggle(e){let t=this.trustByWorkspaceId[e.id],n=t?.loading===!0||t?.saving===!0,r=`${
|
|
1542
|
+
`}renderTrustToggle(e){let t=this.trustByWorkspaceId[e.id],n=t?.loading===!0||t?.saving===!0,r=`${Rx(e.id)}-trusted`;return g`
|
|
1539
1543
|
<div class="workspace-menu-trust">
|
|
1540
1544
|
<div class="workspace-menu-trust-row">
|
|
1541
1545
|
<label for=${r}>
|
|
@@ -1565,7 +1569,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1565
1569
|
${t.length===0?null:g`
|
|
1566
1570
|
<div class="workspace-detail-row">
|
|
1567
1571
|
<dt>Details</dt>
|
|
1568
|
-
<dd><span class="workspace-label">${
|
|
1572
|
+
<dd><span class="workspace-label">${Px(t)}</span></dd>
|
|
1569
1573
|
</div>
|
|
1570
1574
|
`}
|
|
1571
1575
|
</dl>
|
|
@@ -1573,16 +1577,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1573
1577
|
<button type="button" class="detail-copy" title=${i} aria-label=${i} @click=${()=>{this.copyDetail(e,t)}}>
|
|
1574
1578
|
<span aria-hidden="true">${r?`✓`:`⧉`}</span>
|
|
1575
1579
|
</button>
|
|
1576
|
-
`}async copyDetail(e,t){await
|
|
1580
|
+
`}async copyDetail(e,t){await Ex(t)&&(this.copiedDetailKey=e,window.setTimeout(()=>{this.copiedDetailKey===e&&(this.copiedDetailKey=void 0)},1200))}delete(e){this.isDeleting(e)||(this.openMenuWorkspaceId=void 0,this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}openMenu(e,t){this.menuStyle=Zb(t,{constrainTo:`viewport`}),this.openMenuWorkspaceId=e}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuStyle=Zb(t,{constrainTo:`viewport`}),this.openMenuWorkspaceId=e;let n=this.workspaces.find(t=>t.id===e);n!==void 0&&this.loadTrust(n)}handleWorkspaceKeydown(e,t){if(e.key===`Escape`&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}ux(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=[ig,h`
|
|
1577
1581
|
.workspace-menu-trust { display: flex; flex-direction: column; gap: 3px; padding: var(--pi-space-2) var(--pi-space-1); }
|
|
1578
1582
|
.workspace-menu-trust-row { display: flex; align-items: center; justify-content: space-between; gap: var(--pi-space-4); }
|
|
1579
1583
|
.workspace-menu-trust label { display: flex; align-items: center; gap: var(--pi-space-3); cursor: pointer; }
|
|
1580
1584
|
.workspace-menu-trust input { cursor: pointer; }
|
|
1581
1585
|
.workspace-trust-link { color: var(--pi-accent); font-size: var(--pi-text-xs); text-align: right; white-space: nowrap; }
|
|
1582
1586
|
.workspace-trust-error { color: var(--pi-danger, #c0392b); line-height: 1.3; }
|
|
1583
|
-
`]}};H([b({attribute:!1})],W.prototype,`workspaces`,void 0),H([b({attribute:!1})],W.prototype,`selected`,void 0),H([b({attribute:!1})],W.prototype,`machineId`,void 0),H([b({type:Boolean,reflect:!0})],W.prototype,`collapsible`,void 0),H([b({type:Boolean,reflect:!0})],W.prototype,`collapsed`,void 0),H([b({type:Boolean})],W.prototype,`tiles`,void 0),H([b({attribute:!1})],W.prototype,`workspaceLabelItems`,void 0),H([b({attribute:!1})],W.prototype,`statusSnapshot`,void 0),H([b({attribute:!1})],W.prototype,`deletingWorkspaceIds`,void 0),H([b({attribute:!1})],W.prototype,`onSelect`,void 0),H([b({attribute:!1})],W.prototype,`onDelete`,void 0),H([b({attribute:!1})],W.prototype,`onToggleCollapsed`,void 0),H([b({attribute:!1})],W.prototype,`onFocusPreviousSection`,void 0),H([b({attribute:!1})],W.prototype,`onFocusNextSection`,void 0),H([b({attribute:!1})],W.prototype,`onCancelKeyboardNavigation`,void 0),H([x()],W.prototype,`openMenuWorkspaceId`,void 0),H([x()],W.prototype,`menuStyle`,void 0),H([x()],W.prototype,`copiedDetailKey`,void 0),H([x()],W.prototype,`trustByWorkspaceId`,void 0),W=H([y(`workspace-list`)],W);function
|
|
1584
|
-
`).toLowerCase()}function
|
|
1585
|
-
`).toLowerCase()}function
|
|
1587
|
+
`]}};H([b({attribute:!1})],W.prototype,`workspaces`,void 0),H([b({attribute:!1})],W.prototype,`selected`,void 0),H([b({attribute:!1})],W.prototype,`machineId`,void 0),H([b({type:Boolean,reflect:!0})],W.prototype,`collapsible`,void 0),H([b({type:Boolean,reflect:!0})],W.prototype,`collapsed`,void 0),H([b({type:Boolean})],W.prototype,`tiles`,void 0),H([b({attribute:!1})],W.prototype,`workspaceLabelItems`,void 0),H([b({attribute:!1})],W.prototype,`statusSnapshot`,void 0),H([b({attribute:!1})],W.prototype,`deletingWorkspaceIds`,void 0),H([b({attribute:!1})],W.prototype,`onSelect`,void 0),H([b({attribute:!1})],W.prototype,`onDelete`,void 0),H([b({attribute:!1})],W.prototype,`onToggleCollapsed`,void 0),H([b({attribute:!1})],W.prototype,`onFocusPreviousSection`,void 0),H([b({attribute:!1})],W.prototype,`onFocusNextSection`,void 0),H([b({attribute:!1})],W.prototype,`onCancelKeyboardNavigation`,void 0),H([x()],W.prototype,`openMenuWorkspaceId`,void 0),H([x()],W.prototype,`menuStyle`,void 0),H([x()],W.prototype,`copiedDetailKey`,void 0),H([x()],W.prototype,`trustByWorkspaceId`,void 0),W=H([y(`workspace-list`)],W);function Lx(e){return`${e.label}${e.isMain?` · main`:``}`}function Rx(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}function zx(e){return e.slice(-8)}function Bx(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?zx(e.id):e.firstMessage}function Vx(e){return e.replace(/[/\\]+$/u,``)}function Hx(e){return[e.id,e.path].join(`
|
|
1588
|
+
`).toLowerCase()}function Ux(e){return[e.name??``,e.firstMessage].join(`
|
|
1589
|
+
`).toLowerCase()}function Wx(e){return e.length>=6&&/^[0-9a-f-]+$/.test(e)&&/[0-9]/.test(e)}function Gx(e,t){let n=Jx(t);if(n.length===0)return!0;let r=Ux(e),i=Hx(e);return n.every(e=>Wx(e)?r.includes(e)||i.includes(e):r.includes(e)||i.includes(e)||Yx(e,r))}function Kx(e,t){if(Jx(t).length===0)return[...e];let n=new Set;return e.forEach((r,i)=>{if(!Gx(r.session,t))return;n.add(i);let a=r.depth-1;for(let t=i-1;t>=0&&a>=0;--t)e[t]?.depth===a&&(n.add(t),--a)}),e.filter((e,t)=>n.has(t))}function qx(e,t){return e>=5||t.trim()!==``}function Jx(e){return e.trim().toLowerCase().split(/\s+/u).filter(Boolean)}function Yx(e,t){let n=0;for(let r of t)if(r===e[n]&&(n+=1),n===e.length)return!0;return e.length===0}function Xx(e,t,n){if(t.size===0)return[...e];let r=[],i;for(let a of e){if(a.depth===0){i=a.hasMissingParent?void 0:a,r.push(a);continue}(i===void 0||!t.has(n(i)))&&r.push(a)}return r}var Zx=`parent unavailable`,Qx=`Parent session is not available in this workspace`,G=class extends v{constructor(...e){super(...e),this.sessions=[],this.statuses={},this.activities={},this.sending={},this.unreadSessionIds=new Set,this.startingCount=0,this.canStart=!1,this.collapsible=!1,this.collapsed=!1,this.menuStyle=``,this.archivedExpanded=!1,this.collapsedSubtreeRoots=new Set,this.searchQuery=``,this.selectionScopes=new Set,this.longPress=new qb({onLongPress:()=>{this.onRowHeld()},setTimer:(e,t)=>window.setTimeout(e,t),clearTimer:e=>{window.clearTimeout(e)}}),this.selectedSessionIds=new Set,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has(`sessions`)&&(this.openMenuSessionId!==void 0&&!this.sessions.some(e=>e.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),this.sessions.some(e=>e.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has(`collapsed`)&&this.collapsed&&(this.openMenuSessionId=void 0);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}this.shouldRevealSelectedRow(e)&&this.scrollSelectedIntoView()}shouldRevealSelectedRow(e){if(this.collapsed)return!1;if(e.has(`collapsed`))return!0;if(!e.has(`selected`))return!1;let t=e.get(`selected`);return t?.id!==this.selected?.id||t?.archived===!0&&this.selected?.archived!==!0}async focusSelectedOrFirst(){return await this.updateComplete,dx(this.renderRoot,{fallbackSelector:`.section-toggle, h2 button:not([disabled])`})}render(){let e=oS(this.sessions),t=new Set(e.map(e=>e.session.id)),n=e.map(e=>e.session).filter(e=>eS(e)===`current`),r=sS(this.sessions.filter(e=>e.archived===!0&&!t.has(e.id)),this.sessions),i=nS(this.sessions),a=$x(n,this.unreadSessionIds),o=this.searchQuery.trim()!==``,s=Kx(e,this.searchQuery),c=o?s:Xx(s,this.collapsedSubtreeRoots,e=>e.session.path),l=Kx(r,this.searchQuery),u=this.archivedExpanded||o&&l.length>0,d=o&&s.length===0&&l.length===0;return g`
|
|
1586
1590
|
<section>
|
|
1587
1591
|
${this.renderHeading(e.length+r.length,n,a)}
|
|
1588
1592
|
${this.collapsed?null:g`
|
|
@@ -1606,7 +1610,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1606
1610
|
</div>
|
|
1607
1611
|
`}
|
|
1608
1612
|
</section>
|
|
1609
|
-
`}renderSearch(e){if(!
|
|
1613
|
+
`}renderSearch(e){if(!qx(e,this.searchQuery))return null;let t=this.searchQuery!==``;return g`
|
|
1610
1614
|
<div class="session-search">
|
|
1611
1615
|
<input
|
|
1612
1616
|
class="session-search-input"
|
|
@@ -1631,7 +1635,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1631
1635
|
${this.renderCleanupButton()}
|
|
1632
1636
|
${this.renderStartButton()}
|
|
1633
1637
|
</h2>
|
|
1634
|
-
`;let r=this.selected===void 0?`No session selected`:
|
|
1638
|
+
`;let r=this.selected===void 0?`No session selected`:Bx(this.selected),i=this.selected?.path??r;return g`
|
|
1635
1639
|
<h2>
|
|
1636
1640
|
<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>
|
|
1637
1641
|
${this.renderCurrentSelectionButton(t)}
|
|
@@ -1668,7 +1672,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1668
1672
|
<button class="danger" title="Permanently delete selected archived sessions" ?disabled=${t.length===0} @click=${()=>{this.confirmDeleteSelectedArchived()}}>Delete</button>
|
|
1669
1673
|
</div>
|
|
1670
1674
|
</div>
|
|
1671
|
-
`}renderSelectionControls(e,t){let n=this.selectedSessions(e).length;return n===0?g`<button @click=${()=>{this.selectVisibleSessions(t)}}>Select visible</button>`:g`<button @click=${()=>{this.clearSelection(e)}}>Clear selected (${n})</button>`}renderSession(e,t,n){let{session:r}=e,i=Math.min(e.depth,2),a=e.depth===0&&t>0,o
|
|
1675
|
+
`}renderSelectionControls(e,t){let n=this.selectedSessions(e).length;return n===0?g`<button @click=${()=>{this.selectVisibleSessions(t)}}>Select visible</button>`:g`<button @click=${()=>{this.clearSelection(e)}}>Clear selected (${n})</button>`}renderSession(e,t,n){let{session:r}=e,i=Math.min(e.depth,2),a=e.depth===0&&t>0,o=eS(r)===n,s=this.selectionScopes.has(n),c=s&&o,l=c&&this.selectedSessionIds.has(r.id),u=this.statuses[r.id],d=this.activities[r.id],f=rS(r,u,d,this.sending[r.id]===!0),p=iS(r,this.unreadSessionIds),m=nf(r,u),ee=rf(r,u);return g`
|
|
1672
1676
|
<div
|
|
1673
1677
|
class="action-row ${this.selected?.id===r.id?`selected`:``} ${l?`bulk-selected`:``} ${r.archived===!0?`archived`:``} ${s?`selecting`:``} ${p?`unread`:``} ${a?`has-subtree-toggle`:``} ${e.depth>0?`is-child`:``}"
|
|
1674
1678
|
style=${`--depth:${String(i)}`}
|
|
@@ -1679,7 +1683,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1679
1683
|
absolutely positioned against the row, so moving it out keeps its
|
|
1680
1684
|
place on screen while letting the primary region be a real button
|
|
1681
1685
|
without nesting one control inside another. -->
|
|
1682
|
-
${c?g`<input class="session-checkbox" type="checkbox" aria-label=${`Select ${
|
|
1686
|
+
${c?g`<input class="session-checkbox" type="checkbox" aria-label=${`Select ${Bx(r)}`} .checked=${l} @click=${e=>{e.stopPropagation()}} @change=${()=>{this.toggleSelected(r.id)}}>`:null}
|
|
1683
1687
|
${a?this.renderSubtreeToggle(e,n):null}
|
|
1684
1688
|
<button
|
|
1685
1689
|
type="button"
|
|
@@ -1692,7 +1696,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1692
1696
|
@contextmenu=${e=>{this.selectionScopes.has(n)&&e.preventDefault()}}
|
|
1693
1697
|
@click=${()=>{this.longPress.consumeSuppressedClick()||this.activateSessionRow(r,n)}}
|
|
1694
1698
|
>
|
|
1695
|
-
<span class="action-name-line"><span class="action-name" dir="auto">${this.renderRowMarker(e)}${
|
|
1699
|
+
<span class="action-name-line"><span class="action-name" dir="auto">${this.renderRowMarker(e)}${Bx(r)}</span>${this.renderRowBadges(e)}</span><small>${this.renderSessionMetaPrefix(r,u,d)}${String(r.messageCount)} messages</small>
|
|
1696
1700
|
${this.renderActivity(f,p)}
|
|
1697
1701
|
</button>
|
|
1698
1702
|
<div class="action-menu">
|
|
@@ -1722,14 +1726,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1722
1726
|
type="button"
|
|
1723
1727
|
class="subtree-toggle"
|
|
1724
1728
|
title=${n?`Show subagents`:`Hide subagents`}
|
|
1725
|
-
aria-label=${n?`Expand subagents under ${
|
|
1729
|
+
aria-label=${n?`Expand subagents under ${Bx(e.session)}`:`Collapse subagents under ${Bx(e.session)}`}
|
|
1726
1730
|
aria-expanded=${n?`false`:`true`}
|
|
1727
1731
|
@pointerdown=${e=>{e.stopPropagation()}}
|
|
1728
1732
|
@click=${t=>{t.stopPropagation(),this.toggleSubtreeCollapsed(e.session.path)}}
|
|
1729
1733
|
>
|
|
1730
1734
|
<span class="subtree-chevron ${n?`collapsed`:``}" aria-hidden="true">▾</span>
|
|
1731
1735
|
</button>
|
|
1732
|
-
`}toggleSubtreeCollapsed(e){let t=new Set(this.collapsedSubtreeRoots);t.has(e)?t.delete(e):t.add(e),this.collapsedSubtreeRoots=t}renderRowMarker(e){return e.hasMissingParent?g`<span class="tree-marker orphan-marker" title=${
|
|
1736
|
+
`}toggleSubtreeCollapsed(e){let t=new Set(this.collapsedSubtreeRoots);t.has(e)?t.delete(e):t.add(e),this.collapsedSubtreeRoots=t}renderRowMarker(e){return e.hasMissingParent?g`<span class="tree-marker orphan-marker" title=${Qx} aria-label=${Zx}>↳</span>`:e.depth>0?g`<span class="tree-marker">↳</span>`:null}renderRowBadges(e){return e.depth<=2?null:g`<span class="row-badges"><span class="badge">depth ${e.depth}</span></span>`}handleSessionKeydown(e,t,n){ux(e,{activate:()=>{this.activateSessionRow(t,n)},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){if(this.selectionScopes.has(t)&&eS(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}confirmArchiveWithDescendants(e,t){let n=t===1?`descendant session`:`descendant sessions`;confirm(`Archive “${Bx(e)}” and ${String(t)} ${n}?`)&&this.onArchiveWithDescendants?.(e)}promptRename(e){let t=e.name??``,n=prompt(`Name for this session:`,t);if(n===null)return;let r=n.trim();r===``||r===t||this.onRename?.(e,r)}confirmDeleteArchived(e){confirm(`Permanently delete archived session “${Bx(e)}”? This cannot be undone.`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){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=tS(this.selectedSessionIds,e.map(e=>e.id)),this.onDeleteArchivedMany?.(e))}markSelectedCurrentRead(){let e=this.selectedSessions(`current`).filter(e=>this.unreadSessionIds.has(e.id));e.length!==0&&this.onMarkReadMany?.(e)}archiveSelectedCurrent(){let e=this.selectedSessions(`current`).filter(e=>nf(e,this.statuses[e.id]));this.selectedSessionIds=tS(this.selectedSessionIds,e.map(e=>e.id)),this.onArchiveMany?.(e)}startRowHold(e,t,n){e.pointerType!==`mouse`&&(this.heldSession={session:t,scope:n},this.longPress.start(e))}onRowHeld(){let e=this.heldSession;e!==void 0&&(this.heldSession=void 0,this.selectionScopes.has(e.scope)||(this.selectionScopes=new Set([...this.selectionScopes,e.scope])),this.toggleSelected(e.session.id))}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=>eS(t)===e).map(e=>e.id);this.selectedSessionIds=tS(this.selectedSessionIds,t)}toggleSelected(e){let t=new Set(this.selectedSessionIds);t.has(e)?t.delete(e):t.add(e),this.selectedSessionIds=t}selectVisibleSessions(e){this.selectedSessionIds=new Set([...this.selectedSessionIds,...e.map(e=>e.id)])}selectedSessions(e){return this.sessions.filter(t=>this.selectedSessionIds.has(t.id)&&eS(t)===e)}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=Zb(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 rf(e,t)?n?.phase===`active`?`creating · `:n?.phase===`error`?`error · `:`new · `:e.archived===!0?`read-only · `:``}renderActivity(e,t){return ax(e,t?`Unread session activity`:void 0)}static{this.styles=[ig,eg,h`
|
|
1733
1737
|
h2 { min-height: 30px; gap: var(--pi-space-2); }
|
|
1734
1738
|
/* The shared heading spreads its children across the full width, which
|
|
1735
1739
|
floats the checkbox, the unread count, Clean up and the start button
|
|
@@ -1814,7 +1818,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1814
1818
|
.action-menu-toggle { min-width: 36px; min-height: 36px; }
|
|
1815
1819
|
.bulk-row button { min-height: 36px; }
|
|
1816
1820
|
}
|
|
1817
|
-
`]}};H([b({attribute:!1})],G.prototype,`sessions`,void 0),H([b({attribute:!1})],G.prototype,`statuses`,void 0),H([b({attribute:!1})],G.prototype,`activities`,void 0),H([b({attribute:!1})],G.prototype,`sending`,void 0),H([b({attribute:!1})],G.prototype,`unreadSessionIds`,void 0),H([b({attribute:!1})],G.prototype,`selected`,void 0),H([b({type:Number})],G.prototype,`startingCount`,void 0),H([b({type:Boolean})],G.prototype,`canStart`,void 0),H([b({type:Boolean,reflect:!0})],G.prototype,`collapsible`,void 0),H([b({type:Boolean,reflect:!0})],G.prototype,`collapsed`,void 0),H([b({attribute:!1})],G.prototype,`onSelect`,void 0),H([b({attribute:!1})],G.prototype,`onStart`,void 0),H([b({attribute:!1})],G.prototype,`onToggleCollapsed`,void 0),H([b({attribute:!1})],G.prototype,`onArchivedCollapsed`,void 0),H([b({attribute:!1})],G.prototype,`onFocusPreviousSection`,void 0),H([b({attribute:!1})],G.prototype,`onFocusNextSection`,void 0),H([b({attribute:!1})],G.prototype,`onCancelKeyboardNavigation`,void 0),H([b({attribute:!1})],G.prototype,`onArchive`,void 0),H([b({attribute:!1})],G.prototype,`onArchiveWithDescendants`,void 0),H([b({attribute:!1})],G.prototype,`onArchiveMany`,void 0),H([b({attribute:!1})],G.prototype,`onRestore`,void 0),H([b({attribute:!1})],G.prototype,`onDelete`,void 0),H([b({attribute:!1})],G.prototype,`onDeleteArchived`,void 0),H([b({attribute:!1})],G.prototype,`onDeleteArchivedMany`,void 0),H([b({attribute:!1})],G.prototype,`onDetachParent`,void 0),H([b({attribute:!1})],G.prototype,`onRename`,void 0),H([b({attribute:!1})],G.prototype,`onMarkRead`,void 0),H([b({attribute:!1})],G.prototype,`onMarkReadMany`,void 0),H([b({attribute:!1})],G.prototype,`onReload`,void 0),H([b({attribute:!1})],G.prototype,`onOpenTree`,void 0),H([b({attribute:!1})],G.prototype,`onCleanup`,void 0),H([x()],G.prototype,`openMenuSessionId`,void 0),H([x()],G.prototype,`menuStyle`,void 0),H([x()],G.prototype,`archivedExpanded`,void 0),H([x()],G.prototype,`collapsedSubtreeRoots`,void 0),H([x()],G.prototype,`searchQuery`,void 0),H([x()],G.prototype,`selectionScopes`,void 0),H([x()],G.prototype,`selectedSessionIds`,void 0),G=H([y(`session-list`)],G);function
|
|
1821
|
+
`]}};H([b({attribute:!1})],G.prototype,`sessions`,void 0),H([b({attribute:!1})],G.prototype,`statuses`,void 0),H([b({attribute:!1})],G.prototype,`activities`,void 0),H([b({attribute:!1})],G.prototype,`sending`,void 0),H([b({attribute:!1})],G.prototype,`unreadSessionIds`,void 0),H([b({attribute:!1})],G.prototype,`selected`,void 0),H([b({type:Number})],G.prototype,`startingCount`,void 0),H([b({type:Boolean})],G.prototype,`canStart`,void 0),H([b({type:Boolean,reflect:!0})],G.prototype,`collapsible`,void 0),H([b({type:Boolean,reflect:!0})],G.prototype,`collapsed`,void 0),H([b({attribute:!1})],G.prototype,`onSelect`,void 0),H([b({attribute:!1})],G.prototype,`onStart`,void 0),H([b({attribute:!1})],G.prototype,`onToggleCollapsed`,void 0),H([b({attribute:!1})],G.prototype,`onArchivedCollapsed`,void 0),H([b({attribute:!1})],G.prototype,`onFocusPreviousSection`,void 0),H([b({attribute:!1})],G.prototype,`onFocusNextSection`,void 0),H([b({attribute:!1})],G.prototype,`onCancelKeyboardNavigation`,void 0),H([b({attribute:!1})],G.prototype,`onArchive`,void 0),H([b({attribute:!1})],G.prototype,`onArchiveWithDescendants`,void 0),H([b({attribute:!1})],G.prototype,`onArchiveMany`,void 0),H([b({attribute:!1})],G.prototype,`onRestore`,void 0),H([b({attribute:!1})],G.prototype,`onDelete`,void 0),H([b({attribute:!1})],G.prototype,`onDeleteArchived`,void 0),H([b({attribute:!1})],G.prototype,`onDeleteArchivedMany`,void 0),H([b({attribute:!1})],G.prototype,`onDetachParent`,void 0),H([b({attribute:!1})],G.prototype,`onRename`,void 0),H([b({attribute:!1})],G.prototype,`onMarkRead`,void 0),H([b({attribute:!1})],G.prototype,`onMarkReadMany`,void 0),H([b({attribute:!1})],G.prototype,`onReload`,void 0),H([b({attribute:!1})],G.prototype,`onOpenTree`,void 0),H([b({attribute:!1})],G.prototype,`onCleanup`,void 0),H([x()],G.prototype,`openMenuSessionId`,void 0),H([x()],G.prototype,`menuStyle`,void 0),H([x()],G.prototype,`archivedExpanded`,void 0),H([x()],G.prototype,`collapsedSubtreeRoots`,void 0),H([x()],G.prototype,`searchQuery`,void 0),H([x()],G.prototype,`selectionScopes`,void 0),H([x()],G.prototype,`selectedSessionIds`,void 0),G=H([y(`session-list`)],G);function $x(e,t){return e.filter(e=>iS(e,t)).length}function eS(e){return e.archived===!0?`archived`:`current`}function tS(e,t){let n=new Set(t);return new Set([...e].filter(e=>!n.has(e)))}function nS(e){let t=new Map;for(let n of e){if(n.parentSessionPath===void 0)continue;let e=Vx(n.parentSessionPath),r=t.get(e)??[];r.push(n),t.set(e,r)}let n=(e,r)=>{let i=Vx(e.path);if(r.has(i))return 0;let a=new Set(r);a.add(i);let o=0;for(let e of t.get(i)??[])a.has(Vx(e.path))||(e.archived!==!0&&(o+=1),o+=n(e,a));return o};return new Map(e.map(e=>[e.id,n(e,new Set)]))}function rS(e,t,n,r){if(Fc(e)||e.archived===!0)return;if(r)return`sending`;let i=xm(t,n);if(!(i===`working`&&n?.startup===!0&&!cS(t)))return i}function iS(e,t){return Fc(e)||e.archived===!0?!1:t.has(e.id)}function aS(e){return new Map(e.map(e=>[Vx(e.path),e]))}function oS(e){let t=aS(e),n=new Set;for(let r of e){if(r.archived===!0)continue;n.add(r.id);let e=r.parentSessionPath===void 0?void 0:Vx(r.parentSessionPath),i=new Set([Vx(r.path)]);for(;e!==void 0&&!i.has(e);){i.add(e);let r=t.get(e);if(r===void 0)break;n.add(r.id),e=r.parentSessionPath===void 0?void 0:Vx(r.parentSessionPath)}}return sS(e.filter(e=>n.has(e.id)))}function sS(e,t=e){let n=aS(e),r=t===e?n:aS(t),i=new Map,a=[];for(let t of e){let e=t.parentSessionPath,r=e===void 0?void 0:n.get(Vx(e));if(r===void 0){a.push(t);continue}let o=Vx(r.path),s=i.get(o)??[];s.push(t),i.set(o,s)}let o=[],s=(e,t,n)=>{let a=Vx(e.path);if(n.has(a))return;let c=e.parentSessionPath;o.push({session:e,depth:t,hasMissingParent:c!==void 0&&!r.has(Vx(c))});let l=new Set(n);l.add(a);for(let e of i.get(a)??[])s(e,t+1,l)};for(let e of a)s(e,0,new Set);return o}function cS(e){return e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}var lS=`button, input, select, textarea, a[href], [tabindex]`,uS=class extends v{constructor(...e){super(...e),this.busy=!1,this.handleKeyDown=e=>{if(e.key===`Tab`){this.trapTabFocus(e);return}if(e.key===`Escape`){if(e.preventDefault(),e.stopPropagation(),this.busy){this.onBusyEscape?.();return}this.onClose?.()}}}connectedCallback(){super.connectedCallback(),this.modalRegistration=Rh({element:this,paintElement:gS(this),focus:()=>{this.focusDialogContent()},onTopChange:()=>{this.requestUpdate()}}),this.addEventListener(`keydown`,this.handleKeyDown)}disconnectedCallback(){this.removeEventListener(`keydown`,this.handleKeyDown);let e=this.modalRegistration;this.modalRegistration=void 0,super.disconnectedCallback(),e?.unregister()}firstUpdated(){this.focusDialog()}focusDialog(){this.modalRegistration?.focus()}focusDialogContent(){let e=this.initialFocusTarget();e!==null&&Yh(e)||this.section!==void 0&&Yh(this.section)}render(){let e=this.modalRegistration?.isTop===!0;return g`
|
|
1818
1822
|
<div class="backdrop" @mousedown=${e=>{this.handleBackdropMouseDown(e)}}>
|
|
1819
1823
|
<section
|
|
1820
1824
|
role="dialog"
|
|
@@ -1825,7 +1829,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1825
1829
|
tabindex="-1"
|
|
1826
1830
|
><slot></slot></section>
|
|
1827
1831
|
</div>
|
|
1828
|
-
`}initialFocusTarget(){if(this.initialFocus===void 0)return null;try{return this.querySelector(this.initialFocus)}catch{return null}}trapTabFocus(e){let t=
|
|
1832
|
+
`}initialFocusTarget(){if(this.initialFocus===void 0)return null;try{return this.querySelector(this.initialFocus)}catch{return null}}trapTabFocus(e){let t=dS(this);if(t.length===0){e.preventDefault(),this.section?.focus();return}let n=Xh(this.ownerDocument),r=t.findIndex(e=>e===n);if(r===-1){e.preventDefault(),(e.shiftKey?t.at(-1):t[0])?.focus();return}let i=!e.shiftKey&&r===t.length-1,a=e.shiftKey&&r===0;!i&&!a||(e.preventDefault(),(e.shiftKey?t.at(-1):t[0])?.focus())}handleBackdropMouseDown(e){e.target!==e.currentTarget||this.busy||this.onClose?.()}static{this.styles=h`
|
|
1829
1833
|
/* Host dialogs tune this shell with custom properties (defaults match a
|
|
1830
1834
|
centered 720px dialog):
|
|
1831
1835
|
--modal-surface-place-items backdrop grid alignment (default center)
|
|
@@ -1836,7 +1840,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1836
1840
|
:host { display: block; width: 100%; height: 100%; }
|
|
1837
1841
|
.backdrop { box-sizing: border-box; width: 100%; height: 100%; display: grid; place-items: var(--modal-surface-place-items, center); padding: var(--modal-surface-backdrop-padding, 0); background: var(--pi-overlay); overflow: hidden; }
|
|
1838
1842
|
section[role="dialog"] { box-sizing: border-box; width: var(--modal-surface-width, min(720px, 100%)); max-width: var(--modal-surface-max-width, 100%); height: var(--modal-surface-height, auto); max-height: var(--modal-surface-max-height, 100%); min-height: var(--modal-surface-min-height, auto); display: flex; flex-direction: column; border: var(--modal-surface-border, 1px solid var(--pi-border)); border-radius: var(--modal-surface-radius, 12px); background: var(--pi-bg); box-shadow: var(--modal-surface-shadow, 0 20px 60px var(--pi-shadow-strong)); overflow: hidden; }
|
|
1839
|
-
`}};H([b({attribute:!1})],
|
|
1843
|
+
`}};H([b({attribute:!1})],uS.prototype,`onClose`,void 0),H([b({type:Boolean})],uS.prototype,`busy`,void 0),H([b({attribute:!1})],uS.prototype,`onBusyEscape`,void 0),H([b({attribute:!1})],uS.prototype,`initialFocus`,void 0),H([b({attribute:!1})],uS.prototype,`label`,void 0),H([S(`section`)],uS.prototype,`section`,void 0),uS=H([y(`modal-surface`)],uS);function dS(e){let t=[],n=e=>{e instanceof HTMLElement&&mS(e)&&t.push(e);for(let t of hS(e))n(t)};for(let t of hS(e))n(t);return fS(t)}function fS(e){let t=new Map;for(let n of e){let e=pS(n);if(e===null)continue;let r=t.get(e.form)??new Map;t.set(e.form,r);let i=r.get(e.name);(i===void 0||e.checked&&!i.checked)&&r.set(e.name,e)}let n=new Set(Array.from(t.values()).flatMap(e=>Array.from(e.values())));return e.filter(e=>pS(e)===null||n.has(e))}function pS(e){return!(e instanceof HTMLInputElement)||e.type!==`radio`||e.name===``?null:e}function mS(e){return e.matches(`:disabled`)||Zh(e)||e instanceof HTMLInputElement&&e.type===`hidden`?!1:e.matches(lS)&&e.tabIndex>=0}function hS(e){if(e instanceof HTMLSlotElement){let t=e.assignedNodes({flatten:!0}),n=t.length===0?e.childNodes:t;return Array.from(n).filter(e=>e instanceof Element)}let t=e instanceof Element?e.shadowRoot??e:e;return Array.from(t.children)}function gS(e){let t=e.getRootNode();return t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host:e}var _S=class extends v{constructor(...e){super(...e),this.loading=!1,this.running=!1,this.error=``,this.draft={...Cm},this.formError=``}willUpdate(e){e.has(`preview`)&&(this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd))}render(){let e=wm(this.draft),t=this.selectedPreview(),n=Em({draft:this.draft,preview:t,previewRequest:this.previewRequest,loading:this.loading,running:this.running}),r=n?`Run cleanup`:t!==void 0&&!Dm(t)?`Select at least one project to run cleanup`:`Preview cleanup before running it`;return g`
|
|
1840
1844
|
<modal-surface .onClose=${()=>{this.onClose?.()}} .label=${`Clean up sessions`}>
|
|
1841
1845
|
<header>
|
|
1842
1846
|
<div>
|
|
@@ -1861,15 +1865,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1861
1865
|
`}renderForm(e){let t=this.loading||this.running,n=wm(this.draft),r=this.preview!==void 0&&n.ok&&Tm(n.request)!==Tm(this.previewRequest)&&Dm(this.preview);return g`
|
|
1862
1866
|
<fieldset ?disabled=${t}>
|
|
1863
1867
|
<label class="toggle-row">
|
|
1864
|
-
<input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:
|
|
1868
|
+
<input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:vS(e)})}}>
|
|
1865
1869
|
<span>Archive non-archived sessions idle for more than</span>
|
|
1866
|
-
<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:
|
|
1870
|
+
<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:yS(e)})}}>
|
|
1867
1871
|
<span>days</span>
|
|
1868
1872
|
</label>
|
|
1869
1873
|
<label class="toggle-row delete-row">
|
|
1870
|
-
<input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:
|
|
1874
|
+
<input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:vS(e)})}}>
|
|
1871
1875
|
<span>Delete archived sessions archived for more than</span>
|
|
1872
|
-
<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:
|
|
1876
|
+
<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:yS(e)})}}>
|
|
1873
1877
|
<span>days</span>
|
|
1874
1878
|
</label>
|
|
1875
1879
|
</fieldset>
|
|
@@ -1906,7 +1910,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1906
1910
|
${t.length===0?g`<p class="hint" role="status">Select at least one project to run cleanup.</p>`:null}
|
|
1907
1911
|
`}renderProjectRow(e,t){return g`
|
|
1908
1912
|
<tr class=${t?``:`unselected`}>
|
|
1909
|
-
<td class="select-cell"><input type="checkbox" aria-label=${`Clean up ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${t=>{this.setProjectSelected(e.cwd,
|
|
1913
|
+
<td class="select-cell"><input type="checkbox" aria-label=${`Clean up ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${t=>{this.setProjectSelected(e.cwd,vS(t))}}></td>
|
|
1910
1914
|
<th title=${e.cwd} dir="auto">${e.cwd}</th>
|
|
1911
1915
|
<td>${e.archiveCount}</td>
|
|
1912
1916
|
<td>${e.deleteCount}</td>
|
|
@@ -1963,7 +1967,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1963
1967
|
table { min-width: 560px; }
|
|
1964
1968
|
thead th:first-child, td.select-cell { width: 58px; }
|
|
1965
1969
|
}
|
|
1966
|
-
`}};H([b({attribute:!1})],
|
|
1970
|
+
`}};H([b({attribute:!1})],_S.prototype,`preview`,void 0),H([b({attribute:!1})],_S.prototype,`previewRequest`,void 0),H([b({attribute:!1})],_S.prototype,`result`,void 0),H([b({type:Boolean})],_S.prototype,`loading`,void 0),H([b({type:Boolean})],_S.prototype,`running`,void 0),H([b({type:String})],_S.prototype,`error`,void 0),H([b({attribute:!1})],_S.prototype,`onPreview`,void 0),H([b({attribute:!1})],_S.prototype,`onRun`,void 0),H([b({attribute:!1})],_S.prototype,`onClose`,void 0),H([x()],_S.prototype,`draft`,void 0),H([x()],_S.prototype,`formError`,void 0),H([x()],_S.prototype,`selectedProjectCwds`,void 0),_S=H([y(`session-cleanup-dialog`)],_S);function vS(e){return e.target instanceof HTMLInputElement&&e.target.checked}function yS(e){return e.target instanceof HTMLInputElement?e.target.value:``}function bS(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=ES(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:DS(d,r),activeLeafId:d}}function xS(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 SS(e){return e.activeLeafId===null?e.orderedIds.at(-1):e.activeLeafId}function CS(e,t,n){let r=xS(e,t.foldedIds).map(e=>e.node.id),i=OS(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 wS(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 TS(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(Rt)} characters or fewer.`}:{ok:!0,choice:{mode:`custom`,instructions:t.trim()}}}function ES(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 DS(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 OS(e,t){return t!==void 0&&e.includes(t)?t:e.at(-1)}var kS={nodes:[],activeLeafId:null,activePathIds:[]},AS=8,jS={user:{label:`User`,tone:`user`,bookkeeping:!1},assistant:{label:`Assistant`,tone:`assistant`,bookkeeping:!1},"tool-result":{label:`Tool result`,tone:`tool`,bookkeeping:!1},bash:{label:`Shell`,tone:`shell`,bookkeeping:!1},"custom-message":{label:`Custom message`,tone:`context`,bookkeeping:!1},compaction:{label:`Compaction`,tone:`context`,bookkeeping:!1},"branch-summary":{label:`Branch summary`,tone:`context`,bookkeeping:!1},"model-change":{label:`Model`,tone:`metadata`,bookkeeping:!0},"thinking-level-change":{label:`Thinking`,tone:`metadata`,bookkeeping:!0},"session-info":{label:`Session info`,tone:`metadata`,bookkeeping:!0},label:{label:`Label`,tone:`metadata`,bookkeeping:!0},custom:{label:`Custom`,tone:`metadata`,bookkeeping:!0},other:{label:`Other`,tone:`metadata`,bookkeeping:!0}},MS=class extends v{constructor(...e){super(...e),this.tree=kS,this.foldedIds=new Set,this.step=`tree`,this.operation=`continue`,this.summaryMode=`none`,this.customInstructions=``,this.busy=!1,this.aborting=!1,this.error=``,this.statusMessage=``,this.model=bS(kS),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():e===`operation`?this.renderRoot.querySelector(`input[name='session-tree-operation']:checked`)?.focus():this.renderRoot.querySelector(`input[name='session-tree-summary']:checked`)?.focus())}render(){return g`
|
|
1967
1971
|
<modal-surface
|
|
1968
1972
|
.label=${`Navigate session tree`}
|
|
1969
1973
|
.initialFocus=${this.selectedId===void 0?`.close-button`:`[data-tree-node-id][tabindex='0']`}
|
|
@@ -1981,7 +1985,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1981
1985
|
${this.step===`tree`?this.renderTreeStep():this.renderActionStep()}
|
|
1982
1986
|
${this.renderFooter()}
|
|
1983
1987
|
</modal-surface>
|
|
1984
|
-
`}renderTreeStep(){let e=
|
|
1988
|
+
`}renderTreeStep(){let e=xS(this.model,this.foldedIds);return g`
|
|
1985
1989
|
<div class="body tree-step">
|
|
1986
1990
|
<div class="tree-intro">
|
|
1987
1991
|
<p>Select the history entry where you would like to continue.</p>
|
|
@@ -2000,7 +2004,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2000
2004
|
</div>
|
|
2001
2005
|
`}
|
|
2002
2006
|
</div>
|
|
2003
|
-
`}renderTreeRow(e){let t=e.node.id===this.selectedId,n=e.childIds.length>0&&!this.foldedIds.has(e.node.id),r=
|
|
2007
|
+
`}renderTreeRow(e){let t=e.node.id===this.selectedId,n=e.childIds.length>0&&!this.foldedIds.has(e.node.id),r=FS(e.node.kind),i=[`tree-row`,t?`selected`:``,e.activePath?`active-path`:``,e.activeLeaf?`active-leaf`:``,r.bookkeeping?`bookkeeping`:``].filter(e=>e!==``).join(` `),a=NS(e.branchDepth);return g`
|
|
2004
2008
|
<div
|
|
2005
2009
|
class=${i}
|
|
2006
2010
|
style=${`--tree-indent: ${String(a*16)}px; --tree-indent-mobile: ${String(a*12)}px;`}
|
|
@@ -2033,7 +2037,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2033
2037
|
${e.node.timestamp===void 0?null:g`<time datetime=${e.node.timestamp}>${e.node.timestamp}</time>`}
|
|
2034
2038
|
</span>
|
|
2035
2039
|
</div>
|
|
2036
|
-
`}renderKindBadge(e){return g`<span class=${`kind kind-tone-${e.tone}`}>${e.label}</span>`}renderActionStep(){let e=this.selectedId===void 0?void 0:this.model.nodesById.get(this.selectedId),t=
|
|
2040
|
+
`}renderKindBadge(e){return g`<span class=${`kind kind-tone-${e.tone}`}>${e.label}</span>`}renderActionStep(){let e=this.selectedId===void 0?void 0:this.model.nodesById.get(this.selectedId),t=TS(this.summaryMode,this.customInstructions);return g`
|
|
2037
2041
|
<div class="body confirmation-step">
|
|
2038
2042
|
<div class="confirmation-card">
|
|
2039
2043
|
<div>
|
|
@@ -2042,7 +2046,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2042
2046
|
</div>
|
|
2043
2047
|
${e===void 0?g`<div class="empty">The selected history entry is no longer available.</div>`:g`
|
|
2044
2048
|
<div class="selected-entry">
|
|
2045
|
-
${this.renderKindBadge(
|
|
2049
|
+
${this.renderKindBadge(FS(e.kind))}
|
|
2046
2050
|
<strong dir="auto">${e.summary}</strong>
|
|
2047
2051
|
<p>${this.selectedEntryDescription(e.kind)}</p>
|
|
2048
2052
|
</div>
|
|
@@ -2081,7 +2085,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2081
2085
|
${this.error===``?null:g`<div class="dialog-error" role="alert">${this.error}</div>`}
|
|
2082
2086
|
</div>
|
|
2083
2087
|
</div>
|
|
2084
|
-
`}selectedEntryDescription(e){return this.operation===`fork`?e===`user`?`The new session will branch before this user message, and its text will return to the prompt editor as the new session draft.`:`The new session will include this entry and all history leading to it.`:
|
|
2088
|
+
`}selectedEntryDescription(e){return this.operation===`fork`?e===`user`?`The new session will branch before this user message, and its text will return to the prompt editor as the new session draft.`:`The new session will include this entry and all history leading to it.`:PS(e)?`This message’s text will return to the prompt editor for optional editing and resubmission in this session.`:`The prompt editor will be empty after continuing from this entry in this session.`}renderOperationOption(e,t,n){return g`
|
|
2085
2089
|
<label class=${`choice-option${this.operation===e?` selected`:``}`}>
|
|
2086
2090
|
<input
|
|
2087
2091
|
type="radio"
|
|
@@ -2120,7 +2124,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2120
2124
|
${this.primaryActionLabel()}
|
|
2121
2125
|
</button>
|
|
2122
2126
|
</footer>
|
|
2123
|
-
`}resetTree(){this.operationGeneration+=1,this.model=
|
|
2127
|
+
`}resetTree(){this.operationGeneration+=1,this.model=bS(this.tree),this.selectedId=SS(this.model),this.foldedIds=new Set,this.step=`tree`,this.operation=`continue`,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=wS(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){if(e.key===`Escape`)return;let t=CS(this.model,{selectedId:this.selectedId,foldedIds:this.foldedIds},e.key);if(t.handled){if(e.preventDefault(),e.stopPropagation(),t.action===`confirm`){this.continueToAction();return}this.selectedId=t.selectedId,this.foldedIds=t.foldedIds,this.pendingFocus=`tree`}}continueToAction(){this.busy||this.selectedId===void 0||!this.model.nodesById.has(this.selectedId)||(TS(this.summaryMode,this.customInstructions).ok||(this.summaryMode=`none`,this.customInstructions=``),this.step=`action`,this.error=``,this.statusMessage=``,this.pendingFocus=`operation`)}returnToTree(){this.busy||(this.step=`tree`,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`)}selectOperation(e){this.busy||(this.operation=e,this.error=``,this.statusMessage=``,this.pendingFocus=`operation`)}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=``)}primaryActionLabel(){return this.busy?this.operation===`fork`?`Forking…`:this.summaryMode===`none`?`Continuing…`:`Summarizing…`:this.operation===`continue`?`Continue from here`:`Fork into new session`}submitSelectedOperation(){return this.operation===`continue`?this.submitNavigation():this.submitFork()}async submitNavigation(){if(this.busy||this.selectedId===void 0)return;let e=TS(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: ${IS(e)}`}}async submitFork(){if(this.busy||this.selectedId===void 0)return;let e=this.onFork;if(e===void 0){this.error=`Fork from the session tree is unavailable. Close and reopen /tree, then try again.`;return}let t=this.selectedId,n=++this.operationGeneration;this.busy=!0,this.error=``,this.statusMessage=``;try{let r=await e(t);if(n!==this.operationGeneration)return;this.busy=!1,r.cancelled&&(this.statusMessage=`Fork cancelled. No new session was created; your selected history entry is unchanged.`)}catch(e){if(n!==this.operationGeneration)return;this.busy=!1,this.statusMessage=``,this.error=IS(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: ${IS(e)}`}}requestDismissal(){this.step===`action`?this.returnToTree():this.onCancel?.()}requestBusyEscape(){this.operation===`continue`&&this.summaryMode!==`none`&&this.abortNavigation()}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`
|
|
2124
2128
|
:host { position: fixed; inset: 0; z-index: 40; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
2125
2129
|
* { box-sizing: border-box; }
|
|
2126
2130
|
/* Full-viewport shell: the surface's centered-card defaults are overridden
|
|
@@ -2220,9 +2224,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2220
2224
|
.custom-focus, .validation-error { margin-inline-start: 0; }
|
|
2221
2225
|
footer { flex-wrap: wrap; }
|
|
2222
2226
|
}
|
|
2223
|
-
`}};H([b({attribute:!1})],jS.prototype,`tree`,void 0),H([b({attribute:!1})],jS.prototype,`onNavigate`,void 0),H([b({attribute:!1})],jS.prototype,`onFork`,void 0),H([b({attribute:!1})],jS.prototype,`onAbort`,void 0),H([b({attribute:!1})],jS.prototype,`onCancel`,void 0),H([x()],jS.prototype,`selectedId`,void 0),H([x()],jS.prototype,`foldedIds`,void 0),H([x()],jS.prototype,`step`,void 0),H([x()],jS.prototype,`operation`,void 0),H([x()],jS.prototype,`summaryMode`,void 0),H([x()],jS.prototype,`customInstructions`,void 0),H([x()],jS.prototype,`busy`,void 0),H([x()],jS.prototype,`aborting`,void 0),H([x()],jS.prototype,`error`,void 0),H([x()],jS.prototype,`statusMessage`,void 0),jS=H([y(`session-tree-navigator`)],jS);function MS(e){return Math.min(Math.max(0,e),kS)}function NS(e){return e===`user`||e===`custom-message`}function PS(e){return AS[e]}function FS(e){return e instanceof Error?e.message:String(e)}var{I:IS}=ut,LS=e=>e,RS=()=>document.createComment(``),zS=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new IS(r.insertBefore(RS(),i),r.insertBefore(RS(),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=LS(e).nextSibling;LS(r).insertBefore(e,i),e=t}}}return n},BS=(e,t,n=e)=>(e._$AI(t,n),e),VS={},HS=(e,t=VS)=>e._$AH=t,US=e=>e._$AH,WS=e=>{e._$AR(),e._$AA.remove()},GS=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},KS=dg(class extends fg{constructor(e){if(super(e),e.type!==ug.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=US(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]=BS(i[d],a[p]),d++,p++;else if(s[f]===o[m])c[m]=BS(i[f],a[m]),f--,m--;else if(s[d]===o[m])c[m]=BS(i[d],a[m]),zS(e,c[m+1],i[d]),d++,m--;else if(s[f]===o[p])c[p]=BS(i[f],a[p]),zS(e,i[d],i[f]),f--,p++;else if(l===void 0&&(l=GS(o,p,m),u=GS(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=zS(e,i[d]);BS(t,a[p]),c[p]=t}else c[p]=BS(n,a[p]),zS(e,i[d],n),i[t]=null;p++}else WS(i[f]),f--;else WS(i[d]),d++;for(;p<=m;){let t=zS(e,c[m+1]);BS(t,a[p]),c[p++]=t}for(;d<=f;){let e=i[d++];e!==null&&WS(e)}return this.ut=o,HS(e,c),Xe}}),qS=`pi-web:chat-groups:`,JS={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(XS(e));return t===null||t===``?void 0:ZS(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(XS(e),JSON.stringify(t))}catch{}}},YS=class{constructor(e=JS){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&&$S(i,this.openGroupKeys)&&$S(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 XS(e){return`${qS}${e}`}function ZS(e){if(Array.isArray(e))return{open:QS(e),closedDefaultOpen:[]};if(eC(e))return{open:Array.isArray(e.open)?QS(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?QS(e.closedDefaultOpen):[]}}function QS(e){return e.filter(e=>typeof e==`string`)}function $S(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function eC(e){return typeof e==`object`&&!!e}function tC(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=>aC(e,t)),s=e.parts.filter(t=>!aC(e,t)),c=t+r,l={...e.source===void 0?{}:{source:e.source},...e.meta===void 0?{}:{meta:e.meta}};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,...l};if(rC(t)){let e=iC(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 nC(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 rC(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function iC(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function aC(e,t){return e.source===`compaction`||e.source===`branch_summary`?!1:t.type===`skillInvocation`||t.type===`skillRead`||t.type===`image`||t.type===`askUserRecord`||t.type===`text`&&(e.role===`user`||e.role===`assistant`||e.role===`system`||e.role===`bash`)}function oC(e,t,n){let r=e.length;if(r===0||t.length===0||n.length!==r+1||n[r-1]!==e[r-1])return;let i=n[r],a=e[r-1];if(i===void 0||a===void 0)return;let o=t.at(-1);if(o===void 0)return;let s=t.slice(0,-1),c,l;o.kind===`group`?(c=o.startIndex,l=[...o.messages,i]):(c=o.index,l=[a,i]);let u=tC(l,c);return[...s,...u]}function sC(e,t){let n=lC(fC(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function cC(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=uC(r,t.markerOffset);return}e.scrollTop=dC(e.scrollHeight,t.distanceFromBottom)}function lC(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 uC(e,t){return e-t}function dC(e,t){return Math.max(0,e-t)}function fC(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 pC=600,mC=1;function hC(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:gC(e)||_C(e)}function gC(e){return e.scrollTop<(e.topThreshold??Math.max(pC,e.clientHeight))}function _C(e){return e.scrollHeight<=e.clientHeight+mC}var vC=`pi-web:chat-scroll:`,yC=180,bC=48,xC=2,SC={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)}},CC={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},wC=class{constructor(e=SC,t=CC){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=yC){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=xC){if(e===``||t===void 0||!DC(t))return`skipped`;try{if(kC(t,r))return this.storage.setItem(TC(e),JSON.stringify({mode:`bottom`})),`saved`;let i=jC(t,n);if(i===void 0)return`skipped`;let a=AC(t,i);return this.storage.setItem(TC(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||!DC(t))return{status:`skipped`};let i=NC(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(TC(e));if(t===null||t===``)return;let n=JSON.parse(t);return EC(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!DC(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function TC(e){return`${vC}${e}`}function EC(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 DC(e){return e.clientHeight>0&&e.scrollHeight>0}function OC(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function kC(e,t=bC){return OC(e)<t}function AC(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:PC(t)??``,offset:t.getBoundingClientRect().top-n}}function jC(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(PC(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 MC(e,t){let n=e.getBoundingClientRect();return t.find(e=>{let t=e.getBoundingClientRect();return t.bottom>=n.top&&t.top<=n.bottom})}function NC(e,t){return e.find(e=>PC(e)===t)}function PC(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}var FC={left:!1,right:!1},IC=1;function LC(e){if(e===void 0)return FC;let t=Math.max(0,e.scrollWidth-e.clientWidth);return{left:e.scrollLeft>IC,right:t-e.scrollLeft>IC}}function RC(e){return`${e.left?` can-scroll-left`:``}${e.right?` can-scroll-right`:``}`}var zC=e=>{if(!(typeof ResizeObserver>`u`))return new ResizeObserver(()=>{e()})},BC=class{constructor(e,t=zC){this.onChange=e,this.createObserver=t,this.current=FC}get edges(){return this.current}observe(e){if(this.element!==e&&(this.observer?.disconnect(),this.observer=void 0,this.element=e,e!==void 0)){let t=this.createObserver(()=>{this.refresh()});t!==void 0&&(t.observe(e),this.observer=t)}this.refresh()}refresh(){let e=LC(this.element);e.left===this.current.left&&e.right===this.current.right||(this.current=e,this.onChange())}dispose(){this.observer?.disconnect(),this.observer=void 0,this.element=void 0,this.current=FC}};function VC(e){return e.role===`user`&&HC(e)!==void 0}function HC(e){if(e.role!==`user`)return;let t=[],n=[];for(let r of e.parts){if(UC(r)){r.text!==``&&t.push(r.text);continue}r.type===`image`&&r.data!==``&&r.mimeType!==``&&n.push({kind:`image`,mimeType:r.mimeType,data:r.data})}let r=t.join(`
|
|
2227
|
+
`}};H([b({attribute:!1})],MS.prototype,`tree`,void 0),H([b({attribute:!1})],MS.prototype,`onNavigate`,void 0),H([b({attribute:!1})],MS.prototype,`onFork`,void 0),H([b({attribute:!1})],MS.prototype,`onAbort`,void 0),H([b({attribute:!1})],MS.prototype,`onCancel`,void 0),H([x()],MS.prototype,`selectedId`,void 0),H([x()],MS.prototype,`foldedIds`,void 0),H([x()],MS.prototype,`step`,void 0),H([x()],MS.prototype,`operation`,void 0),H([x()],MS.prototype,`summaryMode`,void 0),H([x()],MS.prototype,`customInstructions`,void 0),H([x()],MS.prototype,`busy`,void 0),H([x()],MS.prototype,`aborting`,void 0),H([x()],MS.prototype,`error`,void 0),H([x()],MS.prototype,`statusMessage`,void 0),MS=H([y(`session-tree-navigator`)],MS);function NS(e){return Math.min(Math.max(0,e),AS)}function PS(e){return e===`user`||e===`custom-message`}function FS(e){return jS[e]}function IS(e){return e instanceof Error?e.message:String(e)}var{I:LS}=ut,RS=e=>e,zS=()=>document.createComment(``),BS=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new LS(r.insertBefore(zS(),i),r.insertBefore(zS(),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=RS(e).nextSibling;RS(r).insertBefore(e,i),e=t}}}return n},VS=(e,t,n=e)=>(e._$AI(t,n),e),HS={},US=(e,t=HS)=>e._$AH=t,WS=e=>e._$AH,GS=e=>{e._$AR(),e._$AA.remove()},KS=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},qS=fg(class extends pg{constructor(e){if(super(e),e.type!==dg.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=WS(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]=VS(i[d],a[p]),d++,p++;else if(s[f]===o[m])c[m]=VS(i[f],a[m]),f--,m--;else if(s[d]===o[m])c[m]=VS(i[d],a[m]),BS(e,c[m+1],i[d]),d++,m--;else if(s[f]===o[p])c[p]=VS(i[f],a[p]),BS(e,i[d],i[f]),f--,p++;else if(l===void 0&&(l=KS(o,p,m),u=KS(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=BS(e,i[d]);VS(t,a[p]),c[p]=t}else c[p]=VS(n,a[p]),BS(e,i[d],n),i[t]=null;p++}else GS(i[f]),f--;else GS(i[d]),d++;for(;p<=m;){let t=BS(e,c[m+1]);VS(t,a[p]),c[p++]=t}for(;d<=f;){let e=i[d++];e!==null&&GS(e)}return this.ut=o,US(e,c),Xe}}),JS=`pi-web:chat-groups:`,YS={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(ZS(e));return t===null||t===``?void 0:QS(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(ZS(e),JSON.stringify(t))}catch{}}},XS=class{constructor(e=YS){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&&eC(i,this.openGroupKeys)&&eC(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 ZS(e){return`${JS}${e}`}function QS(e){if(Array.isArray(e))return{open:$S(e),closedDefaultOpen:[]};if(tC(e))return{open:Array.isArray(e.open)?$S(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?$S(e.closedDefaultOpen):[]}}function $S(e){return e.filter(e=>typeof e==`string`)}function eC(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function tC(e){return typeof e==`object`&&!!e}function nC(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=>oC(e,t)),s=e.parts.filter(t=>!oC(e,t)),c=t+r,l={...e.source===void 0?{}:{source:e.source},...e.meta===void 0?{}:{meta:e.meta}};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,...l};if(iC(t)){let e=aC(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 rC(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 iC(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function aC(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function oC(e,t){return e.source===`compaction`||e.source===`branch_summary`?!1:t.type===`skillInvocation`||t.type===`skillRead`||t.type===`image`||t.type===`askUserRecord`||t.type===`text`&&(e.role===`user`||e.role===`assistant`||e.role===`system`||e.role===`bash`)}function sC(e,t,n){let r=e.length;if(r===0||t.length===0||n.length!==r+1||n[r-1]!==e[r-1])return;let i=n[r],a=e[r-1];if(i===void 0||a===void 0)return;let o=t.at(-1);if(o===void 0)return;let s=t.slice(0,-1),c,l;o.kind===`group`?(c=o.startIndex,l=[...o.messages,i]):(c=o.index,l=[a,i]);let u=nC(l,c);return[...s,...u]}function cC(e,t){let n=uC(pC(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function lC(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=dC(r,t.markerOffset);return}e.scrollTop=fC(e.scrollHeight,t.distanceFromBottom)}function uC(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 dC(e,t){return e-t}function fC(e,t){return Math.max(0,e-t)}function pC(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 mC=600,hC=1;function gC(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:_C(e)||vC(e)}function _C(e){return e.scrollTop<(e.topThreshold??Math.max(mC,e.clientHeight))}function vC(e){return e.scrollHeight<=e.clientHeight+hC}var yC=`pi-web:chat-scroll:`,bC=180,xC=48,SC=2,CC={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)}},wC={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},TC=class{constructor(e=CC,t=wC){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=bC){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=SC){if(e===``||t===void 0||!OC(t))return`skipped`;try{if(AC(t,r))return this.storage.setItem(EC(e),JSON.stringify({mode:`bottom`})),`saved`;let i=MC(t,n);if(i===void 0)return`skipped`;let a=jC(t,i);return this.storage.setItem(EC(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||!OC(t))return{status:`skipped`};let i=PC(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(EC(e));if(t===null||t===``)return;let n=JSON.parse(t);return DC(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!OC(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function EC(e){return`${yC}${e}`}function DC(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 OC(e){return e.clientHeight>0&&e.scrollHeight>0}function kC(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function AC(e,t=xC){return kC(e)<t}function jC(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:FC(t)??``,offset:t.getBoundingClientRect().top-n}}function MC(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(FC(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 NC(e,t){let n=e.getBoundingClientRect();return t.find(e=>{let t=e.getBoundingClientRect();return t.bottom>=n.top&&t.top<=n.bottom})}function PC(e,t){return e.find(e=>FC(e)===t)}function FC(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}var IC={left:!1,right:!1},LC=1;function RC(e){if(e===void 0)return IC;let t=Math.max(0,e.scrollWidth-e.clientWidth);return{left:e.scrollLeft>LC,right:t-e.scrollLeft>LC}}function zC(e){return`${e.left?` can-scroll-left`:``}${e.right?` can-scroll-right`:``}`}var BC=e=>{if(!(typeof ResizeObserver>`u`))return new ResizeObserver(()=>{e()})},VC=class{constructor(e,t=BC){this.onChange=e,this.createObserver=t,this.current=IC}get edges(){return this.current}observe(e){if(this.element!==e&&(this.observer?.disconnect(),this.observer=void 0,this.element=e,e!==void 0)){let t=this.createObserver(()=>{this.refresh()});t!==void 0&&(t.observe(e),this.observer=t)}this.refresh()}refresh(){let e=RC(this.element);e.left===this.current.left&&e.right===this.current.right||(this.current=e,this.onChange())}dispose(){this.observer?.disconnect(),this.observer=void 0,this.element=void 0,this.current=IC}};function HC(e){return e.role===`user`&&UC(e)!==void 0}function UC(e){if(e.role!==`user`)return;let t=[],n=[];for(let r of e.parts){if(WC(r)){r.text!==``&&t.push(r.text);continue}r.type===`image`&&r.data!==``&&r.mimeType!==``&&n.push({kind:`image`,mimeType:r.mimeType,data:r.data})}let r=t.join(`
|
|
2224
2228
|
|
|
2225
|
-
`).trim();if(!(r===``&&n.length===0))return{text:r,attachments:n}}function
|
|
2229
|
+
`).trim();if(!(r===``&&n.length===0))return{text:r,attachments:n}}function WC(e){return e.type===`text`}function GC(e){return e.status===`complete`||e.status===`completed`||e.status===`abandoned`}function KC(e){return e.status===`paused`||e.status===`blocked`||e.status===`budget_limited`}function qC(e){return e.totalTaskCount<=0?0:Math.min(1,Math.max(0,e.completedTaskCount/e.totalTaskCount))}function JC(e){return e.totalTaskCount<=0?`No tasks`:`${String(e.completedTaskCount)}/${String(e.totalTaskCount)}`}function YC(e){switch(e){case`active`:return`Active`;case`paused`:return`Paused`;case`blocked`:return`Blocked`;case`complete`:case`completed`:return`Complete`;case`abandoned`:return`Abandoned`;case`budget_limited`:return`Budget reached`;default:return e.replace(/_/gu,` `)}}function XC(e){if(e.currentTaskId!==void 0)return ZC(e.tasks,e.currentTaskId)}function ZC(e,t){for(let n of e){if(n.id===t)return n;let e=n.subtasks===void 0?void 0:ZC(n.subtasks,t);if(e!==void 0)return e}}function QC(e,t=0){let n=[];for(let r of e)n.push({task:r,depth:t}),r.subtasks!==void 0&&n.push(...QC(r.subtasks,t+1));return n}function $C(e){if(!(e===void 0||e<=0))return e>=1e6?`${(e/1e6).toFixed(1)}M tokens`:e>=1e3?`${String(Math.round(e/1e3))}k tokens`:`${String(e)} tokens`}function ew(e){if(GC(e))return[];let t=KC(e)?[{label:`Resume`,command:`/goal-resume`,description:`Resume this goal in the focused session`,destructive:!1}]:[{label:`Pause`,command:`/goal-pause`,description:`Pause this goal`,destructive:!1}];return t.push({label:`Abandon`,command:`/goal-clear`,description:`Archive this goal after confirmation`,destructive:!0}),t}var tw=class extends v{constructor(...e){super(...e),this.goals=[],this.loading=!1,this.canRunCommands=!0,this.expanded=new Set}render(){return g`
|
|
2226
2230
|
<section>
|
|
2227
2231
|
<h2>
|
|
2228
2232
|
Goals
|
|
@@ -2238,7 +2242,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2238
2242
|
</h2>
|
|
2239
2243
|
${this.goals.length===0?this.renderEmpty():g`<div class="goal-list">${this.goals.map(e=>this.renderGoal(e))}</div>`}
|
|
2240
2244
|
</section>
|
|
2241
|
-
`}openGoalsLabel(){let e=this.goals.filter(e=>!
|
|
2245
|
+
`}openGoalsLabel(){let e=this.goals.filter(e=>!GC(e)).length;return e===0?``:`${String(e)} open`}renderCommands(e){let t=ew(e);return t.length===0?null:g`
|
|
2242
2246
|
<div class="goal-commands">
|
|
2243
2247
|
${t.map(t=>g`
|
|
2244
2248
|
<button
|
|
@@ -2250,7 +2254,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2250
2254
|
>${t.label}</button>
|
|
2251
2255
|
`)}
|
|
2252
2256
|
</div>
|
|
2253
|
-
`}renderEmpty(){return g`<p class="empty">${this.loading?`Loading goals…`:`No goals recorded for this workspace.`}</p>`}renderGoal(e){let t=this.expanded.has(e.id),n=
|
|
2257
|
+
`}renderEmpty(){return g`<p class="empty">${this.loading?`Loading goals…`:`No goals recorded for this workspace.`}</p>`}renderGoal(e){let t=this.expanded.has(e.id),n=qC(e),r=$C(e.tokensUsed),i=XC(e),a=GC(e)?`done`:KC(e)?`blocked`:`active`;return g`
|
|
2254
2258
|
<article class=${`goal ${a}`}>
|
|
2255
2259
|
<button
|
|
2256
2260
|
class="goal-header"
|
|
@@ -2261,8 +2265,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2261
2265
|
>
|
|
2262
2266
|
<span class="goal-caret" aria-hidden="true">${t?`▾`:`▸`}</span>
|
|
2263
2267
|
<span class="goal-objective">${e.objective}</span>
|
|
2264
|
-
<span class=${`goal-status ${a}`}>${
|
|
2265
|
-
<span class="goal-ratio">${
|
|
2268
|
+
<span class=${`goal-status ${a}`}>${YC(e.status)}</span>
|
|
2269
|
+
<span class="goal-ratio">${JC(e)}</span>
|
|
2266
2270
|
</button>
|
|
2267
2271
|
<div
|
|
2268
2272
|
class="goal-bar"
|
|
@@ -2270,7 +2274,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2270
2274
|
aria-valuemin="0"
|
|
2271
2275
|
aria-valuemax=${String(e.totalTaskCount)}
|
|
2272
2276
|
aria-valuenow=${String(e.completedTaskCount)}
|
|
2273
|
-
aria-label=${`${e.objective}: ${
|
|
2277
|
+
aria-label=${`${e.objective}: ${JC(e)} tasks complete`}
|
|
2274
2278
|
>
|
|
2275
2279
|
<span class="goal-bar-fill" style=${`transform: scaleX(${String(n)})`}></span>
|
|
2276
2280
|
</div>
|
|
@@ -2283,7 +2287,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2283
2287
|
${r===void 0?_:g`<span class="goal-reason">${r}</span>`}
|
|
2284
2288
|
${n===void 0?_:g`<span class="goal-tokens">${n}</span>`}
|
|
2285
2289
|
</p>
|
|
2286
|
-
`}renderDetail(e,t,n){let r=
|
|
2290
|
+
`}renderDetail(e,t,n){let r=QC(e.tasks);return g`
|
|
2287
2291
|
<div class="goal-detail">
|
|
2288
2292
|
${e.pauseReason===void 0?_:g`<p class="goal-reason detail">${e.pauseReason}</p>`}
|
|
2289
2293
|
${e.verificationContract===void 0?_:g`<p class="goal-contract"><span class="label">Verification</span>${e.verificationContract}</p>`}
|
|
@@ -2319,7 +2323,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2319
2323
|
</span>
|
|
2320
2324
|
${n?g`<span class="task-now" title="The task the agent reported working on">now</span>`:_}
|
|
2321
2325
|
</li>
|
|
2322
|
-
`}toggle(e){let t=new Set(this.expanded);t.delete(e)||t.add(e),this.expanded=t}static{this.styles=[
|
|
2326
|
+
`}toggle(e){let t=new Set(this.expanded);t.delete(e)||t.add(e),this.expanded=t}static{this.styles=[ig,h`
|
|
2323
2327
|
h2 { min-height: 30px; }
|
|
2324
2328
|
h2 > .section-count { flex: 1 1 auto; margin-inline-start: var(--pi-space-3); color: var(--pi-muted); font-size: var(--pi-text-2xs); font-weight: 400; letter-spacing: normal; }
|
|
2325
2329
|
.refresh-entry { flex: 0 0 auto; display: inline-grid; place-items: center; width: 34px; height: 34px; padding: 0; font-size: var(--pi-text-sm); }
|
|
@@ -2392,7 +2396,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2392
2396
|
@container (max-width: 580px) {
|
|
2393
2397
|
.goal-header, .refresh-entry { min-height: 42px; }
|
|
2394
2398
|
}
|
|
2395
|
-
`]}};H([b({attribute:!1})],
|
|
2399
|
+
`]}};H([b({attribute:!1})],tw.prototype,`goals`,void 0),H([b({type:Boolean})],tw.prototype,`loading`,void 0),H([b({attribute:!1})],tw.prototype,`onRefresh`,void 0),H([b({attribute:!1})],tw.prototype,`onArchive`,void 0),H([b({attribute:!1})],tw.prototype,`onRunCommand`,void 0),H([b({type:Boolean})],tw.prototype,`canRunCommands`,void 0),H([x()],tw.prototype,`expanded`,void 0),H([x()],tw.prototype,`confirmingArchiveId`,void 0),tw=H([y(`goal-panel`)],tw);function nw(e){let t=e?.trim();if(t===void 0||t===``)return;let n=t.indexOf(`/`),r=n===-1?void 0:t.slice(0,n),i=n===-1?t:t.slice(n+1),a=i.lastIndexOf(`:`),o=a===-1?i:i.slice(0,a),s=a===-1?void 0:i.slice(a+1);if(o!==``)return{...r===void 0||r===``?{}:{provider:r},model:o,...s===void 0||s===``?{}:{thinking:s},label:s===void 0||s===``?o:`${o} · ${s}`}}function rw(e){typeof CSS<`u`&&CSS.supports(`field-sizing`,`content`)||(e.style.height=`auto`,e.style.height=`${String(e.scrollHeight)}px`)}var iw=class extends v{constructor(...e){super(...e),this.draftSessionId=``,this.answers={},this.step=0,this.confirmingPartialSubmit=!1,this.submitting=!1}willUpdate(e){if(!e.has(`ask`)&&!e.has(`outcome`)&&!e.has(`draftSessionId`))return;let t=this.currentModelIdentity();t!==this.modelIdentity&&(this.modelIdentity=t,this.answers=this.loadCurrentDraft(),this.confirmingPartialSubmit=!1,this.submitting=!1)}render(){return this.outcome===void 0?this.ask===void 0?null:this.renderOpenAsk(this.ask):this.renderRecord(this.outcome)}renderOpenAsk(e){let t=Hl(e.questions,this.answers),n=Ul(e.questions,this.answers);return g`
|
|
2396
2400
|
<article class="card open-card" aria-labelledby="ask-user-heading">
|
|
2397
2401
|
<header class="card-header">
|
|
2398
2402
|
<h2 id="ask-user-heading">Questions</h2>
|
|
@@ -2413,7 +2417,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2413
2417
|
<fieldset
|
|
2414
2418
|
id=${this.questionFieldsetId(n)}
|
|
2415
2419
|
class=${`question${i?` answered`:``}`}
|
|
2416
|
-
aria-describedby=${
|
|
2420
|
+
aria-describedby=${ug(a)}
|
|
2417
2421
|
tabindex="-1"
|
|
2418
2422
|
>
|
|
2419
2423
|
<legend>
|
|
@@ -2515,7 +2519,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2515
2519
|
${r.fromDraft?g`<p class="draft-note">Draft answer · not sent</p>`:null}
|
|
2516
2520
|
`}
|
|
2517
2521
|
</section>
|
|
2518
|
-
`}changeOption(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;if(e.multiple!==!0){r.checked&&this.setAnswer(e,{values:[t]});return}let i=this.answers[e.id],a=r.checked?[...new Set([...i?.values??[],t])]:(i?.values??[]).filter(e=>e!==t);this.setAnswer(e,{values:a,...i?.otherText===void 0?{}:{otherText:i.otherText}})}changeOther(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;let i=this.answers[e.id];e.multiple===!0?this.setAnswer(e,{values:[...i?.values??[]],...r.checked?{otherText:i?.otherText??``}:{}}):r.checked&&this.setAnswer(e,{values:[],otherText:this.isOtherSelected(e,i)?i?.otherText??``:``}),r.checked&&this.focusOtherInput(t)}changeOtherText(e,t){let n=t.currentTarget;if(!(n instanceof HTMLTextAreaElement))return;
|
|
2522
|
+
`}changeOption(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;if(e.multiple!==!0){r.checked&&this.setAnswer(e,{values:[t]});return}let i=this.answers[e.id],a=r.checked?[...new Set([...i?.values??[],t])]:(i?.values??[]).filter(e=>e!==t);this.setAnswer(e,{values:a,...i?.otherText===void 0?{}:{otherText:i.otherText}})}changeOther(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;let i=this.answers[e.id];e.multiple===!0?this.setAnswer(e,{values:[...i?.values??[]],...r.checked?{otherText:i?.otherText??``}:{}}):r.checked&&this.setAnswer(e,{values:[],otherText:this.isOtherSelected(e,i)?i?.otherText??``:``}),r.checked&&this.focusOtherInput(t)}changeOtherText(e,t){let n=t.currentTarget;if(!(n instanceof HTMLTextAreaElement))return;rw(n);let r=this.answers[e.id];this.setAnswer(e,{values:[...r?.values??[]],otherText:n.value.slice(0,Pt)})}setAnswer(e,t){let n=t.values.length===0&&t.otherText===void 0?Object.fromEntries(Object.entries(this.answers).filter(([t])=>t!==e.id)):{...this.answers,[e.id]:t};this.answers=n,this.confirmingPartialSubmit=!1,this.ask!==void 0&&this.draftSessionId!==``&&Rl(this.draftSessionId,this.ask.askId,n)}handleSubmit(e,t){if(e.preventDefault(),!this.submitting){if(Ul(t.questions,this.answers).length>0){this.showPartialSubmitConfirmation();return}this.submitAnswers(t)}}submitAnswers(e){if(this.submitting)return;this.submitting=!0;let t=this.onSubmit;if(t===void 0){this.submitting=!1;return}let n=e.askId;Promise.resolve().then(()=>t(n,Wl(e.questions,this.answers))).catch(()=>{}).finally(()=>{this.ask?.askId===n&&(this.submitting=!1)})}async showPartialSubmitConfirmation(){this.confirmingPartialSubmit=!0,await this.updateComplete,this.renderRoot.querySelector(`.send-anyway`)?.focus()}keepEditing(e,t){this.confirmingPartialSubmit=!1;let n=t[0];n!==void 0&&this.focusQuestion(e.questions.indexOf(n))}focusQuestion(e){e<0||this.updateComplete.then(()=>{let t=this.renderRoot.querySelector(`#${this.questionFieldsetId(e)}`);(t?.querySelector(`input, textarea`)??t)?.focus()})}async focusOtherInput(e){await this.updateComplete,this.renderRoot.querySelector(`#${this.otherInputId(e)}`)?.focus()}isOtherSelected(e,t){return t?.otherText===void 0?!1:e.multiple===!0||t.values.length===0}displayedRecordAnswer(e,t){if(t.answered)return{values:[...t.values],...t.otherText===void 0?{}:{otherText:t.otherText},fromDraft:!1};if(e.reason!==`superseded`)return;let n=Wl([t.question],this.answers).answers[0];if(n!==void 0)return{values:[...n.values],...n.otherText===void 0?{}:{otherText:n.otherText},fromDraft:!0}}optionLabel(e,t){return e.options.find(e=>e.value===t)?.label??t}currentModelIdentity(){if(this.outcome!==void 0)return`record:${this.draftSessionId}:${this.outcome.askId}`;if(this.ask!==void 0)return`open:${this.draftSessionId}:${this.ask.askId}`}loadCurrentDraft(){let e=this.outcome?.askId??this.ask?.askId;return e===void 0||this.draftSessionId===``?{}:Ll(this.draftSessionId,e)}questionGroupName(e,t){return`ask-user:${e.askId}:${t.id}`}questionFieldsetId(e){return`ask-user-question-${String(e)}`}questionDetailId(e){return`ask-user-question-detail-${String(e)}`}otherInputId(e){return`ask-user-other-${String(e)}`}recordQuestionHeadingId(e){return`ask-user-record-question-${String(e)}`}static{this.styles=h`
|
|
2519
2523
|
:host {
|
|
2520
2524
|
display: block;
|
|
2521
2525
|
box-sizing: border-box;
|
|
@@ -2700,9 +2704,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2700
2704
|
.confirmation-actions { justify-content: flex-end; }
|
|
2701
2705
|
.primary-action { min-height: 42px; }
|
|
2702
2706
|
}
|
|
2703
|
-
`}};H([b({attribute:!1})],
|
|
2707
|
+
`}};H([b({attribute:!1})],iw.prototype,`ask`,void 0),H([b({attribute:!1})],iw.prototype,`outcome`,void 0),H([b({attribute:!1})],iw.prototype,`draftSessionId`,void 0),H([b({attribute:!1})],iw.prototype,`onSubmit`,void 0),H([x()],iw.prototype,`answers`,void 0),H([x()],iw.prototype,`step`,void 0),H([x()],iw.prototype,`confirmingPartialSubmit`,void 0),H([x()],iw.prototype,`submitting`,void 0),iw=H([y(`ask-user-card`)],iw);var aw=1e3,ow=120;function sw(e){let t=e.replace(/\r\n/g,`
|
|
2704
2708
|
`).replace(/^\n+/,``).trimEnd(),n=t.indexOf(`
|
|
2705
|
-
`);if(n===-1)return t.length<=
|
|
2709
|
+
`);if(n===-1)return t.length<=ow?{heading:t}:{heading:`${t.slice(0,ow).trimEnd()}\u2026`,body:t};let r=t.slice(0,n).trimEnd(),i=r.length<=ow,a=i?r:`${r.slice(0,ow).trimEnd()}\u2026`,o=i?t.slice(n+1).replace(/\n+$/,``):t;return o.trim()===``?{heading:a}:{heading:a,body:o}}function cw(e){switch(e){case`answered`:return`Answered`;case`cancelled`:return`Cancelled`;case`timeout`:return`Timed out`;case`aborted`:return`Aborted`;case`session-ended`:return`Session ended`}}function lw(e){switch(e.reason){case`answered`:{let t=e.answer;return t===void 0?`Closed without an answer.`:typeof t==`boolean`?`Answered: ${t?`Yes`:`No`}`:t===``?`Answered with an empty response.`:`Answered: ${t}`}case`cancelled`:return`Dismissed without an answer.`;case`timeout`:return`No answer was given before the dialog timed out.`;case`aborted`:return`The run ended before this dialog was answered.`;case`session-ended`:return`The session ended before this dialog was answered.`}}function uw(e,t){if(e===void 0)return;let n=Date.parse(e);if(!Number.isFinite(n))return;let r=n-t;if(r<=0)return`Auto-cancel imminent`;let i=Math.ceil(r/1e3);if(i>=3600){let e=Math.floor(i/3600),t=Math.floor(i%3600/60);return`Auto-cancels in ${String(e)}h ${String(t)}m`}if(i>=60){let e=Math.floor(i/60);return`Auto-cancels in ${String(e)}m ${String(i%60)}s`}return`Auto-cancels in ${String(i)}s`}var dw=class extends v{constructor(...e){super(...e),this.inputValue=``,this.closing=!1,this.countdownNow=0}connectedCallback(){super.connectedCallback(),this.syncCountdownTimer()}disconnectedCallback(){this.stopCountdownTimer(),super.disconnectedCallback()}willUpdate(e){if(!e.has(`dialog`)&&!e.has(`outcome`))return;let t=this.currentIdentity();t!==this.dialogIdentity&&(this.dialogIdentity=t,this.inputValue=``,this.closing=!1),this.syncCountdownTimer()}render(){return this.outcome===void 0?this.dialog===void 0?null:this.renderOpen(this.dialog):this.renderClosed(this.outcome)}renderOpen(e){let t=uw(e.timeoutAt,this.countdownNow===0?Date.now():this.countdownNow),{heading:n,body:r}=sw(e.title);return g`
|
|
2706
2710
|
<article class="card open-card" aria-labelledby="extension-dialog-heading">
|
|
2707
2711
|
<header class="card-header">
|
|
2708
2712
|
<h2 id="extension-dialog-heading">${n}</h2>
|
|
@@ -2734,7 +2738,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2734
2738
|
type="text"
|
|
2735
2739
|
name="dialog-answer"
|
|
2736
2740
|
aria-label="Your answer"
|
|
2737
|
-
placeholder=${
|
|
2741
|
+
placeholder=${ug(e.placeholder)}
|
|
2738
2742
|
maxlength=${String(Lt)}
|
|
2739
2743
|
.value=${this.inputValue}
|
|
2740
2744
|
?disabled=${this.closing}
|
|
@@ -2748,15 +2752,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2748
2752
|
`}renderClosed(e){return g`
|
|
2749
2753
|
<article class="card closed-card" aria-labelledby="extension-dialog-closed-heading">
|
|
2750
2754
|
<header class="card-header">
|
|
2751
|
-
<h2 id="extension-dialog-closed-heading">${
|
|
2752
|
-
<span class=${`header-status ${e.reason}`}>${
|
|
2755
|
+
<h2 id="extension-dialog-closed-heading">${sw(e.dialog.title).heading}</h2>
|
|
2756
|
+
<span class=${`header-status ${e.reason}`}>${cw(e.reason)}</span>
|
|
2753
2757
|
</header>
|
|
2754
|
-
<p class="closed-summary">${
|
|
2758
|
+
<p class="closed-summary">${lw(e)}</p>
|
|
2755
2759
|
<footer class="dialog-footer">
|
|
2756
2760
|
<button class="secondary-action" type="button" @click=${()=>{this.dismissClosed(e)}}>Dismiss</button>
|
|
2757
2761
|
</footer>
|
|
2758
2762
|
</article>
|
|
2759
|
-
`}answerDialog(e,t){this.closeWith(e,()=>this.onAnswer?.(e.dialogId,t))}cancelDialog(e){this.closeWith(e,()=>this.onCancel?.(e.dialogId))}submitInput(e,t){e.preventDefault(),this.answerDialog(t,this.inputValue)}closeWith(e,t){if(this.closing)return;this.closing=!0;let n=e.dialogId;Promise.resolve().then(t).catch(()=>{}).finally(()=>{this.dialog?.dialogId===n&&(this.closing=!1)})}changeInput(e){let t=e.currentTarget;t instanceof HTMLInputElement&&(this.inputValue=t.value)}dismissClosed(e){this.onDismiss?.(e.dialog.dialogId)}currentIdentity(){if(this.outcome!==void 0)return`closed:${this.outcome.dialog.dialogId}`;if(this.dialog!==void 0)return`open:${this.dialog.dialogId}`}syncCountdownTimer(){let e=this.isConnected&&this.outcome===void 0&&this.dialog?.timeoutAt!==void 0;if(e&&this.countdownTimer===void 0){this.countdownNow=Date.now(),this.countdownTimer=window.setInterval(()=>{this.countdownNow=Date.now()},
|
|
2763
|
+
`}answerDialog(e,t){this.closeWith(e,()=>this.onAnswer?.(e.dialogId,t))}cancelDialog(e){this.closeWith(e,()=>this.onCancel?.(e.dialogId))}submitInput(e,t){e.preventDefault(),this.answerDialog(t,this.inputValue)}closeWith(e,t){if(this.closing)return;this.closing=!0;let n=e.dialogId;Promise.resolve().then(t).catch(()=>{}).finally(()=>{this.dialog?.dialogId===n&&(this.closing=!1)})}changeInput(e){let t=e.currentTarget;t instanceof HTMLInputElement&&(this.inputValue=t.value)}dismissClosed(e){this.onDismiss?.(e.dialog.dialogId)}currentIdentity(){if(this.outcome!==void 0)return`closed:${this.outcome.dialog.dialogId}`;if(this.dialog!==void 0)return`open:${this.dialog.dialogId}`}syncCountdownTimer(){let e=this.isConnected&&this.outcome===void 0&&this.dialog?.timeoutAt!==void 0;if(e&&this.countdownTimer===void 0){this.countdownNow=Date.now(),this.countdownTimer=window.setInterval(()=>{this.countdownNow=Date.now()},aw);return}e||this.stopCountdownTimer()}stopCountdownTimer(){this.countdownTimer!==void 0&&(window.clearInterval(this.countdownTimer),this.countdownTimer=void 0)}static{this.styles=h`
|
|
2760
2764
|
:host {
|
|
2761
2765
|
display: block;
|
|
2762
2766
|
box-sizing: border-box;
|
|
@@ -2892,7 +2896,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2892
2896
|
.primary-action, .secondary-action, .option-button { min-height: 42px; }
|
|
2893
2897
|
.dialog-detail { max-height: min(40vh, 320px); }
|
|
2894
2898
|
}
|
|
2895
|
-
`}};H([b({attribute:!1})],
|
|
2899
|
+
`}};H([b({attribute:!1})],dw.prototype,`dialog`,void 0),H([b({attribute:!1})],dw.prototype,`outcome`,void 0),H([b({attribute:!1})],dw.prototype,`onAnswer`,void 0),H([b({attribute:!1})],dw.prototype,`onCancel`,void 0),H([b({attribute:!1})],dw.prototype,`onDismiss`,void 0),H([x()],dw.prototype,`inputValue`,void 0),H([x()],dw.prototype,`closing`,void 0),H([x()],dw.prototype,`countdownNow`,void 0),dw=H([y(`extension-dialog-card`)],dw);var fw=class extends v{constructor(...e){super(...e),this.positionPercent=0,this.loadedPercent=100}render(){let e=pw(this.positionPercent),t=pw(this.loadedPercent),n=`Message position: about ${String(Math.round(e))}% through conversation. ${String(Math.round(t))}% of messages loaded.`;return g`
|
|
2896
2900
|
<div
|
|
2897
2901
|
class="meter"
|
|
2898
2902
|
style=${`--position:${e.toFixed(2)}%;`}
|
|
@@ -2915,18 +2919,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2915
2919
|
.track { position: relative; height: 4px; margin-top: 4px; border-radius: 999px; background: color-mix(in srgb, var(--pi-border-muted) 34%, transparent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--pi-bg) 55%, transparent); }
|
|
2916
2920
|
.progress { position: absolute; left: 0; width: var(--position); top: 0; bottom: 0; border-radius: 999px; background: color-mix(in srgb, var(--pi-accent) 42%, var(--pi-border-muted)); }
|
|
2917
2921
|
.marker { position: absolute; left: var(--position); top: 50%; width: 10px; height: 10px; border: 2px solid var(--pi-bg); border-radius: 50%; background: var(--pi-accent); box-shadow: 0 2px 8px var(--pi-shadow); transform: translate(-50%, -50%); }
|
|
2918
|
-
`}};H([b({type:Number})],
|
|
2922
|
+
`}};H([b({type:Number})],fw.prototype,`positionPercent`,void 0),H([b({type:Number})],fw.prototype,`loadedPercent`,void 0),fw=H([y(`conversation-meter`)],fw);function pw(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}var mw=new B.Renderer;mw.html=({text:e})=>vw(e);var hw=300,gw=new Map;function _w(e){let t=gw.get(e);if(t!==void 0)return t;let n=bw(B.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:mw}));if(gw.set(e,n),gw.size>hw){let e=gw.keys().next().value;e!==void 0&&gw.delete(e)}return n}function vw(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}var yw=`table-scroll`;function bw(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`)&&!Sw(t.value)&&e.removeAttribute(t.name)}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),xw(t.content),t.innerHTML}function xw(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(yw)===!0)return;let t=document.createElement(`div`);t.className=yw,t.setAttribute(`role`,`region`),t.setAttribute(`aria-label`,`Table`),t.setAttribute(`tabindex`,`0`),e.before(t),t.append(e)})}function Sw(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}var Cw=class extends v{constructor(...e){super(...e),this.text=``,this.parsedText=``,this.parsedHtml=``,this.enhancedForHtml=``,this.streamingSuffix=``,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(){if(!(this.parsedText.length>0&&this.text.startsWith(this.parsedText)&&this.text.length>this.parsedText.length))return this.text!==this.parsedText&&(this.parsedHtml=_w(this.text),this.parsedText=this.text),this.settleTimer=void 0,this.streamingSuffix=``,g`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${hg(this.parsedHtml)}</div>`;let e=this.text.slice(this.parsedText.length);return this.streamingSuffix=e,this.scheduleSettleParse(),g`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${hg(this.parsedHtml)}${e===``?``:g`<span class="stream-suffix">${e}</span>`}</div>`}updated(){this.enhancedForHtml!==this.parsedHtml&&(this.enhancedForHtml=this.parsedHtml,this.enhanceCodeBlocks())}scheduleSettleParse(){this.settleTimer===void 0&&(this.settleTimer=setTimeout(()=>{this.settleTimer=void 0,this.parsedText!==this.text&&(this.parsedHtml=_w(this.text),this.parsedText=this.text,this.streamingSuffix=``,this.requestUpdate())},350))}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 Ex(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=og}};H([b()],Cw.prototype,`text`,void 0),Cw=H([y(`formatted-text`)],Cw);var ww=180,Tw=class extends v{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=Dw(e.args),n=kw(e.details),r=e.preview,i=n??r?.diff,a=i===void 0?void 0:Aw(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=Ew(e,t);return g`
|
|
2919
2923
|
<section class=${`tool-card ${e.status}`}>
|
|
2920
2924
|
<div class="tool-header">
|
|
2921
2925
|
<div class="tool-title">
|
|
2922
|
-
<span class="status-icon" aria-hidden="true">${
|
|
2926
|
+
<span class="status-icon" aria-hidden="true">${Pw(e.status)}</span>
|
|
2923
2927
|
<strong>${e.toolName}</strong>
|
|
2924
2928
|
${this.renderHeaderTarget(l)}
|
|
2925
2929
|
</div>
|
|
2926
2930
|
<div class="tool-meta">
|
|
2927
|
-
${
|
|
2931
|
+
${Ow(e)===void 0?null:g`<span>${Ow(e)}</span>`}
|
|
2928
2932
|
${a===void 0?null:g`<span class="diff-stats"><b class="added">+${a.added}</b><span>/</span><b class="removed">-${a.removed}</b></span>`}
|
|
2929
|
-
<span class="status-label">${
|
|
2933
|
+
<span class="status-label">${Fw(e.status)}</span>
|
|
2930
2934
|
</div>
|
|
2931
2935
|
</div>
|
|
2932
2936
|
|
|
@@ -2951,7 +2955,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2951
2955
|
`}
|
|
2952
2956
|
</details>
|
|
2953
2957
|
`}renderDiffBody(e,t,n){let r=e.split(`
|
|
2954
|
-
`),i=!this.showFullDiff&&r.length>
|
|
2958
|
+
`),i=!this.showFullDiff&&r.length>ww,a=i?r.slice(0,ww):r;return g`
|
|
2955
2959
|
<details class="diff-details" ?open=${this.diffOpen} @toggle=${e=>{this.onDiffToggle(e)}}>
|
|
2956
2960
|
<summary>
|
|
2957
2961
|
<span>${t}</span>
|
|
@@ -2962,14 +2966,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2962
2966
|
<span>${i?`Showing ${String(a.length)} of ${String(r.length)} lines`:`Full diff`}</span>
|
|
2963
2967
|
<button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?`Copied`:`Copy diff`}</button>
|
|
2964
2968
|
</div>
|
|
2965
|
-
<pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${
|
|
2969
|
+
<pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${jw(e)}>${e}</span>`)}</code></pre>
|
|
2966
2970
|
${i?g`
|
|
2967
2971
|
<button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
|
|
2968
2972
|
Show all ${String(r.length)} diff lines
|
|
2969
2973
|
</button>
|
|
2970
2974
|
`:null}
|
|
2971
2975
|
</details>
|
|
2972
|
-
`}onDiffToggle(e){let t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){if(!await
|
|
2976
|
+
`}onDiffToggle(e){let t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){if(!await Ex(e)){this.copied=!1;return}this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}static{this.styles=h`
|
|
2973
2977
|
:host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
|
|
2974
2978
|
.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); }
|
|
2975
2979
|
.tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
|
|
@@ -3013,24 +3017,24 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3013
3017
|
.diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
|
|
3014
3018
|
.diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
|
|
3015
3019
|
.show-more { justify-self: start; }
|
|
3016
|
-
`}};H([b({attribute:!1})],
|
|
3017
|
-
`))
|
|
3020
|
+
`}};H([b({attribute:!1})],Tw.prototype,`execution`,void 0),H([x()],Tw.prototype,`showFullDiff`,void 0),H([x()],Tw.prototype,`copied`,void 0),H([x()],Tw.prototype,`diffOpen`,void 0),Tw=H([y(`tool-execution-view`)],Tw);function Ew(e,t){if(t!==void 0&&t!==``)return{label:`File`,text:t};let n=Rw(e.args,`command`);if(n!==void 0&&n!==``)return{label:`Command`,text:n};if(e.summary!==``)return{label:`Input`,text:e.summary}}function Dw(e){return Rw(e,`path`)??Rw(e,`file_path`)}function Ow(e){if(e.toolName!==`edit`)return;let t=Lw(e.args,`edits`);if(Array.isArray(t))return`${String(t.length)} edit${t.length===1?``:`s`}`;if(typeof Lw(e.args,`oldText`)==`string`&&typeof Lw(e.args,`newText`)==`string`)return`1 edit`}function kw(e){return Rw(e,`diff`)}function Aw(e){let t=0,n=0;for(let r of e.split(`
|
|
3021
|
+
`))Mw(r)?t++:Nw(r)&&n++;return{added:t,removed:n}}function jw(e){return Mw(e)?`added`:Nw(e)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`+++`)||e.startsWith(`---`)?`file`:e.startsWith(`diff `)||e.startsWith(`index `)?`meta`:`context`}function Mw(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)}function Nw(e){return e.startsWith(`-`)&&!e.startsWith(`---`)}function Pw(e){return e===`success`?`✓`:e===`error`?`✖`:e===`running`?`●`:`○`}function Fw(e){return e===`success`?`done`:e===`error`?`failed`:e===`running`?`running`:`pending`}function Iw(e){return typeof e==`object`&&!!e}function Lw(e,t){return Iw(e)?e[t]:void 0}function Rw(e,t){let n=Lw(e,t);return typeof n==`string`?n:void 0}var zw=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`medium`}),Bw=new Intl.DateTimeFormat(void 0,{timeStyle:`short`});function Vw(e){if(typeof e!=`object`||!e)return;let t=Reflect.get(e,`queuedMessages`);if(Array.isArray(t))return{queuedMessages:t}}function Hw(e){return g`
|
|
3018
3022
|
<svg class=${`notification-icon notification-disclosure-icon${e?``:` expanded`}`} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3019
3023
|
<path d="m9 18 6-6-6-6"></path>
|
|
3020
3024
|
</svg>
|
|
3021
|
-
`}function
|
|
3025
|
+
`}function Uw(){return g`
|
|
3022
3026
|
<svg class="notification-icon notification-close-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3023
3027
|
<path d="M6 6l12 12"></path>
|
|
3024
3028
|
<path d="M18 6 6 18"></path>
|
|
3025
3029
|
</svg>
|
|
3026
|
-
`}function
|
|
3030
|
+
`}function Ww(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 Gw(e){return Kw(e,0,100)}function Kw(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function qw(e){if(e.state===`sending`)return{glyph:`◌`,text:`Sending`,label:`Sending`,tone:`pending`};if(e.state===`failed`)return{glyph:`!`,text:`Not sent`,label:`Not sent - the server never received this message`,tone:`failed`};if(e.state===`queued`){let t=e.kind===`steer`?`Queued to steer`:`Queued`;return{glyph:`✓`,text:t,label:`${t} - the server has this message and the agent will take it next`,tone:`received`}}return e.state===`received`?{glyph:`✓`,text:`Sent`,label:`Sent - the server received this message`,tone:`received`}:{glyph:`✓✓`,text:`Read`,label:`Read - the agent took this message into the conversation`,tone:`delivered`}}function Jw(e){return{src:`data:${e.mimeType};base64,${e.data}`,alt:`attached image`}}function Yw(e){return e===void 0||e===``?`tool output`:`${e} output`}function Xw(e){return`m:${String(e)}`}function Zw(e){return`g:${String(e)}`}function Qw(e){return`e:${String(e)}`}function $w(e){return`g:${String(e)}`}function eT(e){return e?`msg event-group live`:`msg event-group`}function tT(e){return e?`live events`:`events`}function nT(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 rT(e){let t=e.meta?.timestamp;return[t===void 0?void 0:iT(t),aT(e),e.meta?.thinkingLevel].filter(e=>e!==void 0&&e!==``).join(` · `)}function iT(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return zw.format(t)}function aT(e){let t=e.meta?.model;if(t===void 0)return;let n=t.responseId??t.id;return n===void 0||n===``?t.provider:t.provider!==void 0&&t.provider!==``?`${t.provider}/${n}`:n}var K=class extends v{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.askDraftSessionId=``,this.pendingDialogs=[],this.closedDialogs=[],this.warningsVisible=!0,this.pinnedToBottom=!0,this.zoomedImage=void 0,this.collapsedTopDrawerKeys=new Set,this.expandedTopDrawerKeys=new Set,this.goals=[],this.activityFilter=`all`,this.activityScope=`active`,this.turnNowMs=0,this.disclosures=new XS,this.scrollController=new TC,this.drawerTabEdgeTracker=new VC(()=>{this.requestUpdate()}),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.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.status?.queuedMessages??[])},this.handleToggleWarnings=()=>{this.onToggleWarnings?.()},this.closeActivityOutput=()=>{this.activityOutput!==void 0&&this.onCloseActivityOutput?.()},this.onActivityOutputDialogClick=e=>{e.target===this.activityOutputDialog&&this.closeActivityOutput()}}connectedCallback(){super.connectedCallback(),window.addEventListener(`resize`,this.onViewportResize),window.addEventListener(`pagehide`,this.onPageHide),window.visualViewport?.addEventListener(`resize`,this.onViewportResize)}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}disconnectedCallback(){this.stopTurnClock(),this.saveScrollPosition(),this.scrollController.dispose(),this.drawerTabEdgeTracker.dispose(),this.releaseImageZoomModal(),this.releaseActivityOutputModal(),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.scrollToOpenAskFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenAskFrame),this.scrollToOpenAskFrame=void 0),this.scrollToOpenDialogFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenDialogFrame),this.scrollToOpenDialogFrame=void 0),this.conversationRailFrame!==void 0&&cancelAnimationFrame(this.conversationRailFrame),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.turnStartedAtMs=void 0,this.disclosures.syncSession(this.sessionId),this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0,this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0),this.scrollToOpenAskFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenAskFrame),this.scrollToOpenAskFrame=void 0),this.scrollToOpenDialogFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenDialogFrame),this.scrollToOpenDialogFrame=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`)||e.has(`pendingAsk`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`))&&(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();let t=e.has(`pendingAsk`)&&this.isNewPendingAsk(e.get(`pendingAsk`)),n=e.has(`pendingDialogs`)&&this.isNewOpenDialog(e.get(`pendingDialogs`));!e.has(`sessionId`)&&t&&this.pinnedToBottom?this.scrollToOpenAsk():!e.has(`sessionId`)&&n&&this.pinnedToBottom?this.scrollToOpenDialog():!e.has(`sessionId`)&&(e.has(`messages`)||this.queueGrew(e.get(`status`))||e.has(`pendingAsk`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`))&&this.pinnedToBottom&&this.scrollToBottom(),(e.has(`messages`)||e.has(`messageStart`)||e.has(`messageTotal`)||e.has(`hasMore`)||e.has(`loadingMore`))&&this.scheduleConversationRailUpdate(),(e.has(`messages`)||e.has(`messageStart`)||e.has(`hasMore`)||e.has(`loadingMore`)||e.has(`pendingAsk`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`))&&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(),e.has(`activityOutput`)&&this.syncActivityOutputDialog(),this.drawerTabEdgeTracker.observe(this.drawerTabs??void 0),(e.has(`status`)||e.has(`activity`)||e.has(`isSendingPrompt`))&&this.syncTurnClock()}syncImageZoomDialog(){let e=this.imageZoomDialog;if(e!==void 0){if(this.zoomedImage!==void 0){if(this.imageZoomModalRegistration===void 0){let t=Rh({element:e,nativeTopLayer:!0,focus:()=>{(this.renderRoot.querySelector(`.image-zoom-close`)??e).focus()}});this.imageZoomModalRegistration=t;try{e.open||e.showModal()}catch(e){throw this.imageZoomModalRegistration=void 0,t.unregister(),e}}this.imageZoomModalRegistration.focus();return}e.open&&e.close(),this.releaseImageZoomModal()}}syncActivityOutputDialog(){let e=this.activityOutputDialog;if(e!==void 0){if(this.activityOutput!==void 0){if(this.activityOutputModalRegistration===void 0){let t=Rh({element:e,nativeTopLayer:!0,focus:()=>{(this.renderRoot.querySelector(`.activity-output-close`)??e).focus()}});this.activityOutputModalRegistration=t;try{e.open||e.showModal()}catch(e){throw this.activityOutputModalRegistration=void 0,t.unregister(),e}}this.activityOutputModalRegistration.focus();return}e.open&&e.close(),this.releaseActivityOutputModal()}}releaseActivityOutputModal(){let e=this.activityOutputModalRegistration;this.activityOutputModalRegistration=void 0,e?.unregister()}releaseImageZoomModal(){let e=this.imageZoomModalRegistration;this.imageZoomModalRegistration=void 0,e?.unregister()}notificationTargetChanged(e){let t=this.notificationInbox;return!Ww(e)||t===void 0?e!==t:ep(e)!==ep(t)}render(){let e=this.groupedMessages();return g`
|
|
3027
3031
|
${this.renderTopNotices()}
|
|
3028
3032
|
${this.renderNotificationLiveRegions()}
|
|
3029
3033
|
<div class="chat-wrap">
|
|
3030
3034
|
${this.renderConversationRail()}
|
|
3031
3035
|
<div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${e=>{this.onWheel(e)}} @touchstart=${e=>{this.onTouchStart(e)}} @touchmove=${e=>{this.onTouchMove(e)}}>
|
|
3032
3036
|
${this.renderHistoryBoundary()}
|
|
3033
|
-
${
|
|
3037
|
+
${qS(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))}
|
|
3034
3038
|
${this.renderSessionActivity()}
|
|
3035
3039
|
${this.renderQueuedMessages()}
|
|
3036
3040
|
${this.renderOpenAsk()}
|
|
@@ -3040,7 +3044,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3040
3044
|
</div>
|
|
3041
3045
|
${this.renderImageZoom()}
|
|
3042
3046
|
${this.renderActivityOutput()}
|
|
3043
|
-
`}renderTopNotices(){let e=this.renderWarnings(),t=this.renderTopDrawer();return e===null&&t===null?null:g`<div class="top-notices">${e}${t}</div>`}renderTopDrawer(){let e=this.activityPanelState(),t=this.visibleNotificationInbox();if(e===void 0&&t===void 0&&this.goals.length===0)return null;let n=
|
|
3047
|
+
`}renderTopNotices(){let e=this.renderWarnings(),t=this.renderTopDrawer();return e===null&&t===null?null:g`<div class="top-notices">${e}${t}</div>`}renderTopDrawer(){let e=this.activityPanelState(),t=this.visibleNotificationInbox();if(e===void 0&&t===void 0&&this.goals.length===0)return null;let n=bT({activity:e!==void 0,notifications:t!==void 0,goals:this.goals.length>0},this.topDrawerTab),r=this.topDrawerKey(),i=this.expandedTopDrawerKeys.has(r)?!1:this.collapsedTopDrawerKeys.has(r)||!yT(),a=i?`Show session activity and notifications`:`Hide session activity and notifications`,o=t===void 0?0:Xf(t);return g`
|
|
3044
3048
|
<section
|
|
3045
3049
|
class=${`top-drawer${i?` collapsed`:``}`}
|
|
3046
3050
|
role="region"
|
|
@@ -3048,7 +3052,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3048
3052
|
@focusout=${e=>{this.releaseEmptyNotificationTray(e)}}
|
|
3049
3053
|
>
|
|
3050
3054
|
<header class="drawer-header" data-notification-focus="header" tabindex="-1">
|
|
3051
|
-
<div class=${`drawer-tabs-frame${
|
|
3055
|
+
<div class=${`drawer-tabs-frame${zC(this.drawerTabEdgeTracker.edges)}`}>
|
|
3052
3056
|
<div class="drawer-tabs" role="tablist" aria-label="Session drawer sections" @scroll=${()=>{this.drawerTabEdgeTracker.refresh()}} @keydown=${e=>{this.onDrawerTabsKeydown(e)}}>
|
|
3053
3057
|
${e===void 0?null:g`
|
|
3054
3058
|
<button
|
|
@@ -3062,7 +3066,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3062
3066
|
@click=${()=>{this.selectTopDrawerTab(`activity`,i)}}
|
|
3063
3067
|
>
|
|
3064
3068
|
${e.summary.working?g`<span class="subagent-dot working" aria-hidden="true"></span>`:null}
|
|
3065
|
-
<span class="drawer-tab-label">${
|
|
3069
|
+
<span class="drawer-tab-label">${mT({active:e.activeCount,total:e.total})}</span>
|
|
3066
3070
|
</button>
|
|
3067
3071
|
`}
|
|
3068
3072
|
${t===void 0?null:g`
|
|
@@ -3115,7 +3119,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3115
3119
|
aria-expanded=${String(!i)}
|
|
3116
3120
|
aria-controls=${n===`activity`?`session-activity-list`:`session-notification-list`}
|
|
3117
3121
|
@click=${()=>{this.toggleTopDrawer(i)}}
|
|
3118
|
-
>${
|
|
3122
|
+
>${Hw(i)}</button>
|
|
3119
3123
|
</div>
|
|
3120
3124
|
</header>
|
|
3121
3125
|
<div class="drawer-body" ?hidden=${i}>
|
|
@@ -3132,7 +3136,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3132
3136
|
`:null}
|
|
3133
3137
|
</div>
|
|
3134
3138
|
</section>
|
|
3135
|
-
`}visibleNotificationInbox(){let e=this.notificationInbox;if(e?.sessionId!==this.sessionId)return;let t=e.pendingDismissedIds.size>0||e.dismissAllPending,n=this.retainedEmptyNotificationTrayTargetKey===ep(e);if(!(Xf(e)===0&&!t&&!n))return e}topDrawerKey(){let e=this.notificationInbox;return e?.sessionId===this.sessionId?ep(e):JSON.stringify([null,null,this.sessionId])}toggleTopDrawer(e){let t=this.topDrawerKey(),n=new Set(this.collapsedTopDrawerKeys),r=new Set(this.expandedTopDrawerKeys);e?(n.delete(t),r.add(t)):(r.delete(t),n.add(t)),this.collapsedTopDrawerKeys=n,this.expandedTopDrawerKeys=r}selectTopDrawerTab(e,t){this.topDrawerTab=e,t&&this.toggleTopDrawer(t)}renderActivityFilters(e,t){let n=
|
|
3139
|
+
`}visibleNotificationInbox(){let e=this.notificationInbox;if(e?.sessionId!==this.sessionId)return;let t=e.pendingDismissedIds.size>0||e.dismissAllPending,n=this.retainedEmptyNotificationTrayTargetKey===ep(e);if(!(Xf(e)===0&&!t&&!n))return e}topDrawerKey(){let e=this.notificationInbox;return e?.sessionId===this.sessionId?ep(e):JSON.stringify([null,null,this.sessionId])}toggleTopDrawer(e){let t=this.topDrawerKey(),n=new Set(this.collapsedTopDrawerKeys),r=new Set(this.expandedTopDrawerKeys);e?(n.delete(t),r.add(t)):(r.delete(t),n.add(t)),this.collapsedTopDrawerKeys=n,this.expandedTopDrawerKeys=r}selectTopDrawerTab(e,t){this.topDrawerTab=e,t&&this.toggleTopDrawer(t)}renderActivityFilters(e,t){let n=hT(e);return n.length<=1?null:g`
|
|
3136
3140
|
<div class="activity-filters" role="group" aria-label="Filter session activity">
|
|
3137
3141
|
${n.map(e=>g`
|
|
3138
3142
|
<button
|
|
@@ -3143,9 +3147,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3143
3147
|
>${e.label} <span class="activity-filter-count">${String(e.count)}</span></button>
|
|
3144
3148
|
`)}
|
|
3145
3149
|
</div>
|
|
3146
|
-
`}activityPanelState(){let e=this.subagents??[],t=this.subagentRuns??[],n=this.backgroundTasks??[];if(e.length===0&&t.length===0&&n.length===0)return;let r=
|
|
3150
|
+
`}activityPanelState(){let e=this.subagents??[],t=this.subagentRuns??[],n=this.backgroundTasks??[];if(e.length===0&&t.length===0&&n.length===0)return;let r=CT(e),i=sT(t),a=cT(n),o=xT([...r.map(e=>e.status),...i.map(e=>e.status),...a.map(e=>e.status)]),s=[...r,...i,...a].filter(e=>fT(e.status)).length;return{rows:r,runRows:i,taskRows:a,summary:o,total:r.length+i.length+a.length,activeCount:s}}renderActivityPanel(e){let t=gT(this.activityFilter,e),n=e.activeCount===0&&this.activityScope===`active`?`empty-active`:this.activityScope,r=lT([...e.rows.map((e,t)=>({kind:`subagents`,index:t,status:e.status,row:e})),...e.runRows.map((e,t)=>({kind:`runs`,index:t,status:e.status,startedAt:e.run.startedAt,row:e})),...e.taskRows.map((e,t)=>({kind:`tasks`,index:t,status:e.status,startedAt:e.task.startedAt,row:e}))]).filter(e=>t===`all`||t===e.kind),i=r.filter(e=>n===`all`||!pT(e.status)),a=r.filter(e=>pT(e.status)).length;return g`
|
|
3147
3151
|
<div class="subagents-list" id="session-activity-list" role="tabpanel" aria-labelledby="drawer-tab-activity">
|
|
3148
|
-
${e.total===0||n===`empty-active`?g`<p class="drawer-hint">${
|
|
3152
|
+
${e.total===0||n===`empty-active`?g`<p class="drawer-hint">${_T}</p>`:null}
|
|
3149
3153
|
${this.renderActivityFilters(e,t)}
|
|
3150
3154
|
${n===`empty-active`?g`<p class="activity-empty">Nothing running right now.</p>`:null}
|
|
3151
3155
|
${i.map(e=>this.renderActivityEntry(e))}
|
|
@@ -3217,7 +3221,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3217
3221
|
<div class="notification-metadata">
|
|
3218
3222
|
<strong class="notification-severity">${n}</strong>
|
|
3219
3223
|
<span aria-hidden="true">·</span>
|
|
3220
|
-
<time datetime=${t.receivedAt}>${
|
|
3224
|
+
<time datetime=${t.receivedAt}>${Bw.format(new Date(t.receivedAt))}</time>
|
|
3221
3225
|
</div>
|
|
3222
3226
|
<p class="notification-message" dir="auto">${t.message}</p>
|
|
3223
3227
|
${r===void 0?null:g`<p class="notification-truncated">${r}</p>`}
|
|
@@ -3236,15 +3240,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3236
3240
|
title="Dismiss notification"
|
|
3237
3241
|
?disabled=${e.pendingDismissedIds.has(t.id)||e.dismissAllPending||this.onDismissNotification===void 0}
|
|
3238
3242
|
@click=${()=>{this.dismissNotification(t.id)}}
|
|
3239
|
-
>${
|
|
3243
|
+
>${Uw()}</button>
|
|
3240
3244
|
</div>
|
|
3241
3245
|
</article>
|
|
3242
3246
|
`})}
|
|
3243
3247
|
</div>
|
|
3244
3248
|
`}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`
|
|
3245
|
-
<div class="visually-hidden notification-live" aria-live="polite" aria-atomic="false">${
|
|
3246
|
-
<div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${
|
|
3247
|
-
`}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=$f(t.notifications,e),r=ep(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=ep(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===ep(r)&&Xf(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||ep(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}Xf(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}renderWarnings(){let e=
|
|
3249
|
+
<div class="visually-hidden notification-live" aria-live="polite" aria-atomic="false">${qS(t,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${Yf(e)}</span>`)}</div>
|
|
3250
|
+
<div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${qS(n,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${Yf(e)}</span>`)}</div>
|
|
3251
|
+
`}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=$f(t.notifications,e),r=ep(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=ep(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===ep(r)&&Xf(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||ep(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}Xf(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}renderWarnings(){let e=nT(this.status);return!this.warningsVisible||e.length===0?null:g`
|
|
3248
3252
|
<aside class="session-warnings" role="alert" aria-live="polite">
|
|
3249
3253
|
${this.onToggleWarnings===void 0?null:g`
|
|
3250
3254
|
<div class="session-warnings-controls">
|
|
@@ -3265,7 +3269,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3265
3269
|
${e.map(e=>{let t=e.dismissId;return g`
|
|
3266
3270
|
<div class=${e.severityClass}>
|
|
3267
3271
|
<div class="session-warning-head">
|
|
3268
|
-
${
|
|
3272
|
+
${tg(e.severity,`session-warning-icon`)}
|
|
3269
3273
|
${e.source===void 0?null:g`<span class="session-warning-source">${e.source}</span>`}
|
|
3270
3274
|
</div>
|
|
3271
3275
|
<div class="session-warning-body">
|
|
@@ -3301,12 +3305,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3301
3305
|
<img class="image-zoom-full" src=${this.zoomedImage.src} alt=${this.zoomedImage.alt} />
|
|
3302
3306
|
`}
|
|
3303
3307
|
</dialog>
|
|
3304
|
-
`}transcriptMessages(){return Zl(this.messages,[...this.clientQueuedMessages,...this.status?.queuedMessages??[]])}queueGrew(e){let t=
|
|
3308
|
+
`}transcriptMessages(){return Zl(this.messages,[...this.clientQueuedMessages,...this.status?.queuedMessages??[]])}queueGrew(e){let t=Vw(e)?.queuedMessages?.length??0;return(this.status?.queuedMessages??[]).length>t}groupedMessages(){let e=this.transcriptMessages();if(this.groupedMessagesInput===e&&this.groupedMessagesStart===this.messageStart)return this.groupedMessagesCache;let t=this.groupedMessagesInput;if(this.groupedMessagesStart===this.messageStart&&t!==void 0){let n=sC(t,this.groupedMessagesCache,e);if(n!==void 0)return this.groupedMessagesInput=e,this.groupedMessagesCache=n,n}return this.groupedMessagesInput=e,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=nC(e,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`}syncTurnClock(){if(!this.isSessionLive()){this.turnStartedAtMs=void 0,this.stopTurnClock();return}this.turnStartedAtMs??=Date.now(),this.turnNowMs=Date.now(),this.turnClockTimer===void 0&&(this.turnClockTimer=window.setInterval(()=>{this.turnNowMs=Date.now()},1e3))}stopTurnClock(){this.turnClockTimer!==void 0&&(window.clearInterval(this.turnClockTimer),this.turnClockTimer=void 0)}renderActivityDock(){if(this.pendingAsk!==void 0)return null;if(this.isSendingPrompt)return g`
|
|
3305
3309
|
<div class="activity-dock sending" aria-live="polite">
|
|
3306
3310
|
<span class="state-dots"><span class="state-dot"></span><span class="state-dot"></span><span class="state-dot"></span></span>
|
|
3307
3311
|
<span class="activity-text">Sending your message…</span>
|
|
3308
3312
|
</div>
|
|
3309
|
-
`;let e=this.activityState();if(e===void 0)return null;let t=this.activityCategory(e),n=
|
|
3313
|
+
`;let e=this.activityState();if(e===void 0)return null;let t=this.activityCategory(e),n=vT(this.activityPanelState());if(n!==void 0&&(t===`idle`||t===void 0))return g`
|
|
3310
3314
|
<button
|
|
3311
3315
|
type="button"
|
|
3312
3316
|
class="activity-dock background"
|
|
@@ -3318,13 +3322,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3318
3322
|
<span class="activity-text">${n}</span>
|
|
3319
3323
|
<span class="subagent-chevron" aria-hidden="true">›</span>
|
|
3320
3324
|
</button>
|
|
3321
|
-
`;let r=t===`working`?
|
|
3325
|
+
`;let r=t===`working`?dT(this.turnStartedAtMs,this.turnNowMs):void 0;return g`
|
|
3322
3326
|
<div class=${`activity-dock ${t??``}${r?.long===!0?` long-running`:``}`} aria-live="polite">
|
|
3323
3327
|
${t===`working`?g`<span class="state-dots"><span class="state-dot"></span><span class="state-dot"></span><span class="state-dot"></span></span>`:g`<span class="dot"></span>`}
|
|
3324
3328
|
<span class="activity-text">${this.activityText(e)}</span>
|
|
3325
3329
|
${r===void 0?null:g`<span class="activity-elapsed" aria-hidden="true">${r.text}</span>`}
|
|
3326
3330
|
</div>
|
|
3327
|
-
`}revealActivity(){let e=this.topDrawerKey(),t=new Set(this.collapsedTopDrawerKeys);t.delete(e);let n=new Set(this.expandedTopDrawerKeys);n.add(e),this.collapsedTopDrawerKeys=t,this.expandedTopDrawerKeys=n,this.topDrawerTab=`activity`,this.activityScope=`active`}renderDeliveryMark(e){let t=e.meta?.delivery;if(t===void 0)return null;let n=
|
|
3331
|
+
`}revealActivity(){let e=this.topDrawerKey(),t=new Set(this.collapsedTopDrawerKeys);t.delete(e);let n=new Set(this.expandedTopDrawerKeys);n.add(e),this.collapsedTopDrawerKeys=t,this.expandedTopDrawerKeys=n,this.topDrawerTab=`activity`,this.activityScope=`active`}renderDeliveryMark(e){let t=e.meta?.delivery;if(t===void 0)return null;let n=qw(t);return g`
|
|
3328
3332
|
<div class=${`delivery-mark ${n.tone}`} role="status" aria-label=${n.label}>
|
|
3329
3333
|
<span class="delivery-glyph" aria-hidden="true">${n.glyph}</span>
|
|
3330
3334
|
<span class="delivery-text">${n.text}</span>
|
|
@@ -3344,7 +3348,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3344
3348
|
.onSubmit=${this.onSubmitAsk}
|
|
3345
3349
|
></ask-user-card>
|
|
3346
3350
|
`}renderExtensionDialogs(){let e=this.pendingDialogs[0];if(e===void 0&&this.closedDialogs.length===0)return null;let t=this.pendingDialogs.length-1;return g`
|
|
3347
|
-
${
|
|
3351
|
+
${qS(this.closedDialogs,e=>e.dialog.dialogId,e=>g`
|
|
3348
3352
|
<extension-dialog-card
|
|
3349
3353
|
class="closed-dialog-card"
|
|
3350
3354
|
data-scroll-anchor-id=${`closed-dialog:${e.dialog.dialogId}`}
|
|
@@ -3368,7 +3372,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3368
3372
|
<span>The agent is summarizing earlier context. New prompts will be queued until compaction finishes.</span>
|
|
3369
3373
|
${this.pendingMessageCount>0?g`<small>${this.pendingMessageCount} queued ${this.pendingMessageCount===1?`message`:`messages`}</small>`:null}
|
|
3370
3374
|
</aside>
|
|
3371
|
-
`: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`}activityCategory(e){return this.activity?.phase===`error`?`error`:e===`idle`||e===`undefined`?Sm(this.status)?`asking`:`idle`:Sm(this.status)?`asking`:`working`}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(){if(!this.messages.length||this.messageTotal<=0)return null;let e=this.conversationDisplayTotal();return g`<conversation-meter .positionPercent=${this.conversationPositionPercent(e)} .loadedPercent=${this.hasMore?
|
|
3375
|
+
`: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`}activityCategory(e){return this.activity?.phase===`error`?`error`:e===`idle`||e===`undefined`?Sm(this.status)?`asking`:`idle`:Sm(this.status)?`asking`:`working`}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(){if(!this.messages.length||this.messageTotal<=0)return null;let e=this.conversationDisplayTotal();return g`<conversation-meter .positionPercent=${this.conversationPositionPercent(e)} .loadedPercent=${this.hasMore?Gw(this.messages.length/e*100):100}></conversation-meter>`}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 Gw(Kw(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`
|
|
3372
3376
|
<div class="history-boundary">
|
|
3373
3377
|
<button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>Load earlier messages</button>
|
|
3374
3378
|
<span>Scroll up to load earlier messages</span>
|
|
@@ -3381,7 +3385,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3381
3385
|
${e.parts.map(t=>this.renderPart(t,e))}
|
|
3382
3386
|
${this.renderDeliveryMark(e)}
|
|
3383
3387
|
</article>
|
|
3384
|
-
`}renderToolImageOutput(e,t,n){let r=
|
|
3388
|
+
`}renderToolImageOutput(e,t,n){let r=Yw(n);return g`
|
|
3385
3389
|
${this.renderScrollMarker(this.messageScrollMarkerId(t))}
|
|
3386
3390
|
<article class="msg tool-image-output" data-index=${t} data-scroll-anchor-id=${this.messageAnchorKey(t)}>
|
|
3387
3391
|
${this.renderMessageHeader(e,String(t),r)}
|
|
@@ -3389,10 +3393,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3389
3393
|
</article>
|
|
3390
3394
|
`}isToolExecutionOnlyMessage(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`toolExecution`)}isAskUserRecordOnlyMessage(e){return e.parts.length>0&&e.parts.every(e=>e.type===`askUserRecord`)}renderMessageGroup(e,t,n,r){let i=this.groupDisclosureKey(t,n,r),a=this.disclosures.isOpen(i,r);return g`
|
|
3391
3395
|
${this.renderScrollMarker(this.groupScrollMarkerId(n))}
|
|
3392
|
-
<details class=${
|
|
3396
|
+
<details class=${eT(r)} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${a} @toggle=${e=>{this.onGroupToggle(i,e,r)}}>
|
|
3393
3397
|
<summary>
|
|
3394
|
-
<b class="label">${
|
|
3395
|
-
<span>${
|
|
3398
|
+
<b class="label">${tT(r)}</b>
|
|
3399
|
+
<span>${rC(e)}</span>
|
|
3396
3400
|
</summary>
|
|
3397
3401
|
${a?this.renderMessageGroupBody(e,t):null}
|
|
3398
3402
|
</details>
|
|
@@ -3415,7 +3419,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3415
3419
|
</div>
|
|
3416
3420
|
`}queueEntryFor(e){let t=e.meta?.delivery?.clientMessageId;if(t===void 0)return;let n=this.status?.queuedMessages??[],r=n.find(e=>e.clientMessageId===t);if(r!==void 0)return r;let i=/^queued:([^:]+):(.*)$/.exec(t);if(i===null)return;let[,a,o]=i;return n.find(e=>e.kind===a&&e.text===o)}isQueuedLine(e){return this.queueEntryFor(e)!==void 0}renderQueuedBubbleRecall(e){if(this.onRecallQueuedMessage===void 0)return null;let t=this.queueEntryFor(e);return t===void 0?null:g`<button type="button" class="msg-action" data-action="recall" title="Recall: take this message back and put it in the composer" aria-label="Recall this queued message into the composer" @click=${()=>{this.onRecallQueuedMessage?.(t)}}>
|
|
3417
3421
|
<span aria-hidden="true">↩</span>
|
|
3418
|
-
</button>`}renderMessageActions(e,t){let n=this.onResendMessage!==void 0&&
|
|
3422
|
+
</button>`}renderMessageActions(e,t){let n=this.onResendMessage!==void 0&&HC(e),r=this.renderQueuedBubbleRecall(e);if(!this.isCopyableMessage(e)&&!n&&r===null)return null;let i=this.copiedMessageKey===t;return g`
|
|
3419
3423
|
<div class="msg-actions" aria-label="Message actions">
|
|
3420
3424
|
${r}
|
|
3421
3425
|
${n?g`<button type="button" class="msg-action" title="Edit and send again" aria-label="Put this message back in the composer to send again" @click=${t=>{this.resendMessage(e,t)}}>
|
|
@@ -3425,9 +3429,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3425
3429
|
<span aria-hidden="true">${i?`✓`:`⧉`}</span>
|
|
3426
3430
|
</button>`:null}
|
|
3427
3431
|
</div>
|
|
3428
|
-
`}resendMessage(e,t){t.stopPropagation();let n=
|
|
3432
|
+
`}resendMessage(e,t){t.stopPropagation();let n=UC(e);n!==void 0&&this.onResendMessage?.(n)}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(`
|
|
3429
3433
|
|
|
3430
|
-
`);return this.messageCopyTextCache.set(e,n),n}async copyNotification(e){if(!await
|
|
3434
|
+
`);return this.messageCopyTextCache.set(e,n),n}async copyNotification(e){if(!await Ex(e.message))return;let t=e.id;this.copiedNotificationId=t,setTimeout(()=>{this.copiedNotificationId===t&&(this.copiedNotificationId=void 0)},1200)}async copyMessage(e,t,n){n.stopPropagation(),await Ex(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=rT(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`
|
|
3431
3435
|
<details class="part skill-invocation">
|
|
3432
3436
|
<summary><b>[skill]</b> ${e.name}</summary>
|
|
3433
3437
|
<small>${e.location}</small>
|
|
@@ -3444,46 +3448,46 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3444
3448
|
.outcome=${e.outcome}
|
|
3445
3449
|
.draftSessionId=${this.askDraftSessionId}
|
|
3446
3450
|
></ask-user-card>
|
|
3447
|
-
`;if(e.type===`image`){let{src:t,alt:n}=
|
|
3451
|
+
`;if(e.type===`image`){let{src:t,alt:n}=Jw(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`
|
|
3448
3452
|
<details class="part" ?open=${e.isError}>
|
|
3449
3453
|
<summary>${e.isError?`✖`:`✓`} ${e.toolName} result</summary>
|
|
3450
3454
|
<formatted-text .text=${e.text}></formatted-text>
|
|
3451
3455
|
</details>
|
|
3452
|
-
`: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.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&&hC({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||kC(e)}isAtBottom(){let e=this.chat;return!e||OC(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})}))}isNewPendingAsk(e){return this.pendingAsk!==void 0&&(typeof e!=`object`||!e||Reflect.get(e,`askId`)!==this.pendingAsk.askId)}isNewOpenDialog(e){let t=this.pendingDialogs[0];if(t===void 0)return!1;if(!Array.isArray(e))return!0;let n=e[0];return typeof n!=`object`||!n||Reflect.get(n,`dialogId`)!==t.dialogId}scrollToOpenAsk(){this.scrollToOpenAskFrame===void 0&&(this.scrollToBottomFrame!==void 0&&(cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToBottomFrame=void 0),this.scrollToOpenAskFrame=requestAnimationFrame(()=>{this.scrollToOpenAskFrame=void 0,this.withSuppressedScrollSave(()=>{this.alignOpenAskToTop()})}))}alignOpenAskToTop(){let e=this.chat,t=this.renderRoot.querySelector(`.chat > ask-user-card`);return e===void 0||t===null?!1:(e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top,this.syncScrollMetrics(),this.pinnedToBottom=this.isNearBottom(),!0)}scrollToOpenDialog(){this.scrollToOpenDialogFrame===void 0&&(this.scrollToBottomFrame!==void 0&&(cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToBottomFrame=void 0),this.scrollToOpenDialogFrame=requestAnimationFrame(()=>{this.scrollToOpenDialogFrame=void 0,this.withSuppressedScrollSave(()=>{this.alignOpenDialogToTop()})}))}alignOpenDialogToTop(){let e=this.chat,t=this.renderRoot.querySelector(`.chat > extension-dialog-card.open-dialog-card`);return e===void 0||t===null?!1:(e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top,this.syncScrollMetrics(),this.pinnedToBottom=this.isNearBottom(),!0)}restoreScrollPosition(){let e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{if(this.pendingAsk!==void 0&&this.scrollController.readPosition(e)===void 0&&this.alignOpenAskToTop()||this.pendingDialogs.length>0&&this.scrollController.readPosition(e)===void 0&&this.alignOpenDialogToTop())return;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 sC(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(cC(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=Gw(n,0,Math.max(0,e-1));return}this.currentConversationIndex=Gw(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 MC(e,Array.from(this.renderRoot.querySelectorAll(`article.msg`)))??MC(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 Yw(e)}groupRenderKey(e){return Xw(e)}groupAnchorKey(e){return Xw(e)}eventAnchorKey(e){return Zw(e)}messageScrollMarkerId(e){return Yw(e)}groupScrollMarkerId(e){return Qw(e)}static{this.styles=ig}};H([b({attribute:!1})],K.prototype,`messages`,void 0),H([b()],K.prototype,`sessionId`,void 0),H([b({type:Number})],K.prototype,`messageStart`,void 0),H([b({type:Number})],K.prototype,`messageEnd`,void 0),H([b({type:Number})],K.prototype,`messageTotal`,void 0),H([b({type:Boolean})],K.prototype,`hasMore`,void 0),H([b({type:Boolean})],K.prototype,`loadingMore`,void 0),H([b({type:Boolean})],K.prototype,`isSendingPrompt`,void 0),H([b({type:Boolean})],K.prototype,`isCompacting`,void 0),H([b({type:Number})],K.prototype,`pendingMessageCount`,void 0),H([b({attribute:!1})],K.prototype,`clientQueuedMessages`,void 0),H([b({attribute:!1})],K.prototype,`status`,void 0),H([b({attribute:!1})],K.prototype,`activity`,void 0),H([b({attribute:!1})],K.prototype,`pendingAsk`,void 0),H([b({attribute:!1})],K.prototype,`askDraftSessionId`,void 0),H([b({attribute:!1})],K.prototype,`onSubmitAsk`,void 0),H([b({attribute:!1})],K.prototype,`pendingDialogs`,void 0),H([b({attribute:!1})],K.prototype,`closedDialogs`,void 0),H([b({attribute:!1})],K.prototype,`onAnswerDialog`,void 0),H([b({attribute:!1})],K.prototype,`onCancelDialog`,void 0),H([b({attribute:!1})],K.prototype,`onDismissClosedDialog`,void 0),H([b({attribute:!1})],K.prototype,`onResendMessage`,void 0),H([b({attribute:!1})],K.prototype,`notificationInbox`,void 0),H([b({attribute:!1})],K.prototype,`subagents`,void 0),H([b({attribute:!1})],K.prototype,`subagentRuns`,void 0),H([b({attribute:!1})],K.prototype,`backgroundTasks`,void 0),H([b({attribute:!1})],K.prototype,`onOpenBackgroundTask`,void 0),H([b({attribute:!1})],K.prototype,`onOpenSubagentRun`,void 0),H([b({attribute:!1})],K.prototype,`onOpenSubagent`,void 0),H([b({attribute:!1})],K.prototype,`onClearServerQueue`,void 0),H([b({attribute:!1})],K.prototype,`onRecallQueuedMessage`,void 0),H([b({attribute:!1})],K.prototype,`onDismissWarning`,void 0),H([b({attribute:!1})],K.prototype,`onDismissNotification`,void 0),H([b({attribute:!1})],K.prototype,`onDismissAllNotifications`,void 0),H([b({type:Boolean})],K.prototype,`warningsVisible`,void 0),H([b({attribute:!1})],K.prototype,`onToggleWarnings`,void 0),H([b({attribute:!1})],K.prototype,`onLoadMore`,void 0),H([b({attribute:!1})],K.prototype,`activityOutput`,void 0),H([b({attribute:!1})],K.prototype,`onCloseActivityOutput`,void 0),H([S(`.chat`)],K.prototype,`chat`,void 0),H([S(`.drawer-tabs`)],K.prototype,`drawerTabs`,void 0),H([S(`dialog.image-zoom`)],K.prototype,`imageZoomDialog`,void 0),H([S(`dialog.activity-output`)],K.prototype,`activityOutputDialog`,void 0),H([x()],K.prototype,`pinnedToBottom`,void 0),H([x()],K.prototype,`zoomedImage`,void 0),H([x()],K.prototype,`expandedMetaKey`,void 0),H([x()],K.prototype,`copiedNotificationId`,void 0),H([x()],K.prototype,`copiedMessageKey`,void 0),H([x()],K.prototype,`currentConversationIndex`,void 0),H([x()],K.prototype,`collapsedTopDrawerKeys`,void 0),H([x()],K.prototype,`expandedTopDrawerKeys`,void 0),H([b({attribute:!1})],K.prototype,`goals`,void 0),H([b({attribute:!1})],K.prototype,`onRunGoalCommand`,void 0),H([x()],K.prototype,`topDrawerTab`,void 0),H([x()],K.prototype,`activityFilter`,void 0),H([x()],K.prototype,`activityScope`,void 0),H([x()],K.prototype,`turnStartedAtMs`,void 0),H([x()],K.prototype,`turnNowMs`,void 0),H([x()],K.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),H([x()],K.prototype,`loadMoreRequested`,void 0),K=H([y(`chat-view`)],K);function aT(e){let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${String(t)}s`;let n=Math.floor(t/60);return n<60?`${String(n)}m ${String(t%60)}s`:`${String(Math.floor(n/60))}h ${String(n%60)}m`}function oT(e){return e.map(e=>{let t=e.status===`running`?`Running`:e.status===`done`?`Done`:e.status===`failed`?`Failed`:e.status===`lost`?`Stopped`:`Unknown`,n=aT(e.elapsedMs),r=e.status===`running`?e.lastActivity??`working`:e.task??``,i=tw(e.model);return{run:e,status:e.status===`lost`?`failed`:e.status,statusLabel:t,duration:n,detail:r,...i===void 0?{}:{modelLabel:i.label,modelTitle:e.model??i.label},ariaLabel:`${t} ${e.agent} subagent, ${n}`+(i===void 0?``:`, on ${i.label}`)+(r===``?``:`, ${r}`)}})}function sT(e){return e.map(e=>{let t=e.status===`running`?`running`:e.status===`completed`?`done`:e.status===`failed`||e.status===`killed`||e.status===`lost`?`failed`:`unknown`,n=e.status===`completed`?`Done`:e.status===`running`?`Running`:e.status===`lost`?`Lost`:e.status.charAt(0).toUpperCase()+e.status.slice(1),r=aT(e.durationMs??0),i=t===`running`?e.command.slice(0,60):e.exitCode===void 0?``:`exit ${String(e.exitCode)}`;return{task:e,status:t,statusLabel:n,duration:r,detail:i,ariaLabel:`${n} background task ${e.name}, ${r}${i===``?``:`, ${i}`}`}})}function cT(e){return[...e].sort((e,t)=>{let n=Number(dT(t.status))-Number(dT(e.status));if(n!==0)return n;let r=Number(fT(e.status))-Number(fT(t.status));if(r!==0)return r;let i=(t.startedAt??``).localeCompare(e.startedAt??``);return i===0?e.kind.localeCompare(t.kind):i})}var lT=600*1e3;function uT(e,t){if(e===void 0)return;let n=Math.max(0,t-e);if(!(n<5e3))return{text:aT(n),long:n>=lT}}function dT(e){return e===`working`||e===`running`}function fT(e){return e===`done`||e===`failed`||e===`error`||e===`lost`}function pT(e){return e.active>0?`Activity · ${String(e.active)} running`:`Activity (${String(e.total)})`}function mT(e){let t=[{id:`subagents`,label:`Subagents`,count:e.rows.length},{id:`runs`,label:`Agent runs`,count:e.runRows.length},{id:`tasks`,label:`Tasks`,count:e.taskRows.length}].filter(e=>e.count>0);return t.length<=1?t.length===0?[]:t:[{id:`all`,label:`All`,count:e.rows.length+e.runRows.length+e.taskRows.length},...t]}function hT(e,t){return e===`subagents`&&t.rows.length>0?`subagents`:e===`runs`&&t.runRows.length>0?`runs`:e===`tasks`&&t.taskRows.length>0?`tasks`:`all`}var gT=`Work this chat started in the background: subagents, agent tool runs and terminal tasks. Open one to read its output.`;function _T(e){if(e===void 0)return;let t=[...e.rows,...e.runRows,...e.taskRows].filter(e=>e.status===`working`||e.status===`running`).length;if(t!==0)return t===1?`idle · 1 background run`:`idle · ${String(t)} background runs`}function vT(){return!1}function yT(e,t){return t===`activity`&&e.activity?`activity`:t===`notifications`&&e.notifications?`notifications`:t===`goals`&&e.goals===!0?`goals`:e.notifications?`notifications`:e.activity?`activity`:e.goals===!0?`goals`:`activity`}function bT(e){let t=e.filter(e=>e===`working`||e===`running`).length,n=e.filter(e=>e===`error`||e===`failed`).length,r=e.length-t-n,i=[];return t>0&&i.push(`${String(t)} running`),n>0&&i.push(`${String(n)} failed`),r>0&&i.push(`${String(r)} done`),{label:i.join(` · `),working:t>0,failed:n>0}}function xT(e){return e===``?`Unknown`:e.charAt(0).toUpperCase()+e.slice(1)}function ST(e){return e.map(e=>{let t=e.status,n=e.sessionId.slice(-8),r=xT(t);return{subagent:e,shortId:n,status:t,statusLabel:r,cwd:e.cwd,ariaLabel:`${r} subagent ${n}`}})}var CT=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function wT(e){return typeof e==`string`&&CT.has(e)}function TT(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 ET=`application/octet-stream`,DT=`Failed to read an attachment.`;async function OT(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(MT(i,e))}catch{r=DT}return{attachments:n,...r===void 0?{}:{error:r}}}function kT(e){return e.kind===`image`&&wT(e.mimeType)}function AT(e){return e.every(e=>kT(e))}function jT(e,t){return AT(t)?e:`folder`}function MT(e,t){return wT(e.type)?{kind:`image`,name:PT(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:PT(e),mimeType:NT(e),data:t,size:e.size}}function NT(e){let t=e.type.trim();return t===``?ET:t}function PT(e){return e.name===``?wT(e.type)?`pasted-image.${TT(e.type)}`:`pasted-file.bin`:e.name}var FT=50,IT=`pi-web:prompt-history:`;function LT(e){return`${IT}${e}`}function RT(e){try{let t=localStorage.getItem(LT(e));if(t===null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.filter(e=>typeof e==`string`&&e.trim()!==``):[]}catch{return[]}}function zT(e,t){try{localStorage.setItem(LT(e),JSON.stringify(t.slice(0,FT)))}catch{}}function BT(e,t){let n=t.trim();if(n===``)return RT(e);let r=[n,...RT(e).filter(e=>e!==n)].slice(0,FT);return zT(e,r),r}function VT(e,t){let n=RT(e),r=t.trim().toLowerCase();if(r===``)return n;let i=r.split(/\s+/u).filter(Boolean);return n.filter(e=>{let t=e.toLowerCase();return i.every(e=>t.includes(e)||HT(e,t))})}function HT(e,t){let n=0;for(let r of e){if(n=t.indexOf(r,n),n===-1)return!1;n+=r.length}return!0}function UT(e){return e===`older`?1:-1}var WT=`(pointer: coarse), (max-width: 760px)`,GT=`pi-web.promptEnterPreference`;function KT(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(WT):void 0}function qT(e){return e===`send`||e===`newline`?e:`auto`}function JT(e=$T()){if(e===void 0)return`auto`;try{return qT(e.getItem(GT))}catch{return`auto`}}function YT(e,t=$T()){if(t!==void 0)try{t.setItem(GT,e)}catch{}}function XT(e=KT(),t=JT()){return t===`send`||t!==`newline`&&e?.matches!==!0}function ZT(e,t,n=KT()){return e?n?.matches!==!0||t:!1}function QT(e,t=KT(),n=JT()){let r=XT(t,n);return e?!r:r}function $T(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var eE=100;function tE(){let e,t,n,r,i=[],a=()=>{r!==void 0&&(window.clearInterval(r),r=void 0),e?.getTracks().forEach(e=>{e.stop()}),e=void 0,n?.close().catch(()=>void 0),n=void 0,t=void 0};return{async start(a){i=[],e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new MediaRecorder(e),t.addEventListener(`dataavailable`,e=>{e.data.size>0&&i.push(e.data)}),t.start(),n=new AudioContext;let o=n.createMediaStreamSource(e),s=n.createAnalyser();s.fftSize=512,o.connect(s);let c=new Uint8Array(s.fftSize);r=window.setInterval(()=>{s.getByteTimeDomainData(c),a(nE(c),eE)},eE)},stop(){let e=t;return e===void 0?(a(),Promise.resolve(new Blob([]))):new Promise(t=>{e.addEventListener(`stop`,()=>{let e=i[0]?.type??`audio/webm`,n=new Blob(i,{type:e});a(),t(n)},{once:!0}),e.stop()})},cancel(){i=[],t?.state===`recording`&&t.stop(),a()}}}function nE(e){let t=0;for(let n of e){let e=Math.abs(n-128)/128;e>t&&(t=e)}return t}function rE(e){return e!==void 0&&e.endpoint.trim()!==``}async function iE(e,t,n){if(!rE(t))return{ok:!1,message:`Dictation is not configured.`};if(e.size===0)return{ok:!1,message:`Nothing was recorded.`};let r=new FormData;r.append(`file`,e,`speech.webm`),t.model!==void 0&&t.model!==``&&r.append(`model`,t.model),t.language!==void 0&&t.language!==``&&r.append(`language`,t.language);let i;try{i=await n.fetch(t.endpoint,{method:`POST`,body:r,...n.signal===void 0?{}:{signal:n.signal}})}catch(e){return{ok:!1,message:`Could not reach the transcription service: ${sE(e)}`}}if(!i.ok)return{ok:!1,message:`Transcription failed (${String(i.status)}).`};let a;try{a=await i.json()}catch{return{ok:!1,message:`The transcription service returned a response that could not be read.`}}let o=aE(a);if(o===void 0)return{ok:!1,message:`The transcription service returned no text.`};let s=o.trim();return s===``?{ok:!1,message:`No speech was recognised.`}:{ok:!0,text:s}}function aE(e){if(typeof e==`string`)return e;let t=oE(e);if(t===void 0)return;for(let e of[`text`,`transcript`,`transcription`]){let n=t[e];if(typeof n==`string`)return n}let n=t.segments;if(!Array.isArray(n))return;let r=n.map(e=>oE(e)?.text).filter(e=>typeof e==`string`).join(` `);return r.trim()===``?void 0:r}function oE(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function sE(e){return e instanceof Error?e.message:String(e)}var cE={"openai-realtime":`append`,deepgram:`replace`,"azure-speech":`replace`};function lE(e){if(e===void 0)return{kind:`unavailable`,reason:`Live transcription is not configured.`};if(e.protocol===`browser`)return{kind:`browser`};let t=e.url?.trim();if(t===void 0||t===``)return{kind:`unavailable`,reason:`Streaming transcription needs a socket url.`};let n=e.tokenEndpoint?.trim();return n===void 0||n===``?{kind:`unavailable`,reason:`Streaming transcription needs a token endpoint so the account key stays on the server.`}:{kind:`socket`,protocol:e.protocol,url:t,tokenEndpoint:n,deltaMode:cE[e.protocol]}}var uE={trailingSilenceMs:900,speechThreshold:.02,maxUtteranceMs:12e4};function dE(e,t,n,r=uE){if(e.kind!==`listening`&&e.kind!==`speaking`&&e.kind!==`trailing`)return e;if(n>=r.maxUtteranceMs)return e.kind===`listening`?{kind:`idle`}:{kind:`transcribing`};let i=t.level>=r.speechThreshold;if(e.kind===`listening`)return i?{kind:`speaking`}:e;if(e.kind===`speaking`)return i?e:{kind:`trailing`,silenceMs:t.elapsedMs};if(i)return{kind:`speaking`};let a=e.silenceMs+t.elapsedMs;return a>=r.trailingSilenceMs?{kind:`transcribing`}:{kind:`trailing`,silenceMs:a}}function fE(e){switch(e.kind){case`idle`:case`denied`:case`error`:return{kind:`listening`};case`listening`:return{kind:`idle`};case`speaking`:case`trailing`:return{kind:`transcribing`};case`transcribing`:case`unavailable`:return e}}function pE(e){return e.kind===`listening`||e.kind===`speaking`||e.kind===`trailing`}function mE(e,t){switch(e.kind){case`idle`:return t?.streaming===!0?`Dictate live`:`Dictate`;case`listening`:return`Listening…`;case`speaking`:return`Listening…`;case`trailing`:return`Listening…`;case`transcribing`:return`Transcribing…`;case`denied`:return`Microphone permission denied`;case`unavailable`:return e.reason;case`error`:return e.message}}var hE=class{constructor(e,t){this.deps=e,this.callbacks=t,this.state={kind:`idle`},this.elapsedMs=0}getState(){return this.state}async toggle(e){if(!rE(e)){this.setState({kind:`unavailable`,reason:`Dictation is not configured.`});return}let t=fE(this.state);if(t.kind===`listening`&&!pE(this.state)){await this.startListening(e);return}if(t.kind===`idle`){this.deps.recorder.cancel(),this.setState({kind:`idle`});return}if(t.kind===`transcribing`){await this.finish(e);return}this.setState(t)}async startListening(e){this.activeConfig=e,this.elapsedMs=0,this.setState({kind:`listening`});try{await this.deps.recorder.start((e,t)=>{this.onFrame(e,t)})}catch(e){this.setState(gE(e)?{kind:`denied`}:{kind:`error`,message:`Microphone unavailable: ${_E(e)}`})}}onFrame(e,t){if(!pE(this.state))return;this.elapsedMs+=t;let n=dE(this.state,{level:e,elapsedMs:t},this.elapsedMs,this.deps.captureConfig??uE);if(n!==this.state){if(n.kind===`transcribing`){this.finish(this.activeConfig);return}n.kind===`idle`&&this.deps.recorder.cancel(),this.setState(n)}}async finish(e){this.setState({kind:`transcribing`});let t;try{t=await this.deps.recorder.stop()}catch(e){this.setState({kind:`error`,message:`Recording failed: ${_E(e)}`});return}if(!rE(e)){this.setState({kind:`unavailable`,reason:`Dictation is not configured.`});return}let n=await(this.deps.transcribe??iE)(t,e,{fetch:this.deps.fetch??globalThis.fetch});if(!n.ok){this.setState({kind:`error`,message:n.message});return}this.callbacks.onTranscript(n.text),this.setState({kind:`idle`})}setState(e){this.state=e,this.callbacks.onState(e)}};function gE(e){if(typeof e!=`object`||!e)return!1;let t=`name`in e?e.name:void 0;return t===`NotAllowedError`||t===`SecurityError`}function _E(e){return e instanceof Error?e.message:String(e)}function vE(){return Ye`
|
|
3456
|
+
`: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.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&&gC({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||AC(e)}isAtBottom(){let e=this.chat;return!e||kC(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})}))}isNewPendingAsk(e){return this.pendingAsk!==void 0&&(typeof e!=`object`||!e||Reflect.get(e,`askId`)!==this.pendingAsk.askId)}isNewOpenDialog(e){let t=this.pendingDialogs[0];if(t===void 0)return!1;if(!Array.isArray(e))return!0;let n=e[0];return typeof n!=`object`||!n||Reflect.get(n,`dialogId`)!==t.dialogId}scrollToOpenAsk(){this.scrollToOpenAskFrame===void 0&&(this.scrollToBottomFrame!==void 0&&(cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToBottomFrame=void 0),this.scrollToOpenAskFrame=requestAnimationFrame(()=>{this.scrollToOpenAskFrame=void 0,this.withSuppressedScrollSave(()=>{this.alignOpenAskToTop()})}))}alignOpenAskToTop(){let e=this.chat,t=this.renderRoot.querySelector(`.chat > ask-user-card`);return e===void 0||t===null?!1:(e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top,this.syncScrollMetrics(),this.pinnedToBottom=this.isNearBottom(),!0)}scrollToOpenDialog(){this.scrollToOpenDialogFrame===void 0&&(this.scrollToBottomFrame!==void 0&&(cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToBottomFrame=void 0),this.scrollToOpenDialogFrame=requestAnimationFrame(()=>{this.scrollToOpenDialogFrame=void 0,this.withSuppressedScrollSave(()=>{this.alignOpenDialogToTop()})}))}alignOpenDialogToTop(){let e=this.chat,t=this.renderRoot.querySelector(`.chat > extension-dialog-card.open-dialog-card`);return e===void 0||t===null?!1:(e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top,this.syncScrollMetrics(),this.pinnedToBottom=this.isNearBottom(),!0)}restoreScrollPosition(){let e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{if(this.pendingAsk!==void 0&&this.scrollController.readPosition(e)===void 0&&this.alignOpenAskToTop()||this.pendingDialogs.length>0&&this.scrollController.readPosition(e)===void 0&&this.alignOpenDialogToTop())return;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 cC(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(lC(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=Kw(n,0,Math.max(0,e-1));return}this.currentConversationIndex=Kw(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 NC(e,Array.from(this.renderRoot.querySelectorAll(`article.msg`)))??NC(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 Xw(e)}groupRenderKey(e){return Zw(e)}groupAnchorKey(e){return Zw(e)}eventAnchorKey(e){return Qw(e)}messageScrollMarkerId(e){return Xw(e)}groupScrollMarkerId(e){return $w(e)}static{this.styles=ag}};H([b({attribute:!1})],K.prototype,`messages`,void 0),H([b()],K.prototype,`sessionId`,void 0),H([b({type:Number})],K.prototype,`messageStart`,void 0),H([b({type:Number})],K.prototype,`messageEnd`,void 0),H([b({type:Number})],K.prototype,`messageTotal`,void 0),H([b({type:Boolean})],K.prototype,`hasMore`,void 0),H([b({type:Boolean})],K.prototype,`loadingMore`,void 0),H([b({type:Boolean})],K.prototype,`isSendingPrompt`,void 0),H([b({type:Boolean})],K.prototype,`isCompacting`,void 0),H([b({type:Number})],K.prototype,`pendingMessageCount`,void 0),H([b({attribute:!1})],K.prototype,`clientQueuedMessages`,void 0),H([b({attribute:!1})],K.prototype,`status`,void 0),H([b({attribute:!1})],K.prototype,`activity`,void 0),H([b({attribute:!1})],K.prototype,`pendingAsk`,void 0),H([b({attribute:!1})],K.prototype,`askDraftSessionId`,void 0),H([b({attribute:!1})],K.prototype,`onSubmitAsk`,void 0),H([b({attribute:!1})],K.prototype,`pendingDialogs`,void 0),H([b({attribute:!1})],K.prototype,`closedDialogs`,void 0),H([b({attribute:!1})],K.prototype,`onAnswerDialog`,void 0),H([b({attribute:!1})],K.prototype,`onCancelDialog`,void 0),H([b({attribute:!1})],K.prototype,`onDismissClosedDialog`,void 0),H([b({attribute:!1})],K.prototype,`onResendMessage`,void 0),H([b({attribute:!1})],K.prototype,`notificationInbox`,void 0),H([b({attribute:!1})],K.prototype,`subagents`,void 0),H([b({attribute:!1})],K.prototype,`subagentRuns`,void 0),H([b({attribute:!1})],K.prototype,`backgroundTasks`,void 0),H([b({attribute:!1})],K.prototype,`onOpenBackgroundTask`,void 0),H([b({attribute:!1})],K.prototype,`onOpenSubagentRun`,void 0),H([b({attribute:!1})],K.prototype,`onOpenSubagent`,void 0),H([b({attribute:!1})],K.prototype,`onClearServerQueue`,void 0),H([b({attribute:!1})],K.prototype,`onRecallQueuedMessage`,void 0),H([b({attribute:!1})],K.prototype,`onDismissWarning`,void 0),H([b({attribute:!1})],K.prototype,`onDismissNotification`,void 0),H([b({attribute:!1})],K.prototype,`onDismissAllNotifications`,void 0),H([b({type:Boolean})],K.prototype,`warningsVisible`,void 0),H([b({attribute:!1})],K.prototype,`onToggleWarnings`,void 0),H([b({attribute:!1})],K.prototype,`onLoadMore`,void 0),H([b({attribute:!1})],K.prototype,`activityOutput`,void 0),H([b({attribute:!1})],K.prototype,`onCloseActivityOutput`,void 0),H([S(`.chat`)],K.prototype,`chat`,void 0),H([S(`.drawer-tabs`)],K.prototype,`drawerTabs`,void 0),H([S(`dialog.image-zoom`)],K.prototype,`imageZoomDialog`,void 0),H([S(`dialog.activity-output`)],K.prototype,`activityOutputDialog`,void 0),H([x()],K.prototype,`pinnedToBottom`,void 0),H([x()],K.prototype,`zoomedImage`,void 0),H([x()],K.prototype,`expandedMetaKey`,void 0),H([x()],K.prototype,`copiedNotificationId`,void 0),H([x()],K.prototype,`copiedMessageKey`,void 0),H([x()],K.prototype,`currentConversationIndex`,void 0),H([x()],K.prototype,`collapsedTopDrawerKeys`,void 0),H([x()],K.prototype,`expandedTopDrawerKeys`,void 0),H([b({attribute:!1})],K.prototype,`goals`,void 0),H([b({attribute:!1})],K.prototype,`onRunGoalCommand`,void 0),H([x()],K.prototype,`topDrawerTab`,void 0),H([x()],K.prototype,`activityFilter`,void 0),H([x()],K.prototype,`activityScope`,void 0),H([x()],K.prototype,`turnStartedAtMs`,void 0),H([x()],K.prototype,`turnNowMs`,void 0),H([x()],K.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),H([x()],K.prototype,`loadMoreRequested`,void 0),K=H([y(`chat-view`)],K);function oT(e){let t=Math.max(0,Math.round(e/1e3));if(t<60)return`${String(t)}s`;let n=Math.floor(t/60);return n<60?`${String(n)}m ${String(t%60)}s`:`${String(Math.floor(n/60))}h ${String(n%60)}m`}function sT(e){return e.map(e=>{let t=e.status===`running`?`Running`:e.status===`done`?`Done`:e.status===`failed`?`Failed`:e.status===`lost`?`Stopped`:`Unknown`,n=oT(e.elapsedMs),r=e.status===`running`?e.lastActivity??`working`:e.task??``,i=nw(e.model);return{run:e,status:e.status===`lost`?`failed`:e.status,statusLabel:t,duration:n,detail:r,...i===void 0?{}:{modelLabel:i.label,modelTitle:e.model??i.label},ariaLabel:`${t} ${e.agent} subagent, ${n}`+(i===void 0?``:`, on ${i.label}`)+(r===``?``:`, ${r}`)}})}function cT(e){return e.map(e=>{let t=e.status===`running`?`running`:e.status===`completed`?`done`:e.status===`failed`||e.status===`killed`||e.status===`lost`?`failed`:`unknown`,n=e.status===`completed`?`Done`:e.status===`running`?`Running`:e.status===`lost`?`Lost`:e.status.charAt(0).toUpperCase()+e.status.slice(1),r=oT(e.durationMs??0),i=t===`running`?e.command.slice(0,60):e.exitCode===void 0?``:`exit ${String(e.exitCode)}`;return{task:e,status:t,statusLabel:n,duration:r,detail:i,ariaLabel:`${n} background task ${e.name}, ${r}${i===``?``:`, ${i}`}`}})}function lT(e){return[...e].sort((e,t)=>{let n=Number(fT(t.status))-Number(fT(e.status));if(n!==0)return n;let r=Number(pT(e.status))-Number(pT(t.status));if(r!==0)return r;let i=(t.startedAt??``).localeCompare(e.startedAt??``);return i===0?e.kind.localeCompare(t.kind):i})}var uT=600*1e3;function dT(e,t){if(e===void 0)return;let n=Math.max(0,t-e);if(!(n<5e3))return{text:oT(n),long:n>=uT}}function fT(e){return e===`working`||e===`running`}function pT(e){return e===`done`||e===`failed`||e===`error`||e===`lost`}function mT(e){return e.active>0?`Activity · ${String(e.active)} running`:`Activity (${String(e.total)})`}function hT(e){let t=[{id:`subagents`,label:`Subagents`,count:e.rows.length},{id:`runs`,label:`Agent runs`,count:e.runRows.length},{id:`tasks`,label:`Tasks`,count:e.taskRows.length}].filter(e=>e.count>0);return t.length<=1?t.length===0?[]:t:[{id:`all`,label:`All`,count:e.rows.length+e.runRows.length+e.taskRows.length},...t]}function gT(e,t){return e===`subagents`&&t.rows.length>0?`subagents`:e===`runs`&&t.runRows.length>0?`runs`:e===`tasks`&&t.taskRows.length>0?`tasks`:`all`}var _T=`Work this chat started in the background: subagents, agent tool runs and terminal tasks. Open one to read its output.`;function vT(e){if(e===void 0)return;let t=[...e.rows,...e.runRows,...e.taskRows].filter(e=>e.status===`working`||e.status===`running`).length;if(t!==0)return t===1?`idle · 1 background run`:`idle · ${String(t)} background runs`}function yT(){return!1}function bT(e,t){return t===`activity`&&e.activity?`activity`:t===`notifications`&&e.notifications?`notifications`:t===`goals`&&e.goals===!0?`goals`:e.notifications?`notifications`:e.activity?`activity`:e.goals===!0?`goals`:`activity`}function xT(e){let t=e.filter(e=>e===`working`||e===`running`).length,n=e.filter(e=>e===`error`||e===`failed`).length,r=e.length-t-n,i=[];return t>0&&i.push(`${String(t)} running`),n>0&&i.push(`${String(n)} failed`),r>0&&i.push(`${String(r)} done`),{label:i.join(` · `),working:t>0,failed:n>0}}function ST(e){return e===``?`Unknown`:e.charAt(0).toUpperCase()+e.slice(1)}function CT(e){return e.map(e=>{let t=e.status,n=e.sessionId.slice(-8),r=ST(t);return{subagent:e,shortId:n,status:t,statusLabel:r,cwd:e.cwd,ariaLabel:`${r} subagent ${n}`}})}var wT=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function TT(e){return typeof e==`string`&&wT.has(e)}function ET(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 DT=`application/octet-stream`,OT=`Failed to read an attachment.`;async function kT(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(NT(i,e))}catch{r=OT}return{attachments:n,...r===void 0?{}:{error:r}}}function AT(e){return e.kind===`image`&&TT(e.mimeType)}function jT(e){return e.every(e=>AT(e))}function MT(e,t){return jT(t)?e:`folder`}function NT(e,t){return TT(e.type)?{kind:`image`,name:FT(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:FT(e),mimeType:PT(e),data:t,size:e.size}}function PT(e){let t=e.type.trim();return t===``?DT:t}function FT(e){return e.name===``?TT(e.type)?`pasted-image.${ET(e.type)}`:`pasted-file.bin`:e.name}var IT=50,LT=`pi-web:prompt-history:`;function RT(e){return`${LT}${e}`}function zT(e){try{let t=localStorage.getItem(RT(e));if(t===null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.filter(e=>typeof e==`string`&&e.trim()!==``):[]}catch{return[]}}function BT(e,t){try{localStorage.setItem(RT(e),JSON.stringify(t.slice(0,IT)))}catch{}}function VT(e,t){let n=t.trim();if(n===``)return zT(e);let r=[n,...zT(e).filter(e=>e!==n)].slice(0,IT);return BT(e,r),r}function HT(e,t){let n=zT(e),r=t.trim().toLowerCase();if(r===``)return n;let i=r.split(/\s+/u).filter(Boolean);return n.filter(e=>{let t=e.toLowerCase();return i.every(e=>t.includes(e)||UT(e,t))})}function UT(e,t){let n=0;for(let r of e){if(n=t.indexOf(r,n),n===-1)return!1;n+=r.length}return!0}function WT(e){return e===`older`?1:-1}var GT=`(pointer: coarse), (max-width: 760px)`,KT=`pi-web.promptEnterPreference`;function qT(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(GT):void 0}function JT(e){return e===`send`||e===`newline`?e:`auto`}function YT(e=eE()){if(e===void 0)return`auto`;try{return JT(e.getItem(KT))}catch{return`auto`}}function XT(e,t=eE()){if(t!==void 0)try{t.setItem(KT,e)}catch{}}function ZT(e=qT(),t=YT()){return t===`send`||t!==`newline`&&e?.matches!==!0}function QT(e,t,n=qT()){return e?n?.matches!==!0||t:!1}function $T(e,t=qT(),n=YT()){let r=ZT(t,n);return e?!r:r}function eE(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var tE=100;function nE(){let e,t,n,r,i=[],a=()=>{r!==void 0&&(window.clearInterval(r),r=void 0),e?.getTracks().forEach(e=>{e.stop()}),e=void 0,n?.close().catch(()=>void 0),n=void 0,t=void 0};return{async start(a){i=[],e=await navigator.mediaDevices.getUserMedia({audio:!0}),t=new MediaRecorder(e),t.addEventListener(`dataavailable`,e=>{e.data.size>0&&i.push(e.data)}),t.start(),n=new AudioContext;let o=n.createMediaStreamSource(e),s=n.createAnalyser();s.fftSize=512,o.connect(s);let c=new Uint8Array(s.fftSize);r=window.setInterval(()=>{s.getByteTimeDomainData(c),a(rE(c),tE)},tE)},stop(){let e=t;return e===void 0?(a(),Promise.resolve(new Blob([]))):new Promise(t=>{e.addEventListener(`stop`,()=>{let e=i[0]?.type??`audio/webm`,n=new Blob(i,{type:e});a(),t(n)},{once:!0}),e.stop()})},cancel(){i=[],t?.state===`recording`&&t.stop(),a()}}}function rE(e){let t=0;for(let n of e){let e=Math.abs(n-128)/128;e>t&&(t=e)}return t}function iE(e){return e!==void 0&&e.endpoint.trim()!==``}async function aE(e,t,n){if(!iE(t))return{ok:!1,message:`Dictation is not configured.`};if(e.size===0)return{ok:!1,message:`Nothing was recorded.`};let r=new FormData;r.append(`file`,e,`speech.webm`),t.model!==void 0&&t.model!==``&&r.append(`model`,t.model),t.language!==void 0&&t.language!==``&&r.append(`language`,t.language);let i;try{i=await n.fetch(t.endpoint,{method:`POST`,body:r,...n.signal===void 0?{}:{signal:n.signal}})}catch(e){return{ok:!1,message:`Could not reach the transcription service: ${cE(e)}`}}if(!i.ok)return{ok:!1,message:`Transcription failed (${String(i.status)}).`};let a;try{a=await i.json()}catch{return{ok:!1,message:`The transcription service returned a response that could not be read.`}}let o=oE(a);if(o===void 0)return{ok:!1,message:`The transcription service returned no text.`};let s=o.trim();return s===``?{ok:!1,message:`No speech was recognised.`}:{ok:!0,text:s}}function oE(e){if(typeof e==`string`)return e;let t=sE(e);if(t===void 0)return;for(let e of[`text`,`transcript`,`transcription`]){let n=t[e];if(typeof n==`string`)return n}let n=t.segments;if(!Array.isArray(n))return;let r=n.map(e=>sE(e)?.text).filter(e=>typeof e==`string`).join(` `);return r.trim()===``?void 0:r}function sE(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t={};for(let[n,r]of Object.entries(e))t[n]=r;return t}function cE(e){return e instanceof Error?e.message:String(e)}var lE={"openai-realtime":`append`,deepgram:`replace`,"azure-speech":`replace`};function uE(e){if(e===void 0)return{kind:`unavailable`,reason:`Live transcription is not configured.`};if(e.protocol===`browser`)return{kind:`browser`};let t=e.url?.trim();if(t===void 0||t===``)return{kind:`unavailable`,reason:`Streaming transcription needs a socket url.`};let n=e.tokenEndpoint?.trim();return n===void 0||n===``?{kind:`unavailable`,reason:`Streaming transcription needs a token endpoint so the account key stays on the server.`}:{kind:`socket`,protocol:e.protocol,url:t,tokenEndpoint:n,deltaMode:lE[e.protocol]}}var dE={trailingSilenceMs:900,speechThreshold:.02,maxUtteranceMs:12e4};function fE(e,t,n,r=dE){if(e.kind!==`listening`&&e.kind!==`speaking`&&e.kind!==`trailing`)return e;if(n>=r.maxUtteranceMs)return e.kind===`listening`?{kind:`idle`}:{kind:`transcribing`};let i=t.level>=r.speechThreshold;if(e.kind===`listening`)return i?{kind:`speaking`}:e;if(e.kind===`speaking`)return i?e:{kind:`trailing`,silenceMs:t.elapsedMs};if(i)return{kind:`speaking`};let a=e.silenceMs+t.elapsedMs;return a>=r.trailingSilenceMs?{kind:`transcribing`}:{kind:`trailing`,silenceMs:a}}function pE(e){switch(e.kind){case`idle`:case`denied`:case`error`:return{kind:`listening`};case`listening`:return{kind:`idle`};case`speaking`:case`trailing`:return{kind:`transcribing`};case`transcribing`:case`unavailable`:return e}}function mE(e){return e.kind===`listening`||e.kind===`speaking`||e.kind===`trailing`}function hE(e,t){switch(e.kind){case`idle`:return t?.streaming===!0?`Dictate live`:`Dictate`;case`listening`:return`Listening…`;case`speaking`:return`Listening…`;case`trailing`:return`Listening…`;case`transcribing`:return`Transcribing…`;case`denied`:return`Microphone permission denied`;case`unavailable`:return e.reason;case`error`:return e.message}}var gE=class{constructor(e,t){this.deps=e,this.callbacks=t,this.state={kind:`idle`},this.elapsedMs=0}getState(){return this.state}async toggle(e){if(!iE(e)){this.setState({kind:`unavailable`,reason:`Dictation is not configured.`});return}let t=pE(this.state);if(t.kind===`listening`&&!mE(this.state)){await this.startListening(e);return}if(t.kind===`idle`){this.deps.recorder.cancel(),this.setState({kind:`idle`});return}if(t.kind===`transcribing`){await this.finish(e);return}this.setState(t)}async startListening(e){this.activeConfig=e,this.elapsedMs=0,this.setState({kind:`listening`});try{await this.deps.recorder.start((e,t)=>{this.onFrame(e,t)})}catch(e){this.setState(_E(e)?{kind:`denied`}:{kind:`error`,message:`Microphone unavailable: ${vE(e)}`})}}onFrame(e,t){if(!mE(this.state))return;this.elapsedMs+=t;let n=fE(this.state,{level:e,elapsedMs:t},this.elapsedMs,this.deps.captureConfig??dE);if(n!==this.state){if(n.kind===`transcribing`){this.finish(this.activeConfig);return}n.kind===`idle`&&this.deps.recorder.cancel(),this.setState(n)}}async finish(e){this.setState({kind:`transcribing`});let t;try{t=await this.deps.recorder.stop()}catch(e){this.setState({kind:`error`,message:`Recording failed: ${vE(e)}`});return}if(!iE(e)){this.setState({kind:`unavailable`,reason:`Dictation is not configured.`});return}let n=await(this.deps.transcribe??aE)(t,e,{fetch:this.deps.fetch??globalThis.fetch});if(!n.ok){this.setState({kind:`error`,message:n.message});return}this.callbacks.onTranscript(n.text),this.setState({kind:`idle`})}setState(e){this.state=e,this.callbacks.onState(e)}};function _E(e){if(typeof e!=`object`||!e)return!1;let t=`name`in e?e.name:void 0;return t===`NotAllowedError`||t===`SecurityError`}function vE(e){return e instanceof Error?e.message:String(e)}function yE(){return Ye`
|
|
3453
3457
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3454
3458
|
<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>
|
|
3455
3459
|
</svg>
|
|
3456
|
-
`}function
|
|
3460
|
+
`}function bE(){return Ye`
|
|
3457
3461
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3458
3462
|
<path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
|
|
3459
3463
|
<path d="M21 3 11.5 12.5"></path>
|
|
3460
3464
|
</svg>
|
|
3461
|
-
`}function
|
|
3465
|
+
`}function xE(){return Ye`
|
|
3462
3466
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3463
3467
|
<path d="M4 7h11"></path>
|
|
3464
3468
|
<path d="M4 12h7"></path>
|
|
3465
3469
|
<path d="M4 17h7"></path>
|
|
3466
3470
|
<path d="m15 14 5 3-5 3z"></path>
|
|
3467
3471
|
</svg>
|
|
3468
|
-
`}function
|
|
3472
|
+
`}function SE(){return bE()}function CE(){return Ye`
|
|
3469
3473
|
<svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3470
3474
|
<rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
|
|
3471
3475
|
</svg>
|
|
3472
|
-
`}function
|
|
3476
|
+
`}function wE(e){let t=Math.max(e.total,1),n=t>1?1.2:0,r=(18-n*(t-1))/t;return Ye`
|
|
3473
3477
|
<svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
3474
3478
|
${Array.from({length:t},(i,a)=>{let o=3+a*(r+n),s=4+(a+1)/t*12,c=20-s;return Ye`<rect class=${a<e.filled?`gauge-bar gauge-bar-active`:`gauge-bar`} x=${o} y=${c} width=${r} height=${s} rx="1"></rect>`})}
|
|
3475
3479
|
</svg>
|
|
3476
|
-
`}var
|
|
3480
|
+
`}var TE=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function EE(e){return e===void 0||e===``?`off`:e}function DE(e,t){let n=t.length>=2?t:TE,r=n.length-1,i=EE(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}var OE=fg(class extends pg{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===dg.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){}}),kE=class extends v{constructor(...e){super(...e),this.items=[],this.selectedIndex=0}render(){return this.items.length?g`
|
|
3477
3481
|
<div class="menu">
|
|
3478
3482
|
${this.items.map((e,t)=>g`
|
|
3479
|
-
<button class=${t===this.selectedIndex?`selected`:``} ${
|
|
3483
|
+
<button class=${t===this.selectedIndex?`selected`:``} ${OE(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
|
|
3480
3484
|
<strong>${e.insertText}</strong>
|
|
3481
3485
|
<span>${e.detail}</span>
|
|
3482
3486
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
3483
3487
|
</button>
|
|
3484
3488
|
`)}
|
|
3485
3489
|
</div>
|
|
3486
|
-
`:null}static{this.styles=
|
|
3490
|
+
`:null}static{this.styles=cg}};H([b({attribute:!1})],kE.prototype,`items`,void 0),H([b({type:Number})],kE.prototype,`selectedIndex`,void 0),H([b({attribute:!1})],kE.prototype,`onPick`,void 0),kE=H([y(`autocomplete-menu`)],kE);var q=class extends v{constructor(...e){super(...e),this.disabled=!1,this.machineId=`local`,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.collapsed=!1,this.availableThinkingLevels=[],this.draft=``,this.currentInputMode={kind:`normal`},this.completions=[],this.selectedIndex=0,this.voiceState={kind:`idle`},this.attachments=[],this.attachmentError=void 0,this.attachingCount=0,this.attachingSettled=Promise.resolve(),this.attachmentSeq=0,this.requestVersion=0,this.historyDraftBeforeBrowse=``,this.editableCompartment=new i,this.readOnlyCompartment=new i,this.mobilePromptEnterMedia=qT(),this.explicitShiftKeyActive=!1,this.pendingPrompts=[],this.openAttachmentZoom=(e,t)=>{this.zoomedAttachment={src:e,alt:t}},this.closeAttachmentZoom=()=>{this.zoomedAttachment=void 0},this.onAttachmentZoomDialogClick=e=>{e.target===this.attachmentZoomDialog&&this.closeAttachmentZoom()},this.flushPendingPrompts=()=>{if(!navigator.onLine)return;let e=Js(this.machineId,this.sessionId??``);if(e===``)return;let t=xd(e);if(t.length===0)return;let n=t;(async()=>{let t=[],r=!1;for(let e of n)try{await this.onSend?.(e.text,e.behavior,e.attachments,e.attachments===void 0?void 0:this.effectiveAttachmentDelivery(),e.clientMessageId===void 0?void 0:{clientMessageId:e.clientMessageId})===!1&&t.push(e)}catch(n){r||=yd(n),t.push(e)}t.length===0?Cd(e):r||Cd(e),this.pendingPrompts=t.length===0?[]:t,n=t})()}}willUpdate(e){if(!e.has(`sessionId`)&&!e.has(`machineId`))return;let t=e.has(`sessionId`)?e.get(`sessionId`):this.sessionId,n=jE(e.has(`machineId`)?e.get(`machineId`):this.machineId,t);n!==void 0&&jl(n,this.draft);let r=jE(this.machineId,this.sessionId);this.draft=r===void 0?``:Al(r),this.currentInputMode=Bd(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has(`status`)&&e.size===1?!AE(e.get(`status`),this.status):!0}firstUpdated(){this.createEditor(),this.pendingPrompts=this.pendingPromptsForSession(),window.addEventListener(`online`,this.flushPendingPrompts)}connectedCallback(){super.connectedCallback(),this.pendingPrompts=this.pendingPromptsForSession()}updated(e){e.has(`collapsed`)&&(this.collapsed?(this.editor?.destroy(),this.editor=void 0):this.createEditor()),e.has(`disabled`)&&this.updateEditorDisabledState(),(e.has(`sessionId`)||e.has(`machineId`))&&this.syncEditorDoc(),this.syncAttachmentZoomDialog()}disconnectedCallback(){window.removeEventListener(`online`,this.flushPendingPrompts),this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){if(this.collapsed)return this.renderCollapsed();let e=this.currentInputMode.kind===`shell`?this.currentInputMode:void 0,t=e!==void 0,n=this.canSteer||this.isCompacting,r=this.disabled||this.sending;return g`
|
|
3487
3491
|
<footer class=${t?`shell-mode`:``} @paste=${e=>{this.handlePaste(e)}} @dragover=${e=>{this.handleDragOver(e)}} @drop=${e=>{this.handleDrop(e)}}>
|
|
3488
3492
|
<input class="attachment-input" type="file" multiple hidden @change=${e=>{this.handleFileInput(e)}} />
|
|
3489
3493
|
${this.renderAttachments()}
|
|
@@ -3491,14 +3495,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3491
3495
|
${t?g`<div class="mode-hint">Shell command${e.excludeFromContext?` · excluded from context`:``}</div>`:null}
|
|
3492
3496
|
${this.isCompacting&&!t?g`<div class="mode-hint">Compacting history · message will be queued</div>`:null}
|
|
3493
3497
|
<div class=${`markdown-editor${this.disabled?` markdown-editor-disabled`:``}`} aria-label="Message pi" aria-disabled=${this.disabled?`true`:`false`}></div>
|
|
3494
|
-
<button class="editor-attach icon-button" ?disabled=${r} title="Attach files" aria-label="Attach files" @click=${()=>{this.attachmentInput?.click()}}>${
|
|
3498
|
+
<button class="editor-attach icon-button" ?disabled=${r} title="Attach files" aria-label="Attach files" @click=${()=>{this.attachmentInput?.click()}}>${yE()}</button>
|
|
3495
3499
|
${this.renderDictateButton(r)}
|
|
3496
3500
|
<autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${e=>{this.pick(e)}}></autocomplete-menu>
|
|
3497
3501
|
</div>
|
|
3498
3502
|
<div class="actions">
|
|
3499
3503
|
${this.renderCompactStatus()}
|
|
3500
|
-
<button class="icon-button send-button" ?disabled=${r} title=${n?`Steer — joins the current turn at the next safe point`:`Send message`} aria-label=${n?`Steer current response (queued if busy)`:`Send message`} @click=${()=>{this.send(this.canSteer?`steer`:`followUp`)}}>${this.canSteer?
|
|
3501
|
-
<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?.()}>${
|
|
3504
|
+
<button class="icon-button send-button" ?disabled=${r} title=${n?`Steer — joins the current turn at the next safe point`:`Send message`} aria-label=${n?`Steer current response (queued if busy)`:`Send message`} @click=${()=>{this.send(this.canSteer?`steer`:`followUp`)}}>${this.canSteer?SE():n?xE():bE()}</button>
|
|
3505
|
+
<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?.()}>${CE()}</button>
|
|
3502
3506
|
</div>
|
|
3503
3507
|
</footer>
|
|
3504
3508
|
${this.renderAttachmentZoom()}
|
|
@@ -3516,22 +3520,22 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3516
3520
|
${this.draftPreview===``?null:g`<span class="expand-composer-draft" dir="auto">${this.draftPreview}</span>`}
|
|
3517
3521
|
</button>
|
|
3518
3522
|
</footer>
|
|
3519
|
-
`}get draftPreview(){let e=(this.editor?.state.doc.toString()??this.draft).trim().replace(/\s+/gu,` `);return e.length>60?`${e.slice(0,59)}…`:e}focusInput(){this.editor?.focus()}restorePrompt(e){this.attachmentError=void 0,this.attachments=e.attachments.filter(e=>e.kind===`image`).map((e,t)=>(this.attachmentSeq+=1,{id:`restored-${String(this.attachmentSeq)}`,kind:`image`,name:e.name??`image-${String(t+1)}`,mimeType:e.mimeType,data:e.data,size:Math.floor(e.data.length*3/4)})),this.replaceText(e.text),this.focusInput()}replaceText(t){this.draft=t;let n=
|
|
3523
|
+
`}get draftPreview(){let e=(this.editor?.state.doc.toString()??this.draft).trim().replace(/\s+/gu,` `);return e.length>60?`${e.slice(0,59)}…`:e}focusInput(){this.editor?.focus()}restorePrompt(e){this.attachmentError=void 0,this.attachments=e.attachments.filter(e=>e.kind===`image`).map((e,t)=>(this.attachmentSeq+=1,{id:`restored-${String(this.attachmentSeq)}`,kind:`image`,name:e.name??`image-${String(t+1)}`,mimeType:e.mimeType,data:e.data,size:Math.floor(e.data.length*3/4)})),this.replaceText(e.text),this.focusInput()}replaceText(t){this.draft=t;let n=jE(this.machineId,this.sessionId);n!==void 0&&jl(n,t);let r=this.editor;if(r!==void 0){let n=r.state.doc.toString();r.dispatch({...n===t?{}:{changes:{from:0,to:n.length,insert:t}},selection:e.cursor(t.length)})}this.requestVersion+=1,this.currentInputMode=Bd(t),this.completions=[],this.selectedIndex=0}get view(){return this.editor}renderCompactStatus(){let e=this.status;if(e===void 0)return null;let t=e.model?.id??`no model`,n=e.model?.provider!==void 0&&e.model.provider!==``?`${e.model.provider}/`:``;return g`
|
|
3520
3524
|
<div class="compact-status" aria-label="Session status">
|
|
3521
3525
|
<button class="select-model" title=${`Select model: ${n}${t}`} @click=${()=>this.onSelectModel?.()}>${n===``?null:g`<span class="select-model-provider">${n}</span>`}<span class="select-model-id">${t}</span></button>
|
|
3522
|
-
<button class="select-thinking icon-button" title=${`Thinking level: ${
|
|
3526
|
+
<button class="select-thinking icon-button" title=${`Thinking level: ${EE(e.thinkingLevel)}`} aria-label=${`Thinking level: ${EE(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${wE(DE(e.thinkingLevel,this.availableThinkingLevels))}</button>
|
|
3523
3527
|
</div>
|
|
3524
3528
|
`}renderAttachments(){return this.attachments.length===0&&this.attachmentError===void 0?null:g`
|
|
3525
3529
|
<div class="attachments" aria-label="Pending attachments">
|
|
3526
3530
|
${this.attachments.map(e=>g`
|
|
3527
|
-
<div class=${`attachment-chip ${
|
|
3531
|
+
<div class=${`attachment-chip ${AT(e)?`attachment-chip-image`:`attachment-chip-file`}`} title=${e.name}>
|
|
3528
3532
|
${this.renderAttachmentPreview(e)}
|
|
3529
3533
|
<button type="button" class="attachment-remove" title="Remove attachment" aria-label=${`Remove ${e.name}`} @click=${()=>{this.removeAttachment(e.id)}}>×</button>
|
|
3530
3534
|
</div>
|
|
3531
3535
|
`)}
|
|
3532
3536
|
${this.attachmentError===void 0?null:g`<div class="attachment-error">${this.attachmentError}</div>`}
|
|
3533
3537
|
</div>
|
|
3534
|
-
`}renderAttachmentPreview(e){if(
|
|
3538
|
+
`}renderAttachmentPreview(e){if(AT(e)){let t=`data:${e.mimeType};base64,${e.data}`;return g`<img
|
|
3535
3539
|
src=${t}
|
|
3536
3540
|
alt=${e.name}
|
|
3537
3541
|
role="button"
|
|
@@ -3540,7 +3544,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3540
3544
|
@click=${()=>{this.openAttachmentZoom(t,e.name)}}
|
|
3541
3545
|
@keydown=${n=>{(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),this.openAttachmentZoom(t,e.name))}}
|
|
3542
3546
|
/>`}return g`
|
|
3543
|
-
<div class="attachment-file-preview" aria-hidden="true">${
|
|
3547
|
+
<div class="attachment-file-preview" aria-hidden="true">${RE(e.name)}</div>
|
|
3544
3548
|
<span class="attachment-file-name">${e.name}</span>
|
|
3545
3549
|
`}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}syncAttachmentZoomDialog(){let e=this.attachmentZoomDialog;if(e!==void 0){if(this.zoomedAttachment!==void 0){try{e.open||e.showModal()}catch{this.zoomedAttachment=void 0;return}(this.renderRoot.querySelector(`.attachment-zoom-close`)??e).focus();return}e.open&&e.close()}}renderAttachmentZoom(){let e=this.zoomedAttachment;return g`
|
|
3546
3550
|
<dialog class="attachment-zoom" @click=${this.onAttachmentZoomDialogClick} @close=${this.closeAttachmentZoom} @cancel=${this.closeAttachmentZoom}>
|
|
@@ -3549,7 +3553,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3549
3553
|
<img class="attachment-zoom-full" src=${e.src} alt=${e.alt} />
|
|
3550
3554
|
`}
|
|
3551
3555
|
</dialog>
|
|
3552
|
-
`}async handlePaste(e){let t=
|
|
3556
|
+
`}async handlePaste(e){let t=FE(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&IE(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=FE(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,this.attachingCount+=1;let t=kT(e,zE);this.attachingSettled=this.attachingSettled.then(async()=>{await t}).catch(()=>void 0);let n;try{n=await t}finally{--this.attachingCount}let{attachments:r,error:i}=n;r.length>0&&(this.attachments=[...this.attachments,...r.map(e=>({id:`attachment-${String(++this.attachmentSeq)}`,...e}))]),i!==void 0&&(this.attachmentError=i)}currentAttachments(){return this.attachments.map(e=>LE(e))}renderDictateButton(e){if(!iE(this.speechToText))return null;let t=uE(this.speechToText.streaming).kind!==`unavailable`,n=hE(this.voiceState,{streaming:t}),r=mE(this.voiceState);return g`
|
|
3553
3557
|
<button
|
|
3554
3558
|
class=${`editor-dictate icon-button${r?` listening`:``}`}
|
|
3555
3559
|
type="button"
|
|
@@ -3559,8 +3563,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3559
3563
|
aria-pressed=${String(r)}
|
|
3560
3564
|
@click=${()=>{this.toggleDictation()}}
|
|
3561
3565
|
>${r?`■`:`●`}</button>
|
|
3562
|
-
`}async toggleDictation(){this.voice??=new
|
|
3563
|
-
`)?``:` `;this.replaceText(`${t}${n}${e}`)}effectiveAttachmentDelivery(){return jT(`inline`,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new m({parent:this.editorHost,state:l.create({doc:this.draft,extensions:[ee(),re(),t(),d.of(` `),r(a,{fallback:!0}),m.lineWrapping,n(),m.contentAttributes.of(e=>VE(e.state.sliceDoc(0,e.state.selection.main.head))),m.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),s(HE()),this.editableCompartment.of(m.editable.of(!this.disabled)),this.readOnlyCompartment.of(l.readOnly.of(this.disabled)),m.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),o.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:`ArrowDown`,run:e=>this.handleEditorArrow(e,`newer`)},{key:`ArrowUp`,run:e=>this.handleEditorArrow(e,`older`)},{key:`Escape`,run:()=>this.closeCompletions()},{key:`Tab`,run:e=>this.handleEditorTab(e)},{key:`Shift-Tab`,run:e=>u.shift?.(e)??!1},{key:`Backspace`,run:e=>te(e)},...c,...f])]})}))}syncEditorDoc(){let t=this.editor;if(!t)return;let n=t.state.doc.toString();n!==this.draft&&t.dispatch({changes:{from:0,to:n.length,insert:this.draft},selection:e.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(m.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(l.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;let t=AE(this.machineId,this.sessionId);t!==void 0&&jl(t,this.draft);let n=Bd(this.draft);Hd(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 I.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(jE);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.projectId!==void 0&&this.workspaceId!==void 0){let n=await I.files(e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId}).catch(ME);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=Fd(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}:{}}})}else if(e.kind===`model`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await I.models({id:this.sessionId,cwd:this.cwd},this.machineId).then(e=>e.models).catch(NE);if(t!==this.requestVersion)return;this.completions=Md(n,e.query).map(t=>({kind:`model`,replaceFrom:e.from,replaceTo:e.to,...t}))}}currentTrigger(){return Ad(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}handleEditorArrow(e,t){return this.completions.length?this.moveCompletion(t===`older`?-1:1):this.browsePromptHistory(e,UT(t))}browsePromptHistory(e,t){let n=AE(this.machineId,this.sessionId);if(n===void 0)return!1;let r=RT(n);if(r.length===0)return!1;let i=e.state.selection.main.head,a=e.state.selection.main.empty,o=e.state.doc.toString();if(this.historyIndex===void 0){if(!(a&&i===o.length&&o.trim()===``))return!1;this.historyDraftBeforeBrowse=o,this.historyIndex=0}else{let e=this.historyIndex+t;if(e<0)return!0;if(e>=r.length)return this.historyIndex=void 0,this.replaceText(this.historyDraftBeforeBrowse),!0;this.historyIndex=e}let s=r[this.historyIndex]??this.historyDraftBeforeBrowse;return this.replaceText(s),!0}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorKeyDown(e,t){if(e.key===`Shift`)return this.explicitShiftKeyActive=!0,!1;if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`r`)return e.preventDefault(),this.openPromptHistoryPicker();if(e.key!==`Enter`)return this.explicitShiftKeyActive=!1,e.key!==`ArrowUp`&&e.key!==`ArrowDown`&&(this.historyIndex=void 0),!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;let n=ZT(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 QT(t,this.mobilePromptEnterMedia,JT())?(this.send(this.canSteer?`steer`:`followUp`),!0):ne(e)||p(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):u.run?.(e)??!1}pick(t){let n=this.editor;if(!n)return;if(t.kind===`history`){this.historyIndex=void 0,this.replaceText(t.insertText),this.completions=[];return}let r=t.kind===`file`&&(t.insertText.endsWith(`/`)||t.cursorOffset!==void 0)?``:` `,i=t.replaceFrom+(t.cursorOffset??t.insertText.length)+r.length,a=t.insertText.endsWith(`"`)&&this.draft.slice(t.replaceTo).startsWith(`"`)?t.replaceTo+1:t.replaceTo;n.dispatch({changes:{from:t.replaceFrom,to:a,insert:`${t.insertText}${r}`},selection:e.cursor(i),scrollIntoView:!0}),this.completions=[]}openPromptHistoryPicker(){let e=AE(this.machineId,this.sessionId);if(e===void 0)return!1;let t=VT(e,this.draft).slice(0,12);return t.length===0?!1:(this.selectedIndex=0,this.completions=t.map(e=>({kind:`history`,replaceFrom:0,replaceTo:this.draft.length,insertText:e,detail:`history`,description:e})),!0)}pendingPromptsForSession(){let e=Js(this.machineId,this.sessionId??``);return e===``?[]:xd(e)}send(e){if(this.disabled||this.sending)return;if(this.attachingCount>0){this.attachingSettled.then(()=>{this.send(e)});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(),o=AE(this.machineId,this.sessionId);o!==void 0&&t!==``&&BT(o,t);let s={text:this.draft,attachments:n};this.resetComposer(),this.deliverAndRestoreOnFailure(t,r,i,a,s)}async deliverAndRestoreOnFailure(e,t,n,r,i){let a,o;try{a=await this.onSend?.(e,t,n,n===void 0?void 0:r)}catch(e){a=!1,o=e}if(a===!1){if(yd(o)){let r=Js(this.machineId,this.sessionId??``);if(r!==``){let i=o instanceof bd?o.clientMessageId:void 0;Sd(r,{text:e,...t===void 0?{}:{behavior:t},...i===void 0?{}:{clientMessageId:i},...n===void 0||n.length===0?{}:{attachments:n},at:new Date().toISOString()}),this.pendingPrompts=xd(r);return}}(this.editor?.state.doc.toString()??this.draft).trim()===``&&(this.attachments=i.attachments,this.replaceText(i.text))}}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=AE(this.machineId,this.sessionId);e!==void 0&&Ml(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=cg}};H([b({type:Boolean})],q.prototype,`disabled`,void 0),H([b()],q.prototype,`sessionId`,void 0),H([b()],q.prototype,`cwd`,void 0),H([b()],q.prototype,`machineId`,void 0),H([b()],q.prototype,`projectId`,void 0),H([b()],q.prototype,`workspaceId`,void 0),H([b({type:Boolean})],q.prototype,`canSteer`,void 0),H([b({type:Boolean})],q.prototype,`isCompacting`,void 0),H([b({type:Boolean})],q.prototype,`canStop`,void 0),H([b({attribute:!1})],q.prototype,`status`,void 0),H([b({type:Boolean})],q.prototype,`sending`,void 0),H([b({type:Boolean,reflect:!0})],q.prototype,`collapsed`,void 0),H([b({attribute:!1})],q.prototype,`onSend`,void 0),H([b({attribute:!1})],q.prototype,`onStop`,void 0),H([b({attribute:!1})],q.prototype,`onSelectModel`,void 0),H([b({attribute:!1})],q.prototype,`onSelectThinking`,void 0),H([b({attribute:!1})],q.prototype,`onExpand`,void 0),H([b({attribute:!1})],q.prototype,`availableThinkingLevels`,void 0),H([S(`.markdown-editor`)],q.prototype,`editorHost`,void 0),H([S(`.attachment-input`)],q.prototype,`attachmentInput`,void 0),H([S(`dialog.attachment-zoom`)],q.prototype,`attachmentZoomDialog`,void 0),H([x()],q.prototype,`currentInputMode`,void 0),H([x()],q.prototype,`completions`,void 0),H([x()],q.prototype,`selectedIndex`,void 0),H([b({attribute:!1})],q.prototype,`speechToText`,void 0),H([x()],q.prototype,`voiceState`,void 0),H([x()],q.prototype,`zoomedAttachment`,void 0),H([x()],q.prototype,`attachments`,void 0),H([x()],q.prototype,`attachmentError`,void 0),H([x()],q.prototype,`attachingCount`,void 0),H([x()],q.prototype,`pendingPrompts`,void 0),q=H([y(`prompt-editor`)],q);function kE(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 AE(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return Js(e,t)}function jE(){return[]}function ME(){return[]}function NE(){return[]}function PE(e){return e===null?[]:Array.from(e.files)}function FE(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function IE(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 LE(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`FILE`}function RE(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 zE={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},BE={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function VE(e){return Bd(e).kind===`normal`?zE:BE}function HE(){let e=document.createElement(`span`);e.className=`composer-placeholder`;let t=document.createElement(`span`);t.className=`composer-placeholder-label`,t.textContent=`Message pi…`;let n=document.createElement(`span`);return n.className=`composer-placeholder-hints`,n.textContent=`/ @ #`,e.append(t,n),e}function UE(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`}}var WE=class extends v{constructor(...e){super(...e),this.warningCount=0,this.warningsExpanded=!1,this.handleToggleWarnings=()=>{this.onToggleWarnings?.()}}render(){let e=this.status;if(e===void 0)return g`<div class="bar muted">No session status yet</div>`;let t=e.contextUsage,n=t?t.percent==null?`context ${jh(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${jh(t.contextWindow)}`:`context unknown`,r=e.tokens,i=UE(this.warningCount,this.warningsExpanded);return g`
|
|
3566
|
+
`}async toggleDictation(){this.voice??=new gE({recorder:nE()},{onState:e=>{this.voiceState=e},onTranscript:e=>{this.insertDictatedText(e)}}),await this.voice.toggle(this.speechToText)}insertDictatedText(e){let t=this.editor?.state.doc.toString()??this.draft,n=t===``||t.endsWith(` `)||t.endsWith(`
|
|
3567
|
+
`)?``:` `;this.replaceText(`${t}${n}${e}`)}effectiveAttachmentDelivery(){return MT(`inline`,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new m({parent:this.editorHost,state:l.create({doc:this.draft,extensions:[ee(),re(),t(),d.of(` `),r(a,{fallback:!0}),m.lineWrapping,n(),m.contentAttributes.of(e=>HE(e.state.sliceDoc(0,e.state.selection.main.head))),m.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),s(UE()),this.editableCompartment.of(m.editable.of(!this.disabled)),this.readOnlyCompartment.of(l.readOnly.of(this.disabled)),m.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),o.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:`ArrowDown`,run:e=>this.handleEditorArrow(e,`newer`)},{key:`ArrowUp`,run:e=>this.handleEditorArrow(e,`older`)},{key:`Escape`,run:()=>this.closeCompletions()},{key:`Tab`,run:e=>this.handleEditorTab(e)},{key:`Shift-Tab`,run:e=>u.shift?.(e)??!1},{key:`Backspace`,run:e=>te(e)},...c,...f])]})}))}syncEditorDoc(){let t=this.editor;if(!t)return;let n=t.state.doc.toString();n!==this.draft&&t.dispatch({changes:{from:0,to:n.length,insert:this.draft},selection:e.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(m.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(l.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;let t=jE(this.machineId,this.sessionId);t!==void 0&&jl(t,this.draft);let n=Bd(this.draft);Hd(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 I.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(ME);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.projectId!==void 0&&this.workspaceId!==void 0){let n=await I.files(e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId}).catch(NE);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=Fd(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}:{}}})}else if(e.kind===`model`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await I.models({id:this.sessionId,cwd:this.cwd},this.machineId).then(e=>e.models).catch(PE);if(t!==this.requestVersion)return;this.completions=Md(n,e.query).map(t=>({kind:`model`,replaceFrom:e.from,replaceTo:e.to,...t}))}}currentTrigger(){return Ad(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}handleEditorArrow(e,t){return this.completions.length?this.moveCompletion(t===`older`?-1:1):this.browsePromptHistory(e,WT(t))}browsePromptHistory(e,t){let n=jE(this.machineId,this.sessionId);if(n===void 0)return!1;let r=zT(n);if(r.length===0)return!1;let i=e.state.selection.main.head,a=e.state.selection.main.empty,o=e.state.doc.toString();if(this.historyIndex===void 0){if(!(a&&i===o.length&&o.trim()===``))return!1;this.historyDraftBeforeBrowse=o,this.historyIndex=0}else{let e=this.historyIndex+t;if(e<0)return!0;if(e>=r.length)return this.historyIndex=void 0,this.replaceText(this.historyDraftBeforeBrowse),!0;this.historyIndex=e}let s=r[this.historyIndex]??this.historyDraftBeforeBrowse;return this.replaceText(s),!0}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorKeyDown(e,t){if(e.key===`Shift`)return this.explicitShiftKeyActive=!0,!1;if((e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`r`)return e.preventDefault(),this.openPromptHistoryPicker();if(e.key!==`Enter`)return this.explicitShiftKeyActive=!1,e.key!==`ArrowUp`&&e.key!==`ArrowDown`&&(this.historyIndex=void 0),!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;let n=QT(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 $T(t,this.mobilePromptEnterMedia,YT())?(this.send(this.canSteer?`steer`:`followUp`),!0):ne(e)||p(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):u.run?.(e)??!1}pick(t){let n=this.editor;if(!n)return;if(t.kind===`history`){this.historyIndex=void 0,this.replaceText(t.insertText),this.completions=[];return}let r=t.kind===`file`&&(t.insertText.endsWith(`/`)||t.cursorOffset!==void 0)?``:` `,i=t.replaceFrom+(t.cursorOffset??t.insertText.length)+r.length,a=t.insertText.endsWith(`"`)&&this.draft.slice(t.replaceTo).startsWith(`"`)?t.replaceTo+1:t.replaceTo;n.dispatch({changes:{from:t.replaceFrom,to:a,insert:`${t.insertText}${r}`},selection:e.cursor(i),scrollIntoView:!0}),this.completions=[]}openPromptHistoryPicker(){let e=jE(this.machineId,this.sessionId);if(e===void 0)return!1;let t=HT(e,this.draft).slice(0,12);return t.length===0?!1:(this.selectedIndex=0,this.completions=t.map(e=>({kind:`history`,replaceFrom:0,replaceTo:this.draft.length,insertText:e,detail:`history`,description:e})),!0)}pendingPromptsForSession(){let e=Js(this.machineId,this.sessionId??``);return e===``?[]:xd(e)}send(e){if(this.disabled||this.sending)return;if(this.attachingCount>0){this.attachingSettled.then(()=>{this.send(e)});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(),o=jE(this.machineId,this.sessionId);o!==void 0&&t!==``&&VT(o,t);let s={text:this.draft,attachments:n};this.resetComposer(),this.deliverAndRestoreOnFailure(t,r,i,a,s)}async deliverAndRestoreOnFailure(e,t,n,r,i){let a,o;try{a=await this.onSend?.(e,t,n,n===void 0?void 0:r)}catch(e){a=!1,o=e}if(a===!1){if(yd(o)){let r=Js(this.machineId,this.sessionId??``);if(r!==``){let i=o instanceof bd?o.clientMessageId:void 0;Sd(r,{text:e,...t===void 0?{}:{behavior:t},...i===void 0?{}:{clientMessageId:i},...n===void 0||n.length===0?{}:{attachments:n},at:new Date().toISOString()}),this.pendingPrompts=xd(r);return}}(this.editor?.state.doc.toString()??this.draft).trim()===``&&(this.attachments=i.attachments,this.replaceText(i.text))}}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=jE(this.machineId,this.sessionId);e!==void 0&&Ml(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=lg}};H([b({type:Boolean})],q.prototype,`disabled`,void 0),H([b()],q.prototype,`sessionId`,void 0),H([b()],q.prototype,`cwd`,void 0),H([b()],q.prototype,`machineId`,void 0),H([b()],q.prototype,`projectId`,void 0),H([b()],q.prototype,`workspaceId`,void 0),H([b({type:Boolean})],q.prototype,`canSteer`,void 0),H([b({type:Boolean})],q.prototype,`isCompacting`,void 0),H([b({type:Boolean})],q.prototype,`canStop`,void 0),H([b({attribute:!1})],q.prototype,`status`,void 0),H([b({type:Boolean})],q.prototype,`sending`,void 0),H([b({type:Boolean,reflect:!0})],q.prototype,`collapsed`,void 0),H([b({attribute:!1})],q.prototype,`onSend`,void 0),H([b({attribute:!1})],q.prototype,`onStop`,void 0),H([b({attribute:!1})],q.prototype,`onSelectModel`,void 0),H([b({attribute:!1})],q.prototype,`onSelectThinking`,void 0),H([b({attribute:!1})],q.prototype,`onExpand`,void 0),H([b({attribute:!1})],q.prototype,`availableThinkingLevels`,void 0),H([S(`.markdown-editor`)],q.prototype,`editorHost`,void 0),H([S(`.attachment-input`)],q.prototype,`attachmentInput`,void 0),H([S(`dialog.attachment-zoom`)],q.prototype,`attachmentZoomDialog`,void 0),H([x()],q.prototype,`currentInputMode`,void 0),H([x()],q.prototype,`completions`,void 0),H([x()],q.prototype,`selectedIndex`,void 0),H([b({attribute:!1})],q.prototype,`speechToText`,void 0),H([x()],q.prototype,`voiceState`,void 0),H([x()],q.prototype,`zoomedAttachment`,void 0),H([x()],q.prototype,`attachments`,void 0),H([x()],q.prototype,`attachmentError`,void 0),H([x()],q.prototype,`attachingCount`,void 0),H([x()],q.prototype,`pendingPrompts`,void 0),q=H([y(`prompt-editor`)],q);function AE(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 jE(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return Js(e,t)}function ME(){return[]}function NE(){return[]}function PE(){return[]}function FE(e){return e===null?[]:Array.from(e.files)}function IE(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function LE(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 RE(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`FILE`}function zE(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 BE={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},VE={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function HE(e){return Bd(e).kind===`normal`?BE:VE}function UE(){let e=document.createElement(`span`);e.className=`composer-placeholder`;let t=document.createElement(`span`);t.className=`composer-placeholder-label`,t.textContent=`Message pi…`;let n=document.createElement(`span`);return n.className=`composer-placeholder-hints`,n.textContent=`/ @ #`,e.append(t,n),e}function WE(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`}}var GE=class extends v{constructor(...e){super(...e),this.warningCount=0,this.warningsExpanded=!1,this.handleToggleWarnings=()=>{this.onToggleWarnings?.()}}render(){let e=this.status;if(e===void 0)return g`<div class="bar muted">No session status yet</div>`;let t=e.contextUsage,n=t?t.percent==null?`context ${Mh(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Mh(t.contextWindow)}`:`context unknown`,r=e.tokens,i=WE(this.warningCount,this.warningsExpanded);return g`
|
|
3564
3568
|
<div class="bar">
|
|
3565
3569
|
${i===void 0||this.onToggleWarnings===void 0?null:g`
|
|
3566
3570
|
<button
|
|
@@ -3571,17 +3575,17 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3571
3575
|
aria-expanded=${String(this.warningsExpanded)}
|
|
3572
3576
|
@click=${this.handleToggleWarnings}
|
|
3573
3577
|
>
|
|
3574
|
-
${
|
|
3578
|
+
${tg(`warning`,`warning-toggle-icon`)}
|
|
3575
3579
|
<span>${i.countText}</span>
|
|
3576
3580
|
</button>
|
|
3577
3581
|
`}
|
|
3578
|
-
<span>↑${
|
|
3579
|
-
<span>↓${
|
|
3582
|
+
<span>↑${Mh(r.input)}</span>
|
|
3583
|
+
<span>↓${Mh(r.output)}</span>
|
|
3580
3584
|
<span class="context">${n}</span>
|
|
3581
|
-
<span>${
|
|
3585
|
+
<span>${Fh(e.cost)}</span>
|
|
3582
3586
|
${e.pendingMessageCount>0?g`<span>${String(e.pendingMessageCount)} queued</span>`:null}
|
|
3583
3587
|
</div>
|
|
3584
|
-
`}static{this.styles=
|
|
3588
|
+
`}static{this.styles=sg}};H([b({attribute:!1})],GE.prototype,`status`,void 0),H([b({type:Number})],GE.prototype,`warningCount`,void 0),H([b({type:Boolean})],GE.prototype,`warningsExpanded`,void 0),H([b({attribute:!1})],GE.prototype,`onToggleWarnings`,void 0),GE=H([y(`status-bar`)],GE);function KE(e){return e.composedPath().some(e=>e instanceof HTMLButtonElement||e instanceof HTMLAnchorElement&&e.hasAttribute(`href`))}var qE=class extends v{constructor(...e){super(...e),this.title=`Select`,this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=``}render(){let e=this.filteredOptions();return g`
|
|
3585
3589
|
<modal-surface
|
|
3586
3590
|
.onClose=${()=>this.onCancel?.()}
|
|
3587
3591
|
.initialFocus=${this.searchable?`input`:`.options`}
|
|
@@ -3598,7 +3602,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3598
3602
|
<button
|
|
3599
3603
|
class=${t===this.selectedIndex?`selected`:``}
|
|
3600
3604
|
aria-current=${t===this.selectedIndex?`true`:_}
|
|
3601
|
-
${
|
|
3605
|
+
${OE(t===this.selectedIndex,e.value)}
|
|
3602
3606
|
@focus=${()=>{this.selectedIndex=t}}
|
|
3603
3607
|
@click=${()=>this.onPick?.(e.value)}
|
|
3604
3608
|
>
|
|
@@ -3609,7 +3613,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3609
3613
|
${e.length===0?g`<div class="empty">No matching options</div>`:null}
|
|
3610
3614
|
</div>
|
|
3611
3615
|
</modal-surface>
|
|
3612
|
-
`}firstUpdated(){this.selectInitialValue()}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(){return Ed(this.options,this.query,e=>`${e.label} ${e.description??``} ${e.value}`)}handleKeyDown(e){if(
|
|
3616
|
+
`}firstUpdated(){this.selectInitialValue()}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(){return Ed(this.options,this.query,e=>`${e.label} ${e.description??``} ${e.value}`)}handleKeyDown(e){if(KE(e))return;let t=this.filteredOptions();if(e.key===`ArrowDown`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key===`ArrowUp`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key===`Enter`){e.preventDefault();let n=t[this.selectedIndex];n&&this.onPick?.(n.value)}}static{this.styles=h`
|
|
3613
3617
|
:host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
3614
3618
|
modal-surface { --modal-surface-width: min(720px, calc(100vw - 40px)); --modal-surface-max-height: min(640px, calc(100vh - 40px)); }
|
|
3615
3619
|
header { display: flex; align-items: center; justify-content: space-between; padding: 12px; border-bottom: 1px solid var(--pi-border); }
|
|
@@ -3625,7 +3629,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3625
3629
|
.options button.selected, .options button:hover { background: var(--pi-selection-bg); }
|
|
3626
3630
|
small { display: block; margin-top: 4px; color: var(--pi-muted); }
|
|
3627
3631
|
.empty { padding: 24px; color: var(--pi-muted); text-align: center; }
|
|
3628
|
-
`}};H([b()],
|
|
3632
|
+
`}};H([b()],qE.prototype,`title`,void 0),H([b({type:Boolean})],qE.prototype,`searchable`,void 0),H([b({attribute:!1})],qE.prototype,`options`,void 0),H([b({attribute:!1})],qE.prototype,`selectedValue`,void 0),H([b({attribute:!1})],qE.prototype,`onPick`,void 0),H([b({attribute:!1})],qE.prototype,`onCancel`,void 0),H([x()],qE.prototype,`selectedIndex`,void 0),H([x()],qE.prototype,`query`,void 0),qE=H([y(`command-picker`)],qE);function JE(e,t){let n=e.toLowerCase();return t.split(/\s+/).every(e=>n.includes(e))}function YE(e){return e.trim().toLowerCase()}function XE(e){return`${e.provider}/${e.id}`}function ZE(e,t){let n=YE(t);return n===``?[...e]:e.filter(e=>JE(`${e.label} ${e.description??``} ${e.value}`,n))}function QE(e,t){let n=YE(t),r=n===``?[...e]:e.filter(e=>JE(`${e.provider} ${e.id} ${e.name??``}`,n));return{rows:r,showGroupHeaders:n===``&&r.some(e=>e.enabled)&&r.some(e=>!e.enabled)}}var $E=class extends v{constructor(...e){super(...e),this.title=`Select Model`,this.options=[],this.catalog=[],this.mode=`enabled`,this.selectedIndex=0,this.query=``,this.pendingToggles=new Set}render(){let e=this.visibleRows();return g`
|
|
3629
3633
|
<modal-surface
|
|
3630
3634
|
.onClose=${()=>this.onCancel?.()}
|
|
3631
3635
|
.initialFocus=${`input.search`}
|
|
@@ -3646,19 +3650,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3646
3650
|
${e.length===0?g`<div class="empty">No matching options</div>`:null}
|
|
3647
3651
|
</div>
|
|
3648
3652
|
</modal-surface>
|
|
3649
|
-
`}firstUpdated(){this.anchorSelectionToSelectedValue()}willUpdate(e){if(!e.has(`catalog`)||this.mode!==`all`)return;let t=e.get(`catalog`);if(t===void 0)return;let n=
|
|
3653
|
+
`}firstUpdated(){this.anchorSelectionToSelectedValue()}willUpdate(e){if(!e.has(`catalog`)||this.mode!==`all`)return;let t=e.get(`catalog`);if(t===void 0)return;let n=QE(t,this.query).rows[this.selectedIndex],r=QE(this.catalog,this.query).rows,i=n===void 0?void 0:XE(n),a=i===void 0?-1:r.findIndex(e=>XE(e)===i);this.selectedIndex=a>=0?a:Math.min(this.selectedIndex,Math.max(r.length-1,0))}renderScopeToggleButton(e,t){return g`<button aria-pressed=${this.mode===e?`true`:`false`} @click=${()=>{this.selectMode(e)}}>${t}</button>`}renderEnabledList(){return ZE(this.options,this.query).map((e,t)=>g`
|
|
3650
3654
|
<button
|
|
3651
3655
|
class=${t===this.selectedIndex?`selected`:``}
|
|
3652
3656
|
aria-current=${t===this.selectedIndex?`true`:_}
|
|
3653
|
-
${
|
|
3657
|
+
${OE(t===this.selectedIndex,e.value)}
|
|
3654
3658
|
@focus=${()=>{this.selectedIndex=t}}
|
|
3655
3659
|
@click=${()=>this.onPick?.(e.value)}
|
|
3656
3660
|
>
|
|
3657
3661
|
<span>${e.label}</span>
|
|
3658
3662
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
3659
3663
|
</button>
|
|
3660
|
-
`)}renderCatalogList(){let e=
|
|
3661
|
-
<div class="catalog-row ${r?`selected`:``}" ${
|
|
3664
|
+
`)}renderCatalogList(){let e=QE(this.catalog,this.query),t=[],n;return e.rows.forEach((r,i)=>{e.showGroupHeaders&&r.enabled!==n&&t.push(g`<div class="group-header">${r.enabled?`Enabled`:`Other models`}</div>`),n=r.enabled,t.push(this.renderCatalogRow(r,i))}),t}renderCatalogRow(e,t){let n=XE(e),r=t===this.selectedIndex,i=this.pendingToggles.has(n);return g`
|
|
3665
|
+
<div class="catalog-row ${r?`selected`:``}" ${OE(r,n)}>
|
|
3662
3666
|
<input
|
|
3663
3667
|
type="checkbox"
|
|
3664
3668
|
.checked=${e.enabled}
|
|
@@ -3676,7 +3680,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3676
3680
|
<small>${e.provider}</small>
|
|
3677
3681
|
</button>
|
|
3678
3682
|
</div>
|
|
3679
|
-
`}visibleRows(){return this.mode===`all`?
|
|
3683
|
+
`}visibleRows(){return this.mode===`all`?QE(this.catalog,this.query).rows.map(e=>({value:XE(e),entry:e})):ZE(this.options,this.query).map(e=>({value:e.value}))}anchorSelectionToSelectedValue(){if(this.selectedValue===void 0){this.selectedIndex=0;return}let e=this.visibleRows().findIndex(e=>e.value===this.selectedValue);this.selectedIndex=e>=0?e:0}selectMode(e){e!==this.mode&&(this.mode=e,this.anchorSelectionToSelectedValue())}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}handleKeyDown(e){if(KE(e))return;let t=this.visibleRows();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.onPick?.(n.value)}else if(e.key===` `&&this.mode===`all`){if(e.composedPath().some(e=>e instanceof HTMLInputElement))return;let n=t[this.selectedIndex];if(n?.entry===void 0)return;e.preventDefault(),this.requestEnabledToggle(n.entry)}}handleEnableToggleClick(e,t){t.preventDefault(),t.currentTarget instanceof HTMLInputElement&&(t.currentTarget.checked=e.enabled),this.requestEnabledToggle(e)}requestEnabledToggle(e){let t=XE(e);if(this.pendingToggles.has(t))return;let n=new Set(this.pendingToggles);n.add(t),this.pendingToggles=n,this.settleEnabledToggle(t,e)}async settleEnabledToggle(e,t){try{await this.onToggleEnabled?.(t.provider,t.id,!t.enabled)}catch(t){console.warn(`Failed to toggle model ${e}`,t)}finally{let t=new Set(this.pendingToggles);t.delete(e),this.pendingToggles=t}}static{this.styles=h`
|
|
3680
3684
|
:host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
3681
3685
|
modal-surface { --modal-surface-width: min(720px, calc(100vw - 40px)); --modal-surface-max-height: min(640px, calc(100vh - 40px)); }
|
|
3682
3686
|
header { display: flex; align-items: center; justify-content: space-between; padding: 12px; border-bottom: 1px solid var(--pi-border); }
|
|
@@ -3697,7 +3701,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3697
3701
|
.group-header { padding: 8px 12px 4px; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; }
|
|
3698
3702
|
small { display: block; margin-top: 4px; color: var(--pi-muted); }
|
|
3699
3703
|
.empty { padding: 24px; color: var(--pi-muted); text-align: center; }
|
|
3700
|
-
`}};H([b()]
|
|
3704
|
+
`}};H([b()],$E.prototype,`title`,void 0),H([b({attribute:!1})],$E.prototype,`options`,void 0),H([b({attribute:!1})],$E.prototype,`catalog`,void 0),H([b({attribute:!1})],$E.prototype,`selectedValue`,void 0),H([b({attribute:!1})],$E.prototype,`onPick`,void 0),H([b({attribute:!1})],$E.prototype,`onCancel`,void 0),H([b({attribute:!1})],$E.prototype,`onToggleEnabled`,void 0),H([x()],$E.prototype,`mode`,void 0),H([x()],$E.prototype,`selectedIndex`,void 0),H([x()],$E.prototype,`query`,void 0),H([x()],$E.prototype,`pendingToggles`,void 0),$E=H([y(`model-picker`)],$E);var eD=class extends v{constructor(...e){super(...e),this.actions=[],this.queryText=``,this.selectedIndex=0}render(){let e=this.filteredActions();return g`
|
|
3701
3705
|
<modal-surface
|
|
3702
3706
|
.onClose=${()=>this.onCancel?.()}
|
|
3703
3707
|
.initialFocus=${`input`}
|
|
@@ -3719,7 +3723,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3719
3723
|
?disabled=${e.enabled===!1}
|
|
3720
3724
|
title=${e.disabledReason??e.title}
|
|
3721
3725
|
aria-current=${t===this.selectedIndex?`true`:_}
|
|
3722
|
-
${
|
|
3726
|
+
${OE(t===this.selectedIndex,e.id)}
|
|
3723
3727
|
@focus=${()=>{this.selectedIndex=t}}
|
|
3724
3728
|
@click=${()=>{this.run(e)}}
|
|
3725
3729
|
>
|
|
@@ -3734,7 +3738,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3734
3738
|
`)}
|
|
3735
3739
|
</div>
|
|
3736
3740
|
</modal-surface>
|
|
3737
|
-
`}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
|
|
3741
|
+
`}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 tD(this.actions,this.queryText)}handleKeyDown(e){if(KE(e))return;let t=this.filteredActions();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=h`
|
|
3738
3742
|
:host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
3739
3743
|
modal-surface { --palette-top: min(12dvh, 90px); --palette-bottom: max(20px, env(safe-area-inset-bottom)); --modal-surface-place-items: start center; --modal-surface-backdrop-padding: var(--palette-top) 20px var(--palette-bottom); --modal-surface-max-height: min(640px, calc(100dvh - var(--palette-top) - var(--palette-bottom))); }
|
|
3740
3744
|
header { display: grid; grid-template-columns: 1fr auto; gap: 8px; padding: 10px; border-bottom: 1px solid var(--pi-border); }
|
|
@@ -3756,7 +3760,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3756
3760
|
.group { grid-column: 1 / -1; font-size: 12px; }
|
|
3757
3761
|
kbd { align-self: center; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 2px 6px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: nowrap; }
|
|
3758
3762
|
.empty { padding: 24px; color: var(--pi-muted); text-align: center; }
|
|
3759
|
-
`}};H([b({attribute:!1})]
|
|
3763
|
+
`}};H([b({attribute:!1})],eD.prototype,`actions`,void 0),H([b({attribute:!1})],eD.prototype,`onRun`,void 0),H([b({attribute:!1})],eD.prototype,`onCancel`,void 0),H([x()],eD.prototype,`queryText`,void 0),H([x()],eD.prototype,`selectedIndex`,void 0),eD=H([y(`action-palette`)],eD);function tD(e,t){let n=YE(t);return e.filter(e=>e.enabled!==!1||e.disabledReason!==void 0).filter(e=>n===``||JE([e.title,e.description??``,e.disabledReason??``,e.group??``,e.shortcut??``].join(` `),n))}var nD=[`error`,`waiting`,`interrupted`,`active`,`unread`,`pinned`,`today`,`yesterday`,`earlier`],rD={error:`Needs attention`,waiting:`Waiting for you`,interrupted:`Interrupted`,active:`Working`,unread:`Finished`,pinned:`Pinned`,today:`Today`,yesterday:`Yesterday`,earlier:`Earlier`},iD=1440*60*1e3,aD=new Set;function oD(e){let t=e.sessions.filter(e=>e.archived!==!0).filter(t=>Gx(t,e.query)),n=new Map;for(let r of t){let t=sD(r,{active:e.activeSessionIds,error:e.errorSessionIds??aD,waiting:e.waitingSessionIds??aD,unread:e.unreadSessionIds??aD,interrupted:e.interruptedSessionIds??aD,pinned:e.pinnedSessionIds??aD},e.now),i=n.get(t)??[];i.push(r),n.set(t,i)}let r=[];for(let e of nD){let t=n.get(e);t===void 0||t.length===0||r.push({id:e,title:rD[e],sessions:t.sort(cD)})}return{groups:r,matchCount:t.length}}function sD(e,t,n){if(t.error.has(e.id))return`error`;if(t.waiting.has(e.id))return`waiting`;if(t.interrupted.has(e.id)&&!t.active.has(e.id))return`interrupted`;if(t.active.has(e.id))return`active`;if(t.unread.has(e.id))return`unread`;if(t.pinned.has(e.id))return`pinned`;let r=Date.parse(e.modified);if(Number.isNaN(r))return`earlier`;let i=n-r;return i<iD?`today`:i<2*iD?`yesterday`:`earlier`}function cD(e,t){return lD(t.modified)-lD(e.modified)}function lD(e){let t=Date.parse(e);return Number.isNaN(t)?0:t}function uD(e,t,n){let r=t.projectId===void 0?void 0:new Set(n.filter(e=>e.projectId===t.projectId).map(e=>e.path));return e.filter(e=>!(t.workspacePath!==void 0&&e.cwd!==t.workspacePath||r!==void 0&&!r.has(e.cwd)))}function dD(e){return e.machineId!==void 0||e.projectId!==void 0||e.workspacePath!==void 0}function fD(e,t){let n=t.trim().toLowerCase().split(/\s+/u).filter(Boolean);return n.length===0?[...e]:e.filter(e=>{let t=`${e.label}\n${e.path}`.toLowerCase();return n.every(e=>t.includes(e))})}function pD(e,t){let n=t.find(t=>t.path===e.cwd),r=`${String(e.messageCount)} ${e.messageCount===1?`message`:`messages`}`;return n===void 0?r:`${n.label} · ${r}`}function mD(e,t,n){return e.some(e=>e.id===t)?e.map(e=>e.id===t?{...e,name:n}:e):e}function hD(e,t,n){let r=new Map;for(let i of e){let e=xm(t[i.id],n[i.id]);e!==void 0&&r.set(i.id,e)}return r}var J=class extends v{constructor(...e){super(...e),this.loading=!1,this.sessions=[],this.workspaces=[],this.activeSessionIds=new Set,this.waitingSessionIds=new Set,this.unreadSessionIds=new Set,this.interruptedSessionIds=new Set,this.errorSessionIds=new Set,this.pinnedSessionIds=new Set,this.projects=[],this.sessionStates=new Map,this.canStartSession=!1,this.query=``,this.filter={},this.renameDraft=``,this.longPress=new qb({onLongPress:()=>{this.openMenuSessionId=this.heldSession?.id},setTimer:(e,t)=>window.setTimeout(e,t),clearTimer:e=>{window.clearTimeout(e)}})}render(){let e=this.model(),t=fD(this.workspaces,this.query).filter(e=>e.id!==this.selectedWorkspace?.id);return g`
|
|
3760
3764
|
<modal-surface
|
|
3761
3765
|
.onClose=${()=>this.onClose?.()}
|
|
3762
3766
|
.initialFocus=${`input`}
|
|
@@ -3819,7 +3823,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3819
3823
|
<button
|
|
3820
3824
|
class=${`row session-row ${t?`selected`:``} ${n?`unread`:``}`}
|
|
3821
3825
|
aria-current=${t?`true`:_}
|
|
3822
|
-
${
|
|
3826
|
+
${OE(t,e.id)}
|
|
3823
3827
|
@click=${()=>{this.openSession(e)}}
|
|
3824
3828
|
@contextmenu=${t=>{t.preventDefault(),this.openMenuSessionId=e.id}}
|
|
3825
3829
|
@pointerdown=${t=>{this.heldSession=e,this.longPress.start(t)}}
|
|
@@ -3827,16 +3831,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3827
3831
|
@pointerup=${()=>{this.longPress.cancel()}}
|
|
3828
3832
|
@pointercancel=${()=>{this.longPress.cancel()}}
|
|
3829
3833
|
>
|
|
3830
|
-
<span class="row-title" dir="auto">${r?g`<span class="pin-mark" title="Pinned" aria-label="Pinned">${`⚑`}</span> `:_}${
|
|
3831
|
-
<span class="row-subtitle">${
|
|
3832
|
-
<span class="row-state">${
|
|
3834
|
+
<span class="row-title" dir="auto">${r?g`<span class="pin-mark" title="Pinned" aria-label="Pinned">${`⚑`}</span> `:_}${Bx(e)}</span>
|
|
3835
|
+
<span class="row-subtitle">${pD(e,this.workspaces)}</span>
|
|
3836
|
+
<span class="row-state">${ax(o,n&&o===void 0?`Unread activity`:void 0)}</span>
|
|
3833
3837
|
${a?g`<span class="row-flag interrupted" title="A restart interrupted this run" aria-label="A restart interrupted this run"></span>`:null}
|
|
3834
3838
|
${o===void 0&&!a&&n?g`<span class="row-flag unread" title="Unread activity" aria-label="Unread activity"></span>`:null}
|
|
3835
3839
|
</button>
|
|
3836
3840
|
<button
|
|
3837
3841
|
class="row-menu-toggle"
|
|
3838
3842
|
title="Session actions"
|
|
3839
|
-
aria-label=${`Actions for ${
|
|
3843
|
+
aria-label=${`Actions for ${Bx(e)}`}
|
|
3840
3844
|
aria-haspopup="menu"
|
|
3841
3845
|
aria-expanded=${this.openMenuSessionId===e.id?`true`:`false`}
|
|
3842
3846
|
@click=${()=>{this.openMenuSessionId=this.openMenuSessionId===e.id?void 0:e.id}}
|
|
@@ -3853,7 +3857,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3853
3857
|
<form class="row rename-row" @submit=${t=>{t.preventDefault(),this.confirmRename(e)}}>
|
|
3854
3858
|
<input
|
|
3855
3859
|
class="rename-input"
|
|
3856
|
-
aria-label=${`Rename ${
|
|
3860
|
+
aria-label=${`Rename ${Bx(e)}`}
|
|
3857
3861
|
.value=${this.renameDraft}
|
|
3858
3862
|
@input=${e=>{e.target instanceof HTMLInputElement&&(this.renameDraft=e.target.value)}}
|
|
3859
3863
|
@keydown=${e=>{e.key===`Escape`&&(e.stopPropagation(),this.renamingSessionId=void 0)}}
|
|
@@ -3863,7 +3867,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3863
3867
|
<button type="button" title="Cancel rename" aria-label="Cancel rename" @click=${()=>{this.renamingSessionId=void 0}}>${`×`}</button>
|
|
3864
3868
|
</div>
|
|
3865
3869
|
</form>
|
|
3866
|
-
`}togglePin(e){this.openMenuSessionId=void 0,this.onTogglePin?.(e)}startRename(e){this.openMenuSessionId=void 0,this.renameDraft=
|
|
3870
|
+
`}togglePin(e){this.openMenuSessionId=void 0,this.onTogglePin?.(e)}startRename(e){this.openMenuSessionId=void 0,this.renameDraft=Bx(e),this.renamingSessionId=e.id}async confirmRename(e){let t=this.renameDraft.trim();this.renamingSessionId=void 0,!(t===``||t===Bx(e))&&await this.onRenameSession?.(e,t)}handleKeyDown(e){if(e.key!==`Enter`||KE(e))return;let t=this.model().groups[0]?.sessions[0];t!==void 0&&(e.preventDefault(),this.openSession(t))}model(){return oD({sessions:uD(this.sessions,this.filter,this.workspaces),activeSessionIds:this.activeSessionIds,errorSessionIds:this.errorSessionIds,waitingSessionIds:this.waitingSessionIds,unreadSessionIds:this.unreadSessionIds,interruptedSessionIds:this.interruptedSessionIds,pinnedSessionIds:this.pinnedSessionIds,query:this.query,now:Date.now()})}renderFilters(){let e=this.projects.filter(e=>this.workspaces.some(t=>t.projectId===e.id));if(e.length===0&&this.workspaces.length<2)return _;let t=dD(this.filter);return g`
|
|
3867
3871
|
<div class="filters" role="group" aria-label="Filter sessions by context">
|
|
3868
3872
|
<button
|
|
3869
3873
|
type="button"
|
|
@@ -3889,7 +3893,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3889
3893
|
>${e.label}</button>
|
|
3890
3894
|
`)}
|
|
3891
3895
|
</div>
|
|
3892
|
-
`}filterWorkspaces(e){if(this.filter.projectId!==void 0){let e=this.workspaces.filter(e=>e.projectId===this.filter.projectId);return e.length>1?e:[]}return e.length===0?this.workspaces:[]}toggleFilter(e){let t=e.projectId!==void 0&&e.projectId===this.filter.projectId||e.workspacePath!==void 0&&e.workspacePath===this.filter.workspacePath;this.filter=t?{}:e}onQueryInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value)}createSession(){this.canStartSession&&(this.onCreateSession?.(),this.onClose?.())}openSession(e){this.onOpenSession?.(e),this.onClose?.()}selectWorkspace(e){this.onSelectWorkspace?.(e),this.query=``}browse(){this.onBrowse?.(),this.onClose?.()}static{this.styles=[
|
|
3896
|
+
`}filterWorkspaces(e){if(this.filter.projectId!==void 0){let e=this.workspaces.filter(e=>e.projectId===this.filter.projectId);return e.length>1?e:[]}return e.length===0?this.workspaces:[]}toggleFilter(e){let t=e.projectId!==void 0&&e.projectId===this.filter.projectId||e.workspacePath!==void 0&&e.workspacePath===this.filter.workspacePath;this.filter=t?{}:e}onQueryInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value)}createSession(){this.canStartSession&&(this.onCreateSession?.(),this.onClose?.())}openSession(e){this.onOpenSession?.(e),this.onClose?.()}selectWorkspace(e){this.onSelectWorkspace?.(e),this.query=``}browse(){this.onBrowse?.(),this.onClose?.()}static{this.styles=[eg,h`
|
|
3893
3897
|
:host { position: fixed; inset: 0; z-index: 25; color: var(--pi-text); font: var(--pi-text-base) var(--pi-font-ui); }
|
|
3894
3898
|
modal-surface {
|
|
3895
3899
|
--modal-surface-place-items: end center;
|
|
@@ -3908,7 +3912,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3908
3912
|
mostly empty cards at a time, so choosing between a dozen sessions meant
|
|
3909
3913
|
scrolling a list that wasted half its width on every row. auto-fit keeps
|
|
3910
3914
|
a single column when there is only room for one. */
|
|
3911
|
-
.rows { display: grid; grid-template-columns: repeat(auto-fit, minmax(
|
|
3915
|
+
.rows { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: var(--pi-space-3); align-content: start; }
|
|
3912
3916
|
.row { position: relative; display: grid; gap: var(--pi-space-1); width: 100%; min-height: 52px; border: 1px solid var(--pi-border); border-radius: var(--pi-radius-lg); background: var(--pi-surface); color: var(--pi-text); padding: var(--pi-space-5) 34px var(--pi-space-5) var(--pi-space-6); text-align: left; cursor: pointer; }
|
|
3913
3917
|
.row:hover:not(:disabled) { background: var(--pi-surface-hover); }
|
|
3914
3918
|
.row:disabled { opacity: .55; cursor: not-allowed; }
|
|
@@ -3939,6 +3943,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3939
3943
|
.row-wrap .session-row { -webkit-touch-callout: none; -webkit-user-select: none; user-select: none; }
|
|
3940
3944
|
.row-menu-toggle { flex: 0 0 auto; width: 40px; min-height: 52px; border: 1px solid var(--pi-border); border-radius: var(--pi-radius-lg); background: var(--pi-surface); color: var(--pi-muted); font-size: var(--pi-text-lg); line-height: 1; cursor: pointer; }
|
|
3941
3945
|
.row-menu-toggle:hover, .row-menu-toggle:focus-visible { color: var(--pi-text); border-color: var(--pi-accent); }
|
|
3946
|
+
/* On a narrow phone the menu button's own column left the name about a
|
|
3947
|
+
hundred pixels, so two tiles read worse than one. The button moves into
|
|
3948
|
+
the tile's corner instead: it is used occasionally, the name is read
|
|
3949
|
+
every time. */
|
|
3950
|
+
@media (max-width: 420px) {
|
|
3951
|
+
.row-wrap { display: block; }
|
|
3952
|
+
/* A half-width tile on one line shows about nine characters, which is
|
|
3953
|
+
fewer than the single-column row it replaced. Two lines give the name
|
|
3954
|
+
back the same room while still fitting twice as many sessions on the
|
|
3955
|
+
screen. */
|
|
3956
|
+
.row-title { padding-right: 26px; white-space: normal; display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
|
|
3957
|
+
.row-menu-toggle { position: absolute; top: 0; right: 0; width: 32px; min-height: 32px; border-color: transparent; background: transparent; }
|
|
3958
|
+
}
|
|
3942
3959
|
.row-menu { position: absolute; top: calc(100% - 4px); right: 0; z-index: 3; display: grid; gap: var(--pi-space-1); min-width: 160px; padding: var(--pi-space-3); border: 1px solid var(--pi-border); border-radius: var(--pi-radius-lg); background: var(--pi-surface); box-shadow: 0 10px 26px var(--pi-shadow); }
|
|
3943
3960
|
.row-menu button { min-height: 40px; border: 0; border-radius: var(--pi-radius-md); background: transparent; color: var(--pi-text); padding: 0 var(--pi-space-5); font: inherit; text-align: left; cursor: pointer; }
|
|
3944
3961
|
.row-menu button:hover:not(:disabled), .row-menu button:focus-visible:not(:disabled) { background: var(--pi-selection-bg); }
|
|
@@ -3951,7 +3968,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3951
3968
|
.empty { margin: var(--pi-space-7) var(--pi-space-2); color: var(--pi-muted); }
|
|
3952
3969
|
footer { flex: 0 0 auto; padding: var(--pi-space-5); padding-bottom: max(10px, env(safe-area-inset-bottom)); border-top: 1px solid var(--pi-border); }
|
|
3953
3970
|
footer button { width: 100%; min-height: 44px; border: 1px solid var(--pi-border); border-radius: var(--pi-radius-lg); background: var(--pi-surface); color: var(--pi-text); cursor: pointer; }
|
|
3954
|
-
`]}};H([b({type:Boolean})],J.prototype,`loading`,void 0),H([b({attribute:!1})],J.prototype,`sessions`,void 0),H([b({attribute:!1})],J.prototype,`workspaces`,void 0),H([b({attribute:!1})],J.prototype,`selectedSession`,void 0),H([b({attribute:!1})],J.prototype,`selectedWorkspace`,void 0),H([b({attribute:!1})],J.prototype,`activeSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`waitingSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`unreadSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`interruptedSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`errorSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`pinnedSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`projects`,void 0),H([b({attribute:!1})],J.prototype,`sessionStates`,void 0),H([b({type:Boolean})],J.prototype,`canStartSession`,void 0),H([b({attribute:!1})],J.prototype,`onCreateSession`,void 0),H([b({attribute:!1})],J.prototype,`onOpenSession`,void 0),H([b({attribute:!1})],J.prototype,`onSelectWorkspace`,void 0),H([b({attribute:!1})],J.prototype,`onBrowse`,void 0),H([b({attribute:!1})],J.prototype,`onClose`,void 0),H([b({attribute:!1})],J.prototype,`onTogglePin`,void 0),H([b({attribute:!1})],J.prototype,`onRenameSession`,void 0),H([x()],J.prototype,`query`,void 0),H([x()],J.prototype,`filter`,void 0),H([x()],J.prototype,`openMenuSessionId`,void 0),H([x()],J.prototype,`renamingSessionId`,void 0),J=H([y(`quick-switcher`)],J);var
|
|
3971
|
+
`]}};H([b({type:Boolean})],J.prototype,`loading`,void 0),H([b({attribute:!1})],J.prototype,`sessions`,void 0),H([b({attribute:!1})],J.prototype,`workspaces`,void 0),H([b({attribute:!1})],J.prototype,`selectedSession`,void 0),H([b({attribute:!1})],J.prototype,`selectedWorkspace`,void 0),H([b({attribute:!1})],J.prototype,`activeSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`waitingSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`unreadSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`interruptedSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`errorSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`pinnedSessionIds`,void 0),H([b({attribute:!1})],J.prototype,`projects`,void 0),H([b({attribute:!1})],J.prototype,`sessionStates`,void 0),H([b({type:Boolean})],J.prototype,`canStartSession`,void 0),H([b({attribute:!1})],J.prototype,`onCreateSession`,void 0),H([b({attribute:!1})],J.prototype,`onOpenSession`,void 0),H([b({attribute:!1})],J.prototype,`onSelectWorkspace`,void 0),H([b({attribute:!1})],J.prototype,`onBrowse`,void 0),H([b({attribute:!1})],J.prototype,`onClose`,void 0),H([b({attribute:!1})],J.prototype,`onTogglePin`,void 0),H([b({attribute:!1})],J.prototype,`onRenameSession`,void 0),H([x()],J.prototype,`query`,void 0),H([x()],J.prototype,`filter`,void 0),H([x()],J.prototype,`openMenuSessionId`,void 0),H([x()],J.prototype,`renamingSessionId`,void 0),J=H([y(`quick-switcher`)],J);var gD=class extends v{constructor(...e){super(...e),this.selectedIndex=0,this.query=``}render(){let e=this.state;return e===void 0?null:g`
|
|
3955
3972
|
<modal-surface
|
|
3956
3973
|
.onClose=${()=>{this.cancel()}}
|
|
3957
3974
|
.initialFocus=${this.initialFocusTarget(e)}
|
|
@@ -3964,7 +3981,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3964
3981
|
</header>
|
|
3965
3982
|
${this.renderBody(e)}
|
|
3966
3983
|
</modal-surface>
|
|
3967
|
-
`}optionsFor(e){switch(e.step){case`method`:return[{key:`oauth`,title:`Use a subscription`,detail:`ChatGPT Plus/Pro, Claude Pro/Max, or GitHub Copilot`,searchText:`Use a subscription`,run:()=>{this.onChooseMethod?.(`oauth`)}},{key:`api_key`,title:`Use provider credentials`,detail:`Configure an API key or provider-specific credentials in the active Pi-compatible profile's auth.json`,searchText:`Use provider credentials`,run:()=>{this.onChooseMethod?.(`api_key`)}}];case`providers`:return e.providers.map(e=>({key:e.id,title:g`${e.name}${e.status.source===void 0?null:g` <em>${
|
|
3984
|
+
`}optionsFor(e){switch(e.step){case`method`:return[{key:`oauth`,title:`Use a subscription`,detail:`ChatGPT Plus/Pro, Claude Pro/Max, or GitHub Copilot`,searchText:`Use a subscription`,run:()=>{this.onChooseMethod?.(`oauth`)}},{key:`api_key`,title:`Use provider credentials`,detail:`Configure an API key or provider-specific credentials in the active Pi-compatible profile's auth.json`,searchText:`Use provider credentials`,run:()=>{this.onChooseMethod?.(`api_key`)}}];case`providers`:return e.providers.map(e=>({key:e.id,title:g`${e.name}${e.status.source===void 0?null:g` <em>${TD(e)}</em>`}`,detail:`${e.id} · ${xD(e.authType)}`,searchText:e.name,run:()=>{this.onSelectProvider?.(e.id,e.authType)}}));case`logout`:return e.providers.map(e=>({key:e.id,title:e.name,detail:`${e.id} · ${xD(e.authType)}`,searchText:e.name,run:()=>{this.onLogoutProvider?.(e.id)}}));case`oauth`:return}}initialFocusTarget(e){if(e.step===`oauth`)return e.flow.prompt===void 0?void 0:`input`;if(e.step===`providers`||e.step===`logout`)return e.providers.length>0?`input`:void 0}stepHasSearch(e){return e.step===`providers`||e.step===`logout`}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(e){let t=YE(this.query);return t===``?e:e.filter(e=>JE(`${e.searchText} ${e.detail} ${e.key}`,t))}visibleOptions(e){let t=this.optionsFor(e);return t===void 0?[]:this.filteredOptions(t)}willUpdate(e){if(!e.has(`state`))return;if(wD(e.get(`state`))!==this.state?.step){this.selectedIndex=0,this.query=``;return}let t=this.state===void 0?void 0:this.visibleOptions(this.state);t!==void 0&&(this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,t.length-1)))}updated(e){if(!e.has(`state`))return;let t=wD(e.get(`state`));if(t===void 0)return;let n=this.state?.step,r=t!==n,i=t===`oauth`&&n===`oauth`&&SD(e.get(`state`))!==SD(this.state);(r||i)&&this.surface?.focusDialog()}dialogTitle(e){switch(e.step){case`method`:return`Configure provider authentication`;case`providers`:return e.authType===void 0?`Select provider authentication`:e.authType===`oauth`?`Select subscription provider`:`Select credential provider`;case`oauth`:return`Login to ${e.flow.providerName}`;case`logout`:return`Remove stored provider authentication`}}renderBody(e){if(e.step===`oauth`)return this.renderOAuth(e);let t=this.optionsFor(e)??[],n=this.filteredOptions(t);return g`
|
|
3968
3985
|
${this.stepHasSearch(e)&&t.length>0?g`
|
|
3969
3986
|
<input aria-label="Search providers" placeholder="Search providers" .value=${this.query} @input=${e=>{this.handleSearchInput(e)}}>
|
|
3970
3987
|
`:null}
|
|
@@ -3973,7 +3990,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3973
3990
|
<button
|
|
3974
3991
|
class=${t===this.selectedIndex?`selected`:``}
|
|
3975
3992
|
aria-current=${t===this.selectedIndex?`true`:_}
|
|
3976
|
-
${
|
|
3993
|
+
${OE(t===this.selectedIndex,e.key)}
|
|
3977
3994
|
@focus=${()=>{this.selectedIndex=t}}
|
|
3978
3995
|
@click=${()=>{e.run()}}
|
|
3979
3996
|
>
|
|
@@ -3982,7 +3999,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3982
3999
|
</button>
|
|
3983
4000
|
`)}
|
|
3984
4001
|
</div>
|
|
3985
|
-
`}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=n===void 0?void 0:
|
|
4002
|
+
`}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=n===void 0?void 0:_D(n.promptType),a=bD(e.machineId,window.location.hostname)&&t.status===`running`&&n?.promptType===`manual_code`;return g`
|
|
3986
4003
|
<div class="form">
|
|
3987
4004
|
${t.auth===void 0?g`<p>Starting login flow…</p>`:g`
|
|
3988
4005
|
<p>Open this authorization link:</p>
|
|
@@ -4016,7 +4033,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4016
4033
|
${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}
|
|
4017
4034
|
${n===void 0&&r===void 0&&t.status===`running`?g`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>Cancel</button></div>`:null}
|
|
4018
4035
|
</div>
|
|
4019
|
-
`}handleKeyDown(e){let t=this.state;if(t===void 0||
|
|
4036
|
+
`}handleKeyDown(e){let t=this.state;if(t===void 0||KE(e))return;if(e.key===`ArrowDown`||e.key===`ArrowUp`){let n=this.visibleOptions(t);if(n.length===0)return;e.preventDefault();let r=e.key===`ArrowDown`?1:-1;this.selectedIndex=(this.selectedIndex+r+n.length)%n.length;return}if(e.key!==`Enter`)return;if(t.step===`oauth`){if(t.flow.prompt===void 0)return;e.preventDefault(),this.onOAuthRespond?.();return}let n=this.visibleOptions(t)[this.selectedIndex];n!==void 0&&(e.preventDefault(),n.run())}cancel(){this.state?.step===`oauth`?this.onOAuthCancel?.():this.onCancel?.()}static{this.styles=[h`
|
|
4020
4037
|
:host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
4021
4038
|
modal-surface { --modal-surface-width: min(720px, calc(100vw - 40px)); --modal-surface-max-height: min(640px, calc(100vh - 40px)); }
|
|
4022
4039
|
header { display: flex; align-items: center; justify-content: space-between; padding: 12px; border-bottom: 1px solid var(--pi-border); }
|
|
@@ -4051,7 +4068,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4051
4068
|
.inline-options button { display: grid; gap: 2px; text-align: left; }
|
|
4052
4069
|
.inline-options small { color: var(--pi-muted); }
|
|
4053
4070
|
em { color: var(--pi-success); font-style: normal; font-size: 12px; }
|
|
4054
|
-
`]}};H([b({attribute:!1})],
|
|
4071
|
+
`]}};H([b({attribute:!1})],gD.prototype,`state`,void 0),H([b({attribute:!1})],gD.prototype,`onChooseMethod`,void 0),H([b({attribute:!1})],gD.prototype,`onSelectProvider`,void 0),H([b({attribute:!1})],gD.prototype,`onLogoutProvider`,void 0),H([b({attribute:!1})],gD.prototype,`onOAuthInput`,void 0),H([b({attribute:!1})],gD.prototype,`onOAuthRespond`,void 0),H([b({attribute:!1})],gD.prototype,`onOAuthCancel`,void 0),H([b({attribute:!1})],gD.prototype,`onCancel`,void 0),H([S(`modal-surface`)],gD.prototype,`surface`,void 0),H([x()],gD.prototype,`selectedIndex`,void 0),H([x()],gD.prototype,`query`,void 0),gD=H([y(`auth-dialog`)],gD);function _D(e){return e===`secret`?`password`:`text`}var vD=new Set([`localhost`,`127.0.0.1`,`::1`]);function yD(e){return vD.has(e.trim().replace(/^\[|\]$/g,``).toLowerCase())}function bD(e,t){return e!==`local`||!yD(t)}function xD(e){return e===`oauth`?`subscription`:`credentials`}function SD(e){if(wD(e)!==`oauth`||typeof e!=`object`||!e||!(`flow`in e))return;let t=e.flow;if(typeof t!=`object`||!t)return;let n=`flowId`in t&&typeof t.flowId==`string`?t.flowId:``,r=`prompt`in t?CD(t.prompt):void 0;if(r!==void 0)return`${n}:prompt:${r}:${`responding`in e&&e.responding===!0?`responding`:`ready`}`;let i=`select`in t?CD(t.select):void 0;return i===void 0?`${n}:waiting:${`status`in t&&typeof t.status==`string`?t.status:`unknown`}`:`${n}:select:${i}`}function CD(e){if(!(typeof e!=`object`||!e||!(`requestId`in e)))return typeof e.requestId==`string`?e.requestId:void 0}function wD(e){if(!(typeof e!=`object`||!e||!(`step`in e)))switch(e.step){case`method`:case`providers`:case`oauth`:case`logout`:return e.step;default:return}}function TD(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 ED=120,DD=class extends v{constructor(...e){super(...e),this.machineId=`local`,this.path=``,this.createMissing=!0,this.submitError=void 0,this.submitting=!1,this.suggestions=[],this.selected=0,this.loading=!1,this.trustTouched=!1,this.suggestionRequestId=0,this.trustRequestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}disconnectedCallback(){this.cancelPendingSuggestions(),super.disconnectedCallback()}scheduleSuggestions(){this.cancelPendingSuggestions(),this.suggestionTimer=setTimeout(()=>{this.suggestionTimer=void 0,this.loadSuggestions()},ED)}cancelPendingSuggestions(){this.suggestionTimer!==void 0&&(clearTimeout(this.suggestionTimer),this.suggestionTimer=void 0)}async loadSuggestions(){let e=++this.suggestionRequestId;this.loading=!0;try{let t=await I.projectDirectories(this.path,this.machineId);if(e!==this.suggestionRequestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.suggestionRequestId&&(this.suggestions=[])}finally{e===this.suggestionRequestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.scheduleSuggestions(),this.trustTouched=!1,this.loadTrust()}pick(e){this.path=e.path,this.selected=0,this.cancelPendingSuggestions(),this.loadSuggestions()}submit(){this.path.trim()===``||this.submitting||(this.submitError=void 0,this.submitting=!0,(async()=>{try{let e=await this.onSubmit?.(this.path,this.createMissing,this.trust===void 0?void 0:{trusted:this.trust.trusted,changed:this.trustTouched});this.submitError=typeof e==`string`&&e!==``?e:void 0}finally{this.submitting=!1}})())}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}async loadTrust(){let e=++this.trustRequestId,t=this.path.trim();if(t===``){e===this.trustRequestId&&(this.trust=void 0);return}e===this.trustRequestId&&(this.trust={...this.trust??{path:t,decision:null,trusted:!1},path:t,loading:!0});try{let n=await Wo.projectTrust(t,this.machineId);if(e!==this.trustRequestId||this.trustTouched)return;this.trust={path:n.path,decision:n.decision,trusted:n.trusted,loading:!1}}catch(n){if(e!==this.trustRequestId||this.trustTouched)return;this.trust={path:t,decision:null,trusted:!1,loading:!1,error:n instanceof Error?n.message:String(n)}}}onTrustChange(e){this.trustTouched=!0,this.trust!==void 0&&(this.trust={...this.trust,trusted:e,loading:!1})}renderTrustChoice(){let e=this.trust===void 0||this.trust.loading||this.trust.error!==void 0;return g`
|
|
4055
4072
|
<label class="check">
|
|
4056
4073
|
<input type="checkbox" .checked=${this.trust?.trusted??!1} ?disabled=${e} @change=${e=>{e.target instanceof HTMLInputElement&&this.onTrustChange(e.target.checked)}} />
|
|
4057
4074
|
<span>Trust this project</span>
|
|
@@ -4138,7 +4155,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4138
4155
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
4139
4156
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
4140
4157
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
4141
|
-
`}};H([b({attribute:!1})],
|
|
4158
|
+
`}};H([b({attribute:!1})],DD.prototype,`onSubmit`,void 0),H([b({attribute:!1})],DD.prototype,`onCancel`,void 0),H([b()],DD.prototype,`machineId`,void 0),H([x()],DD.prototype,`path`,void 0),H([x()],DD.prototype,`createMissing`,void 0),H([x()],DD.prototype,`submitError`,void 0),H([x()],DD.prototype,`submitting`,void 0),H([x()],DD.prototype,`suggestions`,void 0),H([x()],DD.prototype,`selected`,void 0),H([x()],DD.prototype,`loading`,void 0),H([x()],DD.prototype,`trust`,void 0),H([x()],DD.prototype,`trustTouched`,void 0),H([S(`input`)],DD.prototype,`pathInput`,void 0),DD=H([y(`project-dialog`)],DD);var OD=class extends v{constructor(...e){super(...e),this.error=``,this.url=``,this.name=``,this.token=``,this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=``}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;let t=e.target.value,n=kD(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){e.key===`Enter`&&e.target instanceof HTMLInputElement&&e.target.name===`baseUrl`&&AD(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===``||AD(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?AD(this.url):void 0,n=this.validInput()!==void 0&&!this.submitting;return g`
|
|
4142
4159
|
<modal-surface
|
|
4143
4160
|
.onClose=${()=>this.onCancel?.()}
|
|
4144
4161
|
.initialFocus=${`input[name='baseUrl']`}
|
|
@@ -4197,7 +4214,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4197
4214
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
4198
4215
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
4199
4216
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
4200
|
-
`}};H([b({attribute:!1})],
|
|
4217
|
+
`}};H([b({attribute:!1})],OD.prototype,`onSubmit`,void 0),H([b({attribute:!1})],OD.prototype,`onCancel`,void 0),H([b()],OD.prototype,`error`,void 0),H([x()],OD.prototype,`url`,void 0),H([x()],OD.prototype,`name`,void 0),H([x()],OD.prototype,`token`,void 0),H([x()],OD.prototype,`submitting`,void 0),H([S(`input[name='name']`)],OD.prototype,`nameInput`,void 0),OD=H([y(`machine-dialog`)],OD);function kD(e){let t=e.trim();if(t===``)return``;let n=jD(t)??jD(`http://${t.replace(/^\/+/u,``)}`);return n!==void 0&&n.hostname!==``?n.hostname.replace(/^\[(.*)\]$/u,`$1`):MD(t)}function AD(e){let t=e.trim();if(t===``)return`Remote PI WEB 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 jD(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:void 0}catch{return}}function MD(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 ND=class extends v{constructor(...e){super(...e),this.themes=[],this.followSystem=!1}render(){return g`
|
|
4201
4218
|
<settings-panel-frame>
|
|
4202
4219
|
<div class="heading">
|
|
4203
4220
|
<div>
|
|
@@ -4283,7 +4300,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4283
4300
|
.theme-grid { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: var(--pi-space-4); }
|
|
4284
4301
|
.preview { height: 64px; }
|
|
4285
4302
|
}
|
|
4286
|
-
`}};H([b({attribute:!1})],
|
|
4303
|
+
`}};H([b({attribute:!1})],ND.prototype,`themes`,void 0),H([b({attribute:!1})],ND.prototype,`selectedThemeId`,void 0),H([b({attribute:!1})],ND.prototype,`activeThemeId`,void 0),H([b({type:Boolean})],ND.prototype,`followSystem`,void 0),H([b({attribute:!1})],ND.prototype,`onSelectTheme`,void 0),H([b({attribute:!1})],ND.prototype,`onToggleFollowSystem`,void 0),ND=H([y(`settings-appearance-panel`)],ND);var PD={availability:`error`,error:`error`,success:`success`,security:`warning`,warning:`warning`,info:`info`};function FD(e){return e.tone??PD[e.type]}var ID=class extends v{constructor(...e){super(...e),this.heading=``,this.description=``,this.actionLabel=``,this.actionTitle=``,this.actionDisabled=!1,this.notices=[]}render(){return g`
|
|
4287
4304
|
<section class="panel" aria-label=${this.heading||`Settings panel`}>
|
|
4288
4305
|
<header class="section-heading">
|
|
4289
4306
|
<div class="heading-copy">
|
|
@@ -4306,7 +4323,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4306
4323
|
<div class="notice-stack" aria-label="Settings notices">
|
|
4307
4324
|
${this.notices.map(e=>this.renderNotice(e))}
|
|
4308
4325
|
</div>
|
|
4309
|
-
`}renderNotice(e){let t=
|
|
4326
|
+
`}renderNotice(e){let t=FD(e),n=e.role??LD(t),r=e.title;return g`
|
|
4310
4327
|
<article class=${`notice ${t}`} role=${n}>
|
|
4311
4328
|
${r===void 0||r===``?_:g`<strong class="notice-title">${r}</strong>`}
|
|
4312
4329
|
<div class="notice-content">${e.content}</div>
|
|
@@ -4339,13 +4356,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4339
4356
|
.section-heading { display: grid; gap: 12px; }
|
|
4340
4357
|
.heading-actions { justify-self: start; }
|
|
4341
4358
|
}
|
|
4342
|
-
`}};H([b()],
|
|
4343
|
-
`):``}}function
|
|
4344
|
-
`)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function
|
|
4345
|
-
`).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!
|
|
4359
|
+
`}};H([b()],ID.prototype,`heading`,void 0),H([b({attribute:!1})],ID.prototype,`description`,void 0),H([b()],ID.prototype,`actionLabel`,void 0),H([b()],ID.prototype,`actionTitle`,void 0),H([b({type:Boolean})],ID.prototype,`actionDisabled`,void 0),H([b({attribute:!1})],ID.prototype,`notices`,void 0),H([b({attribute:!1})],ID.prototype,`onAction`,void 0),ID=H([y(`settings-panel-frame`)],ID);function LD(e){switch(e){case`error`:return`alert`;case`success`:return`status`;case`warning`:case`info`:return`note`}}function RD(){return{host:``,port:``,allowedHostsMode:`list`,allowedHostsText:``}}function zD(){return{allowedPathsText:``,uploadDefaultFolder:``}}function BD(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(`
|
|
4360
|
+
`):``}}function VD(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
|
|
4361
|
+
`)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function HD(e,t={}){let n=WD(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`||GD(e.allowedHostsText),n}function UD(e){let t=KD(e.allowedPathsText),n=qD(e.uploadDefaultFolder);return{pathAccess:{allowedPaths:t},uploads:n===``?{}:{defaultFolder:n}}}function WD(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.askUser===void 0?{}:{askUser:e.askUser},...e.agent===void 0?{}:{agent:e.agent}}}function GD(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e!==``)}function KD(e){let t=e.split(`
|
|
4362
|
+
`).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!JD(e));if(n!==void 0)throw Error(`Allowed external paths must be absolute paths or start with ~: ${n}`);return t}function qD(e){let t=e.trim();if(t===``)return``;if(YD(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 JD(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)||e.startsWith(`/`)||e.startsWith(`\\`)||/^[A-Za-z]:[\\/]/u.test(e)}function YD(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function XD(e){return g`Gateway server fields edit this local gateway. File access and upload defaults edit ${e}.`}var Y=class extends v{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=RD(),this.machineDraft=zD(),this.gatewayLocalError=``,this.machineLocalError=``}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.gatewayDraft=BD(this.configResponse.config),this.gatewayLocalError=``),e.has(`machineConfigResponse`)&&this.machineConfigResponse!==void 0&&(this.machineDraft=VD(this.machineConfigResponse.config),this.machineLocalError=``)}render(){return g`
|
|
4346
4363
|
<settings-panel-frame
|
|
4347
4364
|
heading="General configuration"
|
|
4348
|
-
.description=${
|
|
4365
|
+
.description=${XD(this.targetLabel)}
|
|
4349
4366
|
actionLabel="Reload"
|
|
4350
4367
|
.actionDisabled=${this.loading||this.machineLoading}
|
|
4351
4368
|
.notices=${this.panelNotices()}
|
|
@@ -4374,7 +4391,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4374
4391
|
<span>Host</span>
|
|
4375
4392
|
${this.renderOverrideBadge(`host`)}
|
|
4376
4393
|
</span>
|
|
4377
|
-
<input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host
|
|
4394
|
+
<input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:$D(e)})}}>
|
|
4378
4395
|
<small>Address the web server should bind to. Leave empty to use PI WEB's default.</small>
|
|
4379
4396
|
</label>
|
|
4380
4397
|
|
|
@@ -4383,7 +4400,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4383
4400
|
<span>Port</span>
|
|
4384
4401
|
${this.renderOverrideBadge(`port`)}
|
|
4385
4402
|
</span>
|
|
4386
|
-
<input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port
|
|
4403
|
+
<input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:$D(e)})}}>
|
|
4387
4404
|
<small>TCP port from 1 to 65535. Leave empty to use PI WEB's default.</small>
|
|
4388
4405
|
</label>
|
|
4389
4406
|
|
|
@@ -4392,11 +4409,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4392
4409
|
<span>Allowed hosts</span>
|
|
4393
4410
|
${this.renderOverrideBadge(`allowedHosts`)}
|
|
4394
4411
|
</span>
|
|
4395
|
-
<select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode
|
|
4412
|
+
<select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:eO(e)===`all`?`all`:`list`})}}>
|
|
4396
4413
|
<option value="list">Only listed hosts</option>
|
|
4397
4414
|
<option value="all">Allow every host</option>
|
|
4398
4415
|
</select>
|
|
4399
|
-
<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:
|
|
4416
|
+
<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:tO(e)})}}></textarea>
|
|
4400
4417
|
<small>Enter one host per line, or choose “Allow every host” to write <code>true</code>.</small>
|
|
4401
4418
|
</div>
|
|
4402
4419
|
|
|
@@ -4426,7 +4443,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4426
4443
|
<span class="field-heading">
|
|
4427
4444
|
<span>External filesystem roots</span>
|
|
4428
4445
|
</span>
|
|
4429
|
-
<textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs /opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:
|
|
4446
|
+
<textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs /opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:tO(e)})}}></textarea>
|
|
4430
4447
|
<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>
|
|
4431
4448
|
</label>
|
|
4432
4449
|
|
|
@@ -4434,7 +4451,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4434
4451
|
<span class="field-heading">
|
|
4435
4452
|
<span>Default upload folder</span>
|
|
4436
4453
|
</span>
|
|
4437
|
-
<input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${vs} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder
|
|
4454
|
+
<input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${vs} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:$D(e)})}}>
|
|
4438
4455
|
<small>Workspace-relative folder for manual file uploads on ${this.targetLabel}. Leave empty to use PI WEB's default <code>${vs}</code>.</small>
|
|
4439
4456
|
</label>
|
|
4440
4457
|
|
|
@@ -4452,18 +4469,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4452
4469
|
<dl>
|
|
4453
4470
|
<div><dt>Host</dt><dd>${e.host??g`<span class="muted">127.0.0.1 default</span>`}</dd></div>
|
|
4454
4471
|
<div><dt>Port</dt><dd>${e.port??g`<span class="muted">8504 default</span>`}</dd></div>
|
|
4455
|
-
<div><dt>Allowed hosts</dt><dd>${
|
|
4472
|
+
<div><dt>Allowed hosts</dt><dd>${ZD(e.allowedHosts)}</dd></div>
|
|
4456
4473
|
</dl>
|
|
4457
4474
|
</section>
|
|
4458
4475
|
`}renderMachineEffectiveConfig(){let e=this.machineConfigResponse?.effectiveConfig??{};return g`
|
|
4459
4476
|
<section class="effective-card" aria-label="Effective selected machine file access and upload summary">
|
|
4460
4477
|
<h3>Effective selected-machine settings</h3>
|
|
4461
4478
|
<dl>
|
|
4462
|
-
<div><dt>External roots</dt><dd>${
|
|
4479
|
+
<div><dt>External roots</dt><dd>${QD(e.pathAccess?.allowedPaths)}</dd></div>
|
|
4463
4480
|
<div><dt>Upload folder</dt><dd>${e.uploads?.defaultFolder??g`<span class="muted">${`.pi-web/uploads`} default</span>`}</dd></div>
|
|
4464
4481
|
</dl>
|
|
4465
4482
|
</section>
|
|
4466
|
-
`}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(
|
|
4483
|
+
`}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(HD(this.gatewayDraft,this.configResponse?.config??{}))}catch(e){this.gatewayLocalError=nO(e)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError=``;try{await this.onSaveMachineConfig?.(UD(this.machineDraft))}catch(e){this.machineLocalError=nO(e)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=``}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=``}static{this.styles=h`
|
|
4467
4484
|
:host { display: block; }
|
|
4468
4485
|
.card-heading { display: grid; gap: 6px; min-width: 0; }
|
|
4469
4486
|
h3, p { margin: 0; }
|
|
@@ -4502,7 +4519,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4502
4519
|
@media (max-width: 760px) {
|
|
4503
4520
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
4504
4521
|
}
|
|
4505
|
-
`}};H([b({attribute:!1})],Y.prototype,`configResponse`,void 0),H([b({attribute:!1})],Y.prototype,`machineConfigResponse`,void 0),H([b({type:Boolean})],Y.prototype,`loading`,void 0),H([b({type:Boolean})],Y.prototype,`machineLoading`,void 0),H([b({type:Boolean})],Y.prototype,`saving`,void 0),H([b()],Y.prototype,`error`,void 0),H([b()],Y.prototype,`machineError`,void 0),H([b()],Y.prototype,`savedMessage`,void 0),H([b()],Y.prototype,`targetLabel`,void 0),H([b({attribute:!1})],Y.prototype,`onReload`,void 0),H([b({attribute:!1})],Y.prototype,`onReloadMachine`,void 0),H([b({attribute:!1})],Y.prototype,`onSave`,void 0),H([b({attribute:!1})],Y.prototype,`onSaveMachineConfig`,void 0),H([x()],Y.prototype,`gatewayDraft`,void 0),H([x()],Y.prototype,`machineDraft`,void 0),H([x()],Y.prototype,`gatewayLocalError`,void 0),H([x()],Y.prototype,`machineLocalError`,void 0),Y=H([y(`settings-general-panel`)],Y);function
|
|
4522
|
+
`}};H([b({attribute:!1})],Y.prototype,`configResponse`,void 0),H([b({attribute:!1})],Y.prototype,`machineConfigResponse`,void 0),H([b({type:Boolean})],Y.prototype,`loading`,void 0),H([b({type:Boolean})],Y.prototype,`machineLoading`,void 0),H([b({type:Boolean})],Y.prototype,`saving`,void 0),H([b()],Y.prototype,`error`,void 0),H([b()],Y.prototype,`machineError`,void 0),H([b()],Y.prototype,`savedMessage`,void 0),H([b()],Y.prototype,`targetLabel`,void 0),H([b({attribute:!1})],Y.prototype,`onReload`,void 0),H([b({attribute:!1})],Y.prototype,`onReloadMachine`,void 0),H([b({attribute:!1})],Y.prototype,`onSave`,void 0),H([b({attribute:!1})],Y.prototype,`onSaveMachineConfig`,void 0),H([x()],Y.prototype,`gatewayDraft`,void 0),H([x()],Y.prototype,`machineDraft`,void 0),H([x()],Y.prototype,`gatewayLocalError`,void 0),H([x()],Y.prototype,`machineLocalError`,void 0),Y=H([y(`settings-general-panel`)],Y);function ZD(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 QD(e){return e===void 0||e.length===0?g`<span class="muted">External paths denied</span>`:e.join(`, `)}function $D(e){return e.target instanceof HTMLInputElement?e.target.value:``}function eO(e){return e.target instanceof HTMLSelectElement?e.target.value:``}function tO(e){return e.target instanceof HTMLTextAreaElement?e.target.value:``}function nO(e){return e instanceof Error?e.message:String(e)}var rO=class extends v{constructor(...e){super(...e),this.loading=!1}render(){let e=this.report?.machines??[];return g`
|
|
4506
4523
|
<section class="fleet">
|
|
4507
4524
|
<header>
|
|
4508
4525
|
<div>
|
|
@@ -4584,7 +4601,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4584
4601
|
.machine { grid-template-columns: auto minmax(0, 1fr); }
|
|
4585
4602
|
.machine .row-actions { grid-row: auto; grid-column: 1 / -1; }
|
|
4586
4603
|
}
|
|
4587
|
-
`}};H([b({attribute:!1})],
|
|
4604
|
+
`}};H([b({attribute:!1})],rO.prototype,`report`,void 0),H([b({type:Boolean})],rO.prototype,`loading`,void 0),H([b({attribute:!1})],rO.prototype,`error`,void 0),H([b({attribute:!1})],rO.prototype,`onRefresh`,void 0),H([b({attribute:!1})],rO.prototype,`onRun`,void 0),H([x()],rO.prototype,`running`,void 0),H([x()],rO.prototype,`lastRun`,void 0),rO=H([y(`settings-fleet-section`)],rO);var iO=class extends v{constructor(...e){super(...e),this.machines=[],this.machineStatuses={},this.fleetLoading=!1,this.draftName=``}render(){return g`
|
|
4588
4605
|
<settings-panel-frame>
|
|
4589
4606
|
<div class="machines-heading">
|
|
4590
4607
|
<div>
|
|
@@ -4657,10 +4674,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4657
4674
|
.machine-grid { grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: var(--pi-space-3); }
|
|
4658
4675
|
.machine-card { min-height: 88px; padding: var(--pi-space-4); }
|
|
4659
4676
|
}
|
|
4660
|
-
`}};H([b({attribute:!1})],
|
|
4677
|
+
`}};H([b({attribute:!1})],iO.prototype,`machines`,void 0),H([b({attribute:!1})],iO.prototype,`machineStatuses`,void 0),H([b({attribute:!1})],iO.prototype,`onAdd`,void 0),H([b({attribute:!1})],iO.prototype,`onRename`,void 0),H([b({attribute:!1})],iO.prototype,`onRemove`,void 0),H([b({attribute:!1})],iO.prototype,`fleetReport`,void 0),H([b({type:Boolean})],iO.prototype,`fleetLoading`,void 0),H([b({attribute:!1})],iO.prototype,`fleetError`,void 0),H([b({attribute:!1})],iO.prototype,`onRefreshFleet`,void 0),H([b({attribute:!1})],iO.prototype,`onRunFleet`,void 0),H([x()],iO.prototype,`renamingId`,void 0),H([x()],iO.prototype,`draftName`,void 0),iO=H([y(`settings-machines-panel`)],iO);function aO(e){return{spawnSessions:e}}function oO(e){return{subsessions:e}}function sO(e){return{askUser:e}}function cO(e,t){return{...e,config:{...e.config,...t.config},effectiveConfig:{...e.effectiveConfig,...t.effectiveConfig},envOverrides:{...e.envOverrides,spawnSessions:t.envOverrides.spawnSessions,subsessions:t.envOverrides.subsessions,askUser:t.envOverrides.askUser}}}var lO=class extends v{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`}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.askUser===!0,o=e?.effectiveConfig.askUser===!0;return g`
|
|
4661
4678
|
<settings-panel-frame
|
|
4662
4679
|
heading="Session daemon"
|
|
4663
|
-
.description=${
|
|
4680
|
+
.description=${uO(this.targetLabel)}
|
|
4664
4681
|
actionLabel="Reload"
|
|
4665
4682
|
.actionDisabled=${this.loading}
|
|
4666
4683
|
.notices=${this.panelNotices()}
|
|
@@ -4730,7 +4747,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4730
4747
|
</section>
|
|
4731
4748
|
`}
|
|
4732
4749
|
</settings-panel-frame>
|
|
4733
|
-
`}panelNotices(){return
|
|
4750
|
+
`}panelNotices(){return dO({error:this.error,savedMessage:this.savedMessage})}renderUnavailableConfigState(){return g`<div class="loading-card">${this.loading?`Loading configuration…`:`Configuration is unavailable. Reload to try again.`}</div>`}async toggleSpawnSessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(aO(t))}async toggleSubsessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(oO(t))}async toggleAskUser(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(sO(t))}static{this.styles=h`
|
|
4734
4751
|
:host { display: block; }
|
|
4735
4752
|
h3 { margin: 0; font-size: 13px; line-height: 1.3; }
|
|
4736
4753
|
.loading-card, .config-path-card, .effective-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
|
|
@@ -4754,10 +4771,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4754
4771
|
@media (max-width: 760px) {
|
|
4755
4772
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
4756
4773
|
}
|
|
4757
|
-
`}};H([b({attribute:!1})],
|
|
4774
|
+
`}};H([b({attribute:!1})],lO.prototype,`configResponse`,void 0),H([b({type:Boolean})],lO.prototype,`loading`,void 0),H([b({type:Boolean})],lO.prototype,`saving`,void 0),H([b()],lO.prototype,`error`,void 0),H([b()],lO.prototype,`savedMessage`,void 0),H([b()],lO.prototype,`targetLabel`,void 0),H([b({attribute:!1})],lO.prototype,`onReload`,void 0),H([b({attribute:!1})],lO.prototype,`onSave`,void 0),lO=H([y(`settings-sessiond-panel`)],lO);function uO(e){return`Agent tool capabilities for sessions on ${e}. Changes are saved immediately but only take effect after the session daemon on that machine restarts.`}function dO(e){let t=[];return e.error!==``&&t.push({type:`error`,content:e.error}),e.savedMessage!==``&&t.push({type:`success`,content:e.savedMessage}),t}function fO(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function pO(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function mO(e){return e.kind===`local`}function hO(e){return e.trim()}function gO(e){if(hO(e)===``)return`Enter a Pi package source accepted by Pi, such as npm:@scope/package, a git/URL source, or a local path.`}function _O(e){return e.scope===`project`?`Project scope`:`User scope`}function vO(e){return e.filtered?`Filtered by current Pi package settings`:`Available in this PI WEB process`}function yO(e){return e.installedPath??`Installed path not reported by Pi`}function bO(e){return e.scope===`user`}function xO(e){if(!bO(e))return`Project-scope Pi packages are listed for visibility, but PI WEB only updates user-scope Pi packages safely from this view.`}function SO(e){return e.length>0&&e.every(bO)}function CO(e){if(e.length===0)return`No Pi packages are configured yet.`;if(!SO(e))return`Update all is disabled while project-scope Pi packages are listed; update user-scope packages individually.`}function wO(e,t,n){return e?.kind===t?n===void 0||e.source===n:!1}function TO(e,t=fO(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 WEB session`:`each idle PI WEB 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 WEB browser plugin changes`:`PI WEB browser plugin changes served by ${t.name}`}.`}function EO(e,t){let n=e.trim();return t.kind===`remote`?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}var DO=class extends v{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=pO(t),r=this.packagesResponse!==void 0;return g`
|
|
4758
4775
|
<settings-panel-frame
|
|
4759
4776
|
heading="Pi packages"
|
|
4760
|
-
.description=${
|
|
4777
|
+
.description=${OO(n)}
|
|
4761
4778
|
actionLabel="Reload"
|
|
4762
4779
|
actionTitle=${`Reload Pi packages from ${n}`}
|
|
4763
4780
|
.actionDisabled=${this.loading||this.isOperating}
|
|
@@ -4774,12 +4791,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4774
4791
|
<label for="package-source">Pi package source</label>
|
|
4775
4792
|
<div class="install-row">
|
|
4776
4793
|
<input id="package-source" .value=${this.installSource} ?disabled=${this.isOperating} placeholder="npm:@scope/package, git URL, or local path" @input=${e=>{this.updateInstallSource(e)}}>
|
|
4777
|
-
<button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${
|
|
4794
|
+
<button type="submit" title="Install this Pi package" ?disabled=${this.isOperating}>${wO(this.operation,`install`)?`Installing…`:`Install`}</button>
|
|
4778
4795
|
</div>
|
|
4779
4796
|
${this.validationMessage===``?null:g`<div class="field-error">${this.validationMessage}</div>`}
|
|
4780
4797
|
<small>Installs run on ${e} and use Pi's default package location, equivalent to <code>pi install <source></code>. PI WEB does not ask you to choose an install location.</small>
|
|
4781
4798
|
</form>
|
|
4782
|
-
`}renderPackageList(e,t){let n=
|
|
4799
|
+
`}renderPackageList(e,t){let n=pO(t),r=CO(e),i=r!==void 0&&e.length>0;return g`
|
|
4783
4800
|
<section class="package-section" aria-label="Configured Pi packages">
|
|
4784
4801
|
<div class="package-toolbar">
|
|
4785
4802
|
<div>
|
|
@@ -4787,7 +4804,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4787
4804
|
<p>This list comes from Pi's package manager settings on ${n}.</p>
|
|
4788
4805
|
</div>
|
|
4789
4806
|
<button class="secondary" title=${r??`Update all user-scope Pi packages`} ?disabled=${this.isOperating||r!==void 0} @click=${()=>{this.updatePackage()}}>
|
|
4790
|
-
${
|
|
4807
|
+
${wO(this.operation,`update-all`)?`Updating…`:`Update all`}
|
|
4791
4808
|
</button>
|
|
4792
4809
|
</div>
|
|
4793
4810
|
${i?g`<div class="action-note">${r}</div>`:null}
|
|
@@ -4798,12 +4815,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4798
4815
|
<div class="package-list">
|
|
4799
4816
|
${e.map(e=>this.renderPackage(e))}
|
|
4800
4817
|
</div>
|
|
4801
|
-
`}renderPackage(e){let t=
|
|
4818
|
+
`}renderPackage(e){let t=xO(e),n=wO(this.operation,`update`,e.source),r=wO(this.operation,`remove`,e.source);return g`
|
|
4802
4819
|
<article class=${`package-card${e.filtered?` filtered`:``}`}>
|
|
4803
4820
|
<div class="package-main">
|
|
4804
4821
|
<strong>${e.source}</strong>
|
|
4805
|
-
<small>${
|
|
4806
|
-
<small>Installed path: <code>${
|
|
4822
|
+
<small>${_O(e)} · ${vO(e)}</small>
|
|
4823
|
+
<small>Installed path: <code>${yO(e)}</code></small>
|
|
4807
4824
|
${t===void 0?null:g`<small class="action-note">${t}</small>`}
|
|
4808
4825
|
</div>
|
|
4809
4826
|
<div class="package-actions">
|
|
@@ -4811,7 +4828,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4811
4828
|
<button class="danger" title="Remove this Pi package" ?disabled=${this.isOperating} @click=${()=>{this.removePackage(e)}}>${r?`Removing…`:`Remove`}</button>
|
|
4812
4829
|
</div>
|
|
4813
4830
|
</article>
|
|
4814
|
-
`}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=
|
|
4831
|
+
`}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=gO(this.installSource);if(t!==void 0){this.validationMessage=t;return}let n=hO(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??fO(void 0)}get isOperating(){return this.operation!==void 0}static{this.styles=h`
|
|
4815
4832
|
:host { display: block; }
|
|
4816
4833
|
.package-toolbar { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
4817
4834
|
.package-toolbar > div, .package-main { display: grid; gap: 6px; min-width: 0; }
|
|
@@ -4846,10 +4863,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4846
4863
|
.package-actions { justify-self: start; flex-wrap: wrap; }
|
|
4847
4864
|
.package-main strong, .package-main small { white-space: normal; }
|
|
4848
4865
|
}
|
|
4849
|
-
`}};H([b({attribute:!1})],
|
|
4866
|
+
`}};H([b({attribute:!1})],DO.prototype,`packagesResponse`,void 0),H([b({type:Boolean})],DO.prototype,`loading`,void 0),H([b({attribute:!1})],DO.prototype,`operation`,void 0),H([b({attribute:!1})],DO.prototype,`targetMachine`,void 0),H([b()],DO.prototype,`error`,void 0),H([b()],DO.prototype,`operationMessage`,void 0),H([b({attribute:!1})],DO.prototype,`onReload`,void 0),H([b({attribute:!1})],DO.prototype,`onInstallPackage`,void 0),H([b({attribute:!1})],DO.prototype,`onRemovePackage`,void 0),H([b({attribute:!1})],DO.prototype,`onUpdatePackage`,void 0),H([x()],DO.prototype,`installSource`,void 0),H([x()],DO.prototype,`validationMessage`,void 0),DO=H([y(`settings-packages-panel`)],DO);function OO(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 WEB browser plugins.`}var kO=class extends v{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.recoveryCommandsSupported=!1,this.error=``,this.savedMessage=``,this.targetLabel=`local (local gateway)`}render(){let e=AO(this.pluginsResponse,this.configResponse),t=this.pluginsResponse!==void 0;return g`
|
|
4850
4867
|
<settings-panel-frame
|
|
4851
4868
|
heading="PI WEB plugins"
|
|
4852
|
-
.description=${
|
|
4869
|
+
.description=${PO(this.targetLabel)}
|
|
4853
4870
|
actionLabel="Reload"
|
|
4854
4871
|
actionTitle=${`Reload PI WEB plugins from ${this.targetLabel}`}
|
|
4855
4872
|
.actionDisabled=${this.loading}
|
|
@@ -4888,11 +4905,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4888
4905
|
</article>
|
|
4889
4906
|
`}renderPluginStatuses(e){let t=e.server;return g`
|
|
4890
4907
|
<div class="status-list" aria-label=${`${e.id} plugin states`}>
|
|
4891
|
-
${t===void 0?g`<span class="status neutral">${e.configOnly?`Configured only`:`Browser only`}</span>`:g`<span class=${`status ${
|
|
4908
|
+
${t===void 0?g`<span class="status neutral">${e.configOnly?`Configured only`:`Browser only`}</span>`:g`<span class=${`status ${MO(t.state)}`}>${jO(t.state)}</span>`}
|
|
4892
4909
|
${e.conflict?g`<span class="status error">Conflict</span>`:_}
|
|
4893
4910
|
${t?.staleRevision===!0?g`<span class="status warning">Stale revision</span>`:_}
|
|
4894
4911
|
${t?.restartRequired===!0?g`<span class="status warning">Restart required</span>`:_}
|
|
4895
|
-
${t?.health===void 0?_:g`<span class=${`status ${
|
|
4912
|
+
${t?.health===void 0?_:g`<span class=${`status ${NO(t.health.status)}`}>Health ${t.health.status}</span>`}
|
|
4896
4913
|
</div>
|
|
4897
4914
|
`}renderRecoveryCommands(){let e=this.pluginsResponse?.serverRuntime,t=(e?.status===`incompatible`&&!this.recoveryCommandsSupported?void 0:e?.recovery)??(this.recoveryCommandsSupported?nn:void 0);return t===void 0?_:g`
|
|
4898
4915
|
<aside class="recovery" aria-label="Offline server-plugin recovery commands">
|
|
@@ -4933,10 +4950,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4933
4950
|
.plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
4934
4951
|
.toggle { justify-self: start; }
|
|
4935
4952
|
}
|
|
4936
|
-
`}};H([b({attribute:!1})],
|
|
4953
|
+
`}};H([b({attribute:!1})],kO.prototype,`pluginsResponse`,void 0),H([b({attribute:!1})],kO.prototype,`configResponse`,void 0),H([b({type:Boolean})],kO.prototype,`loading`,void 0),H([b({type:Boolean})],kO.prototype,`saving`,void 0),H([b({type:Boolean})],kO.prototype,`recoveryCommandsSupported`,void 0),H([b()],kO.prototype,`error`,void 0),H([b()],kO.prototype,`savedMessage`,void 0),H([b()],kO.prototype,`targetLabel`,void 0),H([b({attribute:!1})],kO.prototype,`onReload`,void 0),H([b({attribute:!1})],kO.prototype,`onTogglePlugin`,void 0),kO=H([y(`settings-plugins-panel`)],kO);function AO(e,t){let n=t?.config.plugins??{},r=(e?.plugins??[]).map(e=>{let t=n[e.id],r=t?.enabled??e.enabled;return{...e,enabled:r,configOnly:!1,editable:e.discovered||t!==void 0}}),i=new Set(r.map(({id:e})=>e));for(let[e,t]of Object.entries(n))i.has(e)||r.push({id:e,source:`config`,scope:`local`,machineSpecific:!1,enabled:t.enabled!==!1,discovered:!1,conflict:!1,configOnly:!0,editable:!0});return r.sort((e,t)=>e.id.localeCompare(t.id))}function jO(e){switch(e){case`active`:return`Active`;case`failed`:return`Failed`;case`incompatible`:return`Incompatible`;case`disabled`:return`Disabled`;case`missing`:return`Not active`;case`unknown`:return`Active state unavailable`}}function MO(e){switch(e){case`active`:return`success`;case`disabled`:case`missing`:return`warning`;case`failed`:case`incompatible`:return`error`;case`unknown`:return`neutral`}}function NO(e){switch(e){case`healthy`:return`success`;case`degraded`:return`warning`;case`unhealthy`:return`error`}}function PO(e){return g`Compare desired plugin config with the active sessiond startup snapshot on <strong>${e}</strong>. This is separate from installing Pi packages.`}var FO={capture:!0},IO=[{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 LO(){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 RO=class extends v{constructor(...e){super(...e),this.actions=[],this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.drafts={},this.localError=``,this.promptEnterPreference=YT(),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=Jp(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&&!Yp(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=HO(this.actions),t=this.shortcutResolutions();return g`
|
|
4937
4954
|
<settings-panel-frame
|
|
4938
4955
|
heading="Keyboard shortcuts"
|
|
4939
|
-
.description=${
|
|
4956
|
+
.description=${LO()}
|
|
4940
4957
|
actionLabel="Reload"
|
|
4941
4958
|
.actionDisabled=${this.loading}
|
|
4942
4959
|
.notices=${this.panelNotices()}
|
|
@@ -4967,7 +4984,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4967
4984
|
<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>
|
|
4968
4985
|
</div>
|
|
4969
4986
|
<div class="prompt-enter-options" role="radiogroup" aria-label="Enter and Shift Enter behavior in the chat composer">
|
|
4970
|
-
${
|
|
4987
|
+
${IO.map(e=>g`
|
|
4971
4988
|
<label class="prompt-enter-option">
|
|
4972
4989
|
<input
|
|
4973
4990
|
type="radio"
|
|
@@ -4984,8 +5001,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4984
5001
|
`)}
|
|
4985
5002
|
</div>
|
|
4986
5003
|
</section>
|
|
4987
|
-
`}updatePromptEnterPreference(e){this.promptEnterPreference=e,
|
|
4988
|
-
<article class=${
|
|
5004
|
+
`}updatePromptEnterPreference(e){this.promptEnterPreference=e,XT(e)}renderShortcutRow(e,t){let n=this.configResponse?.config.shortcuts,r=Zp(e,n),i=KO(e,n),a=this.shortcutInputText(e),o=a.trim()===``?void 0:Gp(a),s=o?.ok===!0?o.shortcut:GO(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=VO(t);return g`
|
|
5005
|
+
<article class=${zO(t)}>
|
|
4989
5006
|
<div class="shortcut-main">
|
|
4990
5007
|
<strong>${e.title}</strong>
|
|
4991
5008
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
@@ -4995,8 +5012,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4995
5012
|
<div class="shortcut-editor">
|
|
4996
5013
|
<div class="shortcut-status">
|
|
4997
5014
|
${s!==void 0&&s!==``?g`<kbd>${qp(s)}</kbd>`:g`<span class="unassigned">${i===`disabled`?`Disabled`:`Unassigned`}</span>`}
|
|
4998
|
-
<small class=${u}>${
|
|
4999
|
-
${f===void 0?null:g`<small class=${
|
|
5015
|
+
<small class=${u}>${qO(u)}${l?` · Unsaved`:``}</small>
|
|
5016
|
+
${f===void 0?null:g`<small class=${BO(t)}>${f}</small>`}
|
|
5000
5017
|
</div>
|
|
5001
5018
|
<label class="shortcut-input-label">
|
|
5002
5019
|
<span>Shortcut</span>
|
|
@@ -5009,7 +5026,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5009
5026
|
autocapitalize="off"
|
|
5010
5027
|
spellcheck="false"
|
|
5011
5028
|
?disabled=${this.saving}
|
|
5012
|
-
@input=${t=>{this.updateDraft(e.id,
|
|
5029
|
+
@input=${t=>{this.updateDraft(e.id,JO(t))}}
|
|
5013
5030
|
>
|
|
5014
5031
|
</label>
|
|
5015
5032
|
${d===``?null:g`<small class="recording-hint">${d}</small>`}
|
|
@@ -5021,7 +5038,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5021
5038
|
</div>
|
|
5022
5039
|
</div>
|
|
5023
5040
|
</article>
|
|
5024
|
-
`}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=Zp(e,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: ${qp(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=Gp(this.shortcutInputText(e).trim());if(!t.ok){this.localError=t.message;return}this.localError=``,await this.saveShortcutPreference(e,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=
|
|
5041
|
+
`}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=Zp(e,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: ${qp(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=Gp(this.shortcutInputText(e).trim());if(!t.ok){this.localError=t.message;return}this.localError=``,await this.saveShortcutPreference(e,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=WO(n.shortcuts??{},[e.id,...e.shortcutAliases??[]]),i=t===void 0?r:{...r,[e.id]:t};Object.keys(i).length===0?delete n.shortcuts:n.shortcuts=i,await this.onSave?.(n)}shortcutResolutions(){return new Map(Wp(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=Gp(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()},Vp)}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,FO),!0)}removeRecordingListener(){this.recordingListenerActive&&=(window.removeEventListener(`keydown`,this.onRecordKeyDown,FO),!1)}static{this.styles=h`
|
|
5025
5042
|
:host { display: block; }
|
|
5026
5043
|
h3, p { margin: 0; }
|
|
5027
5044
|
h3 { font-size: 13px; line-height: 1.3; }
|
|
@@ -5077,7 +5094,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5077
5094
|
.shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
5078
5095
|
.shortcut-status, .shortcut-actions { justify-content: flex-start; }
|
|
5079
5096
|
}
|
|
5080
|
-
`}};H([b({attribute:!1})],
|
|
5097
|
+
`}};H([b({attribute:!1})],RO.prototype,`actions`,void 0),H([b({attribute:!1})],RO.prototype,`configResponse`,void 0),H([b({type:Boolean})],RO.prototype,`loading`,void 0),H([b({type:Boolean})],RO.prototype,`saving`,void 0),H([b()],RO.prototype,`error`,void 0),H([b()],RO.prototype,`savedMessage`,void 0),H([b({attribute:!1})],RO.prototype,`onReload`,void 0),H([b({attribute:!1})],RO.prototype,`onSave`,void 0),H([x()],RO.prototype,`drafts`,void 0),H([x()],RO.prototype,`localError`,void 0),H([x()],RO.prototype,`promptEnterPreference`,void 0),H([x()],RO.prototype,`recording`,void 0),RO=H([y(`settings-shortcuts-panel`)],RO);function zO(e){return e?.active===!1?`shortcut-row shadowed`:e?.active===!0&&e.shadows.length>0?`shortcut-row shadowing`:`shortcut-row`}function BO(e){return e?.active===!1?`conflict shadowed`:`conflict shadowing`}function VO(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 HO(e){let t=new Map;for(let n of[...e].sort(UO)){let e=n.group??`Other`;t.set(e,[...t.get(e)??[],n])}return[...t.entries()].map(([e,t])=>({name:e,actions:t}))}function UO(e,t){return(e.group??`Other`).localeCompare(t.group??`Other`)||e.title.localeCompare(t.title)}function WO(e,t){let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function GO(e,t){let n=Zp(e,t);if(n!==null)return n??e.shortcut}function KO(e,t){let n=Zp(e,t);return n===null?`disabled`:n===void 0?e.shortcut===void 0||e.shortcut===``?`unassigned`:`default`:`custom`}function qO(e){switch(e){case`default`:return`Default`;case`custom`:return`Custom`;case`disabled`:return`Disabled`;case`unassigned`:return`No default`}}function JO(e){return e.target instanceof HTMLInputElement?e.target.value:``}async function YO(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: ${ZO(t.reason)}`),n.status===`fulfilled`?r.plugins=n.value:i.push(`PI WEB plugins: ${ZO(n.reason)}`),i.length>0&&(r.error=`Failed to load settings: ${i.join(`; `)}`),r}async function XO(e,t){try{return{packagesResponse:await t(e.id),error:``}}catch(t){return{error:`Failed to load Pi packages from ${pO(e)}: ${EO(ZO(t),e)}`}}}function ZO(e){return e instanceof Error?e.message:String(e)}function QO(e,t){return{...e,config:$O(e.config,t.config),effectiveConfig:$O(e.effectiveConfig,t.effectiveConfig)}}function $O(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 ek(e){return e===void 0?{id:`local`,name:`local`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function tk(e){return e.kind===`local`?`${e.name} (local gateway)`:`${e.name} (remote machine)`}function nk(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?qt(t,kt.pluginLifecycle)?{state:`supported`}:{state:`unsupported`,message:ak(e)}:{state:`unknown`}}function rk(e){return`${e.state}:${e.message??``}`}function ik(e){return e?.state===`unsupported`}function ak(e){return`Plugin lifecycle diagnostics are not available on ${e.name}. Update and restart PI WEB on that machine before loading server-backed plugins.`}function ok(e,t){let n=e.trim();return t.kind===`remote`?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 sk(e,t,n){let r=e.plugins??{},i=r[t]??{};return{plugins:{...r,[t]:{...i,enabled:n}}}}function ck(e,t){return{...e,config:lk(e.config,t.config),effectiveConfig:lk(e.effectiveConfig,t.effectiveConfig)}}function lk(e,t){return t.plugins===void 0?e:{...e,plugins:t.plugins}}var X=class extends v{constructor(...e){super(...e),this.section=`general`,this.actions=[],this.machines=[],this.machineStatuses={},this.themes=[],this.followSystemTheme=!1,this.fleetLoading=!1,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`)&&ek(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.pluginLifecycleSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t))}render(){return g`
|
|
5081
5098
|
<modal-surface .onClose=${()=>this.onClose?.()} .label=${`PI WEB settings`}>
|
|
5082
5099
|
<header class="settings-header">
|
|
5083
5100
|
<div>
|
|
@@ -5130,7 +5147,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5130
5147
|
.saving=${this.saving}
|
|
5131
5148
|
.error=${this.sessiondError}
|
|
5132
5149
|
.savedMessage=${this.savedMessage}
|
|
5133
|
-
.targetLabel=${
|
|
5150
|
+
.targetLabel=${tk(this.settingsTarget())}
|
|
5134
5151
|
.onReload=${()=>this.reloadSessiondState()}
|
|
5135
5152
|
.onSave=${e=>this.saveSessiondConfig(e)}
|
|
5136
5153
|
></settings-sessiond-panel>
|
|
@@ -5167,7 +5184,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5167
5184
|
.recoveryCommandsSupported=${this.pluginLifecycleSupport().state===`supported`}
|
|
5168
5185
|
.error=${this.pluginError}
|
|
5169
5186
|
.savedMessage=${this.savedMessage}
|
|
5170
|
-
.targetLabel=${
|
|
5187
|
+
.targetLabel=${tk(this.settingsTarget())}
|
|
5171
5188
|
.onReload=${()=>this.loadPluginsForTarget()}
|
|
5172
5189
|
.onTogglePlugin=${(e,t)=>this.togglePlugin(e,t)}
|
|
5173
5190
|
></settings-plugins-panel>
|
|
@@ -5181,7 +5198,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5181
5198
|
.error=${this.error}
|
|
5182
5199
|
.machineError=${this.accessError}
|
|
5183
5200
|
.savedMessage=${this.savedMessage}
|
|
5184
|
-
.targetLabel=${
|
|
5201
|
+
.targetLabel=${tk(this.settingsTarget())}
|
|
5185
5202
|
.onReload=${()=>this.loadConfig()}
|
|
5186
5203
|
.onReloadMachine=${()=>this.loadAccessConfigForTarget()}
|
|
5187
5204
|
.onSave=${e=>this.saveConfig(e)}
|
|
@@ -5192,7 +5209,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5192
5209
|
<strong>${t}</strong>
|
|
5193
5210
|
<small>${n}</small>
|
|
5194
5211
|
</button>
|
|
5195
|
-
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await
|
|
5212
|
+
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await YO({loadConfig:()=>xo.config(),loadPlugins:()=>Co.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;this.accessLoading=!0,this.accessError=``;try{let n=await xo.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 ${tk(e)}: ${ok(uk(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;this.sessiondLoading=!0,this.sessiondError=``;try{let n=await xo.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 ${tk(e)}: ${ok(uk(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq;this.pluginLoading=!0,this.pluginError=``;try{let n=this.pluginLifecycleSupport(e);if(ik(n)){try{let r=await xo.config(e.id);if(!this.isCurrentPluginLoad(t,e))return;this.selectedPluginConfigResponse=r,this.selectedPluginsResponse=void 0,this.pluginError=n.message??`Plugin lifecycle diagnostics are not available on ${tk(e)}.`}catch(r){if(!this.isCurrentPluginLoad(t,e))return;this.pluginError=`Failed to load PI WEB plugin config from ${tk(e)}: ${ok(uk(r),e)}; ${n.message??`plugin lifecycle diagnostics are unsupported`}`}return}let[r,i]=await Promise.allSettled([xo.config(e.id),Co.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let a=[];r.status===`fulfilled`?this.selectedPluginConfigResponse=r.value:a.push(`config: ${ok(uk(r.reason),e)}`),i.status===`fulfilled`?this.selectedPluginsResponse=i.value:a.push(`PI WEB plugins: ${ok(uk(i.reason),e)}`),this.pluginError=a.length===0?``:`Failed to load PI WEB plugin settings from ${tk(e)}: ${a.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 XO(e,e=>Do.packages(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.pluginLifecycleSupport(n);if(this.selectedPluginConfigResponse===void 0){this.pluginError=`Plugin config is not loaded for ${tk(n)}. Reload before changing plugin enablement.`;return}let i=sk(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await xo.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=ck(this.configResponse,e),this.onConfigSaved?.(this.configResponse.effectiveConfig));let t;if(ik(r)?(this.selectedPluginsResponse=void 0,t=r.message??`Plugin lifecycle diagnostics are not available on ${tk(n)}.`):t=await this.refreshPluginsForTarget(n),!this.isCurrentSettingsTarget(n))return;t!==void 0&&(this.pluginError=t),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(n)&&(this.pluginError=`Failed to save PI WEB plugin config on ${tk(n)}: ${ok(uk(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await xo.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`Failed to save config: ${uk(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget();this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await xo.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=QO(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 ${tk(t)}: ${ok(uk(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget();this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await xo.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=cO(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`Failed to save session-daemon config on ${tk(t)}: ${ok(uk(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`install Pi package`,t,()=>Do.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`remove Pi package`,n,()=>Do.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,()=>Do.update(e,t.id))}async runPiPackageMutation(e,t,n,r){if(this.saving)throw Error(`A settings operation is already running.`);let i=++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(i,n))return;this.packagesResponse={packages:e.packages};let t=mO(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(i,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=TO(e.action,n)}catch(e){throw this.isCurrentPackageMutation(i,n)&&(this.packageError=`Failed to ${t} on ${pO(n)}: ${EO(uk(e),n)}`),e}finally{this.packageMutationSeq===i&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await Co.plugins();return}catch(e){return`Failed to refresh gateway PI WEB plugins: ${uk(e)}`}}async refreshPluginsForTarget(e){try{let t=await Co.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=void 0),`Config saved, but failed to refresh PI WEB plugins from ${tk(e)}: ${ok(uk(t),e)}`}}settingsTarget(){return ek(this.machine)}packageTarget(){return this.settingsTarget()}pluginLifecycleSupport(e=this.settingsTarget()){return nk(e,this.machineRuntime)}pluginLifecycleSupportNeedsReload(e,t){let n=nk(t,e),r=this.pluginLifecycleSupport(t);return rk(n)!==rk(r)}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)}static{this.styles=h`
|
|
5196
5213
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
5197
5214
|
modal-surface { --modal-surface-backdrop-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)); --modal-surface-width: min(980px, 100%); --modal-surface-max-height: min(760px, 100%); --modal-surface-min-height: min(620px, 100%); --modal-surface-radius: 14px; }
|
|
5198
5215
|
.settings-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--pi-border); }
|
|
@@ -5217,7 +5234,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5217
5234
|
.settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
|
|
5218
5235
|
.settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
|
|
5219
5236
|
}
|
|
5220
|
-
`}};H([b({attribute:!1})],X.prototype,`section`,void 0),H([b({attribute:!1})],X.prototype,`actions`,void 0),H([b({attribute:!1})],X.prototype,`machine`,void 0),H([b({attribute:!1})],X.prototype,`machineRuntime`,void 0),H([b({attribute:!1})],X.prototype,`machines`,void 0),H([b({attribute:!1})],X.prototype,`machineStatuses`,void 0),H([b({attribute:!1})],X.prototype,`onAddMachine`,void 0),H([b({attribute:!1})],X.prototype,`onRenameMachine`,void 0),H([b({attribute:!1})],X.prototype,`onRemoveMachine`,void 0),H([b({attribute:!1})],X.prototype,`themes`,void 0),H([b({attribute:!1})],X.prototype,`selectedThemeId`,void 0),H([b({attribute:!1})],X.prototype,`activeThemeId`,void 0),H([b({type:Boolean})],X.prototype,`followSystemTheme`,void 0),H([b({attribute:!1})],X.prototype,`onSelectTheme`,void 0),H([b({attribute:!1})],X.prototype,`onToggleFollowSystem`,void 0),H([b({attribute:!1})],X.prototype,`fleetReport`,void 0),H([b({type:Boolean})],X.prototype,`fleetLoading`,void 0),H([b({attribute:!1})],X.prototype,`fleetError`,void 0),H([b({attribute:!1})],X.prototype,`onRefreshFleet`,void 0),H([b({attribute:!1})],X.prototype,`onRunFleet`,void 0),H([b({attribute:!1})],X.prototype,`onNavigate`,void 0),H([b({attribute:!1})],X.prototype,`onClose`,void 0),H([b({attribute:!1})],X.prototype,`onConfigSaved`,void 0),H([b({attribute:!1})],X.prototype,`onRefreshMachineRuntime`,void 0),H([x()],X.prototype,`configResponse`,void 0),H([x()],X.prototype,`accessConfigResponse`,void 0),H([x()],X.prototype,`sessiondConfigResponse`,void 0),H([x()],X.prototype,`pluginsResponse`,void 0),H([x()],X.prototype,`selectedPluginConfigResponse`,void 0),H([x()],X.prototype,`selectedPluginsResponse`,void 0),H([x()],X.prototype,`packagesResponse`,void 0),H([x()],X.prototype,`loading`,void 0),H([x()],X.prototype,`accessLoading`,void 0),H([x()],X.prototype,`sessiondLoading`,void 0),H([x()],X.prototype,`pluginLoading`,void 0),H([x()],X.prototype,`packageLoading`,void 0),H([x()],X.prototype,`saving`,void 0),H([x()],X.prototype,`packageOperation`,void 0),H([x()],X.prototype,`error`,void 0),H([x()],X.prototype,`accessError`,void 0),H([x()],X.prototype,`sessiondError`,void 0),H([x()],X.prototype,`pluginError`,void 0),H([x()],X.prototype,`packageError`,void 0),H([x()],X.prototype,`savedMessage`,void 0),H([x()],X.prototype,`packageMessage`,void 0),X=H([y(`settings-dialog`)],X);function
|
|
5237
|
+
`}};H([b({attribute:!1})],X.prototype,`section`,void 0),H([b({attribute:!1})],X.prototype,`actions`,void 0),H([b({attribute:!1})],X.prototype,`machine`,void 0),H([b({attribute:!1})],X.prototype,`machineRuntime`,void 0),H([b({attribute:!1})],X.prototype,`machines`,void 0),H([b({attribute:!1})],X.prototype,`machineStatuses`,void 0),H([b({attribute:!1})],X.prototype,`onAddMachine`,void 0),H([b({attribute:!1})],X.prototype,`onRenameMachine`,void 0),H([b({attribute:!1})],X.prototype,`onRemoveMachine`,void 0),H([b({attribute:!1})],X.prototype,`themes`,void 0),H([b({attribute:!1})],X.prototype,`selectedThemeId`,void 0),H([b({attribute:!1})],X.prototype,`activeThemeId`,void 0),H([b({type:Boolean})],X.prototype,`followSystemTheme`,void 0),H([b({attribute:!1})],X.prototype,`onSelectTheme`,void 0),H([b({attribute:!1})],X.prototype,`onToggleFollowSystem`,void 0),H([b({attribute:!1})],X.prototype,`fleetReport`,void 0),H([b({type:Boolean})],X.prototype,`fleetLoading`,void 0),H([b({attribute:!1})],X.prototype,`fleetError`,void 0),H([b({attribute:!1})],X.prototype,`onRefreshFleet`,void 0),H([b({attribute:!1})],X.prototype,`onRunFleet`,void 0),H([b({attribute:!1})],X.prototype,`onNavigate`,void 0),H([b({attribute:!1})],X.prototype,`onClose`,void 0),H([b({attribute:!1})],X.prototype,`onConfigSaved`,void 0),H([b({attribute:!1})],X.prototype,`onRefreshMachineRuntime`,void 0),H([x()],X.prototype,`configResponse`,void 0),H([x()],X.prototype,`accessConfigResponse`,void 0),H([x()],X.prototype,`sessiondConfigResponse`,void 0),H([x()],X.prototype,`pluginsResponse`,void 0),H([x()],X.prototype,`selectedPluginConfigResponse`,void 0),H([x()],X.prototype,`selectedPluginsResponse`,void 0),H([x()],X.prototype,`packagesResponse`,void 0),H([x()],X.prototype,`loading`,void 0),H([x()],X.prototype,`accessLoading`,void 0),H([x()],X.prototype,`sessiondLoading`,void 0),H([x()],X.prototype,`pluginLoading`,void 0),H([x()],X.prototype,`packageLoading`,void 0),H([x()],X.prototype,`saving`,void 0),H([x()],X.prototype,`packageOperation`,void 0),H([x()],X.prototype,`error`,void 0),H([x()],X.prototype,`accessError`,void 0),H([x()],X.prototype,`sessiondError`,void 0),H([x()],X.prototype,`pluginError`,void 0),H([x()],X.prototype,`packageError`,void 0),H([x()],X.prototype,`savedMessage`,void 0),H([x()],X.prototype,`packageMessage`,void 0),X=H([y(`settings-dialog`)],X);function uk(e){return e instanceof Error?e.message:String(e)}var dk=class extends v{constructor(...e){super(...e),this.tool=`core:workspace.files`,this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>void 0,this.workspaceHeaderEdges=new VC(()=>{this.requestUpdate()}),this.onWorkspaceHeaderScroll=()=>{this.workspaceHeaderEdges.refresh()}}updated(){this.workspaceHeaderEdges.observe(this.workspaceHeaderStripElement())}disconnectedCallback(){this.workspaceHeaderEdges.dispose(),super.disconnectedCallback()}render(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:`Select a workspace`,body:`Choose a workspace to use its tools.`});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.find(e=>e.id===this.tool)??t[0];return g`
|
|
5221
5238
|
${this.hideToolTabs?null:g`
|
|
5222
5239
|
<header>
|
|
5223
5240
|
<div class=${this.workspaceHeaderFrameClass()}>
|
|
@@ -5247,12 +5264,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5247
5264
|
<h2>${e.title}</h2>
|
|
5248
5265
|
${e.body===void 0?null:g`<p>${e.body}</p>`}
|
|
5249
5266
|
</section>
|
|
5250
|
-
`}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${
|
|
5267
|
+
`}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${zC(this.workspaceHeaderEdges.edges)}`}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=rg}};H([b({attribute:!1})],dk.prototype,`workspace`,void 0),H([b({attribute:!1})],dk.prototype,`panelContext`,void 0),H([b({attribute:!1})],dk.prototype,`emptyState`,void 0),H([b()],dk.prototype,`tool`,void 0),H([b({attribute:!1})],dk.prototype,`panels`,void 0),H([b({type:Boolean})],dk.prototype,`hideToolTabs`,void 0),H([b({attribute:!1})],dk.prototype,`onSelectTool`,void 0),H([S(`.workspace-header-strip`)],dk.prototype,`workspaceHeaderStrip`,void 0),dk=H([y(`workspace-panel`)],dk);var Z=class extends v{constructor(...e){super(...e),this.machines=[],this.isWorking=!1,this.emphasizeSession=!1,this.renamingSession=!1,this.renameSeed=``,this.renameInputSeeded=!1,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();let e=this.renderRoot.querySelector(`.context-session-input`);e!==null&&!this.renameInputSeeded?(this.renameInputSeeded=!0,e.select()):e===null&&(this.renameInputSeeded=!1)}render(){return this.emphasizeSession&&this.session!==void 0?this.renderSessionLed():this.renderLocationTrail()}renderSessionLed(){let e=yk(this.workspace,this.project,this.machine,this.machines),t=xk(this.session);return g`
|
|
5251
5268
|
<nav class=${this.contextBarClass()} aria-label="Current session">
|
|
5252
5269
|
<button
|
|
5253
5270
|
type="button"
|
|
5254
5271
|
class="context-breadcrumb"
|
|
5255
|
-
title=${
|
|
5272
|
+
title=${bk(this.workspace,this.project)}
|
|
5256
5273
|
aria-label=${`Location: ${e}. Open navigation.`}
|
|
5257
5274
|
@click=${()=>{this.onOpenSection?.(this.breadcrumbSection())}}
|
|
5258
5275
|
>${e}</button>
|
|
@@ -5287,7 +5304,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5287
5304
|
</span>`:g`<button
|
|
5288
5305
|
type="button"
|
|
5289
5306
|
class="context-session-title"
|
|
5290
|
-
title=${
|
|
5307
|
+
title=${Sk(this.session)}
|
|
5291
5308
|
aria-label=${`Session: ${t}. Open session selection.`}
|
|
5292
5309
|
@click=${()=>{this.openSessions()}}
|
|
5293
5310
|
>${t}</button>`}
|
|
@@ -5306,33 +5323,33 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5306
5323
|
>✎</button>`}
|
|
5307
5324
|
${this.hasContextActions()?g`<div class="context-actions inline">${this.renderQuickSwitchButton()}${this.renderToolsButton()}${this.renderActionsButton()}${this.refreshControl}</div>`:null}
|
|
5308
5325
|
</nav>
|
|
5309
|
-
`}onRenameKeydown(e){if(e.key===`Escape`){e.preventDefault(),this.renamingSession=!1;return}e.key===`Enter`&&(e.preventDefault(),this.commitRename())}commitRename(){let e=(this.renderRoot.querySelector(`.context-session-input`)?.value??``).trim();this.renamingSession=!1,!(e===``||e===this.renameSeed||e===this.session?.name)&&this.onRenameSession?.(e)}breadcrumbSection(){return this.workspace===void 0?this.project===void 0&&
|
|
5326
|
+
`}onRenameKeydown(e){if(e.key===`Escape`){e.preventDefault(),this.renamingSession=!1;return}e.key===`Enter`&&(e.preventDefault(),this.commitRename())}commitRename(){let e=(this.renderRoot.querySelector(`.context-session-input`)?.value??``).trim();this.renamingSession=!1,!(e===``||e===this.renameSeed||e===this.session?.name)&&this.onRenameSession?.(e)}breadcrumbSection(){return this.workspace===void 0?this.project===void 0&&fk(this.machines)?`machines`:`projects`:`workspaces`}renderLocationTrail(){let e=fk(this.machines),t=pk(this.machine),n=hk(this.project),r=_k(this.workspace),i=xk(this.session),a=this.session!==void 0;return g`
|
|
5310
5327
|
<nav class=${this.contextBarClass()} aria-label="Current location">
|
|
5311
5328
|
<span class="context-bar-label">Location</span>
|
|
5312
5329
|
<ol class="context-items" @scroll=${this.onContextScroll}>
|
|
5313
5330
|
${e?g`
|
|
5314
5331
|
<li class="context-item">
|
|
5315
|
-
<button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${
|
|
5332
|
+
<button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${mk(this.machine)} aria-label=${`Machine: ${t}. Open machine selection.`} @click=${()=>{this.onOpenSection?.(`machines`)}}>
|
|
5316
5333
|
<span class="context-kind">Machine</span>
|
|
5317
5334
|
<span class="context-value">${t}</span>
|
|
5318
5335
|
</button>
|
|
5319
5336
|
</li>
|
|
5320
5337
|
`:null}
|
|
5321
5338
|
<li class="context-item">
|
|
5322
|
-
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${
|
|
5339
|
+
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${gk(this.project)} aria-label=${`Project: ${n}. Open project selection.`} @click=${()=>{this.onOpenSection?.(`projects`)}}>
|
|
5323
5340
|
<span class="context-kind">Project</span>
|
|
5324
5341
|
<span class="context-value">${n}</span>
|
|
5325
5342
|
</button>
|
|
5326
5343
|
</li>
|
|
5327
5344
|
<li class="context-item">
|
|
5328
|
-
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${
|
|
5345
|
+
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${vk(this.workspace)} aria-label=${`Workspace: ${r}. Open workspace selection.`} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
|
|
5329
5346
|
<span class="context-kind">Workspace</span>
|
|
5330
5347
|
<span class="context-value">${r}</span>
|
|
5331
5348
|
</button>
|
|
5332
5349
|
</li>
|
|
5333
5350
|
${a?g`
|
|
5334
5351
|
<li class="context-item">
|
|
5335
|
-
<button type="button" class="context-chip" title=${
|
|
5352
|
+
<button type="button" class="context-chip" title=${Sk(this.session)} aria-label=${`Session: ${i}. Open session selection.`} @click=${()=>{this.openSessions()}}>
|
|
5336
5353
|
<span class="context-kind">Session</span>
|
|
5337
5354
|
<span class="context-value session-value">${i}</span>
|
|
5338
5355
|
</button>
|
|
@@ -5467,7 +5484,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5467
5484
|
The row scrolls, so the extra width costs the others nothing. */
|
|
5468
5485
|
.context-value.session-value { max-width: min(70vw, 32ch); }
|
|
5469
5486
|
button { cursor: pointer; }
|
|
5470
|
-
`}};H([b({attribute:!1})],Z.prototype,`machines`,void 0),H([b({attribute:!1})],Z.prototype,`machine`,void 0),H([b({attribute:!1})],Z.prototype,`project`,void 0),H([b({attribute:!1})],Z.prototype,`workspace`,void 0),H([b({attribute:!1})],Z.prototype,`session`,void 0),H([b({attribute:!1})],Z.prototype,`refreshControl`,void 0),H([b({attribute:!1})],Z.prototype,`onOpenSection`,void 0),H([b({attribute:!1})],Z.prototype,`onShowActions`,void 0),H([b({attribute:!1})],Z.prototype,`onQuickSwitch`,void 0),H([b({attribute:!1})],Z.prototype,`onOpenTools`,void 0),H([b({attribute:!1})],Z.prototype,`onRenameSession`,void 0),H([b({type:Boolean})],Z.prototype,`isWorking`,void 0),H([b({type:Boolean})],Z.prototype,`emphasizeSession`,void 0),H([S(`.context-items`)],Z.prototype,`contextItems`,void 0),H([x()],Z.prototype,`renamingSession`,void 0),H([x()],Z.prototype,`renameSeed`,void 0),H([x()],Z.prototype,`canScrollLeft`,void 0),H([x()],Z.prototype,`canScrollRight`,void 0),Z=H([y(`app-context-bar`)],Z);function
|
|
5487
|
+
`}};H([b({attribute:!1})],Z.prototype,`machines`,void 0),H([b({attribute:!1})],Z.prototype,`machine`,void 0),H([b({attribute:!1})],Z.prototype,`project`,void 0),H([b({attribute:!1})],Z.prototype,`workspace`,void 0),H([b({attribute:!1})],Z.prototype,`session`,void 0),H([b({attribute:!1})],Z.prototype,`refreshControl`,void 0),H([b({attribute:!1})],Z.prototype,`onOpenSection`,void 0),H([b({attribute:!1})],Z.prototype,`onShowActions`,void 0),H([b({attribute:!1})],Z.prototype,`onQuickSwitch`,void 0),H([b({attribute:!1})],Z.prototype,`onOpenTools`,void 0),H([b({attribute:!1})],Z.prototype,`onRenameSession`,void 0),H([b({type:Boolean})],Z.prototype,`isWorking`,void 0),H([b({type:Boolean})],Z.prototype,`emphasizeSession`,void 0),H([S(`.context-items`)],Z.prototype,`contextItems`,void 0),H([x()],Z.prototype,`renamingSession`,void 0),H([x()],Z.prototype,`renameSeed`,void 0),H([x()],Z.prototype,`canScrollLeft`,void 0),H([x()],Z.prototype,`canScrollRight`,void 0),Z=H([y(`app-context-bar`)],Z);function fk(e){return e.length>0}function pk(e){return e===void 0?`No machine`:`${e.name}${e.kind===`remote`?` · remote`:``}`}function mk(e){return e===void 0?`No machine selected`:e.baseUrl??e.name}function hk(e){return e?.name??`No project`}function gk(e){return e===void 0?`No project selected`:`${e.name} — ${e.path}`}function _k(e){return e===void 0?`No workspace`:`${e.label}${e.isMain?` · main`:``}`}function vk(e){return e===void 0?`No workspace selected`:`${e.label}${e.isMain?` · main`:``} — ${e.path}`}function yk(e,t,n,r){let i=fk(r)&&n!==void 0?`${n.name} / `:``;return e===void 0?t===void 0?i===``?`No workspace`:i.replace(/ \/ $/u,``):`${i}${t.name}`:`${i}${e.isMain&&t!==void 0?t.name:e.label}`}function bk(e,t){return e===void 0?t===void 0?`No workspace selected`:t.path:e.path}function xk(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`:zx(e.id)}function Sk(e){return e===void 0?`No session selected`:e.path}var Ck=class extends v{constructor(...e){super(...e),this.tabs=[]}render(){return g`
|
|
5471
5488
|
<modal-surface .onClose=${()=>this.onClose?.()} .label=${`Views`} .initialFocus=${`button`}>
|
|
5472
5489
|
<header><h2>Go to</h2></header>
|
|
5473
5490
|
<div class="body">
|
|
@@ -5506,7 +5523,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5506
5523
|
.tool-badge { min-width: 20px; border-radius: var(--pi-radius-pill); background: var(--pi-surface-hover); color: var(--pi-text-secondary); padding: 1px var(--pi-space-4); font-size: var(--pi-text-xs); text-align: center; }
|
|
5507
5524
|
.tool-badge.unread { background: var(--pi-selection-bg); color: var(--pi-accent); }
|
|
5508
5525
|
.tool-check { color: var(--pi-accent); }
|
|
5509
|
-
`}};H([b({attribute:!1})],
|
|
5526
|
+
`}};H([b({attribute:!1})],Ck.prototype,`tabs`,void 0),H([b({attribute:!1})],Ck.prototype,`selectedView`,void 0),H([b({attribute:!1})],Ck.prototype,`onSelect`,void 0),H([b({attribute:!1})],Ck.prototype,`onClose`,void 0),Ck=H([y(`app-mobile-tool-sheet`)],Ck);var wk=`PI WEB`;function Tk(e){let t=e?.label.trim();if(!(t===void 0||t===``))return t.split(`/`).filter(e=>e!==``).pop()??t}function Ek(e){if(e.mainView===`chat`&&e.selectedSession!==void 0){let t=Bx(e.selectedSession).trim();if(t!==``)return t}let t=Tk(e.selectedWorkspace);if(t!==void 0)return t;let n=e.selectedProject?.name.trim();if(n!==void 0&&n!==``)return n;let r=e.selectedMachine;if(r!==void 0&&r.kind!==`local`){let e=r.name.trim();if(e!==``)return e}return wk}function Dk(e,t=40){let n=Ek(e);return n.length<=t?n:`${n.slice(0,t-1).trimEnd()}…`}var Ok=class extends v{constructor(...e){super(...e),this.machines=[]}render(){return g`
|
|
5510
5527
|
<nav aria-label="Current context">
|
|
5511
5528
|
${this.machines.length>0?this.renderStep(`machines`,`Machine`,this.selectedMachine?.name,this.onAddMachine,`Add machine`):_}
|
|
5512
5529
|
${this.renderStep(`projects`,`Project`,this.selectedProject?.name,this.onAddProject,`Add project`)}
|
|
@@ -5558,12 +5575,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5558
5575
|
.step.open .add { border-left-color: color-mix(in srgb, var(--pi-accent) 40%, var(--pi-border)); }
|
|
5559
5576
|
@media (pointer: coarse) { .add { width: 40px; } }
|
|
5560
5577
|
.add:hover { color: var(--pi-text); }
|
|
5561
|
-
`}};H([b({attribute:!1})],
|
|
5578
|
+
`}};H([b({attribute:!1})],Ok.prototype,`machines`,void 0),H([b({attribute:!1})],Ok.prototype,`selectedMachine`,void 0),H([b({attribute:!1})],Ok.prototype,`selectedProject`,void 0),H([b({attribute:!1})],Ok.prototype,`selectedWorkspace`,void 0),H([b({attribute:!1})],Ok.prototype,`openSection`,void 0),H([b({attribute:!1})],Ok.prototype,`onOpenSection`,void 0),H([b({attribute:!1})],Ok.prototype,`onAddMachine`,void 0),H([b({attribute:!1})],Ok.prototype,`onAddProject`,void 0),Ok=H([y(`app-context-switcher`)],Ok);var kk=class extends v{constructor(...e){super(...e),this.machines=[],this.statuses={},this.statusSnapshots={},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=Ak(e,this.statuses),n=e.name;return g`
|
|
5562
5579
|
<div class="machine-switcher">
|
|
5563
5580
|
<button
|
|
5564
5581
|
type="button"
|
|
5565
5582
|
class="machine-switcher-button"
|
|
5566
|
-
title=${
|
|
5583
|
+
title=${Mk(e)}
|
|
5567
5584
|
aria-label=${this.machineSwitcherAriaLabel(e)}
|
|
5568
5585
|
aria-expanded=${String(this.open)}
|
|
5569
5586
|
@click=${e=>{this.toggleMenu(e.currentTarget)}}
|
|
@@ -5574,7 +5591,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5574
5591
|
<span class="machine-switcher-kicker">Machine</span>
|
|
5575
5592
|
<span class="machine-switcher-label">${n}</span>
|
|
5576
5593
|
</span>
|
|
5577
|
-
<span class=${`machine-status ${t}`}>${
|
|
5594
|
+
<span class=${`machine-status ${t}`}>${jk(t)}</span>
|
|
5578
5595
|
<span class="machine-chevron" aria-hidden="true">▾</span>
|
|
5579
5596
|
</button>
|
|
5580
5597
|
${this.open?g`
|
|
@@ -5583,17 +5600,17 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5583
5600
|
</div>
|
|
5584
5601
|
`:null}
|
|
5585
5602
|
</div>
|
|
5586
|
-
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=
|
|
5603
|
+
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=Ak(e,this.statuses),r=yx(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return g`
|
|
5587
5604
|
<div class=${`machine-option ${t?`selected`:``} ${r?``:`no-actions`}`}>
|
|
5588
5605
|
<button
|
|
5589
5606
|
type="button"
|
|
5590
5607
|
class="machine-option-main"
|
|
5591
|
-
title=${
|
|
5608
|
+
title=${Mk(e)}
|
|
5592
5609
|
data-machine-id=${e.id}
|
|
5593
5610
|
@click=${()=>{this.select(e)}}
|
|
5594
5611
|
@keydown=${e=>{this.handleMachineOptionKeydown(e)}}
|
|
5595
5612
|
>
|
|
5596
|
-
<span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span><span class=${`machine-option-status ${n}`}><span class="dot" aria-hidden="true"></span>${
|
|
5613
|
+
<span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span><span class=${`machine-option-status ${n}`}><span class="dot" aria-hidden="true"></span>${jk(n)}</span></span>
|
|
5597
5614
|
<small>${e.kind===`local`?`Local Pi Web`:e.baseUrl??`Remote Pi Web`}</small>
|
|
5598
5615
|
</button>
|
|
5599
5616
|
${r?g`
|
|
@@ -5614,7 +5631,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5614
5631
|
</div>
|
|
5615
5632
|
`:null}
|
|
5616
5633
|
</div>
|
|
5617
|
-
`}renderActivity(e){let t=this.statusSnapshots[e.id]?.machine,n=
|
|
5634
|
+
`}renderActivity(e){let t=this.statusSnapshots[e.id]?.machine,n=Ak(e,this.statuses),r=n===`offline`||n===`error`?void 0:nx(t),i=rx(t)?`Unread sessions on this machine`:void 0;return tx(r,r===`terminal`?`Machine terminal active`:`Machine active`,i)}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=Nk(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=Nk(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=Zb(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`
|
|
5618
5635
|
:host { min-width: 0; display: block; }
|
|
5619
5636
|
/* A display rule on :host outranks the HTML hidden attribute, so an element
|
|
5620
5637
|
rendered with the hidden attribute stays on screen unless this says so.
|
|
@@ -5666,7 +5683,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5666
5683
|
.machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
|
|
5667
5684
|
.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); }
|
|
5668
5685
|
@keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
|
|
5669
|
-
`}};H([b({attribute:!1})],
|
|
5686
|
+
`}};H([b({attribute:!1})],kk.prototype,`machines`,void 0),H([b({attribute:!1})],kk.prototype,`selected`,void 0),H([b({attribute:!1})],kk.prototype,`statuses`,void 0),H([b({attribute:!1})],kk.prototype,`statusSnapshots`,void 0),H([b({attribute:!1})],kk.prototype,`onSelect`,void 0),H([b({attribute:!1})],kk.prototype,`onRemove`,void 0),H([b({attribute:!1})],kk.prototype,`onFocusNextSection`,void 0),H([b({attribute:!1})],kk.prototype,`onCancelKeyboardNavigation`,void 0),H([x()],kk.prototype,`open`,void 0),H([x()],kk.prototype,`menuStyle`,void 0),H([x()],kk.prototype,`openActionsMachineId`,void 0),H([x()],kk.prototype,`actionMenuStyle`,void 0),kk=H([y(`machine-switcher`)],kk);function Ak(e,t){return t[e.id]?.status??e.status??`unknown`}function jk(e){return e===`online`?`online`:e===`offline`?`offline`:e===`error`?`error`:`unknown`}function Mk(e){return e.baseUrl??e.name}function Nk(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: ${Pk(t.bottom)};`,`left: ${Pk(r)};`,`width: ${Pk(n)};`,`max-height: ${Pk(i)};`].join(` `)}function Pk(e){return`${String(Math.round(e))}px`}var Q=class extends v{constructor(...e){super(...e),this.machines=[],this.machineStatuses={},this.machineStatusSnapshots={},this.projects=[],this.workspaces=[],this.sessions=[],this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.unreadSessionIds=new Set,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.goals=[],this.goalsLoading=!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)}}headerName(){return Ek({mainView:this.selectedSession===void 0?`navigation`:`chat`,selectedMachine:this.selectedMachine,selectedProject:this.selectedProject,selectedWorkspace:this.selectedWorkspace,selectedSession:this.selectedSession})}render(){if(this.compact)return this.renderCompact();let e=this.compactVisibleSection();return g`
|
|
5670
5687
|
<header>
|
|
5671
5688
|
<strong title=${this.headerName()}>${this.headerName()}</strong>
|
|
5672
5689
|
<div class="header-actions">
|
|
@@ -5692,7 +5709,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5692
5709
|
${e===`sessions`?this.renderGoalPanel():null}
|
|
5693
5710
|
`}renderCompact(){return g`
|
|
5694
5711
|
<div class="compact-shell">
|
|
5695
|
-
${
|
|
5712
|
+
${Fk(this.machines)?g`
|
|
5696
5713
|
<machine-switcher
|
|
5697
5714
|
hidden
|
|
5698
5715
|
.machines=${this.machines}
|
|
@@ -5724,7 +5741,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5724
5741
|
${this.renderWorkspaceList(!1,e!==`workspaces`)}
|
|
5725
5742
|
${this.renderSessionList(!1,e!==`sessions`)}
|
|
5726
5743
|
${e===`sessions`?this.renderGoalPanel():null}
|
|
5727
|
-
`}openSection(e){e===`machines`?this.onToggleMachines?.():e===`projects`?this.onToggleProjects?.():e===`workspaces`?this.onToggleWorkspaces?.():this.onToggleSessions?.()}compactVisibleSection(){return
|
|
5744
|
+
`}openSection(e){e===`machines`?this.onToggleMachines?.():e===`projects`?this.onToggleProjects?.():e===`workspaces`?this.onToggleWorkspaces?.():this.onToggleSessions?.()}compactVisibleSection(){return Fk(this.machines)&&!this.machinesCollapsed?`machines`:this.projectsCollapsed?this.workspacesCollapsed?!this.sessionsCollapsed||this.selectedWorkspace!==void 0?`sessions`:this.selectedProject===void 0?`projects`:`workspaces`:`workspaces`:`projects`}renderMachineList(e,t=!1){return Fk(this.machines)?g`
|
|
5728
5745
|
<machine-list
|
|
5729
5746
|
?hidden=${t}
|
|
5730
5747
|
.machines=${this.machines}
|
|
@@ -5823,7 +5840,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5823
5840
|
.onFocusNextSection=${()=>{this.focusNextFrom(`sessions`)}}
|
|
5824
5841
|
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
5825
5842
|
></session-list>
|
|
5826
|
-
`}selectedMachineStatusSnapshot(){return this.machineStatusSnapshots[L({selectedMachine:this.selectedMachine})]}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}runMaybeAsync(e){e?.()instanceof Promise}focusPreviousFrom(e){let t=
|
|
5843
|
+
`}selectedMachineStatusSnapshot(){return this.machineStatusSnapshots[L({selectedMachine:this.selectedMachine})]}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}runMaybeAsync(e){e?.()instanceof Promise}focusPreviousFrom(e){let t=Ik(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(Lk(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
|
|
5827
5844
|
/* Shell styles do not cross a shadow boundary, so the tap-highlight
|
|
5828
5845
|
suppression is repeated for components that define their own. */
|
|
5829
5846
|
button, [role="button"], a, summary, label, input { -webkit-tap-highlight-color: transparent; }
|
|
@@ -5854,7 +5871,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5854
5871
|
task list cannot push the sessions it belongs to off-screen. */
|
|
5855
5872
|
goal-panel { flex: 0 1 auto; min-height: 0; max-height: var(--pi-nav-goals-max-height, 26vh); overflow: auto; border-top: 1px solid var(--pi-border-muted); }
|
|
5856
5873
|
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
5857
|
-
`}};H([b({attribute:!1})],Q.prototype,`machines`,void 0),H([b({attribute:!1})],Q.prototype,`selectedMachine`,void 0),H([b({attribute:!1})],Q.prototype,`machineStatuses`,void 0),H([b({attribute:!1})],Q.prototype,`machineStatusSnapshots`,void 0),H([b({attribute:!1})],Q.prototype,`projects`,void 0),H([b({attribute:!1})],Q.prototype,`selectedProject`,void 0),H([b({attribute:!1})],Q.prototype,`workspaces`,void 0),H([b({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),H([b({attribute:!1})],Q.prototype,`sessions`,void 0),H([b({attribute:!1})],Q.prototype,`selectedSession`,void 0),H([b({attribute:!1})],Q.prototype,`sessionActivities`,void 0),H([b({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),H([b({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),H([b({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),H([b({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),H([b({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),H([b({attribute:!1})],Q.prototype,`refreshControl`,void 0),H([b({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),H([b({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),H([b({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),H([b({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),H([b({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),H([b({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),H([b({type:Number})],Q.prototype,`startingSessionCount`,void 0),H([b({type:Boolean})],Q.prototype,`canStartSession`,void 0),H([b({attribute:!1})],Q.prototype,`onShowActions`,void 0),H([b({attribute:!1})],Q.prototype,`onOpenSettings`,void 0),H([b({attribute:!1})],Q.prototype,`onAddMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onOpenSessionTree`,void 0),H([b({attribute:!1})],Q.prototype,`onRefreshMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onRenameMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onOpenMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onQuickSwitch`,void 0),H([b({attribute:!1})],Q.prototype,`onAddProject`,void 0),H([b({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),H([b({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),H([b({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),H([b({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),H([b({attribute:!1})],Q.prototype,`onSelectProject`,void 0),H([b({attribute:!1})],Q.prototype,`onCloseProject`,void 0),H([b({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),H([b({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),H([b({attribute:!1})],Q.prototype,`onStartSession`,void 0),H([b({attribute:!1})],Q.prototype,`onSelectSession`,void 0),H([b({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),H([b({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),H([b({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),H([b({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),H([b({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),H([b({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),H([b({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),H([b({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),H([b({attribute:!1})],Q.prototype,`onRenameSession`,void 0),H([b({attribute:!1})],Q.prototype,`goals`,void 0),H([b({type:Boolean})],Q.prototype,`goalsLoading`,void 0),H([b({attribute:!1})],Q.prototype,`onRefreshGoals`,void 0),H([b({attribute:!1})],Q.prototype,`onArchiveGoal`,void 0),H([b({attribute:!1})],Q.prototype,`onRunGoalCommand`,void 0),H([b({attribute:!1})],Q.prototype,`onMarkSessionRead`,void 0),H([b({attribute:!1})],Q.prototype,`onMarkSessionsRead`,void 0),H([b({attribute:!1})],Q.prototype,`onReloadSession`,void 0),H([b({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),H([b({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),H([b({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),H([b({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),H([S(`machine-list`)],Q.prototype,`machineList`,void 0),H([S(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),H([S(`project-list`)],Q.prototype,`projectList`,void 0),H([S(`workspace-list`)],Q.prototype,`workspaceList`,void 0),H([S(`session-list`)],Q.prototype,`sessionList`,void 0),Q=H([y(`app-navigation-panel`)],Q);function
|
|
5874
|
+
`}};H([b({attribute:!1})],Q.prototype,`machines`,void 0),H([b({attribute:!1})],Q.prototype,`selectedMachine`,void 0),H([b({attribute:!1})],Q.prototype,`machineStatuses`,void 0),H([b({attribute:!1})],Q.prototype,`machineStatusSnapshots`,void 0),H([b({attribute:!1})],Q.prototype,`projects`,void 0),H([b({attribute:!1})],Q.prototype,`selectedProject`,void 0),H([b({attribute:!1})],Q.prototype,`workspaces`,void 0),H([b({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),H([b({attribute:!1})],Q.prototype,`sessions`,void 0),H([b({attribute:!1})],Q.prototype,`selectedSession`,void 0),H([b({attribute:!1})],Q.prototype,`sessionActivities`,void 0),H([b({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),H([b({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),H([b({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),H([b({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),H([b({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),H([b({attribute:!1})],Q.prototype,`refreshControl`,void 0),H([b({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),H([b({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),H([b({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),H([b({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),H([b({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),H([b({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),H([b({type:Number})],Q.prototype,`startingSessionCount`,void 0),H([b({type:Boolean})],Q.prototype,`canStartSession`,void 0),H([b({attribute:!1})],Q.prototype,`onShowActions`,void 0),H([b({attribute:!1})],Q.prototype,`onOpenSettings`,void 0),H([b({attribute:!1})],Q.prototype,`onAddMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onOpenSessionTree`,void 0),H([b({attribute:!1})],Q.prototype,`onRefreshMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onRenameMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onOpenMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onQuickSwitch`,void 0),H([b({attribute:!1})],Q.prototype,`onAddProject`,void 0),H([b({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),H([b({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),H([b({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),H([b({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),H([b({attribute:!1})],Q.prototype,`onSelectProject`,void 0),H([b({attribute:!1})],Q.prototype,`onCloseProject`,void 0),H([b({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),H([b({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),H([b({attribute:!1})],Q.prototype,`onStartSession`,void 0),H([b({attribute:!1})],Q.prototype,`onSelectSession`,void 0),H([b({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),H([b({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),H([b({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),H([b({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),H([b({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),H([b({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),H([b({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),H([b({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),H([b({attribute:!1})],Q.prototype,`onRenameSession`,void 0),H([b({attribute:!1})],Q.prototype,`goals`,void 0),H([b({type:Boolean})],Q.prototype,`goalsLoading`,void 0),H([b({attribute:!1})],Q.prototype,`onRefreshGoals`,void 0),H([b({attribute:!1})],Q.prototype,`onArchiveGoal`,void 0),H([b({attribute:!1})],Q.prototype,`onRunGoalCommand`,void 0),H([b({attribute:!1})],Q.prototype,`onMarkSessionRead`,void 0),H([b({attribute:!1})],Q.prototype,`onMarkSessionsRead`,void 0),H([b({attribute:!1})],Q.prototype,`onReloadSession`,void 0),H([b({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),H([b({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),H([b({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),H([b({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),H([b({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),H([S(`machine-list`)],Q.prototype,`machineList`,void 0),H([S(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),H([S(`project-list`)],Q.prototype,`projectList`,void 0),H([S(`workspace-list`)],Q.prototype,`workspaceList`,void 0),H([S(`session-list`)],Q.prototype,`sessionList`,void 0),Q=H([y(`app-navigation-panel`)],Q);function Fk(e){return e.length>0}function Ik(e,t){let n=Rk(t);return n[n.indexOf(e)-1]}function Lk(e,t){let n=Rk(t);return n[n.indexOf(e)+1]??`chat`}function Rk(e){return eb.filter(t=>t!==`machines`||Fk(e))}var zk=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),Bk=420,Vk=4,Hk=class extends v{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`
|
|
5858
5875
|
${this.renderResizeHandle()}
|
|
5859
5876
|
<button
|
|
5860
5877
|
type="button"
|
|
@@ -5884,7 +5901,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5884
5901
|
@dblclick=${e=>{this.onResizeDoubleClick(e)}}
|
|
5885
5902
|
@keydown=${e=>{this.onResizeKeyDown(e)}}
|
|
5886
5903
|
></div>
|
|
5887
|
-
`}resizeAriaValueNow(){return this.panelWidth===void 0?_: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)<=
|
|
5904
|
+
`}resizeAriaValueNow(){return this.panelWidth===void 0?_: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)<=Vk)&&(t.moved=!0,this.commitPanelWidth(gb(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||!zk.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=_b(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<=Bk){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 vb(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(vb(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=mb(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=h`
|
|
5888
5905
|
: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; }
|
|
5889
5906
|
:host([side="navigation"]) { grid-column: 2; }
|
|
5890
5907
|
:host([side="workspace"]) { grid-column: 4; }
|
|
@@ -5911,7 +5928,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5911
5928
|
@media (max-width: 760px) {
|
|
5912
5929
|
:host([side="navigation"]) { display: none; }
|
|
5913
5930
|
}
|
|
5914
|
-
`}};H([b({reflect:!0})],
|
|
5931
|
+
`}};H([b({reflect:!0})],Hk.prototype,`side`,void 0),H([b({type:Boolean,reflect:!0})],Hk.prototype,`collapsed`,void 0),H([b({type:Boolean})],Hk.prototype,`resizable`,void 0),H([b({type:Number})],Hk.prototype,`panelWidth`,void 0),H([b({type:Number})],Hk.prototype,`minWidth`,void 0),H([b({type:Number})],Hk.prototype,`maxWidth`,void 0),H([b()],Hk.prototype,`controls`,void 0),H([b()],Hk.prototype,`resizeLabel`,void 0),H([b()],Hk.prototype,`expandLabel`,void 0),H([b()],Hk.prototype,`collapseLabel`,void 0),H([b({attribute:!1})],Hk.prototype,`onToggle`,void 0),H([b({attribute:!1})],Hk.prototype,`onResizeStart`,void 0),H([b({attribute:!1})],Hk.prototype,`onResize`,void 0),H([b({attribute:!1})],Hk.prototype,`onResizeEnd`,void 0),H([b({attribute:!1})],Hk.prototype,`onReset`,void 0),Hk=H([y(`app-panel-edge-control`)],Hk);var Uk=class extends v{constructor(...e){super(...e),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){let e=`Full page reload`;return g`
|
|
5915
5932
|
<button
|
|
5916
5933
|
class="app-refresh-button"
|
|
5917
5934
|
title=${e}
|
|
@@ -5930,12 +5947,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5930
5947
|
:host, :host * { -webkit-user-select: none; user-select: none; }
|
|
5931
5948
|
.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; }
|
|
5932
5949
|
.app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
5933
|
-
`}};H([b({attribute:!1})],
|
|
5950
|
+
`}};H([b({attribute:!1})],Uk.prototype,`onReload`,void 0),Uk=H([y(`app-refresh-control`)],Uk);var Wk=`pi-web.pinnedSessions`;function Gk(e=Jk()){if(e===void 0)return new Set;try{let t=e.getItem(Wk);if(t===null||t===``)return new Set;let n=JSON.parse(t);return Array.isArray(n)?new Set(n.filter(e=>typeof e==`string`)):new Set}catch{return new Set}}function Kk(e,t=Jk()){if(t!==void 0)try{t.setItem(Wk,JSON.stringify([...e]))}catch{}}function qk(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),n}function Jk(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var Yk=new Set([`text`,`search`,`email`,`url`,`tel`,`password`,`number`,void 0]);function Xk(e){if(e===void 0)return!1;if(e.isContentEditable===!0)return!0;let t=e.tagName.toUpperCase();return t===`TEXTAREA`||t===`INPUT`&&Yk.has(e.type)}function Zk(e=document){let t=e.activeElement;t!==null&&Xk({tagName:t.tagName,...t instanceof HTMLInputElement?{type:t.type}:{},...t instanceof HTMLElement?{isContentEditable:t.isContentEditable}:{}})&&t instanceof HTMLElement&&t.blur()}function Qk(e,t){if(e===``)return null;let n=tA(e);return g`<div class=${`error${n===void 0?``:` transient`}`} role=${n===void 0?`alert`:`status`}>
|
|
5934
5951
|
<span class="error-text">${n??e}</span>
|
|
5935
5952
|
<button type="button" class="error-dismiss" aria-label="Dismiss error" title="Dismiss error" @click=${()=>{t()}}>✕</button>
|
|
5936
|
-
</div>`}function
|
|
5937
|
-
${e.map(e=>g`<p class="deprecation-notice-text">${
|
|
5938
|
-
</div>`}var aA=900*1e3,oA=4e3,sA=15e3;function cA(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.addEventListener==`function`&&typeof t.removeEventListener==`function`}var lA=750,uA=[1e3,3e3,8e3,15e3,3e4],dA={capture:!0},fA=`auto:on`,pA=`auto:off`,mA=`theme:`,hA=$s(`core:workspace.files`),gA=$s(`core:workspace.terminal`),_A=320,vA=2,yA=`(min-width: 1181px)`,$=class extends v{constructor(...e){super(...e),this.state=Hs(),this.sessionUnread=new Im({onChange:e=>{L(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.interruptedSessionIds=new Set,this.unreadSessionIds=this.sessionUnread.unreadSessionIds(L(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new up(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new Cf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new pf,{notifications:this.notifications,onSelectedSessionIdle:()=>{this.workspaces.refreshWorkspaceGoals()},onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t),this.refreshSelfUpdate()},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(L(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)}}),this.machineStatus=new xc(()=>this.state,e=>{this.setState(e)}),this.auth=new Ys(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new yp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new gp),this.projects=new Cc(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new _c(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebStatusController=new Tc(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}),this.files=new pc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Up,this.realtime=new qd,this.machineRealtimeSockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Tp,this.terminalSelection=new Rp,this.appShell=new Gy(this),this.browserResume=new Jy({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new sb(this),this.panelResize=new fb(this),this.navigationSections=new ob(this,()=>this.state),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=bA(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=th()??Zm,this.activeThemeId=Xm,this.isRefreshingApp=!1,this.lastScheduledError=``,this.quickSwitcherOpen=!1,this.composerCollapsed=!1,this.mobileToolSheetOpen=!1,this.quickSwitcherLoading=!1,this.quickSwitcherSessions=[],this.pinnedSessionIds=Wk(),this.quickSwitcherWorkspaces=[],this.settingsSection=Pb(),this.fleetLoading=!1,this.fleetSectionShown=!1,this.shortcutConfig={},this.workspaceUploadDefaultFolder=xs(void 0),this.sessionWarningVisibility=Wm(),this.onPopState=()=>{if(this.modalLayerOpen()){this.closeModalLayer();return}this.currentRouteMatchesUrl()||this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.sessionUnread.refreshAll(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onBrowserOnline=()=>{this.realtime.reconnectNow(),this.sessions.reconnectSocketNow(),this.checkSocketLiveness()},this.onFocusIn=e=>{this.composerCollapsed=_m(e.composedPath())},this.onFocusOut=e=>{let t=e.relatedTarget;t!==null&&(this.composerCollapsed=_m(vm(t)))},this.onDocumentVisibilityChange=()=>{this.updateSubagentPolling(),document.visibilityState===`visible`&&this.refreshSubagents()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.isRenderedModalOpen()||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.selfUpdateCooldownUntil=0,this.onVisualViewportChange=()=>{let e=hm(window.innerHeight,window.visualViewport??void 0);this.style.setProperty(`--pi-app-keyboard-inset`,`${String(Math.round(e))}px`)},this.handleSendPrompt=(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,i),this.handleStopActiveWork=()=>{this.sessions.stopActiveWork().then(e=>{this.restoreToComposer(e)})},this.handleClearServerQueue=e=>{this.restoreToComposer(e),this.sessions.clearServerQueue()},this.handleOpenSubagentRun=e=>{this.sessions.openSubagentRunOutput(e)},this.handleOpenBackgroundTask=e=>{e.hasOutput&&this.sessions.openBackgroundTaskOutput(e)},this.handleCloseActivityOutput=()=>{this.sessions.closeActivityOutput()},this.handleOpenSubagentSession=e=>{this.openSubagent(e)},this.handleRecallQueuedMessage=e=>{this.sessions.recallQueuedMessage(e).then(t=>{t&&this.restoreToComposer([e])})},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleSubmitAsk=(e,t)=>this.sessions.submitAsk(e,t),this.handleAnswerDialog=(e,t)=>this.sessions.answerDialog(e,t),this.handleCancelDialog=e=>this.sessions.cancelDialog(e),this.handleDismissClosedDialog=e=>{this.sessions.dismissClosedDialog(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=Ym(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleResendMessage=e=>{this.promptEditor?.restorePrompt(e)},this.handleSelectModel=()=>{this.openModelDialog()},this.handleToggleModelEnabled=async(e,t,n)=>{let r=await this.sessions.setModelEnabled(e,t,n),i=this.state.modelDialog;r===void 0||i===void 0||this.setState({modelDialog:{...i,catalog:r,options:this.modelDialogOptions(r.filter(e=>e.enabled))}})},this.handleSelectThinking=()=>{this.openThinkingDialog()}}currentRouteMatchesUrl(){let e=this.state,t=new URL(window.location.href),n=e=>{let n=t.searchParams.get(e);return n===null||n===``?void 0:n},r=e.selectedMachine===void 0?void 0:e.selectedMachine.id;return n(`machine`)===(r===`local`?void 0:r)&&n(`project`)===(e.selectedProject===void 0?void 0:e.selectedProject.id)&&n(`workspace`)===(e.selectedWorkspace===void 0?void 0:e.selectedWorkspace.id)&&n(`session`)===(e.selectedSession===void 0?void 0:e.selectedSession.id)}closeModalLayer(){if(this.mobileToolSheetOpen){this.mobileToolSheetOpen=!1;return}if(this.quickSwitcherOpen){this.quickSwitcherOpen=!1;return}let e=this.state;if(e.actionPaletteOpen){this.setState({actionPaletteOpen:!1});return}if(e.projectDialogOpen){this.setState({projectDialogOpen:!1});return}if(e.machineDialogOpen){this.setState({machineDialogOpen:!1});return}if(e.commandDialog!==void 0){this.sessions.cancelCommand();return}if(e.modelDialog!==void 0){this.setState({modelDialog:void 0});return}if(e.thinkingDialog!==void 0){this.setState({thinkingDialog:void 0});return}if(e.themeDialog!==void 0){this.setState({themeDialog:void 0});return}if(this.sessionCleanupDialog!==void 0){this.sessionCleanupDialog=void 0;return}}listenForFormFocus(e){let t=this.renderRoot;if(cA(t)){if(e===`add`){t.addEventListener(`focusin`,this.onFocusIn),t.addEventListener(`focusout`,this.onFocusOut);return}t.removeEventListener(`focusin`,this.onFocusIn),t.removeEventListener(`focusout`,this.onFocusOut)}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility()}updated(){this.committedChatIdentity=wA(this.state),this.syncSelectedSessionReadState(),this.syncFleetOnSettingsSection(),this.syncDocumentTitle()}syncDocumentTitle(){let e=this.state,t=Ek({mainView:e.mainView,selectedMachine:e.selectedMachine,selectedProject:e.selectedProject,selectedWorkspace:e.selectedWorkspace,selectedSession:e.selectedSession});document.title!==t&&(document.title=t)}syncFleetOnSettingsSection(){let e=this.settingsSection===`machines`;e&&!this.fleetSectionShown&&this.refreshFleet(),this.fleetSectionShown=e}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=Km(this.sessionWarningVisibility,e===void 0?void 0:Js(L(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=L(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}markSessionsRead(e){let t=L(this.state);for(let n of e)this.sessionUnread.acknowledge(t,n)}async commitReadyChatAfterRender(e,t){let n=CA(e,t);await this.updateComplete,!(!this.unreadConnected||wA(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}refreshInterruptedRuns(e){this.sessions.loadInterruptedRuns(e).then(e=>{this.interruptedSessionIds=e})}updateSubagentPolling(){let e=bm({hasSelectedSession:this.state.selectedSession!==void 0,documentVisible:document.visibilityState===`visible`});if(e&&this.subagentPollTimer===void 0){this.subagentPollTimer=window.setInterval(()=>{this.refreshSubagents()},oA);return}!e&&this.subagentPollTimer!==void 0&&(window.clearInterval(this.subagentPollTimer),this.subagentPollTimer=void 0)}openSubagent(e){let t=this.quickSwitcherSessions.find(t=>t.id===e.sessionId)??this.state.sessions.find(t=>t.id===e.sessionId);t!==void 0&&this.selectNavigationItem(`sessions`,`chat`,()=>this.sessions.selectSession(t))}async refreshSubagents(){let e=this.state.selectedSession;if(e!==void 0)try{let t=L(this.state),[n,r]=await Promise.all([Mo.subsessions(e,t),Mo.backgroundTasks(e,t).catch(()=>this.state.backgroundTasks)]);if(this.state.selectedSession?.id!==e.id||L(this.state)!==t)return;let i=!jA(n.subsessions,this.state.subagents),a=!MA(n.toolRuns,this.state.subagentRuns),o=!AA(r,this.state.backgroundTasks);if(!i&&!a&&!o)return;this.setState({subagents:n.subsessions,subagentRuns:n.toolRuns,backgroundTasks:r})}catch{}}async refreshSelfUpdate(){if(!(Date.now()<this.selfUpdateCooldownUntil)){this.selfUpdateCooldownUntil=Date.now()+6e4;try{let e=await wo.status();this.setState({selfUpdate:e})}catch(e){console.warn(`Self-update status check failed`,e)}}}async applySelfUpdate(){if(!this.state.selfUpdateApplying){this.setState({selfUpdateApplying:!0});try{let e=await wo.apply();e.started||(this.setState({selfUpdateApplying:!1}),e.error!==void 0&&(this.setState({error:`Update failed: ${e.error}`}),this.scheduleTransientErrorDismissal(`Update failed: ${e.error}`)))}catch{this.setState({selfUpdateApplying:!1}),this.setState({error:`Update request failed`}),this.scheduleTransientErrorDismissal(`Update request failed`)}}}skipSelfUpdate(){let e=this.state.selfUpdate?.latest;if(e!==void 0){try{window.localStorage.setItem(`piWebSelfUpdateSkipped`,e)}catch{}this.setState({selfUpdate:void 0})}}renderSelfUpdateBanner(){let e=this.state.selfUpdate;if(e===void 0||!e.enabled||!e.available)return null;if(this.state.selfUpdateApplying)return g`
|
|
5953
|
+
</div>`}function $k(e){return tA(e)!==void 0}var eA=6e3;function tA(e){if(/session daemon workspace authority unavailable: connect (enoent|econnrefused)/i.test(e)&&/sessiond\.sock/i.test(e))return`Reconnecting to the session daemon…`;if(/\boperation was aborted\b/i.test(e))return`Previous request was interrupted. Retry if the message did not finish.`;if(/remote machine request cancelled/i.test(e))return`Connection changed while the request was in flight. Retrying is usually enough.`;if(/failed to fetch|load failed|networkerror when attempting to fetch/i.test(e))return`Lost connection to PI WEB. Reconnecting…`}function nA(e,t){let n=[];for(let r of e){let e=t[r.id]?.deprecatedAgentInputs;e===void 0||e.length===0||n.push({machineId:r.id,machineName:r.name,inputs:e})}return n}function rA(e){let t=e.inputs.map(iA).join(`; `);return`${e.machineName}: ${t}. Support for deprecated agent configuration inputs will be removed in a future release.`}function iA(e){let t=e.source===`config`?`config key ${e.name}`:`environment variable ${e.name}`;return e.replacement===void 0?`${t} is deprecated and ignored; remove it, there is no replacement`:`${t} is deprecated; set ${e.replacement} instead`}function aA(e){return e.length===0?null:g`<div class="deprecation-notice" role="alert">
|
|
5954
|
+
${e.map(e=>g`<p class="deprecation-notice-text">${rA(e)}</p>`)}
|
|
5955
|
+
</div>`}var oA=900*1e3,sA=4e3,cA=15e3;function lA(e){if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.addEventListener==`function`&&typeof t.removeEventListener==`function`}var uA=750,dA=[1e3,3e3,8e3,15e3,3e4],fA={capture:!0},pA=`auto:on`,mA=`auto:off`,hA=`theme:`,gA=$s(`core:workspace.files`),_A=$s(`core:workspace.terminal`),vA=320,yA=2,bA=`(min-width: 1181px)`,$=class extends v{constructor(...e){super(...e),this.state=Hs(),this.sessionUnread=new Im({onChange:e=>{L(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.interruptedSessionIds=new Set,this.unreadSessionIds=this.sessionUnread.unreadSessionIds(L(this.state),this.state.sessions),this.unreadConnected=!1,this.notifications=new up(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new Cf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new pf,{notifications:this.notifications,onSelectedSessionIdle:()=>{this.workspaces.refreshWorkspaceGoals()},onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t),this.refreshSelfUpdate()},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(L(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)}}),this.machineStatus=new xc(()=>this.state,e=>{this.setState(e)}),this.auth=new Ys(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new yp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new gp),this.projects=new Cc(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new _c(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebStatusController=new Tc(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}),this.files=new pc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Up,this.realtime=new qd,this.machineRealtimeSockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Tp,this.terminalSelection=new Rp,this.appShell=new Ky(this),this.browserResume=new Yy({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new cb(this),this.panelResize=new pb(this),this.navigationSections=new sb(this,()=>this.state),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=xA(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=th()??Zm,this.activeThemeId=Xm,this.isRefreshingApp=!1,this.lastScheduledError=``,this.quickSwitcherOpen=!1,this.composerCollapsed=!1,this.mobileToolSheetOpen=!1,this.quickSwitcherLoading=!1,this.quickSwitcherSessions=[],this.pinnedSessionIds=Gk(),this.quickSwitcherWorkspaces=[],this.settingsSection=Fb(),this.fleetLoading=!1,this.fleetSectionShown=!1,this.shortcutConfig={},this.workspaceUploadDefaultFolder=xs(void 0),this.sessionWarningVisibility=Wm(),this.onPopState=()=>{if(this.modalLayerOpen()){this.closeModalLayer();return}this.currentRouteMatchesUrl()||this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.sessionUnread.refreshAll(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onBrowserOnline=()=>{this.realtime.reconnectNow(),this.sessions.reconnectSocketNow(),this.checkSocketLiveness()},this.onFocusIn=e=>{this.composerCollapsed=_m(e.composedPath())},this.onFocusOut=e=>{let t=e.relatedTarget;t!==null&&(this.composerCollapsed=_m(vm(t)))},this.onDocumentVisibilityChange=()=>{this.updateSubagentPolling(),document.visibilityState===`visible`&&this.refreshSubagents()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.isRenderedModalOpen()||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.selfUpdateCooldownUntil=0,this.onVisualViewportChange=()=>{let e=hm(window.innerHeight,window.visualViewport??void 0);this.style.setProperty(`--pi-app-keyboard-inset`,`${String(Math.round(e))}px`)},this.handleSendPrompt=(e,t,n,r,i)=>this.sendPrompt(e,t,n,r,i),this.handleStopActiveWork=()=>{this.sessions.stopActiveWork().then(e=>{this.restoreToComposer(e)})},this.handleClearServerQueue=e=>{this.restoreToComposer(e),this.sessions.clearServerQueue()},this.handleOpenSubagentRun=e=>{this.sessions.openSubagentRunOutput(e)},this.handleOpenBackgroundTask=e=>{e.hasOutput&&this.sessions.openBackgroundTaskOutput(e)},this.handleCloseActivityOutput=()=>{this.sessions.closeActivityOutput()},this.handleOpenSubagentSession=e=>{this.openSubagent(e)},this.handleRecallQueuedMessage=e=>{this.sessions.recallQueuedMessage(e).then(t=>{t&&this.restoreToComposer([e])})},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleSubmitAsk=(e,t)=>this.sessions.submitAsk(e,t),this.handleAnswerDialog=(e,t)=>this.sessions.answerDialog(e,t),this.handleCancelDialog=e=>this.sessions.cancelDialog(e),this.handleDismissClosedDialog=e=>{this.sessions.dismissClosedDialog(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=Ym(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleResendMessage=e=>{this.promptEditor?.restorePrompt(e)},this.handleSelectModel=()=>{this.openModelDialog()},this.handleToggleModelEnabled=async(e,t,n)=>{let r=await this.sessions.setModelEnabled(e,t,n),i=this.state.modelDialog;r===void 0||i===void 0||this.setState({modelDialog:{...i,catalog:r,options:this.modelDialogOptions(r.filter(e=>e.enabled))}})},this.handleSelectThinking=()=>{this.openThinkingDialog()}}currentRouteMatchesUrl(){let e=this.state,t=new URL(window.location.href),n=e=>{let n=t.searchParams.get(e);return n===null||n===``?void 0:n},r=e.selectedMachine===void 0?void 0:e.selectedMachine.id;return n(`machine`)===(r===`local`?void 0:r)&&n(`project`)===(e.selectedProject===void 0?void 0:e.selectedProject.id)&&n(`workspace`)===(e.selectedWorkspace===void 0?void 0:e.selectedWorkspace.id)&&n(`session`)===(e.selectedSession===void 0?void 0:e.selectedSession.id)}closeModalLayer(){if(this.mobileToolSheetOpen){this.mobileToolSheetOpen=!1;return}if(this.quickSwitcherOpen){this.quickSwitcherOpen=!1;return}let e=this.state;if(e.actionPaletteOpen){this.setState({actionPaletteOpen:!1});return}if(e.projectDialogOpen){this.setState({projectDialogOpen:!1});return}if(e.machineDialogOpen){this.setState({machineDialogOpen:!1});return}if(e.commandDialog!==void 0){this.sessions.cancelCommand();return}if(e.modelDialog!==void 0){this.setState({modelDialog:void 0});return}if(e.thinkingDialog!==void 0){this.setState({thinkingDialog:void 0});return}if(e.themeDialog!==void 0){this.setState({themeDialog:void 0});return}if(this.sessionCleanupDialog!==void 0){this.sessionCleanupDialog=void 0;return}}listenForFormFocus(e){let t=this.renderRoot;if(lA(t)){if(e===`add`){t.addEventListener(`focusin`,this.onFocusIn),t.addEventListener(`focusout`,this.onFocusOut);return}t.removeEventListener(`focusin`,this.onFocusIn),t.removeEventListener(`focusout`,this.onFocusOut)}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility()}updated(){this.committedChatIdentity=TA(this.state),this.syncSelectedSessionReadState(),this.syncFleetOnSettingsSection(),this.syncDocumentTitle()}syncDocumentTitle(){let e=this.state,t=Dk({mainView:e.mainView,selectedMachine:e.selectedMachine,selectedProject:e.selectedProject,selectedWorkspace:e.selectedWorkspace,selectedSession:e.selectedSession});document.title!==t&&(document.title=t)}syncFleetOnSettingsSection(){let e=this.settingsSection===`machines`;e&&!this.fleetSectionShown&&this.refreshFleet(),this.fleetSectionShown=e}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=Km(this.sessionWarningVisibility,e===void 0?void 0:Js(L(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=L(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}markSessionsRead(e){let t=L(this.state);for(let n of e)this.sessionUnread.acknowledge(t,n)}async commitReadyChatAfterRender(e,t){let n=wA(e,t);await this.updateComplete,!(!this.unreadConnected||TA(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}refreshInterruptedRuns(e){this.sessions.loadInterruptedRuns(e).then(e=>{this.interruptedSessionIds=e})}updateSubagentPolling(){let e=bm({hasSelectedSession:this.state.selectedSession!==void 0,documentVisible:document.visibilityState===`visible`});if(e&&this.subagentPollTimer===void 0){this.subagentPollTimer=window.setInterval(()=>{this.refreshSubagents()},sA);return}!e&&this.subagentPollTimer!==void 0&&(window.clearInterval(this.subagentPollTimer),this.subagentPollTimer=void 0)}openSubagent(e){let t=this.quickSwitcherSessions.find(t=>t.id===e.sessionId)??this.state.sessions.find(t=>t.id===e.sessionId);t!==void 0&&this.selectNavigationItem(`sessions`,`chat`,()=>this.sessions.selectSession(t))}async refreshSubagents(){let e=this.state.selectedSession;if(e!==void 0)try{let t=L(this.state),[n,r]=await Promise.all([Mo.subsessions(e,t),Mo.backgroundTasks(e,t).catch(()=>this.state.backgroundTasks)]);if(this.state.selectedSession?.id!==e.id||L(this.state)!==t)return;let i=!MA(n.subsessions,this.state.subagents),a=!NA(n.toolRuns,this.state.subagentRuns),o=!jA(r,this.state.backgroundTasks);if(!i&&!a&&!o)return;this.setState({subagents:n.subsessions,subagentRuns:n.toolRuns,backgroundTasks:r})}catch{}}async refreshSelfUpdate(){if(!(Date.now()<this.selfUpdateCooldownUntil)){this.selfUpdateCooldownUntil=Date.now()+6e4;try{let e=await wo.status();this.setState({selfUpdate:e})}catch(e){console.warn(`Self-update status check failed`,e)}}}async applySelfUpdate(){if(!this.state.selfUpdateApplying){this.setState({selfUpdateApplying:!0});try{let e=await wo.apply();e.started||(this.setState({selfUpdateApplying:!1}),e.error!==void 0&&(this.setState({error:`Update failed: ${e.error}`}),this.scheduleTransientErrorDismissal(`Update failed: ${e.error}`)))}catch{this.setState({selfUpdateApplying:!1}),this.setState({error:`Update request failed`}),this.scheduleTransientErrorDismissal(`Update request failed`)}}}skipSelfUpdate(){let e=this.state.selfUpdate?.latest;if(e!==void 0){try{window.localStorage.setItem(`piWebSelfUpdateSkipped`,e)}catch{}this.setState({selfUpdate:void 0})}}renderSelfUpdateBanner(){let e=this.state.selfUpdate;if(e===void 0||!e.enabled||!e.available)return null;if(this.state.selfUpdateApplying)return g`
|
|
5939
5956
|
<div class="self-update-banner applying" role="status" aria-live="polite">
|
|
5940
5957
|
<span class="state-dots"><span class="state-dot"></span><span class="state-dot"></span><span class="state-dot"></span></span>
|
|
5941
5958
|
<span>正在更新 pi-web(${e.current} → ${e.latest??`new`})… 重启后页面将自动重连。</span>
|
|
@@ -5944,7 +5961,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5944
5961
|
<span>pi-web 有新版本:${e.current} → ${e.latest??`new`}</span>
|
|
5945
5962
|
<button type="button" @click=${()=>{this.applySelfUpdate()}}>Update now</button>
|
|
5946
5963
|
<button type="button" class="skip" @click=${()=>{this.skipSelfUpdate()}}>Skip</button>
|
|
5947
|
-
</div>`}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(L(this.state),this.state.sessions);NA(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=CA(e,t);return wA(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isRenderedModalOpen()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isRenderedModalOpen(){return Rh(this.ownerDocument)}connectedCallback(){super.connectedCallback(),Ct(()=>{this.clearTransientError()}),this.unreadConnected=!0,window.visualViewport?.addEventListener(`resize`,this.onVisualViewportChange),window.visualViewport?.addEventListener(`scroll`,this.onVisualViewportChange),this.onVisualViewportChange(),window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,dA),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.syncSessionUnreadMachines(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},aA),document.addEventListener(`visibilitychange`,this.onDocumentVisibilityChange),this.listenForFormFocus(`add`),this.livenessTimer=window.setInterval(()=>{this.checkSocketLiveness()},sA),window.addEventListener(`online`,this.onBrowserOnline),this.updateSubagentPolling(),this.loadClientConfig(),this.refreshSelfUpdate(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()})}clearTransientError(){this.state.error===``||!Qk(this.state.error)||(this.transientErrorTimer!==void 0&&(window.clearTimeout(this.transientErrorTimer),this.transientErrorTimer=void 0),this.setState({error:``}))}scheduleTransientErrorDismissal(e){this.transientErrorTimer!==void 0&&(window.clearTimeout(this.transientErrorTimer),this.transientErrorTimer=void 0),Qk(e)&&(this.transientErrorTimer=window.setTimeout(()=>{this.transientErrorTimer=void 0,this.state.error===e&&this.setState({error:``})},$k))}disconnectedCallback(){Ct(void 0),this.transientErrorTimer!==void 0&&window.clearTimeout(this.transientErrorTimer),window.visualViewport?.removeEventListener(`resize`,this.onVisualViewportChange),window.visualViewport?.removeEventListener(`scroll`,this.onVisualViewportChange),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,dA),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.subagentPollTimer!==void 0&&window.clearInterval(this.subagentPollTimer),this.subagentPollTimer=void 0,this.livenessTimer!==void 0&&window.clearInterval(this.livenessTimer),this.livenessTimer=void 0,window.removeEventListener(`online`,this.onBrowserOnline),document.removeEventListener(`visibilitychange`,this.onDocumentVisibilityChange),this.listenForFormFocus(`remove`),this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!kA(this.state,e))return;let t=this.state;this.state={...this.state,...e},wA(t)!==wA(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),TA(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),EA(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedSession?.id!==this.state.selectedSession?.id&&this.updateSubagentPolling(),this.composerCollapsed&&this.state.pendingAsk===void 0&&this.state.pendingDialogs.length===0&&(this.composerCollapsed=!1)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=Ob();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()}checkSocketLiveness(){document.visibilityState===`visible`&&(this.realtime.checkLiveness(),this.sessions.checkSocketLiveness())}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.realtime.checkLiveness(),this.sessions.checkSocketLiveness(),this.schedulePiWebStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){await this.sessionUnread.refreshAll(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineStatusSnapshots(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology()])}schedulePiWebStatusRefresh(e=lA){this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.piWebStatusController.refresh()},e)}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshMachineStatusSnapshots(){await Promise.all(this.refreshableMachineIds().map(async e=>{try{await this.machineStatus.refresh(e)}catch(t){console.warn(`Failed to refresh machine status for ${e}`,t)}}))}refreshableMachineIds(){return this.state.machines.length===0?[L(this.state)]:this.state.machines.filter(e=>OA(e,this.state.machineStatuses[e.id])).map(e=>e.id)}async loadClientConfig(){try{this.applyClientConfig((await xo.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEB config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=xs(e),this.speechToTextConfig=e.speechToText}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineStatusSnapshots(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology()]),this.schedulePiWebStatusRefresh()}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.terminal`&&e!==void 0?await this.refreshActiveTerminals(e):await this.invalidateWorkspacePanels(t)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(Ob(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=L(this.state),a=e.projectId===void 0||e.projectId===``?LA():n,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=a.selectedTerminalId;try{if(await this.restoreRouteMachine(e,!1),await this.loadPluginsForSelectedMachine(),!this.isCurrentRouteRestore(o))return;let n=kb(e,e=>this.plugins.resolveWorkspacePanelRouteId(e,L(this.state)));if(this.setState({workspaceTool:n.tool??this.state.workspaceTool,mainView:this.resolveRestoredMainView(r)??n.view??this.defaultRouteView(n),selectedFilePath:a.selectedFilePath,selectedTerminalId:a.selectedTerminalId}),n.projectId===void 0||n.projectId===``){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(n)){a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(n.tool,a.selectedFilePath),t&&this.updateUrl();return}let i=this.state.projects.find(e=>e.id===n.projectId);if(!i){this.setState({selectedFilePath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(i,{workspaceId:n.workspaceId,sessionId:n.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:a.selectedFilePath,selectedTerminalId:a.selectedTerminalId}),a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(n.tool,a.selectedFilePath),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),L(this.state)!==i&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?LA():{selectedFilePath:tc(hA,`file`),selectedTerminalId:tc(gA,`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){jb(e,{replace:!0}),nc(hA,`file`,void 0,{replace:!0}),nc(gA,`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=zA(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>=uA.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(),t!==void 0&&await this.files.restoreFile(t)):e!==void 0&&e!==`core:workspace.terminal`&&await this.invalidateWorkspacePanels(e)}resolveRestoredMainView(e){return e===void 0||e===`chat`||e===`navigation`?e:Ab(e,e=>this.plugins.resolveWorkspacePanelRouteId(e,L(this.state)))}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await HA(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return!this.isRenderedModalOpen()&&this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(e={}){return this.appShell.defaultRouteView(e)}updateUrl(e){this.rememberCurrentMachineNavigation(),jb({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(Dp(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Dp(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){jb(Op(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){nc(hA,`file`,e.selectedFilePath,{replace:!0}),nc(gA,`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)??Ep(e.id);if(await this.restoreRouteFor(Op(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)}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool(`core:workspace.terminal`)}terminalCommandRunsForOrigin(e,t=L(this.state)){let n=RA(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=Vb(e,{api:{runTerminalCommand:(e,n)=>No.runTerminalCommand(e,n,t),listCommandRuns:e=>No.listCommandRuns(e,t),getCommandRun:e=>No.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((L(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`),L(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){nc(gA,`terminal`,e,t)}terminalWorkspaceKey(e){return`${L(this.state)}:${e.path}`}selectMainView(e){if(e!==`navigation`&&e!==`chat`){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl()}openSettings(e=`general`){this.settingsSection=e,Fb(e)}async refreshFleet(){this.fleetLoading=!0,this.fleetError=void 0;try{this.fleetReport=await To.report()}catch(e){this.fleetError=e instanceof Error?e.message:String(e)}finally{this.fleetLoading=!1}}async runFleetOperation(e,t){this.fleetError=void 0;try{return await To.run(e,t)}catch(e){this.fleetError=e instanceof Error?e.message:String(e);return}finally{this.refreshFleet()}}closeSettings(){this.settingsSection=void 0,Fb(void 0)}navigateSettings(e){this.settingsSection=e,Fb(e)}restoreSettingsRoute(){this.settingsSection=Pb()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;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))}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));e.add(L(this.state)),this.sessionUnread.retainMachines(e);for(let t of e)this.sessionUnread.projection(t)===void 0&&this.sessionUnread.refresh(t)}connectRealtime(){let e=L(this.state);this.refreshInterruptedRuns(e),this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.clearTransientError(),this.sessionUnread.refresh(e),this.sessions.hydrateSessionStatuses(e,{replaceKnown:!0}),this.sessions.refreshCurrentWorkspaceSessions(e),this.refreshInterruptedRuns(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t)},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 qd;e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.sessionUnread.refresh(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=L(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>DA(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`machine.status`&&this.machineStatus.apply(e,t.status)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`machine.status`?this.machineStatus.apply(e,t.status):IA(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=L(this.state);try{let n=await No.terminals(e.projectId,e.id,t);if(L(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=FA(e),r=FA(t);n&&!r&&(this.setState({fileTreeStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&((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({piWebStatus:void 0}),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`?this.files.refreshFiles():e!==`core:workspace.terminal`&&this.invalidateWorkspacePanels(e)}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
|
|
5964
|
+
</div>`}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(L(this.state),this.state.sessions);PA(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=wA(e,t);return TA(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isRenderedModalOpen()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isRenderedModalOpen(){return zh(this.ownerDocument)}connectedCallback(){super.connectedCallback(),Ct(()=>{this.clearTransientError()}),this.unreadConnected=!0,window.visualViewport?.addEventListener(`resize`,this.onVisualViewportChange),window.visualViewport?.addEventListener(`scroll`,this.onVisualViewportChange),this.onVisualViewportChange(),window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,fA),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.syncSessionUnreadMachines(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},oA),document.addEventListener(`visibilitychange`,this.onDocumentVisibilityChange),this.listenForFormFocus(`add`),this.livenessTimer=window.setInterval(()=>{this.checkSocketLiveness()},cA),window.addEventListener(`online`,this.onBrowserOnline),this.updateSubagentPolling(),this.loadClientConfig(),this.refreshSelfUpdate(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()})}clearTransientError(){this.state.error===``||!$k(this.state.error)||(this.transientErrorTimer!==void 0&&(window.clearTimeout(this.transientErrorTimer),this.transientErrorTimer=void 0),this.setState({error:``}))}scheduleTransientErrorDismissal(e){this.transientErrorTimer!==void 0&&(window.clearTimeout(this.transientErrorTimer),this.transientErrorTimer=void 0),$k(e)&&(this.transientErrorTimer=window.setTimeout(()=>{this.transientErrorTimer=void 0,this.state.error===e&&this.setState({error:``})},eA))}disconnectedCallback(){Ct(void 0),this.transientErrorTimer!==void 0&&window.clearTimeout(this.transientErrorTimer),window.visualViewport?.removeEventListener(`resize`,this.onVisualViewportChange),window.visualViewport?.removeEventListener(`scroll`,this.onVisualViewportChange),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,fA),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.subagentPollTimer!==void 0&&window.clearInterval(this.subagentPollTimer),this.subagentPollTimer=void 0,this.livenessTimer!==void 0&&window.clearInterval(this.livenessTimer),this.livenessTimer=void 0,window.removeEventListener(`online`,this.onBrowserOnline),document.removeEventListener(`visibilitychange`,this.onDocumentVisibilityChange),this.listenForFormFocus(`remove`),this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!AA(this.state,e))return;let t=this.state;this.state={...this.state,...e},TA(t)!==TA(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),EA(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),DA(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),t.selectedSession?.id!==this.state.selectedSession?.id&&this.updateSubagentPolling(),this.composerCollapsed&&this.state.pendingAsk===void 0&&this.state.pendingDialogs.length===0&&(this.composerCollapsed=!1)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=kb();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()}checkSocketLiveness(){document.visibilityState===`visible`&&(this.realtime.checkLiveness(),this.sessions.checkSocketLiveness())}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.realtime.checkLiveness(),this.sessions.checkSocketLiveness(),this.schedulePiWebStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){await this.sessionUnread.refreshAll(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineStatusSnapshots(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology()])}schedulePiWebStatusRefresh(e=uA){this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.piWebStatusController.refresh()},e)}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshMachineStatusSnapshots(){await Promise.all(this.refreshableMachineIds().map(async e=>{try{await this.machineStatus.refresh(e)}catch(t){console.warn(`Failed to refresh machine status for ${e}`,t)}}))}refreshableMachineIds(){return this.state.machines.length===0?[L(this.state)]:this.state.machines.filter(e=>kA(e,this.state.machineStatuses[e.id])).map(e=>e.id)}async loadClientConfig(){try{this.applyClientConfig((await xo.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEB config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=xs(e),this.speechToTextConfig=e.speechToText}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineStatusSnapshots(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology()]),this.schedulePiWebStatusRefresh()}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.terminal`&&e!==void 0?await this.refreshActiveTerminals(e):await this.invalidateWorkspacePanels(t)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(kb(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=L(this.state),a=e.projectId===void 0||e.projectId===``?RA():n,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=a.selectedTerminalId;try{if(await this.restoreRouteMachine(e,!1),await this.loadPluginsForSelectedMachine(),!this.isCurrentRouteRestore(o))return;let n=Ab(e,e=>this.plugins.resolveWorkspacePanelRouteId(e,L(this.state)));if(this.setState({workspaceTool:n.tool??this.state.workspaceTool,mainView:this.resolveRestoredMainView(r)??n.view??this.defaultRouteView(n),selectedFilePath:a.selectedFilePath,selectedTerminalId:a.selectedTerminalId}),n.projectId===void 0||n.projectId===``){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(n)){a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(n.tool,a.selectedFilePath),t&&this.updateUrl();return}let i=this.state.projects.find(e=>e.id===n.projectId);if(!i){this.setState({selectedFilePath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(i,{workspaceId:n.workspaceId,sessionId:n.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:a.selectedFilePath,selectedTerminalId:a.selectedTerminalId}),a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(n.tool,a.selectedFilePath),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),L(this.state)!==i&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?RA():{selectedFilePath:tc(gA,`file`),selectedTerminalId:tc(_A,`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){Mb(e,{replace:!0}),nc(gA,`file`,void 0,{replace:!0}),nc(_A,`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=BA(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>=dA.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(),t!==void 0&&await this.files.restoreFile(t)):e!==void 0&&e!==`core:workspace.terminal`&&await this.invalidateWorkspacePanels(e)}resolveRestoredMainView(e){return e===void 0||e===`chat`||e===`navigation`?e:jb(e,e=>this.plugins.resolveWorkspacePanelRouteId(e,L(this.state)))}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await UA(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return!this.isRenderedModalOpen()&&this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(e={}){return this.appShell.defaultRouteView(e)}updateUrl(e){this.rememberCurrentMachineNavigation(),Mb({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(Dp(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Dp(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Mb(Op(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){nc(gA,`file`,e.selectedFilePath,{replace:!0}),nc(_A,`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)??Ep(e.id);if(await this.restoreRouteFor(Op(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)}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool(`core:workspace.terminal`)}terminalCommandRunsForOrigin(e,t=L(this.state)){let n=zA(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=Hb(e,{api:{runTerminalCommand:(e,n)=>No.runTerminalCommand(e,n,t),listCommandRuns:e=>No.listCommandRuns(e,t),getCommandRun:e=>No.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((L(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`),L(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){nc(_A,`terminal`,e,t)}terminalWorkspaceKey(e){return`${L(this.state)}:${e.path}`}selectMainView(e){if(e!==`navigation`&&e!==`chat`){this.openWorkspaceTool(e);return}this.setState({mainView:e}),this.updateUrl()}openSettings(e=`general`){this.settingsSection=e,Ib(e)}async refreshFleet(){this.fleetLoading=!0,this.fleetError=void 0;try{this.fleetReport=await To.report()}catch(e){this.fleetError=e instanceof Error?e.message:String(e)}finally{this.fleetLoading=!1}}async runFleetOperation(e,t){this.fleetError=void 0;try{return await To.run(e,t)}catch(e){this.fleetError=e instanceof Error?e.message:String(e);return}finally{this.refreshFleet()}}closeSettings(){this.settingsSection=void 0,Ib(void 0)}navigateSettings(e){this.settingsSection=e,Ib(e)}restoreSettingsRoute(){this.settingsSection=Fb()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;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))}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));e.add(L(this.state)),this.sessionUnread.retainMachines(e);for(let t of e)this.sessionUnread.projection(t)===void 0&&this.sessionUnread.refresh(t)}connectRealtime(){let e=L(this.state);this.refreshInterruptedRuns(e),this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.clearTransientError(),this.sessionUnread.refresh(e),this.sessions.hydrateSessionStatuses(e,{replaceKnown:!0}),this.sessions.refreshCurrentWorkspaceSessions(e),this.refreshInterruptedRuns(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t)},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 qd;e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.sessionUnread.refresh(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=L(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>OA(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`machine.status`&&this.machineStatus.apply(e,t.status)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`machine.status`?this.machineStatus.apply(e,t.status):LA(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=L(this.state);try{let n=await No.terminals(e.projectId,e.id,t);if(L(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=IA(e),r=IA(t);n&&!r&&(this.setState({fileTreeStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&((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({piWebStatus:void 0}),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`?this.files.refreshFiles():e!==`core:workspace.terminal`&&this.invalidateWorkspacePanels(e)}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
|
|
5948
5965
|
<workspace-panel
|
|
5949
5966
|
id="workspace-panel"
|
|
5950
5967
|
.workspace=${e}
|
|
@@ -5990,7 +6007,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
5990
6007
|
.onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
|
|
5991
6008
|
.onReset=${()=>{this.resetResizablePanel(`workspace`)}}
|
|
5992
6009
|
></app-panel-edge-control>
|
|
5993
|
-
`}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-vA
|
|
6010
|
+
`}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-yA-vA);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(bA).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()}selectedMachineRuntime(){return this.state.machineRuntimes[L(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:``}}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){let t=L(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let n=await Mo.cleanupPreview(e,t);if(L(this.state)!==t)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:n,previewRequest:e,result:void 0,loading:!1,error:``}}catch(e){L(this.state)===t&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`Failed to preview cleanup: ${VA(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupDialog;if(t?.preview===void 0||Tm(t.previewRequest)!==Tm(e)){this.sessionCleanupDialog={...t??{},error:`Preview cleanup before running it.`};return}let n=L(this.state);this.sessionCleanupDialog={...t,running:!0,error:``};try{let t=await Mo.cleanup(e,n);if(L(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){L(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`Failed to run cleanup: ${VA(e)}`})}}renderNavigationPanel(){return g`
|
|
5994
6011
|
<app-navigation-panel
|
|
5995
6012
|
.machines=${this.state.machines}
|
|
5996
6013
|
.selectedMachine=${this.state.selectedMachine}
|
|
@@ -6060,7 +6077,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6060
6077
|
.onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
|
|
6061
6078
|
.onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
|
|
6062
6079
|
></app-navigation-panel>
|
|
6063
|
-
`}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq;if(await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await n()},i),!i())return;let a=t;e===`projects`&&(this.navigationSections.advanceAfterSelection(`projects`,{workspaceCount:this.state.workspaces.length}),this.state.workspaces.length===1&&this.state.selectedWorkspace!==void 0&&(a=`sessions`)),await this.focusNavigationTarget(a)}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}canStartSession(){return this.state.selectedWorkspace!==void 0}activeSessionIds(){let e=new Set;for(let t of this.quickSwitcherSessions)Us(this.state.sessionStatuses[t.id],this.state.sessionActivities[t.id])&&e.add(t.id);return e}sessionStateKinds(){return
|
|
6080
|
+
`}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq;if(await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await n()},i),!i())return;let a=t;e===`projects`&&(this.navigationSections.advanceAfterSelection(`projects`,{workspaceCount:this.state.workspaces.length}),this.state.workspaces.length===1&&this.state.selectedWorkspace!==void 0&&(a=`sessions`)),await this.focusNavigationTarget(a)}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}canStartSession(){return this.state.selectedWorkspace!==void 0}activeSessionIds(){let e=new Set;for(let t of this.quickSwitcherSessions)Us(this.state.sessionStatuses[t.id],this.state.sessionActivities[t.id])&&e.add(t.id);return e}sessionStateKinds(){return hD(this.quickSwitcherSessions,this.state.sessionStatuses,this.state.sessionActivities)}errorSessionIds(){let e=new Set;for(let[t,n]of this.sessionStateKinds())n===`error`&&e.add(t);return e}togglePinnedSession(e){this.pinnedSessionIds=qk(this.pinnedSessionIds,e.id),Kk(this.pinnedSessionIds)}waitingSessionIds(){let e=new Set;for(let t of this.quickSwitcherSessions)Sm(this.state.sessionStatuses[t.id])&&e.add(t.id);return e}modalLayerOpen(){return this.quickSwitcherOpen||this.mobileToolSheetOpen||this.state.actionPaletteOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.sessionCleanupDialog!==void 0}pushModalLayerFrame(){window.history.pushState({},``)}openActionPalette(){this.pushModalLayerFrame(),this.setState({actionPaletteOpen:!0})}openProjectDialog(){this.pushModalLayerFrame(),this.setState({projectDialogOpen:!0})}openQuickSwitcher(){Zk(),this.quickSwitcherOpen=!0,this.pushModalLayerFrame(),this.loadQuickSwitcherData(this.quickSwitcherSessions.length>0);let e=L(this.state);e!==``&&this.refreshInterruptedRuns(e)}applyRenameToQuickSwitcher(e,t){this.quickSwitcherSessions=mD(this.quickSwitcherSessions,e,t)}async loadQuickSwitcherData(e=!1){let t=L(this.state);if(!(!e&&this.quickSwitcherMachineId===t&&(this.quickSwitcherSessions.length>0||this.quickSwitcherWorkspaces.length>0||this.quickSwitcherLoading))){this.quickSwitcherLoading=!0;try{let e=this.state.projects.length>0?this.state.projects:await ko.projects(t),n=FA((await Promise.all(e.map(async e=>{try{return await jo.workspaces(e.id,t)}catch{return[]}}))).flat()),r=await Promise.all(n.map(async e=>{try{return await Mo.sessions(e.path,t)}catch{return[]}}));this.quickSwitcherMachineId=t,this.quickSwitcherWorkspaces=n,this.quickSwitcherSessions=FA(r.flat()).sort((e,t)=>Date.parse(t.modified)-Date.parse(e.modified))}catch(e){L(this.state)===t&&this.setState({error:`Failed to load sessions: ${VA(e)}`})}finally{L(this.state)===t&&(this.quickSwitcherLoading=!1)}}}async openSessionFromQuickSwitcher(e){await this.sessions.selectSession(e),await this.focusChatComposer()}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`&&!Fk(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 UA(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!==`chat`&&this.selectMainView(`chat`),await this.updateComplete,await UA(),!this.isRenderedModalOpen()&&this.promptEditor?.focusInput()}async navigateSessionTree(e,t){let n=L(this.state),r=this.state.selectedSession?.id,i=await this.sessions.navigateTree(e,t);return!i.cancelled&&r!==void 0&&L(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer(),i}async forkSessionTree(e){return this.sessions.forkFromTree(e)}async openSessionTree(e){this.state.selectedSession?.id!==e.id&&await this.sessions.selectSession(e),await this.sessions.runCommand(`/tree`)}closeSessionTreeNavigator(){this.sessions.closeTreeDialog(),this.focusChatComposer()}renderSessionTreeNavigator(e){return e.treeDialog===void 0?null:g`
|
|
6064
6081
|
<session-tree-navigator
|
|
6065
6082
|
.tree=${e.treeDialog}
|
|
6066
6083
|
.onNavigate=${(e,t)=>this.navigateSessionTree(e,t)}
|
|
@@ -6068,13 +6085,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6068
6085
|
.onAbort=${()=>this.sessions.abortTreeNavigation()}
|
|
6069
6086
|
.onCancel=${()=>{this.closeSessionTreeNavigator()}}
|
|
6070
6087
|
></session-tree-navigator>
|
|
6071
|
-
`}visibleWorkspacePanels(){let e=this.state.selectedWorkspace;if(e===void 0)return[];let t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(e=>e.visible?.(t)??!0)}workspacePanelEmptyState(){let e=this.state.selectedProject;return this.state.isLoadingProjects?{title:`Loading projects…`,body:`Looking for projects you have added to PI WEB.`}:e===void 0?this.state.projects.length===0?{title:`No projects yet`,body:`Use Actions → Add Project to add a folder. Workspace tools will appear here after you choose a workspace.`}:{title:`Select a project`,body:`Choose a project from the sidebar, then select a workspace to use its tools.`}:this.state.isLoadingWorkspaces?{title:`Loading workspaces…`,body:`Preparing workspace tools for ${e.name}.`}:this.state.workspaces.length===0?{title:`No workspaces found`,body:`${e.name} does not have any available workspaces. Try selecting the project again or re-adding it.`}:{title:`Select a workspace`,body:`Choose a workspace in ${e.name} to use its tools.`}}sessionEmptyMessage(){return this.state.isLoadingProjects?`Loading projects…`:this.state.selectedWorkspace===void 0?this.state.selectedProject===void 0?this.state.projects.length===0?`Add a project to start a session.`:`Select a project and workspace to start a session.`:`Select a workspace to start a session.`:`Select or start a session.`}mobilePanelBadge(e){let t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){let t=SA(this.state),n=r=>{let i=Fy(r,e,t.id);return ky({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),...i===void 0?{}:{backend:i},host:this.createWorkspaceHost()},n)};return n(xA())}createWorkspaceFiles(e,t){return Iy(jo,e,t,()=>{this.files.refreshFiles()})}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){let t=SA(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i.registrationPluginId,n),o=Fy(i,e,n);return Oy({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),...o===void 0?{}:{backend:o},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(),piWebUnstable:{terminalCommandRuns:a},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,selectedFileLoadError:this.state.selectedFileLoadError,fileTreeStale:this.state.fileTreeStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:Ss(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)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(xA())}invalidateWorkspacePanels(e){let t=this.state.selectedWorkspace;return t===void 0?Promise.resolve():this.plugins.invalidateWorkspacePanels(this.createWorkspacePanelContext(t),e)}getActions(){return Rb(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.workspaceSurfaceActions(),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}workspaceSurfaceActions(){return[{id:`core:workspace.refresh-current`,title:`Refresh Current Panel`,shortcut:`mod+shift+r`,group:`Workspace`,enabled:this.state.selectedWorkspace!==void 0,run:()=>this.refreshCurrentWorkspaceSurface()}]}sessionActions(){return[{id:`app.sessions.quick-switch`,title:`Open Session`,description:`Search and open a session, or start a new one, without walking the navigation panel`,shortcut:`mod+p`,group:`Sessions`,run:()=>{this.openQuickSwitcher()}},{id:`app.sessions.new`,title:`New Session`,description:`Start a session in the selected workspace`,shortcut:`mod+shift+n`,group:`Sessions`,enabled:this.canStartSession(),...this.canStartSession()?{}:{disabledReason:`Select a workspace first`},run:()=>{this.startSessionAndOpenChat()}},{id:`app.sessions.cleanup`,title:`Clean Up Sessions`,description:`Preview and manually clean up idle or archived sessions on the selected machine`,group:`Sessions`,run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{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(){let e=this.gatewayPluginLoadPromise;if(e!==void 0)return e;let t=this.loadExternalPlugins().then(e=>{!e&&this.gatewayPluginLoadPromise===t&&(this.gatewayPluginLoadPromise=void 0)});return this.gatewayPluginLoadPromise=t,t}loadExternalPlugins(){return this.registerExternalPlugins(`PI WEB plugins`,()=>ay(`pi-web-plugins/manifest.json`,{shouldLoadPlugin:e=>!this.plugins.hasPlugin(e.id)}))}async loadPluginsForSelectedMachine(){await this.ensureGatewayPluginsLoaded();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.state.machineRuntimes[e.id];if(t?.ok===!0&&!qt(t,kt.pluginLifecycle)){console.warn(`PI WEB plugins from ${e.name} require a matching plugin lifecycle capability; update and restart PI WEB on that machine`);return}let n=this.machinePluginLoadPromises.get(e.id);if(n!==void 0)return n;let r=this.registerExternalPlugins(`PI WEB plugins from ${e.name}`,()=>ay(`api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:t=>!this.plugins.hasPlugin(Gs(e.id,t.id))&&this.plugins.shouldLoadRemotePlugin(t.id,t.machineSpecific)})).then(t=>{t&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,r),await r}async registerExternalPlugins(e,t){try{let e=await t(),n=e.failures.length===0;for(let t of e.failures)console.warn(`Failed to load PI WEB plugin ${t.entry.id} (${t.entry.module})`,t.error);for(let t of e.registrations)if(!this.plugins.hasPlugin(t.id))try{this.plugins.register(t)}catch(e){n=!1,console.warn(`Failed to register PI WEB plugin ${t.id}`,e)}return this.applyPreferredTheme(!1),this.requestUpdate(),n}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=>Dy({state:this.state,prompt:this.createPromptEditor(),piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:e=>{this.openSettings(e)}},openActionPalette:()=>{this.openActionPalette()},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()},openModelPicker:()=>this.openModelDialog(),openThinkingLevelPicker:()=>this.openThinkingDialog(),selectMainView:e=>{this.selectMainView(e)},selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.files.refreshFiles(),refreshWorkspacePanels:e=>this.invalidateWorkspacePanels(e),refreshAppData:()=>this.refreshAppData(),checkForPiWebUpdates:()=>this.piWebStatusController.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:async()=>{await this.sessions.stopActiveWork()}},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!mh(e)){this.setState({error:`Workspace removal is not available`});return}if(yh(this.state,e))return;let t=e.removal,n=hh(e);if(t===void 0||n===void 0||!confirm(n))return;let r=L(this.state);try{let n=await jo.deleteWorkspace(e.projectId,e.id,t.precondition,r);if(L(this.state)!==r)return;this.recordWorkspaceDeletionRun(n,r);let i=await this.workspaceForCommandRun(n);if(L(this.state)!==r)return;i!==void 0&&this.openRuntimeTerminal(r,i,{terminalId:n.terminalId})}catch(e){L(this.state)===r&&this.setState({error:`Failed to start workspace removal: ${BA(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(L(this.state)!==t)return;let n=bh(e);n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;let e=L(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(gh(t.id));if(L(this.state)!==e)return;let r=_h(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))xh(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(xh);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=L(this.state)){if(L(this.state)!==t)return;let n=RA(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=bh(e);if(r!==void 0){if(this.handledWorkspaceDeletionRunIds.add(n),e.status===`succeeded`){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,r),L(this.state)!==t)return;this.setState({workspaceDeletionRuns:VA(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&(this.setState({error:`Workspace removal failed. See terminal output.`}),this.updateWorkspaceDeletionPolling())}}async focusPromptEditorSoon(){await this.updateComplete,this.promptEditor?.focusInput()}openMachineDialog(){this.pushModalLayerFrame(),this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async renameMachine(e,t){let n=t.trim();n===``||n===e.name||await this.machines.updateMachine(e,{name:n})}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 WEB 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,t]=await Promise.all([this.sessions.listModels(),this.sessions.listModelCatalog()]),n=this.currentModelValue();this.setState({modelDialog:{title:`Select Model`,...n===void 0?{}:{selectedValue:n},options:this.modelDialogOptions(e),catalog:t}})}currentModelValue(){let e=this.state.status?.model?.provider,t=this.state.status?.model?.id;return e!==void 0&&t!==void 0?`${e}/${t}`:void 0}modelDialogOptions(e){let t=this.currentModelValue();return e.map(e=>{let n=e.provider??``,r=e.id??``,i=`${n}/${r}`;return{value:i,label:`${r}${i===t?` ✓ current`:``}`,description:n}})}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))}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?pA:fA;this.pushModalLayerFrame(),this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${mA}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${mA}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}selectTheme(e){let t=this.plugins.getThemes().find(t=>t.id===e);t!==void 0&&(this.themePreference={themeId:t.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}setFollowSystemTheme(e){this.themePreference={themeId:this.themePreference.themeId,auto:e},this.applyPreferredTheme(!0)}pickTheme(e){if(this.setState({themeDialog:void 0}),e===fA||e===pA){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===fA},this.applyPreferredTheme(!0);return}if(!e.startsWith(mA))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,rh(t),e&&nh(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return ih({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return oh(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.pushModalLayerFrame(),this.setState({thinkingDialog:{title:`Select Thinking Level`,selectedValue:t,options:e.map(e=>{let n=UA(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)}async runGoalCommand(e){this.state.selectedSession!==void 0&&await this.sendPrompt(e)}async sendPrompt(e,t,n,r,i){return!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)?!0:await this.sessions.send(e,t,n,r,i)}restoreToComposer(e){let t=e.map(e=>e.text).filter(e=>e.trim()!==``);t.length!==0&&(this.promptEditor?.replaceText(t.join(`
|
|
6088
|
+
`}visibleWorkspacePanels(){let e=this.state.selectedWorkspace;if(e===void 0)return[];let t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(e=>e.visible?.(t)??!0)}workspacePanelEmptyState(){let e=this.state.selectedProject;return this.state.isLoadingProjects?{title:`Loading projects…`,body:`Looking for projects you have added to PI WEB.`}:e===void 0?this.state.projects.length===0?{title:`No projects yet`,body:`Use Actions → Add Project to add a folder. Workspace tools will appear here after you choose a workspace.`}:{title:`Select a project`,body:`Choose a project from the sidebar, then select a workspace to use its tools.`}:this.state.isLoadingWorkspaces?{title:`Loading workspaces…`,body:`Preparing workspace tools for ${e.name}.`}:this.state.workspaces.length===0?{title:`No workspaces found`,body:`${e.name} does not have any available workspaces. Try selecting the project again or re-adding it.`}:{title:`Select a workspace`,body:`Choose a workspace in ${e.name} to use its tools.`}}sessionEmptyMessage(){return this.state.isLoadingProjects?`Loading projects…`:this.state.selectedWorkspace===void 0?this.state.selectedProject===void 0?this.state.projects.length===0?`Add a project to start a session.`:`Select a project and workspace to start a session.`:`Select a workspace to start a session.`:`Select or start a session.`}mobilePanelBadge(e){let t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){let t=CA(this.state),n=r=>{let i=Iy(r,e,t.id);return Ay({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),...i===void 0?{}:{backend:i},host:this.createWorkspaceHost()},n)};return n(SA())}createWorkspaceFiles(e,t){return Ly(jo,e,t,()=>{this.files.refreshFiles()})}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){let t=CA(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i.registrationPluginId,n),o=Iy(i,e,n);return ky({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),...o===void 0?{}:{backend:o},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(),piWebUnstable:{terminalCommandRuns:a},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,selectedFileLoadError:this.state.selectedFileLoadError,fileTreeStale:this.state.fileTreeStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:Ss(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)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(SA())}invalidateWorkspacePanels(e){let t=this.state.selectedWorkspace;return t===void 0?Promise.resolve():this.plugins.invalidateWorkspacePanels(this.createWorkspacePanelContext(t),e)}getActions(){return zb(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.workspaceSurfaceActions(),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}workspaceSurfaceActions(){return[{id:`core:workspace.refresh-current`,title:`Refresh Current Panel`,shortcut:`mod+shift+r`,group:`Workspace`,enabled:this.state.selectedWorkspace!==void 0,run:()=>this.refreshCurrentWorkspaceSurface()}]}sessionActions(){return[{id:`app.sessions.quick-switch`,title:`Open Session`,description:`Search and open a session, or start a new one, without walking the navigation panel`,shortcut:`mod+p`,group:`Sessions`,run:()=>{this.openQuickSwitcher()}},{id:`app.sessions.new`,title:`New Session`,description:`Start a session in the selected workspace`,shortcut:`mod+shift+n`,group:`Sessions`,enabled:this.canStartSession(),...this.canStartSession()?{}:{disabledReason:`Select a workspace first`},run:()=>{this.startSessionAndOpenChat()}},{id:`app.sessions.cleanup`,title:`Clean Up Sessions`,description:`Preview and manually clean up idle or archived sessions on the selected machine`,group:`Sessions`,run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{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(){let e=this.gatewayPluginLoadPromise;if(e!==void 0)return e;let t=this.loadExternalPlugins().then(e=>{!e&&this.gatewayPluginLoadPromise===t&&(this.gatewayPluginLoadPromise=void 0)});return this.gatewayPluginLoadPromise=t,t}loadExternalPlugins(){return this.registerExternalPlugins(`PI WEB plugins`,()=>oy(`pi-web-plugins/manifest.json`,{shouldLoadPlugin:e=>!this.plugins.hasPlugin(e.id)}))}async loadPluginsForSelectedMachine(){await this.ensureGatewayPluginsLoaded();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.state.machineRuntimes[e.id];if(t?.ok===!0&&!qt(t,kt.pluginLifecycle)){console.warn(`PI WEB plugins from ${e.name} require a matching plugin lifecycle capability; update and restart PI WEB on that machine`);return}let n=this.machinePluginLoadPromises.get(e.id);if(n!==void 0)return n;let r=this.registerExternalPlugins(`PI WEB plugins from ${e.name}`,()=>oy(`api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:t=>!this.plugins.hasPlugin(Gs(e.id,t.id))&&this.plugins.shouldLoadRemotePlugin(t.id,t.machineSpecific)})).then(t=>{t&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,r),await r}async registerExternalPlugins(e,t){try{let e=await t(),n=e.failures.length===0;for(let t of e.failures)console.warn(`Failed to load PI WEB plugin ${t.entry.id} (${t.entry.module})`,t.error);for(let t of e.registrations)if(!this.plugins.hasPlugin(t.id))try{this.plugins.register(t)}catch(e){n=!1,console.warn(`Failed to register PI WEB plugin ${t.id}`,e)}return this.applyPreferredTheme(!1),this.requestUpdate(),n}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=>Oy({state:this.state,prompt:this.createPromptEditor(),piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:e=>{this.openSettings(e)}},openActionPalette:()=>{this.openActionPalette()},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()},openModelPicker:()=>this.openModelDialog(),openThinkingLevelPicker:()=>this.openThinkingDialog(),selectMainView:e=>{this.selectMainView(e)},selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.files.refreshFiles(),refreshWorkspacePanels:e=>this.invalidateWorkspacePanels(e),refreshAppData:()=>this.refreshAppData(),checkForPiWebUpdates:()=>this.piWebStatusController.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:async()=>{await this.sessions.stopActiveWork()}},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!mh(e)){this.setState({error:`Workspace removal is not available`});return}if(yh(this.state,e))return;let t=e.removal,n=hh(e);if(t===void 0||n===void 0||!confirm(n))return;let r=L(this.state);try{let n=await jo.deleteWorkspace(e.projectId,e.id,t.precondition,r);if(L(this.state)!==r)return;this.recordWorkspaceDeletionRun(n,r);let i=await this.workspaceForCommandRun(n);if(L(this.state)!==r)return;i!==void 0&&this.openRuntimeTerminal(r,i,{terminalId:n.terminalId})}catch(e){L(this.state)===r&&this.setState({error:`Failed to start workspace removal: ${VA(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(L(this.state)!==t)return;let n=bh(e);n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;let e=L(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(gh(t.id));if(L(this.state)!==e)return;let r=_h(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))xh(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(xh);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=L(this.state)){if(L(this.state)!==t)return;let n=zA(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=bh(e);if(r!==void 0){if(this.handledWorkspaceDeletionRunIds.add(n),e.status===`succeeded`){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,r),L(this.state)!==t)return;this.setState({workspaceDeletionRuns:HA(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&(this.setState({error:`Workspace removal failed. See terminal output.`}),this.updateWorkspaceDeletionPolling())}}async focusPromptEditorSoon(){await this.updateComplete,this.promptEditor?.focusInput()}openMachineDialog(){this.pushModalLayerFrame(),this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async renameMachine(e,t){let n=t.trim();n===``||n===e.name||await this.machines.updateMachine(e,{name:n})}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 WEB 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,t]=await Promise.all([this.sessions.listModels(),this.sessions.listModelCatalog()]),n=this.currentModelValue();this.setState({modelDialog:{title:`Select Model`,...n===void 0?{}:{selectedValue:n},options:this.modelDialogOptions(e),catalog:t}})}currentModelValue(){let e=this.state.status?.model?.provider,t=this.state.status?.model?.id;return e!==void 0&&t!==void 0?`${e}/${t}`:void 0}modelDialogOptions(e){let t=this.currentModelValue();return e.map(e=>{let n=e.provider??``,r=e.id??``,i=`${n}/${r}`;return{value:i,label:`${r}${i===t?` ✓ current`:``}`,description:n}})}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))}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?mA:pA;this.pushModalLayerFrame(),this.setState({themeDialog:{title:`Select Theme`,selectedValue:n===void 0?r:`${hA}${n}`,options:[{value:r,label:`Auto ${this.themePreference.auto?`✓ on`:`off`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${hA}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}selectTheme(e){let t=this.plugins.getThemes().find(t=>t.id===e);t!==void 0&&(this.themePreference={themeId:t.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}setFollowSystemTheme(e){this.themePreference={themeId:this.themePreference.themeId,auto:e},this.applyPreferredTheme(!0)}pickTheme(e){if(this.setState({themeDialog:void 0}),e===pA||e===mA){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===pA},this.applyPreferredTheme(!0);return}if(!e.startsWith(hA))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,rh(t),e&&nh(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return ih({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return oh(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.pushModalLayerFrame(),this.setState({thinkingDialog:{title:`Select Thinking Level`,selectedValue:t,options:e.map(e=>{let n=WA(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)}async runGoalCommand(e){this.state.selectedSession!==void 0&&await this.sendPrompt(e)}async sendPrompt(e,t,n,r,i){return!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)?!0:await this.sessions.send(e,t,n,r,i)}restoreToComposer(e){let t=e.map(e=>e.text).filter(e=>e.trim()!==``);t.length!==0&&(this.promptEditor?.replaceText(t.join(`
|
|
6072
6089
|
|
|
6073
6090
|
`)),this.promptEditor?.focusInput())}renderChatView(e,t){return g`
|
|
6074
6091
|
<chat-view .goals=${this.state.workspaceGoals} .onRunGoalCommand=${(e,t)=>this.runGoalCommand(t)} .sessionId=${t.id} .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} .activity=${e.activity} .pendingAsk=${e.pendingAsk} .pendingDialogs=${e.pendingDialogs} .closedDialogs=${e.closedDialogs} .onAnswerDialog=${this.handleAnswerDialog} .onCancelDialog=${this.handleCancelDialog} .onDismissClosedDialog=${this.handleDismissClosedDialog} .onResendMessage=${this.handleResendMessage} .askDraftSessionId=${Js(L(e),t.id)} .onSubmitAsk=${this.handleSubmitAsk} .notificationInbox=${qf(e.selectedNotificationInbox)} .subagents=${e.subagents} .subagentRuns=${e.subagentRuns} .backgroundTasks=${e.backgroundTasks} .activityOutput=${e.activityOutput} .onCloseActivityOutput=${this.handleCloseActivityOutput} .onOpenSubagent=${this.handleOpenSubagentSession} .onOpenSubagentRun=${this.handleOpenSubagentRun} .onOpenBackgroundTask=${this.handleOpenBackgroundTask} .onClearServerQueue=${this.handleClearServerQueue} .onRecallQueuedMessage=${this.handleRecallQueuedMessage} .onDismissWarning=${this.handleDismissWarning} .onDismissNotification=${this.handleDismissNotification} .onDismissAllNotifications=${this.handleDismissAllNotifications} .warningsVisible=${!this.sessionWarningVisibility.collapsed} .onToggleWarnings=${this.handleToggleWarnings} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
|
|
6075
6092
|
`}renderStatusBar(e){let t=this.sessionWarningVisibility.warningCount;return g`
|
|
6076
6093
|
<status-bar .status=${e.status} .warningCount=${t} .warningsExpanded=${t>0&&!this.sessionWarningVisibility.collapsed} .onToggleWarnings=${this.handleToggleWarnings}></status-bar>
|
|
6077
|
-
`}renderErrorBanner(e){return e!==this.lastScheduledError&&(this.lastScheduledError=e,this.scheduleTransientErrorDismissal(e)),
|
|
6094
|
+
`}renderErrorBanner(e){return e!==this.lastScheduledError&&(this.lastScheduledError=e,this.scheduleTransientErrorDismissal(e)),Qk(e,()=>{this.setState({error:``})})}renderContextBar(){return this.appShell.isMobileNavigationLayout?g`
|
|
6078
6095
|
<app-context-bar
|
|
6079
6096
|
.machines=${this.state.machines}
|
|
6080
6097
|
.machine=${this.state.selectedMachine}
|
|
@@ -6082,7 +6099,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6082
6099
|
.workspace=${this.state.selectedWorkspace}
|
|
6083
6100
|
.session=${this.state.selectedSession}
|
|
6084
6101
|
?emphasizeSession=${this.state.mainView===`chat`}
|
|
6085
|
-
?isWorking=${this.state.mainView===`chat`&&this.state.selectedSession!==void 0&&
|
|
6102
|
+
?isWorking=${this.state.mainView===`chat`&&this.state.selectedSession!==void 0&&IA(this.state)}
|
|
6086
6103
|
.refreshControl=${this.appShell.shouldShowAppRefreshInContextBar()?this.renderAppRefresh():void 0}
|
|
6087
6104
|
.onOpenSection=${e=>{this.openNavigationSection(e)}}
|
|
6088
6105
|
.onQuickSwitch=${()=>{this.openQuickSwitcher()}}
|
|
@@ -6097,16 +6114,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6097
6114
|
.onSelect=${e=>{this.selectMainView(e)}}
|
|
6098
6115
|
.onClose=${()=>{this.mobileToolSheetOpen=!1}}
|
|
6099
6116
|
></app-mobile-tool-sheet>
|
|
6100
|
-
`:null}openMobileToolSheet(){this.pushModalLayerFrame(),this.mobileToolSheetOpen=!0}mobileMainTabs(){let e
|
|
6117
|
+
`:null}openMobileToolSheet(){this.pushModalLayerFrame(),this.mobileToolSheetOpen=!0}mobileMainTabs(){let e=$x(this.state.sessions,this.unreadSessionIds);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;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>`}render(){let e=this.state;return g`
|
|
6101
6118
|
<div class=${this.panelCollapse.shellClass(e.mainView,e.selectedWorkspace!==void 0)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints(`navigation`),workspace:this.resizablePanelConstraints(`workspace`)})}>
|
|
6102
6119
|
<aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
|
|
6103
6120
|
${this.renderNavigationPanelEdgeControl()}
|
|
6104
|
-
<main class=${
|
|
6121
|
+
<main class=${ub(e.mainView)}>
|
|
6105
6122
|
${this.renderContextBar()}
|
|
6106
6123
|
|
|
6107
6124
|
${this.renderErrorBanner(e.error)}
|
|
6108
6125
|
${this.renderSelfUpdateBanner()}
|
|
6109
|
-
${
|
|
6126
|
+
${aA(nA(e.machines,e.machineRuntimes))}
|
|
6110
6127
|
<div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
|
|
6111
6128
|
${e.selectedSession?g`
|
|
6112
6129
|
${this.renderChatView(e,e.selectedSession)}
|
|
@@ -6152,4 +6169,4 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
6152
6169
|
${e.themeDialog===void 0?null:g`<command-picker title=${e.themeDialog.title} .options=${e.themeDialog.options} .selectedValue=${e.themeDialog.selectedValue} .onPick=${e=>{this.pickTheme(e)}} .onCancel=${()=>{this.setState({themeDialog:void 0})}}></command-picker>`}
|
|
6153
6170
|
${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)}} .machines=${e.machines} .machineStatuses=${e.machineStatuses} .onAddMachine=${()=>{this.openMachineDialog()}} .onRenameMachine=${async(e,t)=>{await this.renameMachine(e,t)}} .onRemoveMachine=${e=>{this.removeMachine(e)}} .fleetReport=${this.fleetReport} ?fleetLoading=${this.fleetLoading} .fleetError=${this.fleetError} .onRefreshFleet=${()=>this.refreshFleet()} .onRunFleet=${(e,t)=>this.runFleetOperation(e,t)} .themes=${this.plugins.getThemes()} .selectedThemeId=${this.resolveCurrentThemePreference().selectedTheme?.id} .activeThemeId=${this.activeThemeId} ?followSystemTheme=${this.themePreference.auto} .onSelectTheme=${e=>{this.selectTheme(e)}} .onToggleFollowSystem=${e=>{this.setFollowSystemTheme(e)}}></settings-dialog>`}
|
|
6154
6171
|
</div>
|
|
6155
|
-
`}static{this.styles=
|
|
6172
|
+
`}static{this.styles=ng}};H([x()],$.prototype,`state`,void 0),H([S(`chat-view`)],$.prototype,`chatView`,void 0),H([S(`prompt-editor`)],$.prototype,`promptEditor`,void 0),H([S(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),H([S(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),H([S(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),H([x()],$.prototype,`interruptedSessionIds`,void 0),H([x()],$.prototype,`unreadSessionIds`,void 0),H([x()],$.prototype,`activeThemeId`,void 0),H([x()],$.prototype,`isRefreshingApp`,void 0),H([x()],$.prototype,`quickSwitcherOpen`,void 0),H([x()],$.prototype,`composerCollapsed`,void 0),H([x()],$.prototype,`mobileToolSheetOpen`,void 0),H([x()],$.prototype,`quickSwitcherLoading`,void 0),H([x()],$.prototype,`quickSwitcherSessions`,void 0),H([x()],$.prototype,`pinnedSessionIds`,void 0),H([x()],$.prototype,`quickSwitcherWorkspaces`,void 0),H([x()],$.prototype,`sessionCleanupDialog`,void 0),H([x()],$.prototype,`settingsSection`,void 0),H([x()],$.prototype,`fleetReport`,void 0),H([x()],$.prototype,`fleetLoading`,void 0),H([x()],$.prototype,`fleetError`,void 0),H([x()],$.prototype,`shortcutConfig`,void 0),H([x()],$.prototype,`workspaceUploadDefaultFolder`,void 0),H([x()],$.prototype,`speechToTextConfig`,void 0),$=H([y(`pi-web-app`)],$);function xA(){let e=new wy;return e.register({id:`core`,plugin:Qv}),e.register({id:`themes`,plugin:ay}),e}function SA(){return{registrationPluginId:`core`,sourcePluginId:`core`}}function CA(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 wA(e,t){return JSON.stringify([e,t.id,t.cwd])}function TA(e){let t=e.selectedSession;return t===void 0?void 0:wA(L(e),t)}function EA(e,t){return e.machines!==t.machines}function DA(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function OA(e,t){return kA(e,t)}function kA(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function AA(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function jA(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];return r?.id===e.id&&r.status===e.status&&r.exitCode===e.exitCode&&r.durationMs===e.durationMs})}function MA(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];return r?.sessionId===e.sessionId&&r.status===e.status})}function NA(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];return r?.runId===e.runId&&r.status===e.status&&r.elapsedMs===e.elapsedMs&&r.lastActivity===e.lastActivity})}function PA(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function FA(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function IA(e){return Us(e.status,e.activity)}function LA(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function RA(){return{}}function zA(e,t){return JSON.stringify([e,t])}function BA(e){return dA[Math.min(e,dA.length-1)]??3e4}function VA(e){return e instanceof Error?e.message:String(e)}function HA(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function UA(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function WA(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{h as _,dg as a,hs as c,x as d,b as f,g,Xe as h,pg as i,No as l,v as m,H as n,Bp as o,y as p,fg as r,zp as s,Ex as t,S as u};
|