@chainingintention/pi-web-cn 1.202608.3 → 1.202608.4
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-4gPJstDS.js → CodeViewer-CWHRo84w.js} +1 -1
- package/dist/client/assets/{TerminalPanel-BOafuuU6.js → TerminalPanel-CoYwbZrx.js} +1 -1
- package/dist/client/assets/{UnifiedDiffViewer-BZewUESj.js → UnifiedDiffViewer-DbtJHQ4S.js} +1 -1
- package/dist/client/assets/{index-DHGDF1O1.js → index-Bdbjyy7F.js} +228 -218
- package/dist/client/index.html +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeViewer-CWHRo84w.js","./vendor-editor-core-vUi74DnD.js","./vendor-editor-languages-DoaXUodB.js","./vendor-editor-legacy-CYBnW6ZU.js","./TerminalPanel-CoYwbZrx.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,X as o,Z as s,d as c,f as l,j as u,l as d,p as f,q as p,u as m}from"./vendor-editor-core-vUi74DnD.js";import{a as ee,o as te,s as ne}from"./vendor-editor-languages-DoaXUodB.js";(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 re=globalThis,ie=re.ShadowRoot&&(re.ShadyCSS===void 0||re.ShadyCSS.nativeShadow)&&`adoptedStyleSheets`in Document.prototype&&`replace`in CSSStyleSheet.prototype,ae=Symbol(),oe=new WeakMap,se=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==ae)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(ie&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=oe.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&oe.set(t,e))}return e}toString(){return this.cssText}},ce=e=>new se(typeof e==`string`?e:e+``,void 0,ae),h=(e,...t)=>new se(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,ae),le=(e,t)=>{if(ie)e.adoptedStyleSheets=t.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(let n of t){let t=document.createElement(`style`),r=re.litNonce;r!==void 0&&t.setAttribute(`nonce`,r),t.textContent=n.cssText,e.appendChild(t)}},ue=ie?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t=``;for(let n of e.cssRules)t+=n.cssText;return ce(t)})(e):e,{is:de,defineProperty:fe,getOwnPropertyDescriptor:pe,getOwnPropertyNames:me,getOwnPropertySymbols:he,getPrototypeOf:ge}=Object,_e=globalThis,ve=_e.trustedTypes,ye=ve?ve.emptyScript:``,be=_e.reactiveElementPolyfillSupport,xe=(e,t)=>e,Se={toAttribute(e,t){switch(t){case Boolean:e=e?ye: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}},Ce=(e,t)=>!de(e,t),we={attribute:!0,type:String,converter:Se,reflect:!1,useDefault:!1,hasChanged:Ce};Symbol.metadata??=Symbol(`metadata`),_e.litPropertyMetadata??=new WeakMap;var Te=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=we){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&&fe(this.prototype,e,r)}}static getPropertyDescriptor(e,t,n){let{get:r,set:i}=pe(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)??we}static _$Ei(){if(this.hasOwnProperty(xe(`elementProperties`)))return;let e=ge(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(xe(`finalized`)))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(xe(`properties`))){let e=this.properties,t=[...me(e),...he(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(ue(e))}else e!==void 0&&t.push(ue(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 le(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?Se: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?Se: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??Ce)(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){}};Te.elementStyles=[],Te.shadowRootOptions={mode:`open`},Te[xe(`elementProperties`)]=new Map,Te[xe(`finalized`)]=new Map,be?.({ReactiveElement:Te}),(_e.reactiveElementVersions??=[]).push(`2.1.2`);var Ee=globalThis,De=e=>e,Oe=Ee.trustedTypes,ke=Oe?Oe.createPolicy(`lit-html`,{createHTML:e=>e}):void 0,Ae=`$lit$`,je=`lit$${Math.random().toFixed(9).slice(2)}$`,Me=`?`+je,Ne=`<${Me}>`,Pe=document,Fe=()=>Pe.createComment(``),Ie=e=>e===null||typeof e!=`object`&&typeof e!=`function`,Le=Array.isArray,Re=e=>Le(e)||typeof e?.[Symbol.iterator]==`function`,ze=`[
|
|
3
3
|
\f\r]`,Be=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ve=/-->/g,He=/>/g,Ue=RegExp(`>|${ze}(?:([^\\s"'>=/]+)(${ze}*=${ze}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,`g`),We=/'/g,Ge=/"/g,Ke=/^(?:script|style|textarea|title)$/i,qe=e=>(t,...n)=>({_$litType$:e,strings:t,values:n}),g=qe(1),Je=qe(2),Ye=Symbol.for(`lit-noChange`),_=Symbol.for(`lit-nothing`),Xe=new WeakMap,Ze=Pe.createTreeWalker(Pe,129);function Qe(e,t){if(!Le(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return ke===void 0?t:ke.createHTML(t)}var $e=(e,t)=>{let n=e.length-1,r=[],i,a=t===2?`<svg>`:t===3?`<math>`:``,o=Be;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===Be?c[1]===`!--`?o=Ve:c[1]===void 0?c[2]===void 0?c[3]!==void 0&&(o=Ue):(Ke.test(c[2])&&(i=RegExp(`</`+c[2],`g`)),o=Ue):o=He:o===Ue?c[0]===`>`?(o=i??Be,l=-1):c[1]===void 0?l=-2:(l=o.lastIndex-c[2].length,s=c[1],o=c[3]===void 0?Ue:c[3]===`"`?Ge:We):o===Ge||o===We?o=Ue:o===Ve||o===He?o=Be:(o=Ue,i=void 0);let d=o===Ue&&e[t+1].startsWith(`/>`)?` `:``;a+=o===Be?n+Ne:l>=0?(r.push(s),n.slice(0,l)+Ae+n.slice(l)+je+d):n+je+(l===-2?t:d)}return[Qe(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},et=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]=$e(t,n);if(this.el=e.createElement(l,r),Ze.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=Ze.nextNode())!==null&&c.length<s;){if(i.nodeType===1){if(i.hasAttributes())for(let e of i.getAttributeNames())if(e.endsWith(Ae)){let t=u[o++],n=i.getAttribute(e).split(je),r=/([.?@])?(.*)/.exec(t);c.push({type:1,index:a,name:r[2],strings:n,ctor:r[1]===`.`?at:r[1]===`?`?ot:r[1]===`@`?st:it}),i.removeAttribute(e)}else e.startsWith(je)&&(c.push({type:6,index:a}),i.removeAttribute(e));if(Ke.test(i.tagName)){let e=i.textContent.split(je),t=e.length-1;if(t>0){i.textContent=Oe?Oe.emptyScript:``;for(let n=0;n<t;n++)i.append(e[n],Fe()),Ze.nextNode(),c.push({type:2,index:++a});i.append(e[t],Fe())}}}else if(i.nodeType===8)if(i.data===Me)c.push({type:2,index:a});else{let e=-1;for(;(e=i.data.indexOf(je,e+1))!==-1;)c.push({type:7,index:a}),e+=je.length-1}a++}}static createElement(e,t){let n=Pe.createElement(`template`);return n.innerHTML=e,n}};function tt(e,t,n=e,r){if(t===Ye)return t;let i=r===void 0?n._$Cl:n._$Co?.[r],a=Ie(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=tt(e,i._$AS(e,t.values),i,r)),t}var nt=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??Pe).importNode(t,!0);Ze.currentNode=r;let i=Ze.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new rt(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new ct(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=Ze.nextNode(),a++)}return Ze.currentNode=Pe,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++}},rt=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=tt(this,e,t),Ie(e)?e===_||e==null||e===``?(this._$AH!==_&&this._$AR(),this._$AH=_):e!==this._$AH&&e!==Ye&&this._(e):e._$litType$===void 0?e.nodeType===void 0?Re(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!==_&&Ie(this._$AH)?this._$AA.nextSibling.data=e:this.T(Pe.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=et.createElement(Qe(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new nt(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=Xe.get(e.strings);return t===void 0&&Xe.set(e.strings,t=new et(e)),t}k(t){Le(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(Fe()),this.O(Fe()),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=De(e).nextSibling;De(e).remove(),e=t}}setConnected(e){this._$AM===void 0&&(this._$Cv=e,this._$AP?.(e))}},it=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=tt(this,e,t,0),a=!Ie(e)||e!==this._$AH&&e!==Ye,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=tt(this,r[n+o],t,o),s===Ye&&(s=this._$AH[o]),a||=!Ie(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??``)}},at=class extends it{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===_?void 0:e}},ot=class extends it{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==_)}},st=class extends it{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=tt(this,e,t,0)??_)===Ye)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)}},ct=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){tt(this,e)}},lt={M:Ae,P:je,A:Me,C:1,L:$e,R:nt,D:Re,V:tt,I:rt,H:it,N:ot,U:st,B:at,F:ct},ut=Ee.litHtmlPolyfillSupport;ut?.(et,rt),(Ee.litHtmlVersions??=[]).push(`3.3.3`);var dt=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new rt(t.insertBefore(Fe(),e),e,void 0,n??{})}return i._$AI(e),i},ft=globalThis,v=class extends Te{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=dt(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ye}};v._$litElement$=!0,v.finalized=!0,ft.litElementHydrateSupport?.({LitElement:v});var pt=ft.litElementPolyfillSupport;pt?.({LitElement:v}),(ft.litElementVersions??=[]).push(`4.2.2`);var y=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},mt={attribute:!0,type:String,converter:Se,reflect:!1,hasChanged:Ce},ht=(e=mt,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`?ht(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 gt=(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 gt(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 gt(n,r,{get(){return a(this)}})}}var _t=`management`;function vt(e=Et()){return Tt(e)===_t}function yt(e=Dt()){return vt(e?.search)?`management`:`normal`}function bt(e,t=Dt(),n=`management`){return Ct(e,t,n,!0)}function xt(e,t=Dt(),n=`management`){return Ct(e,t,n,!1)}function St(e){if(e!==`management`||globalThis.history===void 0)return;let t=Dt();t===void 0||wt(t)?.token===void 0||(t.searchParams.delete(`token`),globalThis.history.replaceState(globalThis.history.state,``,`${t.pathname}${t.search}${t.hash}`))}function Ct(e,t,n,r){if(n===`normal`||t===void 0)return e;let i=wt(t);if(i===void 0)return e;let a=new URL(e,t.origin);return a.searchParams.set(`embed`,i.embed),i.token!==void 0&&a.searchParams.set(`token`,i.token),`${a.pathname}${a.search}${r?a.hash:``}`}function wt(e){if(e===void 0)return;let t=Tt(e.search),n=e.searchParams.get(`token`)?.trim();if(t===_t)return{embed:t,...n===void 0||n===``?{}:{token:n}}}function Tt(e){if(e===void 0||e===``)return;let t=new URLSearchParams(e).get(`embed`)?.trim();return t===``?void 0:t}function Et(){return typeof window>`u`?void 0:window.location.search}function Dt(){if(globalThis.location===void 0)return;let e=globalThis.location;if(typeof e.href==`string`&&e.href!==``)return new URL(e.href);let t=typeof e.protocol==`string`&&e.protocol!==``?e.protocol:`http:`,n=typeof e.host==`string`&&e.host!==``?e.host:`localhost`,r=typeof e.search==`string`?e.search:``;return new URL(`${t}//${n}/${r}`)}function Ot(e,t=At()){let n=new URL(t.viteBaseUrl,t.documentBaseUrl);return new URL(jt(e),n).toString()}function kt(e,t=At()){let n=new URL(Ot(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 At(){return{viteBaseUrl:`./`,documentBaseUrl:typeof document>`u`?`http://localhost/`:document.baseURI}}function jt(e){return e.startsWith(`/`)?`.${e}`:e}var Mt=yt();function Nt(e){Mt=e}function Pt(e){return Ot(bt(e,void 0,Mt))}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(Pt(e),{...n,headers:r});if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(It(e)??i.statusText)}return St(Mt),t(await i.json())}async function Ft(e,t){let n=await fetch(Pt(e));if(n.status===204){St(Mt);return}if(n.status!==404){if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(It(e)??n.statusText)}return St(Mt),t(await n.json())}}function It(e){if(Lt(e))return typeof e.error==`string`?e.error:void 0}function Lt(e){return typeof e==`object`&&!!e}var w={sessionsDeleteArchived:`sessions.deleteArchived`,sessionsBulkMutations:`sessions.bulkMutations`,sessionsCleanup:`sessions.cleanup`,sessionsReload:`sessions.reload`,sessionsClearQueue:`sessions.clearQueue`,sessionsPersistedState:`sessions.persistedState`,sessionsNotifications:`sessions.notifications`,sessionsUnread:`sessions.unread`,sessionsAskUser:`sessions.askUser`,promptAttachments:`prompt.attachments`,workspaceFileSuggestions:`workspace.fileSuggestions`,piPackagesManage:`piPackages.manage`,selectedMachineSettings:`settings.selectedMachine`,agentProfileConfig:`settings.agentProfile`},Rt=1e3,zt=32*1024,Bt=8*1024,Vt=1e3,Ht=4e3;function Ut(e){return(e.split(/[\\/]/u).at(-1)?.toLowerCase()??e.toLowerCase()).replace(/(?:\.[cm]?js|\.exe|\.cmd)$/iu,``)===`pi`}function Wt(e){return!e.includes(`/`)&&!e.includes(`\\`)&&Ut(e)}var Gt=new Set([`schemaVersion`,`revision`,`command`,`dir`,`sessionDirEnvKeys`]),Kt=/^sha256:[0-9a-f]{64}$/u,qt=/^[A-Za-z0-9_][A-Za-z0-9._+-]*$/u,Jt=new Set([`PI_WEB_AGENT_SESSION_DIR`,`PI_CODING_AGENT_SESSION_DIR`]);function Yt(e){if(!en(e)||Object.keys(e).some(e=>!Gt.has(e)))return;let t=e.schemaVersion,n=e.revision,r=e.command,i=e.dir,a=e.sessionDirEnvKeys;if(t===1&&!(typeof n!=`string`||!Kt.test(n))&&!(typeof r!=`string`||!Xt(r))&&!(typeof i!=`string`||!Zt(i))&&$t(a)&&new Set(a).size===a.length&&!(a[0]!==`PI_WEB_AGENT_SESSION_DIR`||a.some(e=>!Jt.has(e))))return Object.freeze({schemaVersion:t,revision:n,command:r,dir:i,sessionDirEnvKeys:Object.freeze([...a])})}function Xt(e){return e!==e.trim()||/[\s;&|`$<>]/u.test(e)?!1:Zt(e)?!e.endsWith(`/`)&&!e.endsWith(`\\`):qt.test(e)}function Zt(e){if(e===``||e!==e.trim()||Qt(e))return!1;let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function Qt(e){for(let t of e){let e=t.charCodeAt(0);if(e<32||e===127)return!0}return!1}function $t(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function en(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var tn=Object.values(w),nn=new Set(tn);w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.sessionsAskUser,w.promptAttachments,w.workspaceFileSuggestions,w.piPackagesManage,w.selectedMachineSettings,w.agentProfileConfig,w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.sessionsAskUser,w.promptAttachments,w.sessionsDeleteArchived,w.sessionsBulkMutations,w.sessionsCleanup,w.sessionsReload,w.sessionsClearQueue,w.sessionsPersistedState,w.sessionsNotifications,w.sessionsUnread,w.sessionsAskUser,w.promptAttachments,w.workspaceFileSuggestions,w.piPackagesManage,w.selectedMachineSettings,w.agentProfileConfig;function rn(e){return typeof e==`string`&&nn.has(e)}function T(e,t){return e?.capabilities?.includes(t)===!0}function an(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(rn)}function on(e){return typeof e==`object`&&!!e}function E(e){if(!on(e))throw Error(`Expected object response`);return e}function D(e,t){let n=e[t];if(typeof n!=`string`)throw Error(`Expected string field: ${t}`);return n}function O(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`string`)throw Error(`Expected optional string field: ${t}`);return n}}function k(e,t){let n=e[t];if(typeof n!=`number`)throw Error(`Expected number field: ${t}`);return n}function A(e,t){let n=e[t];if(typeof n!=`boolean`)throw Error(`Expected boolean field: ${t}`);return n}function j(e){return t=>{if(!Array.isArray(t))throw Error(`Expected array response`);return t.map(e)}}function sn(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function cn(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function ln(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};let t=E(e);return{messages:sn(t.messages),start:k(t,`start`),total:k(t,`total`)}}function un(e){let t=E(e);return j(dn)(t.machines)}function dn(e){let t=E(e),n=mn(t,`kind`),r=O(t,`baseUrl`),i=hn(t,`status`),a=O(t,`statusMessage`);return{id:D(t,`id`),name:D(t,`name`),kind:n,...r===void 0?{}:{baseUrl:r},createdAt:D(t,`createdAt`),updatedAt:D(t,`updatedAt`),...i===void 0?{}:{status:i},...a===void 0?{}:{statusMessage:a}}}function fn(e){let t=E(e),n=hn(t,`status`),r=O(t,`error`);return{machineId:D(t,`machineId`),ok:A(t,`ok`),checkedAt:D(t,`checkedAt`),...n===void 0?{}:{status:n},...t.web===void 0?{}:{web:Wi(t.web)},...t.sessiond===void 0?{}:{sessiond:Wi(t.sessiond)},...r===void 0?{}:{error:r}}}function pn(e){let t=E(e),n=O(t,`error`);return{machineId:D(t,`machineId`),ok:A(t,`ok`),checkedAt:D(t,`checkedAt`),...M(`packageName`,O(t,`packageName`)),...M(`generatedAt`,O(t,`generatedAt`)),...t.components===void 0?{}:{components:Hi(t.components)},...t.capabilities===void 0?{}:{capabilities:Xi(t.capabilities)},...n===void 0?{}:{error:n}}}function mn(e,t){let n=D(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function hn(e,t){let n=O(e,t);if(n!==void 0){if(n!==`unknown`&&n!==`online`&&n!==`offline`&&n!==`error`)throw Error(`Expected machine status field: ${t}`);return n}}function gn(e){let t=E(e);return{id:D(t,`id`),name:D(t,`name`),path:D(t,`path`),createdAt:D(t,`createdAt`)}}function _n(e){let t=E(e),n=O(t,`branch`);return{id:D(t,`id`),projectId:D(t,`projectId`),path:D(t,`path`),label:D(t,`label`),...n===void 0?{}:{branch:n},isMain:A(t,`isMain`),isGitRepo:A(t,`isGitRepo`),isGitWorktree:A(t,`isGitWorktree`),...M(`effectiveConfig`,vn(t.effectiveConfig))}}function vn(e){if(e!==void 0){if(!on(e)||Array.isArray(e))throw Error(`Invalid workspace effectiveConfig field`);return{...M(`uploads`,Si(e.uploads))}}}function yn(e){let t=E(e),n=O(t,`name`),r=Li(t.persisted,`persisted`),i=O(t,`parentSessionPath`),a=O(t,`parentSessionCwd`),o=O(t,`parentSessionId`),s=Ri(t.childSessionsElsewhere,`childSessionsElsewhere`),c=O(t,`archivedAt`);return{id:D(t,`id`),path:D(t,`path`),cwd:D(t,`cwd`),...r===void 0?{}:{persisted:r},...n===void 0?{}:{name:n},created:D(t,`created`),modified:D(t,`modified`),messageCount:k(t,`messageCount`),firstMessage:D(t,`firstMessage`),...i===void 0?{}:{parentSessionPath:i},...a===void 0?{}:{parentSessionCwd:a},...o===void 0?{}:{parentSessionId:o},...s===void 0?{}:{childSessionsElsewhere:s},...t.archived===!0?{archived:!0}:{},...c===void 0?{}:{archivedAt:c}}}function bn(e){let t=E(e);return{configured:A(t,`configured`),authenticated:A(t,`authenticated`)}}function xn(e){return{path:D(E(e),`path`)}}function Sn(e){let t=E(e);if(t.deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0,path:D(t,`path`)}}function Cn(e){return{sessionIds:cn(E(e).sessionIds,`sessionIds`)}}function wn(e){return{pinned:A(E(e),`pinned`)}}function Tn(e){let t=E(e);return{results:j(En)(t.results),matchCount:k(t,`matchCount`),truncated:A(t,`truncated`)}}function En(e){let t=E(e);return{session:yn(t.session),matches:j(Dn)(t.matches)}}function Dn(e){let t=E(e),n=D(t,`role`);if(n!==`user`&&n!==`assistant`)throw Error(`Invalid session content search role`);return{messageIndex:k(t,`messageIndex`),role:n,excerpts:j(On)(t.excerpts),occurrenceCount:k(t,`occurrenceCount`)}}function On(e){let t=E(e);return{text:D(t,`text`),matchRanges:j(e=>{let t=E(e);return{start:k(t,`start`),length:k(t,`length`)}})(t.matchRanges)}}function kn(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function An(e){if(e!==void 0)return{id:D(E(e),`id`)}}function jn(e){let t=E(e),n=An(t.dismiss);return{severity:kn(t.severity),message:D(t,`message`),...M(`source`,O(t,`source`)),...M(`path`,O(t,`path`)),...n===void 0?{}:{dismiss:n}}}function Mn(e){return e===void 0?{}:{warnings:j(jn)(e)}}function Nn(e){let t=E(e);return{value:tr(t,`value`,128),label:tr(t,`label`,Vt),...M(`detail`,nr(t,`detail`,Vt))}}function Pn(e){let t=E(e),n=pr(t.options,Nn,12,`options`);Un(n.map(e=>e.value),`ask option value`),Li(t.allowOther,`allowOther`);let r=Li(t.multiple,`multiple`);return{id:tr(t,`id`,128),question:tr(t,`question`,Vt),...M(`detail`,nr(t,`detail`,Vt)),options:n,allowOther:!0,...r===void 0?{}:{multiple:r}}}function Fn(e){let t=E(e),n=pr(t.questions,Pn,20,`questions`);if(n.length===0)throw Error(`Pending ask has no questions`);return Un(n.map(e=>e.id),`ask question id`),{askId:tr(t,`askId`,128),askedAt:hr(t,`askedAt`),questions:n}}function In(e){return e===void 0?{}:{pendingAsk:Fn(e)}}function Ln(e){let t=E(e);if(t.type!==`ask.opened`)throw Error(`Invalid ask opened event type`);return{type:`ask.opened`,ask:Fn(t.ask)}}function Rn(e){let t=E(e);if(t.type!==`ask.closed`)throw Error(`Invalid ask closed event type`);return{type:`ask.closed`,askId:tr(t,`askId`,128),reason:zn(t.reason)}}function zn(e){if(e!==`submitted`&&e!==`superseded`&&e!==`cancelled`)throw Error(`Invalid ask close reason`);return e}function Bn(e){let t=E(e),n=Pn(t.question),r=pr(t.values,mr,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=nr(t,`otherText`,Ht),o=A(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 Vn(e){let t=E(e),n=pr(t.questions,Bn,20,`questions`),r=gr(t,`answeredCount`),i=cn(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:tr(t,`askId`,128),reason:zn(t.reason),askedAt:hr(t,`askedAt`),closedAt:hr(t,`closedAt`),questions:n,answeredCount:r,unansweredIds:i,summary:hr(t,`summary`)}}function Hn(e){let t=E(e),n=t.result;if(n!==`closed`&&n!==`stale`)throw Error(`Invalid ask close result`);let r=t.outcome===void 0?void 0:Vn(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Ask close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:Wn(t.sessionStatus)}}function Un(e,t){if(new Set(e).size!==e.length)throw Error(`Duplicate ${t}`)}function Wn(e){let t=E(e);return{sessionId:D(t,`sessionId`),...M(`persisted`,Li(t.persisted,`persisted`)),isStreaming:A(t,`isStreaming`),isCompacting:A(t,`isCompacting`),isBashRunning:A(t,`isBashRunning`),pendingMessageCount:k(t,`pendingMessageCount`),queuedMessages:t.queuedMessages===void 0?[]:j(kr)(t.queuedMessages),...M(`messageCount`,xa(t,`messageCount`)),tokens:Ar(t.tokens),cost:k(t,`cost`),...Mr(t.model),...Xr(t.contextUsage),...M(`thinkingLevel`,O(t,`thinkingLevel`)),...Mn(t.warnings),...In(t.pendingAsk)}}function Gn(e){let t=E(e);return{seq:k(t,`seq`),partial:t.partial??null}}function Kn(e){let t=E(e),n=gr(t,`catalogRevision`),r=pr(t.sessions,Qn,Rt,`sessions`);if($n(r),er(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:tr(t,`catalogId`,512),catalogRevision:n,sessions:r}}function qn(e){let t=E(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=tr(t,`sessionId`,512),r=tr(t,`cwd`,zt),i=rr(t,`catalogRevision`),a=t.unread===null?null:Qn(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:tr(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function Jn(e){let t=E(e);if(t.type!==`session.startup`)throw Error(`Invalid session startup event type`);let n=O(t,`startupToken`);if(n===``)throw Error(`Expected non-empty string field: startupToken`);return{type:`session.startup`,...M(`startupToken`,n),activity:Yn(t.activity)}}function Yn(e){let t=E(e);return{sessionId:hr(t,`sessionId`),phase:Zn(t,`phase`),label:hr(t,`label`),...M(`detail`,O(t,`detail`)),at:hr(t,`at`),...M(`startup`,Xn(t))}}function Xn(e){let t=e.startup;if(t!==void 0){if(typeof t!=`boolean`)throw Error(`Expected optional boolean field: startup`);return t}}function Zn(e,t){let n=D(e,t);if(n!==`active`&&n!==`idle`&&n!==`error`)throw Error(`Expected session activity phase field: ${t}`);return n}function Qn(e){let t=E(e),n=tr(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:tr(t,`sessionId`,512),cwd:tr(t,`cwd`,zt),completionOrder:rr(t,`completionOrder`),completedAt:n}}function $n(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 er(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 tr(e,t,n){let r=hr(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function nr(e,t,n){let r=O(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 rr(e,t){let n=gr(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function ir(e){let t=E(e),n=or(t.summary),r=pr(t.notifications,sr,100,`notifications`);if(_r(r),vr(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==br(r))throw Error(`Notification snapshot severity mismatch`);let i=cr(t.dismissThrough),a=r[0]?.order??0;if(i.order!==a)throw Error(`Notification snapshot dismiss cutoff mismatch`);if(i.overflowWatermark<n.discardedCount)throw Error(`Notification snapshot overflow cutoff mismatch`);return{daemonInstanceId:hr(t,`daemonInstanceId`),catalogRevision:gr(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function ar(e){let t=E(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=or(t.summary),r=cr(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=lr(t.delta);if(i.kind===`cleared`&&!yr(n))throw Error(`Notification clear event summary mismatch`);if(i.kind===`added`&&n.retainedCount===0)throw Error(`Notification add event summary mismatch`);return{type:`notifications.inbox`,daemonInstanceId:hr(t,`daemonInstanceId`),catalogRevision:gr(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function or(e){let t=E(e),n=gr(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=gr(t,`discardedCount`),i=dr(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:hr(t,`sessionId`),cwd:hr(t,`cwd`),inboxRevision:gr(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function sr(e){let t=E(e),n=D(t,`message`);if(new TextEncoder().encode(n).byteLength>8192)throw Error(`Notification message exceeds byte limit`);let r=D(t,`receivedAt`);if(!Number.isFinite(Date.parse(r)))throw Error(`Invalid notification receive time`);let i=gr(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:hr(t,`id`),message:n,truncated:A(t,`truncated`),severity:ur(t.severity),receivedAt:r,order:i}}function cr(e){let t=E(e);return{order:gr(t,`order`),overflowWatermark:gr(t,`overflowWatermark`)}}function lr(e){let t=E(e);switch(t.kind){case`added`:{let e=O(t,`evictedNotificationId`);return{kind:`added`,notification:sr(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=pr(t.notificationIds,mr,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:fr(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function ur(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function dr(e){return e===void 0?void 0:ur(e)}function fr(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 pr(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 mr(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function hr(e,t){let n=D(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function gr(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 _r(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 vr(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 yr(e){return e.retainedCount===0&&e.discardedCount===0}function br(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function xr(e){let t=E(e),n=t.skippedBusySessionIds===void 0?void 0:cn(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:D(t,`generatedAt`),thresholds:Er(t.thresholds),projects:j(Dr)(t.projects),totals:Or(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function Sr(e){let t=E(e);return{...xr(t),archivedSessionIds:cn(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:cn(t.deletedSessionIds,`deletedSessionIds`)}}function Cr(e){let t=E(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:cn(t.archivedSessionIds,`archivedSessionIds`),failures:j(Tr)(t.failures),generatedAt:D(t,`generatedAt`)}}function wr(e){let t=E(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:cn(t.deletedSessionIds,`deletedSessionIds`),failures:j(Tr)(t.failures),generatedAt:D(t,`generatedAt`)}}function Tr(e){let t=E(e);return{sessionId:D(t,`sessionId`),error:D(t,`error`)}}function Er(e){let t=E(e);return{...M(`archiveIdleDays`,xa(t,`archiveIdleDays`)),...M(`deleteArchivedDays`,xa(t,`deleteArchivedDays`))}}function Dr(e){let t=E(e);return{cwd:D(t,`cwd`),archiveCount:k(t,`archiveCount`),deleteCount:k(t,`deleteCount`)}}function Or(e){let t=E(e);return{archiveCount:k(t,`archiveCount`),deleteCount:k(t,`deleteCount`)}}function kr(e){let t=E(e),n=D(t,`kind`);if(n!==`steer`&&n!==`followUp`)throw Error(`Invalid queued message kind`);return{kind:n,text:D(t,`text`)}}function Ar(e){let t=E(e);return{input:k(t,`input`),output:k(t,`output`),cacheRead:k(t,`cacheRead`),cacheWrite:k(t,`cacheWrite`),total:k(t,`total`)}}function jr(e){let t=E(e);return{...M(`provider`,O(t,`provider`)),...M(`id`,O(t,`id`)),...M(`name`,O(t,`name`)),...M(`contextWindow`,xa(t,`contextWindow`)),...M(`reasoning`,t.reasoning)}}function Mr(e){return e===void 0?{}:{model:jr(e)}}function Nr(e){let t=E(e);return{models:j(jr)(t.models)}}function Pr(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function Fr(e){let t=E(e);return{levels:j(Pr)(t.levels)}}function Ir(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function Lr(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 Rr(e){let t=E(e),n=t.source===void 0?void 0:Lr(t.source);return{configured:A(t,`configured`),...M(`source`,n),...M(`label`,O(t,`label`))}}function zr(e){let t=E(e),n=t.loginFlow;if(n!==void 0&&n!==`interactive`)throw Error(`Invalid auth provider login flow`);return{id:D(t,`id`),name:D(t,`name`),authType:Ir(t.authType),status:Rr(t.status),...n===void 0?{}:{loginFlow:n}}}function Br(e){let t=E(e);return{providers:j(zr)(t.providers)}}function Vr(e){let t=E(e);return{flowId:D(t,`flowId`),providerId:D(t,`providerId`),providerName:D(t,`providerName`),status:Hr(t.status),progress:j(e=>{if(typeof e!=`string`)throw Error(`Expected progress item string`);return e})(t.progress),...M(`error`,O(t,`error`)),...M(`auth`,Ur(t.auth)),...M(`prompt`,Gr(t.prompt)),...M(`select`,qr(t.select)),...M(`info`,Jr(t.info))}}function Hr(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function Ur(e){if(e===void 0)return;let t=E(e);return{url:D(t,`url`),...M(`instructions`,O(t,`instructions`)),...M(`deviceCode`,Wr(t.deviceCode))}}function Wr(e){if(e===void 0)return;let t=E(e);return{userCode:D(t,`userCode`),...M(`intervalSeconds`,xa(t,`intervalSeconds`)),...M(`expiresInSeconds`,xa(t,`expiresInSeconds`))}}function Gr(e){if(e===void 0)return;let t=E(e),n=D(t,`kind`);if(n!==`prompt`&&n!==`manual`)throw Error(`Invalid OAuth prompt kind`);let r=t.promptType===void 0?n===`manual`?`manual_code`:`text`:Kr(t.promptType);return{requestId:D(t,`requestId`),message:D(t,`message`),kind:n,promptType:r,...M(`placeholder`,O(t,`placeholder`)),...M(`allowEmpty`,ba(t,`allowEmpty`))}}function Kr(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function qr(e){if(e===void 0)return;let t=E(e);return{requestId:D(t,`requestId`),message:D(t,`message`),options:j(sa)(t.options)}}function Jr(e){if(e!==void 0)return j(e=>{let t=E(e);return{message:D(t,`message`),...M(`links`,t.links===void 0?void 0:j(Yr)(t.links))}})(e)}function Yr(e){let t=E(e);return{url:D(t,`url`),...M(`label`,O(t,`label`))}}function Xr(e){if(e===void 0)return{};let t=E(e);return{contextUsage:{tokens:Sa(t,`tokens`),contextWindow:k(t,`contextWindow`),percent:Sa(t,`percent`)}}}function Zr(e){let t=E(e),n=D(t,`source`);if(n!==`extension`&&n!==`prompt`&&n!==`skill`&&n!==`builtin`)throw Error(`Invalid command source`);return{name:D(t,`name`),source:n,...M(`description`,O(t,`description`))}}function Qr(e){let t=E(e),n=D(t,`kind`);if(n!==`tracked`&&n!==`untracked`&&n!==`other`)throw Error(`Invalid file kind`);return{path:D(t,`path`),kind:n}}function $r(e){let t=E(e);return{path:D(t,`path`),entries:j(ei)(t.entries),scannedAt:D(t,`scannedAt`),truncated:A(t,`truncated`)}}function ei(e){let t=E(e),n=D(t,`type`);if(n!==`file`&&n!==`directory`&&n!==`symlink`)throw Error(`Invalid file tree entry type`);return{name:D(t,`name`),path:D(t,`path`),type:n,...M(`size`,xa(t,`size`)),...M(`modifiedAt`,O(t,`modifiedAt`))}}function ti(e){let t=E(e),n=D(t,`encoding`);if(n!==`utf8`)throw Error(`Invalid file encoding`);return{path:D(t,`path`),...M(`language`,O(t,`language`)),...M(`mediaType`,ai(t.mediaType)),...M(`mimeType`,O(t,`mimeType`)),encoding:n,size:k(t,`size`),modifiedAt:D(t,`modifiedAt`),content:D(t,`content`),truncated:A(t,`truncated`),binary:A(t,`binary`)}}function ni(e){let t=E(e);return{path:D(t,`path`),size:k(t,`size`),modifiedAt:D(t,`modifiedAt`),created:A(t,`created`)}}function ri(e){let t=E(e);return{path:D(t,`path`),existed:A(t,`existed`)}}function ii(e){let t=E(e);return{fromPath:D(t,`fromPath`),toPath:D(t,`toPath`),size:k(t,`size`),modifiedAt:D(t,`modifiedAt`)}}function ai(e){if(e!==void 0){if(e!==`image`)throw Error(`Invalid file media type`);return e}}function oi(e){let t=E(e);return{isGitRepo:A(t,`isGitRepo`),hash:D(t,`hash`),...M(`branch`,O(t,`branch`)),...M(`upstream`,O(t,`upstream`)),...M(`ahead`,xa(t,`ahead`)),...M(`behind`,xa(t,`behind`)),files:j(si)(t.files),submodules:t.submodules===void 0?[]:cn(t.submodules,`submodules`)}}function si(e){let t=E(e);return{path:D(t,`path`),...M(`oldPath`,O(t,`oldPath`)),index:ci(t.index),workingTree:ci(t.workingTree),...M(`submoduleFromCommit`,O(t,`submoduleFromCommit`)),...M(`submoduleToCommit`,O(t,`submoduleToCommit`))}}function ci(e){switch(e){case`unmodified`:case`modified`:case`added`:case`deleted`:case`renamed`:case`copied`:case`untracked`:case`ignored`:case`conflicted`:return e;default:throw Error(`Invalid git file state`)}}function li(e){let t=E(e);return{...M(`path`,O(t,`path`)),staged:A(t,`staged`),hash:D(t,`hash`),diff:D(t,`diff`),truncated:A(t,`truncated`)}}function ui(e){let t=E(e);return{id:D(t,`id`),cwd:D(t,`cwd`),name:D(t,`name`),createdAt:D(t,`createdAt`),exited:A(t,`exited`),...M(`exitCode`,xa(t,`exitCode`)),...M(`commandRunId`,O(t,`commandRunId`))}}function di(e){let t=E(e);return{id:D(t,`id`),origin:D(t,`origin`),projectId:D(t,`projectId`),workspaceId:D(t,`workspaceId`),terminalId:D(t,`terminalId`),title:D(t,`title`),command:D(t,`command`),status:fi(t.status),...M(`exitCode`,xa(t,`exitCode`)),createdAt:D(t,`createdAt`),...M(`startedAt`,O(t,`startedAt`)),...M(`completedAt`,O(t,`completedAt`)),metadata:pi(t.metadata,`metadata`)}}function fi(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function pi(e,t){let n=E(e);return Object.fromEntries(Object.entries(n).map(([e,n])=>{if(typeof n!=`string`)throw Error(`Expected string record field: ${t}.${e}`);return[e,n]}))}function mi(e){let t=E(e);return{cwd:D(t,`cwd`),hasSessionActivity:A(t,`hasSessionActivity`),hasTerminalActivity:A(t,`hasTerminalActivity`),updatedAt:D(t,`updatedAt`)}}function hi(e){let t=E(e);return{workspaces:j(mi)(t.workspaces),generatedAt:D(t,`generatedAt`)}}function gi(e){let t=E(e);return{path:D(t,`path`),exists:A(t,`exists`),config:_i(t.config),effectiveConfig:_i(t.effectiveConfig),envOverrides:Di(t.envOverrides)}}function _i(e){let t=E(e);return{...M(`host`,O(t,`host`)),...M(`port`,xa(t,`port`)),...M(`allowedHosts`,yi(t.allowedHosts)),...M(`shortcuts`,Ti(t.shortcuts)),...M(`plugins`,Ei(t.plugins)),...M(`pathAccess`,bi(t.pathAccess)),...M(`uploads`,Si(t.uploads)),...M(`maxUploadBytes`,xa(t,`maxUploadBytes`)),...M(`agent`,vi(t.agent)),...M(`spawnSessions`,ba(t,`spawnSessions`)),...M(`subsessions`,ba(t,`subsessions`)),...M(`askUser`,ba(t,`askUser`))}}function vi(e){if(e!==void 0){if(!on(e)||Array.isArray(e))throw Error(`Invalid PI WEB agent field`);return{...M(`command`,O(e,`command`)),...M(`dir`,O(e,`dir`))}}}function yi(e){if(e!==void 0){if(e===!0)return!0;if(Ci(e))return e;throw Error(`Invalid PI WEB allowedHosts field`)}}function bi(e){if(e===void 0)return;if(!on(e))throw Error(`Invalid PI WEB pathAccess field`);let t=e.allowedPaths;return{...M(`allowedPaths`,xi(t,`pathAccess.allowedPaths`))}}function xi(e,t){if(e!==void 0){if(wi(e))return e;throw Error(`Invalid PI WEB ${t} field`)}}function Si(e){if(e!==void 0){if(!on(e)||Array.isArray(e))throw Error(`Invalid PI WEB uploads field`);return{...M(`defaultFolder`,O(e,`defaultFolder`))}}}function Ci(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function wi(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function Ti(e){if(e!==void 0){if(!on(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 Ei(e){if(e!==void 0){if(!on(e)||Array.isArray(e))throw Error(`Invalid PI WEB plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!on(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&&(!on(r)||Array.isArray(r)))throw Error(`Invalid PI WEB plugin settings field`);return[e,t]}))}}function Di(e){let t=E(e);return{host:A(t,`host`),port:A(t,`port`),allowedHosts:A(t,`allowedHosts`),spawnSessions:A(t,`spawnSessions`),subsessions:A(t,`subsessions`),askUser:ba(t,`askUser`)??!1,agentCommand:ba(t,`agentCommand`)??!1,agentDir:ba(t,`agentDir`)??!1,...Oi(t),agentSessionDir:ba(t,`agentSessionDir`)??!1}}function Oi(e){let t=e.agentDirSource;if(t===void 0)return{};if(t!==`pi-web`&&t!==`pi-compatibility`)throw Error(`Invalid PI WEB agentDirSource field`);return{agentDirSource:t}}function ki(e){let t=E(e);return{packages:j(ji)(t.packages)}}function Ai(e){let t=E(e),n=O(t,`source`),r=t.scope===void 0?void 0:Mi(t.scope),i=Li(t.removed,`removed`);return{action:Ni(t.action),...M(`source`,n),...M(`scope`,r),...M(`removed`,i),packages:j(ji)(t.packages)}}function ji(e){let t=E(e);return{source:D(t,`source`),scope:Mi(t.scope),filtered:A(t,`filtered`),...M(`installedPath`,O(t,`installedPath`))}}function Mi(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function Ni(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function Pi(e){let t=E(e);return{plugins:j(Fi)(t.plugins)}}function Fi(e){let t=E(e);return{id:D(t,`id`),module:D(t,`module`),source:D(t,`source`),scope:Ii(t.scope),machineSpecific:Li(t.machineSpecific,`machineSpecific`)??!1,enabled:A(t,`enabled`)}}function Ii(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEB plugin scope`);return e}function Li(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function Ri(e,t){if(e!==void 0){if(typeof e!=`number`||!Number.isInteger(e)||e<0)throw Error(`Expected optional count field: ${t}`);return e===0?void 0:e}}function zi(e){let t=E(e);return{packageName:D(t,`packageName`),generatedAt:D(t,`generatedAt`),components:Vi(t.components),release:Ki(t.release),commands:qi(t.commands),messages:j(Ji)(t.messages)}}function Bi(e){let t=E(e);return{packageName:D(t,`packageName`),generatedAt:D(t,`generatedAt`),components:Hi(t.components),capabilities:Xi(t.capabilities)}}function Vi(e){let t=E(e);return{web:Wi(t.web),sessiond:Wi(t.sessiond)}}function Hi(e){let t=E(e);return{web:Ui(t.web),sessiond:Ui(t.sessiond)}}function Ui(e){let t=E(e),n=Yi(t.component),r=t.activeAgentProfile,i=r===void 0?void 0:Yt(r);if(r!==void 0&&(n!==`sessiond`||i===void 0))throw Error(`Invalid active agent profile descriptor`);return{component:n,label:D(t,`label`),...M(`runtimeVersion`,O(t,`runtimeVersion`)),available:A(t,`available`),capabilities:Xi(t.capabilities),...M(`activeAgentProfile`,i),...M(`error`,O(t,`error`))}}function Wi(e){let t=E(e);return{component:Yi(t.component),label:D(t,`label`),...M(`runtimeVersion`,O(t,`runtimeVersion`)),...M(`installedVersion`,O(t,`installedVersion`)),stale:A(t,`stale`),available:A(t,`available`),...M(`installation`,Gi(t.installation)),...M(`error`,O(t,`error`))}}function Gi(e){if(e===void 0)return;let t=E(e),n=D(t,`kind`);if(n!==`pi-package`&&n!==`npm-global`&&n!==`local`&&n!==`docker`&&n!==`unknown`)throw Error(`Invalid PI 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`,O(t,`path`)),...M(`source`,O(t,`source`)),...r===void 0?{}:{scope:r},...M(`npmRoot`,O(t,`npmRoot`)),...i===void 0?{}:{dockerMode:i}}}function Ki(e){let t=E(e);return{packageName:D(t,`packageName`),...M(`latestVersion`,O(t,`latestVersion`)),updateAvailable:A(t,`updateAvailable`),...M(`checkedAt`,O(t,`checkedAt`)),...t.skipped===!0?{skipped:!0}:{},...M(`error`,O(t,`error`))}}function qi(e){let t=E(e);return{...M(`update`,O(t,`update`)),...M(`restart`,O(t,`restart`)),...M(`restartWeb`,O(t,`restartWeb`)),...M(`restartSessiond`,O(t,`restartSessiond`)),...M(`status`,O(t,`status`))}}function Ji(e){let t=E(e);return{id:D(t,`id`),severity:Zi(t.severity),title:D(t,`title`),body:D(t,`body`),...M(`command`,O(t,`command`))}}function Yi(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEB service component`);return e}function Xi(e){let t=an(e);if(t===void 0)throw Error(`Invalid PI WEB capabilities`);return t}function Zi(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEB status severity`);return e}function Qi(e){let t=E(e),n=D(t,`type`);if(n===`unsupported`)return{type:n,message:D(t,`message`)};if(n===`select`)return{type:n,requestId:D(t,`requestId`),title:D(t,`title`),options:j(sa)(t.options)};if(n===`tree`)return{type:n,tree:$i(t.tree)};if(n===`done`)return{type:n,...M(`message`,O(t,`message`)),...ca(t.session),...M(`promptDraft`,O(t,`promptDraft`))};throw Error(`Invalid command result type`)}function $i(e){let t=E(e),n=j(ea)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=ia(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:oa(t.activePathIds,`activePathIds`)}}function ea(e){let t=E(e);return{id:aa(t,`id`),parentId:ia(t,`parentId`),kind:ta(t.kind),summary:D(t,`summary`),...M(`timestamp`,O(t,`timestamp`)),...M(`label`,O(t,`label`))}}function ta(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 na(e){let t=E(e),n=A(t,`cancelled`);if(Object.hasOwn(t,`summaryEntry`))throw Error(`Invalid session tree navigation result field: summaryEntry`);if(n){ra(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 ra(t,`aborted`,`session tree navigation result`),{cancelled:n,...M(`editorText`,O(t,`editorText`))}}function ra(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function ia(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 aa(e,t){let n=D(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function oa(e,t){let n=cn(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function sa(e){let t=E(e);return{value:D(t,`value`),label:D(t,`label`),...M(`description`,O(t,`description`))}}function ca(e){return e===void 0?{}:{session:yn(e)}}function la(e){if(E(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function ua(e){let t=E(e);return j(da)(t.attachments)}function da(e){let t=E(e);return{path:D(t,`path`),mimeType:D(t,`mimeType`),size:k(t,`size`)}}function fa(e){if(E(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function pa(e){if(E(e).aborted!==!0)throw Error(`Expected aborted response`);return{aborted:!0}}function ma(e){if(E(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function ha(e){let t=E(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:cn(t.sessionIds,`sessionIds`),r=xa(t,`archivedCount`),i=xa(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function ga(e){if(E(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function _a(e){if(E(e).deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0}}function va(e){if(E(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function ya(e){if(E(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function ba(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEB ${t} field`);return n}}function xa(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function Sa(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 Ca(e){return typeof e==`string`?e:e.id}function wa(e){return typeof e==`string`?void 0:e.cwd}function Ta(e,t,n,r){let i=new URLSearchParams;r?.path!==void 0&&i.set(`path`,r.path),r?.staged===!0&&i.set(`staged`,`true`);let a=i.toString();return`api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(n)}/git/diff${a?`?${a}`:``}`}function Ea(e,t,n=`local`){let r=new URLSearchParams,i=wa(e);i!==void 0&&i!==``&&r.set(`cwd`,i),t?.limit!==void 0&&r.set(`limit`,String(t.limit)),t?.before!==void 0&&r.set(`before`,String(t.before));let a=r.toString();return`api/machines/${encodeURIComponent(n)}/sessions/${encodeURIComponent(Ca(e))}/messages${a===``?``:`?${a}`}`}function Da(e,t,n,r){let i=new URLSearchParams({path:n});return r?.createDirs===!1&&i.set(`createDirs`,`false`),r?.overwrite===!1&&i.set(`overwrite`,`false`),Ot(bt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`))}function Oa(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),Ot(bt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`))}function ka(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),Ot(bt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${i.toString()}`))}var N=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`;function Aa(e){return typeof e==`string`?e:e.id}function ja(e){return typeof e==`string`?void 0:e.cwd}function Ma(e,t=`local`){return`${N(t)}/sessions/${encodeURIComponent(Aa(e))}`}function P(e,t,n=`local`){return`${Ma(e,n)}/${t}`}function Na(e,t,n=`local`){return`${P(e,t,n)}${Fa(e)}`}function Pa(e,t=`local`){return`${Ma(e,t)}${Fa(e)}`}function Fa(e){let t=ja(e);return t===void 0||t===``?``:`?${new URLSearchParams({cwd:t}).toString()}`}function F(e,t={}){let n=ja(e);return JSON.stringify(n===void 0||n===``?t:{cwd:n,...t})}function Ia(e){return JSON.stringify({sessions:e.map(La)})}function La(e){let t=Aa(e),n=ja(e);return n===void 0||n===``?{id:t}:{id:t,cwd:n}}function Ra(e,t){let n=new URLSearchParams;t.projectId!==void 0&&n.set(`projectId`,t.projectId);let r=n.toString();return`${N(t.machineId)}/auth/${e}${r===``?``:`?${r}`}`}function za(e){return e===`local`?`api/pi-web/status`:`${N(e)}/pi-web/status`}var Ba={piWebStatus:(e=`local`)=>C(za(e),zi),checkForUpdates:(e=`local`)=>C(`${za(e)}?refresh=1`,zi,{cache:`no-store`}),piWebRuntime:()=>C(`api/pi-web/runtime`,Bi)},Va={machines:()=>C(`api/machines`,un),addMachine:e=>C(`api/machines`,dn,{method:`POST`,body:JSON.stringify(e)}),deleteMachine:e=>C(`api/machines/${encodeURIComponent(e)}`,e=>e,{method:`DELETE`}),health:e=>C(`api/machines/${encodeURIComponent(e)}/health`,fn),runtime:(e,t=!1)=>C(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,pn,t?{cache:`no-store`}:{})};function Ha(e){return e===void 0?`api/config`:`${N(e)}/config`}function Ua(e){return e===void 0?`api/plugins`:`${N(e)}/plugins`}var Wa={config:e=>C(Ha(e),gi),saveConfig:(e,t)=>C(Ha(t),gi,{method:`PUT`,body:JSON.stringify({config:e})})},Ga={status:()=>C(`api/normal-auth/status`,bn),setup:e=>C(`api/normal-auth/setup`,la,{method:`POST`,body:JSON.stringify({password:e})}),login:e=>C(`api/normal-auth/login`,la,{method:`POST`,body:JSON.stringify({password:e})}),changePassword:(e,t)=>C(`api/normal-auth/change-password`,la,{method:`POST`,body:JSON.stringify({currentPassword:e,newPassword:t})})},Ka={plugins:e=>C(Ua(e),Pi)};function qa(e=``,t){let n=t===void 0?`api/pi-packages`:`${N(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var Ja={packages:e=>C(qa(``,e),ki),install:(e,t)=>{let n={source:e};return C(qa(`install`,t),Ai,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return C(qa(`remove`,n),Ai,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return C(qa(`update`,t),Ai,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}},Ya={workspaceActivity:(e=`local`)=>C(`${N(e)}/activity`,hi)},Xa={projects:(e=`local`)=>C(`${N(e)}/projects`,j(gn)),addProject:(e,t,n,r=`local`)=>C(`${N(r)}/projects`,gn,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>C(`${N(t)}/projects/${encodeURIComponent(e)}`,fa,{method:`DELETE`}),projectDirectories:(e,t=`local`)=>C(`${N(t)}/project-directories?q=${encodeURIComponent(e)}`,j(Qr))};function Za(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()}`,ni,{method:`PUT`,body:c,headers:{"Content-Type":s?`application/octet-stream`:`text/plain`}})}var Qa={workspaces:(e,t=`local`)=>C(`${N(t)}/projects/${encodeURIComponent(e)}/workspaces`,j(_n)),deleteWorkspace:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,di,{method:`DELETE`}),workspaceTree:(e,t,n=``,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,$r),workspaceFile:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,ti),optionalWorkspaceFile:(e,t,n,r=`local`)=>Ft(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}&optional=true`,ti),createWorkspaceFile:(e,t,n,r=`local`)=>Za(e,t,n,new Uint8Array,void 0,r),writeWorkspaceFile:Za,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()}`,ri,{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()}`,ii,{method:`POST`})},createWorkspaceDirectory:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,xn,{method:`POST`,body:JSON.stringify({path:n})}),moveWorkspaceDirectory:(e,t,n,r,i=`local`)=>C(`${N(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,xn,{method:`PATCH`,body:JSON.stringify({fromPath:n,toPath:r})}),deleteWorkspaceDirectory:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(n)}`,Sn,{method:`DELETE`}),downloadWorkspaceFile:(e,t,n,r=`local`)=>io(e,t,n,r)},$a={sessions:(e,t=`local`)=>C(`${N(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(yn)),search:(e,t,n=`local`)=>C(`${N(n)}/sessions/search?${new URLSearchParams({cwd:e,q:t}).toString()}`,j(yn)),searchContent:(e,t,n=`local`)=>C(`${N(n)}/sessions/search-content?${new URLSearchParams({cwd:e,q:t}).toString()}`,Tn),pinned:(e,t=`local`)=>C(`${N(t)}/sessions/pins?cwd=${encodeURIComponent(e)}`,Cn),pin:(e,t=`local`)=>C(`${Ma(e,t)}/pin`,wn,{method:`PUT`,body:F(e)}),unpin:(e,t=`local`)=>C(`${Ma(e,t)}/pin${Fa(e)}`,wn,{method:`DELETE`}),unreadCatalog:(e=`local`)=>C(`${N(e)}/sessions/unread`,Kn,{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),Kn,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>C(Na(e,`notifications`,t),ir),dismissNotification:(e,t,n,r=`local`)=>C(P(e,`notifications/dismiss`,r),ir,{method:`POST`,body:F(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>C(P(e,`notifications/dismiss-all`,r),ir,{method:`POST`,body:F(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`,n)=>C(`${N(t)}/sessions`,yn,{method:`POST`,body:JSON.stringify(n===void 0?{cwd:e}:{cwd:e,startupToken:n})}),cleanupPreview:(e,t=`local`)=>C(`${N(t)}/sessions/cleanup/preview`,xr,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>C(`${N(t)}/sessions/cleanup`,Sr,{method:`POST`,body:JSON.stringify(e)}),archiveMany:(e,t=`local`)=>C(`${N(t)}/sessions/bulk/archive`,Cr,{method:`POST`,body:Ia(e)}),deleteArchivedMany:(e,t=`local`)=>C(`${N(t)}/sessions/bulk/delete-archived`,wr,{method:`POST`,body:Ia(e)}),messages:(e,t,n=`local`)=>C(Ea(e,t,n),ln),status:(e,t=`local`)=>C(Na(e,`status`,t),Wn),streamSnapshot:(e,t=`local`)=>C(Na(e,`stream-snapshot`,t),Gn),models:(e,t=`local`)=>C(Na(e,`models`,t),Nr),setModel:(e,t,n,r=`local`)=>C(P(e,`model`,r),Wn,{method:`POST`,body:F(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>C(P(e,`model/cycle`,n),Wn,{method:`POST`,body:F(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>C(Na(e,`thinking-levels`,t),Fr),setThinkingLevel:(e,t,n=`local`)=>C(P(e,`thinking-level`,n),Wn,{method:`POST`,body:F(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>C(P(e,`thinking-level/cycle`,t),Wn,{method:`POST`,body:F(e)}),commands:(e,t=`local`)=>C(Na(e,`commands`,t),j(Zr)),prompt:(e,t,n,r=`local`,i)=>C(P(e,`prompt`,r),la,{method:`POST`,body:F(e,{text:t,...n===void 0?{}:{streamingBehavior:n},...i!==void 0&&i.length>0?{attachments:i}:{}})}),saveAttachments:(e,t,n=`local`,r)=>C(P(e,`attachments`,n),ua,{method:`POST`,body:F(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>C(P(e,`shell`,n),la,{method:`POST`,body:F(e,{text:t})}),runCommand:(e,t,n=`local`)=>C(P(e,`commands/run`,n),Qi,{method:`POST`,body:F(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>C(P(e,`commands/respond`,r),Qi,{method:`POST`,body:F(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>C(P(e,`tree/navigate`,n),na,{method:`POST`,body:F(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary})}),abort:(e,t=`local`)=>C(P(e,`abort`,t),pa,{method:`POST`,body:F(e)}),stop:(e,t=`local`)=>C(P(e,`stop`,t),ma,{method:`POST`,body:F(e)}),archive:(e,t=`local`)=>C(P(e,`archive`,t),ha,{method:`POST`,body:F(e)}),archiveWithDescendants:(e,t=`local`)=>C(P(e,`archive-tree`,t),ha,{method:`POST`,body:F(e)}),restore:(e,t=`local`)=>C(P(e,`restore`,t),ga,{method:`POST`,body:F(e)}),deleteArchived:(e,t=`local`)=>C(Pa(e,t),_a,{method:`DELETE`}),detachParent:(e,t=`local`)=>C(P(e,`detach-parent`,t),va,{method:`POST`,body:F(e)}),reloadSession:(e,t=`local`)=>C(P(e,`reload`,t),ya,{method:`POST`,body:F(e)}),clearQueue:(e,t=`local`)=>C(P(e,`queue/clear`,t),Wn,{method:`POST`,body:F(e)}),dismissWarning:(e,t,n=`local`)=>C(P(e,`warnings/dismiss`,n),Wn,{method:`POST`,body:F(e,{dismissId:t})}),submitAsk:(e,t,n,r=`local`)=>C(P(e,`ask/submit`,r),Hn,{method:`POST`,body:F(e,{askId:t,answers:n.answers})}),cancelAsk:(e,t,n=`local`)=>C(P(e,`ask/cancel`,n),Hn,{method:`POST`,body:F(e,{askId:t})}),authProviders:e=>{let t=new URLSearchParams;e.mode!==void 0&&t.set(`mode`,e.mode),e.authType!==void 0&&t.set(`authType`,e.authType),e.projectId!==void 0&&t.set(`projectId`,e.projectId);let n=t.toString();return C(`${N(e.machineId)}/auth/providers${n===``?``:`?${n}`}`,Br)},saveApiKey:(e,t,n)=>C(Ra(`api-key`,n),la,{method:`POST`,body:JSON.stringify({providerId:e,key:t})}),startInteractiveApiKeyLogin:(e,t)=>C(Ra(`api-key/interactive`,t),Vr,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t)=>C(Ra(`logout`,t),la,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t)=>C(Ra(`oauth`,t),Vr,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t)=>C(Ra(`oauth/${encodeURIComponent(e)}`,t),Vr),respondOAuthFlow:(e,t,n,r)=>C(Ra(`oauth/${encodeURIComponent(e)}/respond`,r),Vr,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t)=>C(Ra(`oauth/${encodeURIComponent(e)}/cancel`,t),Vr,{method:`POST`})},eo={terminals:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j(ui)),startTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ui,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,fa,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,fa,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>C(`${N(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,ui,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,di,{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${no(e)}`,j(di)),getCommandRun:(e,t=`local`)=>to(e,t),cancelCommandRun:(e,t=`local`)=>C(`${N(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,di,{method:`POST`})};async function to(e,t){return Ft(`${N(t)}/terminal-command-runs/${encodeURIComponent(e)}`,di)}function no(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 ro(e){if(!ao(e))return;let t=e.error;return typeof t==`string`?t:void 0}async function io(e,t,n,r){let i=await fetch(ka(e,t,n,{machineId:r}));if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(ro(e)??i.statusText)}let a=await i.blob(),o=URL.createObjectURL(a),s=document.createElement(`a`);s.href=o;let c=n.split(`/`).pop();s.download=c===void 0||c===``?`download`:c,document.body.append(s),s.click(),s.remove(),URL.revokeObjectURL(o)}function ao(e){return typeof e==`object`&&!!e}var oo={files:(e,t,n={})=>{let r=new URLSearchParams({q:t});return n.kind!==void 0&&r.set(`kind`,n.kind),n.mode!==void 0&&r.set(`mode`,n.mode),n.scope!==void 0&&r.set(`scope`,n.scope),n.workspaceScoped===!0&&n.projectId!==void 0&&n.workspaceId!==void 0?C(`${N(n.machineId)}/projects/${encodeURIComponent(n.projectId)}/workspaces/${encodeURIComponent(n.workspaceId)}/files?${r.toString()}`,j(Qr)):(r.set(`cwd`,e),C(`${N(n.machineId)}/files?${r.toString()}`,j(Qr)))}},so={gitStatus:(e,t,n=`local`)=>C(`${N(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,oi),gitDiff:(e,t,n,r=`local`)=>C(Ta(r,e,t,n),li)},I={...Ba,...Va,...Wa,...Ga,...Ka,...Ja,...Ya,...Xa,...Qa,...$a,...eo,...oo,...so};function co(e,t=`local`,n=yt()){let r=typeof e==`string`?void 0:e.cwd,i=r===void 0||r===``?``:`?${new URLSearchParams({cwd:r}).toString()}`,a=typeof e==`string`?e:e.id,o=xt(`${fo(t)}/sessions/${encodeURIComponent(a)}/events${i}`,void 0,n);return new WebSocket(kt(o))}function lo(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(kt(`${fo(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function uo(e=`local`,t=yt()){let n=xt(`${fo(e)}/events`,void 0,t);return new WebSocket(kt(n))}function fo(e){return`api/machines/${encodeURIComponent(e)}`}var po=`.pi-web/uploads`,mo=class extends Error{constructor(e=`工作区上传已取消`){super(e),this.name=`WorkspaceUploadCancelledError`}},ho=class extends Error{constructor(e,t){super(Eo(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function go(e){return e?.uploads?.defaultFolder??`.pi-web/uploads`}function _o(e,t){return e?.uploads?.defaultFolder??t}function vo(e,t){let n=ko(e,`上传目标`,{allowEmpty:!0}),r=ko(t,`上传文件名`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function yo(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`,Da(e,t,n.path,So(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(Co(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(ni(jo(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(Mo(i)))},i.onerror=()=>{l(Error(`工作区上传失败`))},i.onabort=()=>{l(new mo(o?void 0:`工作区上传已中止`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function bo(e,t,n,r={}){let i=r.destinationFolder??`.pi-web/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:vo(i,e.name),loaded:0,total:e.size,percent:To(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(wo(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 mo;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=yo(e,t,{path:p.path,file:f},{...xo(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(Oo(e,c))throw e;let t=Do(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 ho(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function xo(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 So(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function Co(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:To(e.loaded,n),lengthComputable:e.lengthComputable}}function wo(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:To(i,r),done:n}}function To(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function Eo(e){return e.length===1?e[0]?.error??`工作区上传失败`:`${String(e.length)} 个文件上传失败`}function Do(e){return e instanceof Error?e.message:String(e)}function Oo(e,t){return t.requested||e instanceof mo}function ko(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t}不能为空`)}if(Ao(r))throw Error(`${t}必须是工作区相对路径`);let i=r.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(i.length===0){if(n.allowEmpty)return``;throw Error(`${t}不能为空`)}if(i.some(e=>e===`..`))throw Error(`${t}不能包含路径穿越`);return i.join(`/`)}function Ao(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function jo(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function Mo(e){let t=No(e);return Po(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function No(e){try{return jo(e)}catch{return}}function Po(e){return typeof e==`object`&&!!e}function Fo(){return{sessions:[],pinnedSessionIds:[],sessionSearchQuery:``,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``,sessionSearchTarget:void 0,clientQueuedSessionMessages:{},startingSessionCount:0,selectedNotificationInbox:void 0,treeDialog:void 0,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,selectedTerminalId:void 0,error:``}}function Io(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},projects:[],workspaces:[],sessions:[],pinnedSessionIds:[],sessionSearchQuery:``,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``,sessionSearchTarget:void 0,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,status:void 0,activity:void 0,pendingAsk:void 0,availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},selectedNotificationInbox:void 0,workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,treeDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:`core:workspace.files`,mainView:`chat`,fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,workspaceUploadBatches:{},gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:``}}function Lo(e,t){return t?.phase===`active`&&t.startup!==!0||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function Ro(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}var zo=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Bo(e){return zo.some(t=>t===e)}function Vo(e){return e===void 0||e===``?`off`:e}function Ho(e){let t=Vo(e);return Bo(t)?{off:`关闭`,minimal:`最低`,low:`低`,medium:`中`,high:`高`,xhigh:`极高`,max:`最高`}[t]??t:t}function Uo(e){switch(e){case`off`:return`不使用推理`;case`minimal`:return`极简推理(约 1k tokens)`;case`low`:return`轻量推理(约 2k tokens)`;case`medium`:return`中等推理(约 8k tokens)`;case`high`:return`深度推理(约 16k tokens)`;case`xhigh`:return`最大推理(约 32k tokens)`;case`max`:return`最高推理(约 64k tokens)`;default:return}}function Wo(e,t){let n=t.length>=2?t:zo,r=n.length-1,i=Vo(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}function Go(e,t){return`${e}:${t}`}function Ko(e,t){return`${e}:${t}`}function L(e){return e.selectedMachine?.id??`local`}var qo=class{constructor(){this.pendingByKey=new Map}request(e,t){let n=this.pendingByKey.get(e);if(n!==void 0)return n.latestRefresh=t,n.started&&(n.trailing=!0),n.promise;let r={promise:Promise.resolve(),latestRefresh:t,started:!1,trailing:!1};return r.promise=Promise.resolve().then(async()=>{let e,t;do{r.trailing=!1;let n=r.latestRefresh;r.started=!0,t=!1;try{await n()}catch(n){e=n,t=!0}}while(this.hasTrailingRequest(r));if(t)throw e}).finally(()=>{this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e)}),this.pendingByKey.set(e,r),r.promise}hasTrailingRequest(e){return e.trailing}},Jo=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new qo,this.api=n.api??Ya,this.onActivityApplied=n.onActivityApplied}refresh(e=L(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,Yo(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=L(this.getState())){let n=this.getState(),r=L(n)===t,i=Xo(n.machineActivities[t]??(r?n.workspaceActivities:{}),e);this.setState({machineActivities:{...n.machineActivities,[t]:i},...r?{workspaceActivities:i}:{}}),this.onActivityApplied?.(t)}applyMachineActivitySnapshot(e,t){let n=this.getState();this.setState({machineActivities:{...n.machineActivities,[e]:t},...L(n)===e?{workspaceActivities:t}:{}}),this.onActivityApplied?.(e)}};function Yo(e){let t={};for(let n of e.workspaces)Ro(n)&&(t[n.cwd]=n);return t}function Xo(e,t){let n={...e};return Ro(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}var Zo=class{constructor(e,t,n,r){this.getState=e,this.setState=t,this.applyStatus=n,this.oauthOperationGeneration=0,this.pollGeneration=0,this.api=r.api??I,this.pollIntervalMs=r.pollIntervalMs??1e3,this.scope=r.scope}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=ts(e);return t===void 0?!1:(t.command===`login`?this.openLogin(t.providerId):this.openLogout(t.providerId),!0)}async openLogin(e){let t=this.captureTarget();if(t!==void 0){if(e!==void 0&&e!==``){await this.openLoginProvider(e,t);return}this.setState({authDialog:{step:`method`,target:t}})}}async chooseLoginMethod(e){let t=this.getState().authDialog;if(t?.step===`method`)try{let{providers:n}=await this.api.authProviders({mode:`login`,authType:e,...$o(t.target)});this.setState({authDialog:{step:`providers`,mode:`login`,authType:e,providers:n,target:t.target}})}catch(e){this.setState({error:String(e)})}}async selectLoginProvider(e,t){let n=this.getState().authDialog;if(n?.step!==`providers`)return;let r=n.providers.find(n=>n.id===e&&(t===void 0||n.authType===t));r!==void 0&&(r.authType===`oauth`||r.loginFlow===`interactive`?await this.startOAuth(r,n.target):this.setState({authDialog:{step:`apiKey`,provider:r,value:``,target:n.target}}))}updateApiKey(e){let t=this.getState().authDialog;if(t?.step!==`apiKey`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,value:e}})}async saveApiKey(){let e=this.getState().authDialog;if(e?.step!==`apiKey`)return;let t=e.value.trim();if(t===``){this.setState({authDialog:{...e,error:`必须填写 API key`}});return}let n={...e};delete n.error,this.setState({authDialog:{...n,saving:!0}});try{let n=e.target;await this.api.saveApiKey(e.provider.id,t,n),this.closeDialog(),this.refreshStatus(n)}catch(t){this.setState({authDialog:{...e,saving:!1,error:String(t)}})}}async openLogout(e){let t=this.captureTarget();if(t!==void 0)try{let{providers:n}=await this.api.authProviders({mode:`logout`,...$o(t)});if(e!==void 0&&e!==``){let r=n.find(t=>t.id===e);r!==void 0&&!this.rejectRemoteOAuth(`logout`,r,t)?await this.logoutProviderForTarget(r.id,t):r===void 0&&this.setState({error:`没有 ${e} 的已保存凭据`});return}this.setState({authDialog:{step:`logout`,providers:n,target:t}})}catch(e){this.setState({error:String(e)})}}async logoutProvider(e){let t=this.getState().authDialog;if(t?.step!==`logout`)return;let n=t.providers.find(t=>t.id===e);n===void 0||this.rejectRemoteOAuth(`logout`,n,t.target)||await this.logoutProviderForTarget(e,t.target)}async logoutProviderForTarget(e,t){try{await this.api.logoutProvider(e,t),this.closeDialog(),this.refreshStatus(t)}catch(e){this.setState({error:String(e)})}}updateOAuthInput(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,inputValue:e}})}async respondOAuth(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n=t.flow.prompt??t.flow.select;if(n===void 0)return;let r=this.oauthOperationGeneration,i=t.flow.flowId,a=n.requestId,o=e??t.inputValue??``,s={...t};delete s.error,this.setState({authDialog:{...s,responding:!0}});try{let e=await this.api.respondOAuthFlow(t.flow.flowId,n.requestId,o,t.target);this.updateOAuthFlow(e,t.target)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||es(t.flow)!==a)return;this.setState({authDialog:{...t,responding:!1,error:String(e)}})}}async cancelOAuth(){let e=this.getState().authDialog;if(e?.step!==`oauth`){this.closeDialog();return}let t=e.flow.flowId,n=e.target;this.closeDialog();try{await this.api.cancelOAuthFlow(t,n)}catch{}}closeDialog(){this.oauthOperationGeneration+=1,this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(e,t){try{let{providers:n}=await this.api.authProviders({mode:`login`,...$o(t)}),r=n.filter(t=>t.id===e);if(r.length===0){this.setState({error:`找不到认证提供商:${e}`});return}if(r.length>1){this.setState({authDialog:{step:`providers`,mode:`login`,providers:r,target:t}});return}let i=r[0];if(i===void 0)return;i.authType===`oauth`||i.loginFlow===`interactive`?await this.startOAuth(i,t):this.setState({authDialog:{step:`apiKey`,provider:i,value:``,target:t}})}catch(e){this.setState({error:String(e)})}}async startOAuth(e,t){if(this.rejectRemoteOAuth(`login`,e,t))return;let n=++this.oauthOperationGeneration;this.stopPolling();try{let r=e.authType===`oauth`?await this.api.startOAuthLogin(e.id,t):await this.api.startInteractiveApiKeyLogin(e.id,t);if(n!==this.oauthOperationGeneration){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){n===this.oauthOperationGeneration&&this.setState({error:String(e)})}}rejectRemoteOAuth(e,t,n){let r=this.getState().selectedMachine;if(t.authType!==`oauth`||n.machineKind!==`remote`)return!1;let i=r?.baseUrl??`对应的远程 PI WEB 实例`,a=e===`login`?`登录`:`退出`;return this.setState({error:`远程机器的 OAuth ${a}必须直接在 ${i} 上配置。`}),!0}updateOAuthFlow(e,t){if(e.status===`complete`){this.stopPolling(),this.closeDialog(),this.refreshStatus(t);return}(e.status===`error`||e.status===`cancelled`)&&(this.oauthOperationGeneration+=1,this.stopPolling());let n=this.getState().authDialog,r=n?.step===`oauth`&&n.flow.flowId===e.flowId?n.inputValue??``:``,i=n?.step===`oauth`?es(n.flow):void 0,a=es(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,inputValue:s,responding:c,target:t}})}startPolling(e,t){this.stopPolling();let n=this.oauthOperationGeneration,r=this.pollGeneration;this.pollTimer=window.setInterval(()=>{this.poll(e,t,n,r)},this.pollIntervalMs)}stopPolling(){this.pollGeneration+=1,this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(e,t,n,r){if(r!==this.pollGeneration)return;let i=this.currentOAuthDialog(n,e);if(i===void 0||!Qo(i.target,t)){this.stopPolling();return}let a=es(i.flow);try{this.updateOAuthFlow(await this.api.oauthFlow(e,i.target),i.target)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o===void 0||!Qo(o.target,t)||es(o.flow)!==a)return;this.stopPolling(),this.setState({authDialog:{...o,error:String(i)}})}}currentOAuthDialog(e,t){if(e!==this.oauthOperationGeneration)return;let n=this.getState().authDialog;return n?.step===`oauth`&&n.flow.flowId===t?n:void 0}async refreshStatus(e){let t=this.selectedSessionForMachine(e.machineId);if(t!==void 0&&this.targetStillSelected(e))try{this.applyStatus(await this.api.status(t,e.machineId))}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}captureTarget(){let e=this.getState(),t=e.selectedMachine,n={machineId:L(e),...t?.kind===void 0?{}:{machineKind:t.kind}};if(this.scope===`management`)return n;let r=e.selectedProject;if(r===void 0){this.setState({error:`请先选择项目,再配置提供商认证。`});return}return{...n,projectId:r.id,projectName:r.name}}targetStillSelected(e){return L(this.getState())===e.machineId?e.projectId===void 0||this.getState().selectedProject?.id===e.projectId:!1}};function Qo(e,t){return e.machineId===t.machineId&&e.projectId===t.projectId}function $o(e){return e.projectId===void 0?{machineId:e.machineId}:{machineId:e.machineId,projectId:e.projectId,...e.projectName===void 0?{}:{projectName:e.projectName}}}function es(e){return e.prompt?.requestId??e.select?.requestId}function ts(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 ns(e){return e.replaceAll(`:`,`.`)}function rs(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 is(e,t){let n=rs(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function as(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));os(i,r)}function os(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 ss(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:vo(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:ps(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:ps(0,n),status:`uploading`,startedAt:e.startedAt}}function cs(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 ls(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=fs(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function us(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:`因前面的文件上传失败而未上传。`});return{...e,files:r,...fs(r),status:`error`,error:t,completedAt:n}}function ds(e,t){let n=`上传已取消`,r=e.files.map(e=>e.status===`completed`||e.status===`error`?e:{...e,status:`cancelled`,error:n});return{...e,files:r,...fs(r),status:`cancelled`,error:n,completedAt:t}}function fs(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function ps(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var ms=ns(`core:workspace.files`),hs=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.updateUrl=n,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.api=r.api??I,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??bo,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=await Promise.all(Object.keys(this.getState().expandedDirs).map(async r=>{try{return[r,(await this.api.workspaceTree(e.id,t.id,r,n)).entries]}catch(e){if(gs(e))return;throw e}})),a=Object.fromEntries(i.filter(e=>e!==void 0));this.setState({fileTree:r.entries,expandedDirs:a,fileTreeStale:!1,error:``})}catch(e){this.setState({error:String(e)})}}async expandDir(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){if(this.getState().expandedDirs[e]!==void 0){this.setState({expandedDirs:ys(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},error:``})}catch(e){this.setState({error:String(e)})}}}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),as(ms,`file`,e),this.updateUrl({replace:!0}),await this.restoreFile(e)}selectDirectory(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),as(ms,`file`,void 0,{replace:!0}),this.updateUrl({replace:!0})}async restoreFile(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0)){this.setState({selectedFilePath:e,selectedFileContent:void 0});try{let r=await this.api.workspaceFile(t.id,n.id,e,L(this.getState()));this.getState().selectedFilePath===e&&this.setState({selectedFileContent:r,error:``})}catch(t){if(this.getState().selectedFilePath!==e)return;if(gs(t)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:``}),as(ms,`file`,void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(t)})}}}async createFile(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0||e===``))try{await this.api.createWorkspaceFile(t.id,n.id,e,L(this.getState())),await this.refreshFiles(),await this.selectFile(e),this.setState({error:``})}catch(e){this.setState({error:String(e)})}}async createDirectory(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0||e===``))try{await this.api.createWorkspaceDirectory(t.id,n.id,e,L(this.getState())),await this.refreshFiles(),this.selectDirectory(e),this.setState({error:``})}catch(e){this.setState({error:String(e)})}}async moveSelectedPath(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace,r=this.getState().selectedFilePath;if(!(t===void 0||n===void 0||r===void 0||r===``||e===``))try{let i=L(this.getState());bs(this.getState())===`directory`?(await this.api.moveWorkspaceDirectory(t.id,n.id,r,e,i),await this.refreshFiles(),this.selectDirectory(e)):(await this.api.moveWorkspaceFile(t.id,n.id,r,e,void 0,i),await this.refreshFiles(),await this.selectFile(e)),this.setState({error:``})}catch(e){this.setState({error:String(e)})}}async deleteSelectedPath(){let e=this.getState().selectedProject,t=this.getState().selectedWorkspace,n=this.getState().selectedFilePath;if(!(e===void 0||t===void 0||n===void 0||n===``))try{let r=L(this.getState());bs(this.getState())===`directory`?await this.api.deleteWorkspaceDirectory(e.id,t.id,n,r):await this.api.deleteWorkspaceFile(e.id,t.id,n,r),await this.refreshFiles(),this.clearSelection(),this.setState({error:``})}catch(e){this.setState({error:String(e)})}}async downloadSelectedFile(){let e=this.getState().selectedProject,t=this.getState().selectedWorkspace,n=this.getState().selectedFilePath;if(!(e===void 0||t===void 0||n===void 0||n===``||bs(this.getState())===`directory`))try{await this.api.downloadWorkspaceFile(e.id,t.id,n,L(this.getState())),this.setState({error:``})}catch(e){this.setState({error:String(e)})}}clearSelection(){this.setState({selectedFilePath:void 0,selectedFileContent:void 0}),as(ms,`file`,void 0,{replace:!0}),this.updateUrl({replace:!0})}startWorkspaceUpload(e,t){let n=this.getState().selectedProject,r=this.getState().selectedWorkspace;if(n===void 0||r===void 0){this.setState({error:`上传文件前请选择工作区。`});return}if(e.length===0)return;let i=L(this.getState()),a=t.overwrite??!1,o=t.createDirs??!0,s;try{s=ss({id:this.createUploadBatchId(),projectId:n.id,workspaceId:r.id,machineId:i,destinationFolder:t.destinationFolder,overwrite:a,createDirs:o,files:e,startedAt:this.now()})}catch(e){this.setState({error:String(e)});return}this.setUploadBatch(s);let c;try{c=this.uploadWorkspaceFiles(n.id,r.id,e,{destinationFolder:t.destinationFolder,machineId:i,overwrite:a,createDirs:o,onProgress:e=>{this.updateUploadProgress(s.id,e)}})}catch(e){return this.failUploadBatch(s.id,e),{batchId:s.id,done:Promise.resolve()}}this.uploadTasks.set(s.id,c);let l=c.promise.then(async e=>{await this.completeUploadBatch(s.id,e,t)}).catch(async e=>{await this.handleUploadFailure(s.id,e,t)}).finally(()=>{this.uploadTasks.delete(s.id)});return{batchId:s.id,done:l}}cancelWorkspaceUpload(e){let t=this.getUploadBatch(e);t?.status===`uploading`&&(this.setUploadBatch(ds(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:ys(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(cs(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(ls(r,t,this.now()),{error:``}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshFiles();let i=t[0]?.path;n.selectUploadedFile!==!1&&i!==void 0&&this.isCurrentWorkspaceBatch(r)&&await this.selectFile(i)}async handleUploadFailure(e,t,n){let r=this.failUploadBatch(e,t);if(!(t instanceof ho)||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(_s(t)){let e=ds(n,this.now());return this.setUploadBatch(e),e}let r=vs(t),i=us(n,r,this.now());return this.setUploadBatch(i,{error:r}),i}getUploadBatch(e){return this.getState().workspaceUploadBatches[e]}setUploadBatch(e,t={}){this.setState({workspaceUploadBatches:{...this.getState().workspaceUploadBatches,[e.id]:e},...t})}isCurrentWorkspaceBatch(e){let t=this.getState();return t.selectedProject?.id===e.projectId&&t.selectedWorkspace?.id===e.workspaceId&&L(t)===e.machineId}};function gs(e){let t=String(e);return t.includes(`Path does not exist`)||t.includes(`ENOENT`)||t.includes(`no such file or directory`)}function _s(e){return e instanceof mo}function vs(e){return e instanceof Error?e.message:String(e)}function ys(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function bs(e){let t=e.selectedFilePath;return t===void 0?`file`:xs(e.fileTree,e.expandedDirs,t)?.type===`directory`?`directory`:`file`}function xs(e,t,n){let r=e.find(e=>e.path===n);if(r!==void 0)return r;for(let e of Object.values(t)){let t=e.find(e=>e.path===n);if(t!==void 0)return t}}var Ss=ns(`core:workspace.git`),Cs=class{constructor(e,t,n){this.getState=e,this.setState=t,this.updateUrl=n}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){let e=this.getState().selectedProject,t=this.getState().selectedWorkspace;if(!(e===void 0||t===void 0))try{let n=await I.gitStatus(e.id,t.id,L(this.getState()));this.setState({gitStatus:n,gitStale:!1,error:``});let r=this.getState().selectedDiffPath;r!==void 0&&(n.files.some(e=>e.path===r)?await this.refreshDiff(r):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),as(Ss,`diff`,void 0,{replace:!0})))}catch(e){this.setState({error:String(e)})}}async selectDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:`core:workspace.git`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.git`}),as(Ss,`diff`,e),this.updateUrl({replace:!0}),await this.refreshDiff(e)}async restoreDiff(e){this.setState({selectedDiffPath:e,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(e)}async refreshDiff(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(!(t===void 0||n===void 0))try{let[r,i]=await Promise.all([I.gitDiff(t.id,n.id,{path:e},L(this.getState())),I.gitDiff(t.id,n.id,{path:e,staged:!0},L(this.getState()))]);this.setState({selectedDiff:r,selectedStagedDiff:i,error:``})}catch(e){this.setState({error:String(e)})}}updatePolling(){this.dispose();let e=this.getState();(e.workspaceTool===`core:workspace.git`||e.mainView===`core:workspace.git`)&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}},ws=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,machineActivities:Es(this.getState().machineActivities,r),machineRuntimes:Es(this.getState().machineRuntimes,r)}),this.refreshMachineHealthFor(t),this.refreshMachineRuntimeFor(t)}catch(e){this.setState({error:String(e)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(e,t={}){this.getState().selectedMachine?.id!==e.id&&(this.setState({selectedMachine:e,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...Fo()}),t.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(e.id),this.refreshMachineRuntime(e.id))}async addMachine(e){this.setState({error:``});try{let t=await 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:`无法移除本地机器。`});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:Ts(this.getState().machineStatuses,e.id),machineRuntimes:Ts(this.getState().machineRuntimes,e.id),machineActivities:Ts(this.getState().machineActivities,e.id)}),n&&i!==void 0?(t.selectFallback===!1||await this.selectMachine(i),i):void 0}catch(e){this.setState({error:String(e)});return}}}async refreshMachineHealth(e=this.getState().selectedMachine?.id??`local`){try{let t=await 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} 暂不可用,正在重新连接…`}}),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 Ts(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Es(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var Ds=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.api=r.api??I,this.onProjectsApplied=r.onProjectsApplied}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}),this.onProjectsApplied?.(e)}catch(t){L(this.getState())===e&&this.setState({error:String(t)})}finally{L(this.getState())===e&&this.setState({isLoadingProjects:!1})}}async addProject(e,t){if(e.trim()===``)return;let n=L(this.getState());try{let r=await this.api.addProject(e.trim(),void 0,t,n);if(L(this.getState())!==n)return;let i=this.getState().projects;this.setState({projects:[...i.filter(e=>e.id!==r.id),r],projectDialogOpen:!1}),this.onProjectsApplied?.(n),await this.workspaces.selectProject(r)}catch(e){L(this.getState())===n&&this.setState({error:String(e)})}}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)}),this.onProjectsApplied?.(t),n.selectedProject?.id===e&&this.workspaces.clearSelection()}catch(e){L(this.getState())===t&&this.setState({error:String(e)})}}};function Os(e,t){return t[e.path]}function ks(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function As(e,t,n){return Ns(Ps(e,t,n))}function js(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function Ms(e){return Ns(Object.values(e??{}))}function Ns(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function Ps(e,t,n){return Object.values(n).filter(n=>js(e,t,n.cwd))}var Fs=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.machineGeneration=0,this.activityMachineGeneration=-1,this.projectTopologyGeneration=0,this.nextCwdActivation=0,this.observedActiveCwds=new Set,this.cwdActivations=new Map,this.attemptedCwdActivations=new Map,this.api=n.api??Qa,this.onError=n.onError}handleActivityApplied(e){return L(this.getState())===e?(this.activityMachineGeneration=this.machineGeneration,this.reconcile(e)):Promise.resolve()}handleProjectsApplied(e){return L(this.getState())!==e||(this.projectTopologyGeneration+=1,this.attemptedCwdActivations.clear(),this.activePass=void 0,this.activityMachineGeneration!==this.machineGeneration)?Promise.resolve():this.reconcile(e)}handleSelectedMachineChanged(){this.machineGeneration+=1,this.projectTopologyGeneration+=1,this.observedActiveCwds.clear(),this.cwdActivations.clear(),this.attemptedCwdActivations.clear(),this.activePass=void 0}reconcile(e){let t=this.getState();if(L(t)!==e)return Promise.resolve();let n=this.syncActiveCwds(t),r=new Map([...n].filter(([e,n])=>!Is(t.projects,t.workspacesByProjectId,e)&&this.attemptedCwdActivations.get(e)!==n)),i=this.activePass;if(i!==void 0)return(i.machineGeneration!==this.machineGeneration||i.projectTopologyGeneration!==this.projectTopologyGeneration||[...r].some(([e,t])=>i.cwdActivations.get(e)!==t))&&(i.trailingRequested=!0),i.promise;if(r.size===0||t.projects.length===0)return Promise.resolve();let a={machineGeneration:this.machineGeneration,projectTopologyGeneration:this.projectTopologyGeneration,machineId:e,projects:t.projects.map(e=>({id:e.id,path:e.path,startingWorkspaces:t.workspacesByProjectId[e.id]})),cwdActivations:r,trailingRequested:!1,promise:Promise.resolve()};return this.activePass=a,a.promise=this.runPass(a),a.promise}async runPass(e){if(await Promise.all(e.projects.map(async t=>{try{let n=await this.api.workspaces(t.id,e.machineId);this.applyProjectWorkspaces(e,t,n)}catch(n){this.isPassScopeCurrent(e)&&this.reportError({machineId:e.machineId,projectId:t.id,error:n})}})),this.activePass!==e)return;let t=this.getState(),n=this.syncActiveCwds(t);for(let[r,i]of e.cwdActivations)n.get(r)===i&&!Is(t.projects,t.workspacesByProjectId,r)&&this.attemptedCwdActivations.set(r,i);let r=e.trailingRequested;this.activePass=void 0,r&&await this.reconcile(L(this.getState()))}applyProjectWorkspaces(e,t,n){if(this.activePass!==e||!this.isPassScopeCurrent(e))return;let r=this.getState();r.projects.find(e=>e.id===t.id)?.path===t.path&&r.workspacesByProjectId[t.id]===t.startingWorkspaces&&this.setState({workspacesByProjectId:{...r.workspacesByProjectId,[t.id]:n}})}isPassScopeCurrent(e){return e.machineGeneration===this.machineGeneration&&e.projectTopologyGeneration===this.projectTopologyGeneration&&L(this.getState())===e.machineId}syncActiveCwds(e){let t=new Set(Object.values(e.workspaceActivities).filter(Ro).map(e=>e.cwd));for(let e of this.observedActiveCwds)t.has(e)||(this.cwdActivations.delete(e),this.attemptedCwdActivations.delete(e));for(let e of t)this.observedActiveCwds.has(e)||(this.nextCwdActivation+=1,this.cwdActivations.set(e,this.nextCwdActivation),this.attemptedCwdActivations.delete(e));return this.observedActiveCwds=t,new Map([...t].map(e=>[e,this.cwdActivations.get(e)??0]))}reportError(e){if(this.onError!==void 0)try{this.onError(e)}catch{}}};function Is(e,t,n){return e.some(e=>js(e,t[e.id]??[],n))}var Ls=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??Ba,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}),Rs(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 Rs(e){if(e.release.error!==void 0)throw Error(`PI WEB 更新检查失败:${e.release.error}`);if(e.release.skipped===!0)throw Error(`由于离线或版本检查设置禁用了远程版本检查,已跳过 PI WEB 更新检查`)}var zs=`pi-web:cached-new-sessions:v1`,Bs=`browserCachedNew`,Vs=`local`;function Hs(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Us(e,t=Vs,n=Hs()){if(e.messageCount!==0||e.archived===!0)return;let r=Ys(n).filter(n=>n.id!==e.id||n.machineId!==t);Xs([Ws(e,t),...r],n)}function Ws(e,t=Vs){return{...e,browserCachedNew:!0,machineId:t}}function Gs(e,t=Vs,n=Hs()){Xs(Ys(n).filter(n=>n.id!==e||n.machineId!==t),n)}function Ks(e,t,n=Vs,r=Hs()){let i=new Set(t.map(e=>e.id)),a=Ys(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&Xs(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function qs(e){return e!==void 0&&Qs(e)&&e.browserCachedNew===!0}function Js(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:Vs},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Ys(e=Hs()){try{let t=e?.getItem(zs);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>Zs(e)):[]}catch{return[]}}function Xs(e,t=Hs()){try{e.length===0?t?.removeItem(zs):t?.setItem(zs,JSON.stringify(e))}catch{}}function Zs(e){if(!$s(e))return[];let t=ec(e,`id`),n=ec(e,`path`),r=ec(e,`cwd`),i=ec(e,`created`),a=ec(e,`modified`),o=ec(e,`firstMessage`),s=nc(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=tc(e,`name`),l=tc(e,`parentSessionPath`),u=tc(e,`machineId`)??Vs;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 Qs(e){return Bs in e}function $s(e){return typeof e==`object`&&!!e}function ec(e,t){let n=e[t];return typeof n==`string`?n:void 0}function tc(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function nc(e,t){let n=e[t];return typeof n==`number`?n:void 0}function rc(e,t){return Tc(t===void 0?e.flatMap(cc):e.flatMap((e,n)=>cc(e).map(e=>({...e,transcriptIndex:t+n})))).filter(e=>e.parts.length>0)}function ic(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function ac(e,t){let n=mc(t);return n===void 0?e:{...e,meta:n}}function oc(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,ic(t,n)]}function sc(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 cc(e){if(uc(e))return[e];if(R(e,`role`)===`bashExecution`)return[ac(_c(e),e)];let t=R(e,`role`),n=vc(t),r=yc(Nc(e,`content`),e),i=t===`toolResult`?xc(R(e,`toolName`)??``,Nc(e,`details`)):void 0,a=i===void 0?r:[...r,i],o=n===`user`?dc(a):void 0;if(o!==void 0)return o.map(t=>ac(t,e));let s=pc(e);if(n===`tool`)return[ac({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?[ac({role:l,parts:c,...s===void 0?{}:{source:s}},e)]:[],d=lc(e);return d===void 0?u:[...u,ac(d,e)]}function lc(e){if(R(e,`role`)!==`assistant`||R(e,`stopReason`)!==`error`)return;let t=R(e,`errorMessage`)?.trim();return ic(`system`,`模型响应失败:${t===void 0||t===``?`模型返回了错误。`:t}`)}function uc(e){let t=R(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(Nc(e,`parts`))}function dc(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=fc(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 fc(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 pc(e){let t=R(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function mc(e){let t=hc(Nc(e,`timestamp`)),n=gc(e);if(!(t===void 0&&n===void 0))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n}}}function hc(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 gc(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 _c(e){let t=R(e,`command`)??``,n=Pc(e,`excludeFromContext`)===!0?[`已从上下文中排除`,``,`$ ${t}`]:[`$ ${t}`],r=Nc(e,`output`);r!=null&&n.push(``,Ic(r));let i=Nc(e,`exitCode`);i!=null&&n.push(``,`退出码 ${Ic(i)}`),Pc(e,`cancelled`)===!0&&n.push(``,`已取消`),Pc(e,`truncated`)===!0&&n.push(``,`输出已截断`);let a=R(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`完整输出:${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
|
|
4
4
|
`)}]}}function vc(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function yc(e,t){let n=bc(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=Nc(e,`arguments`),r=R(e,`id`),i=t===`read`?wc(R(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:Ac(n),...n===void 0?{}:{args:n}}]:[{type:`skillRead`,...i,...r===void 0?{}:{toolCallId:r}}]}if(t===`image`){let t=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 kc(e)}).map(e=>e.type===`text`&&R(t,`role`)===`toolResult`?Cc(e.text,t):e):kc(e):[n]}function bc(e){if(!(R(e,`role`)!==`custom`||R(e,`customType`)!==`pi-web.ask.answers`))return Sc(Nc(e,`details`))}function xc(e,t){if(e===`ask_user`)return Sc(Nc(t,`superseded`))}function Sc(e){try{return{type:`askUserRecord`,outcome:Vn(e)}}catch{return}}function Cc(e,t){let n=R(t,`toolCallId`),r=Nc(t,`content`),i=Nc(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:Pc(t,`isError`)===!0}}function wc(e){if(e===void 0||e===``)return;let t=e.replace(/\\/g,`/`);if(!t.endsWith(`/SKILL.md`)&&t!==`SKILL.md`)return;let n=t.split(`/`).at(-2);if(!(n===void 0||n===``))return{name:n,path:e}}function Tc(e){let t=[],n=new Map;for(let r of e){let e=[],i={...r.transcriptIndex===void 0?{}:{transcriptIndex:r.transcriptIndex},...r.source===void 0?{}:{source:r.source},...r.meta===void 0?{}:{meta:r.meta}},a=()=>{e.length!==0&&(t.push({role:r.role,parts:e,...i}),e=[])};for(let o of r.parts){if(o.type===`toolCall`){a();let e=Ec(o),r=t.length;t.push({role:`tool`,parts:[e],...i}),e.toolCallId!==void 0&&n.set(e.toolCallId,{lineIndex:r,partIndex:0});continue}if(o.type===`toolResult`){let e=o.toolCallId===void 0?void 0:n.get(o.toolCallId);if(e!==void 0&&Dc(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function Ec(e){return{type:`toolExecution`,...e.toolCallId===void 0?{}:{toolCallId:e.toolCallId},toolName:e.toolName,summary:e.summary,...e.args===void 0?{}:{args:e.args},status:`pending`}}function Dc(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=Oc(n.details)??i.preview,o={...i,status:n.isError?`error`:`success`,resultText:n.text,...n.content===void 0?{}:{content:n.content},...n.details===void 0?{}:{details:n.details},...a===void 0?{}:{preview:a}};return e[t.lineIndex]={...r,parts:[...r.parts.slice(0,t.partIndex),o,...r.parts.slice(t.partIndex+1)]},!0}function Oc(e){let t=Nc(e,`preview`);if(!Mc(t))return;let n=R(t,`diff`),r=R(t,`error`),i=Fc(t,`firstChangedLine`);if(!(n===void 0&&r===void 0&&i===void 0))return{...n===void 0?{}:{diff:n},...r===void 0?{}:{error:r},...i===void 0?{}:{firstChangedLine:i}}}function kc(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:Ac(e)}]:[{type:`text`,text:Ic(e)}]}function Ac(e){if(!Mc(e))return Ic(e);let t=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}: ${jc(t)}`).join(` · `)}function jc(e){return typeof e==`string`?e.length>80?`${e.slice(0,77)}…`:e:typeof e==`number`||typeof e==`boolean`?String(e):Array.isArray(e)?`${String(e.length)} item${e.length===1?``:`s`}`:typeof e==`object`&&e?`object`:``}function Mc(e){return typeof e==`object`&&!!e}function Nc(e,t){return Mc(e)?e[t]:void 0}function R(e,t){let n=Nc(e,t);return typeof n==`string`?n:void 0}function Pc(e,t){let n=Nc(e,t);return typeof n==`boolean`?n:void 0}function Fc(e,t){let n=Nc(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Ic(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var Lc=`pi-web:prompt-draft:`;function Rc(e){return`${Lc}${e}`}function zc(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Bc(e,t=zc()){try{return t?.getItem(Rc(e))??``}catch{return``}}function Vc(e,t,n=zc()){try{t?n?.setItem(Rc(e),t):n?.removeItem(Rc(e))}catch{}}function Hc(e,t=zc()){try{t?.removeItem(Rc(e))}catch{}}function Uc(e,t,n=zc()){let r=Bc(e,n);r!==``&&(Vc(t,r,n),Hc(e,n))}var Wc=`pi-web:ask-draft:`;function Gc(e,t){return`${Wc}${e}:${t}`}function Kc(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function qc(e,t,n=Kc()){try{let r=n?.getItem(Gc(e,t));return r==null?{}:Xc(r)}catch{return{}}}function Jc(e,t,n,r=Kc()){try{let i=Object.entries(n).filter(([,e])=>e.values.length>0||(e.otherText??``)!==``);i.length===0?r?.removeItem(Gc(e,t)):r?.setItem(Gc(e,t),JSON.stringify(Object.fromEntries(i)))}catch{}}function Yc(e,t,n=Kc()){try{n?.removeItem(Gc(e,t))}catch{}}function Xc(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=Zc(r);t!==void 0&&(n[e]=t)}return n}function Zc(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 Qc(e,t){return e.filter(e=>tl(e,t[e.id])!==void 0).length}function $c(e,t){return e.filter(e=>tl(e,t[e.id])===void 0)}function el(e,t){let n=[];for(let r of e){let e=tl(r,t[r.id]);e!==void 0&&n.push(e)}return{answers:n}}function tl(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=nl(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 nl(e){if(e===void 0)return;let t=e.trim().slice(0,Ht);return t===``?void 0:t}function rl(e,t){return ic(`bash`,`${t===!0?`已从上下文中排除
|
|
@@ -757,7 +757,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
|
|
|
757
757
|
.review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
758
758
|
.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; }
|
|
759
759
|
footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
|
|
760
|
-
`]}};B([b({attribute:!1})],Fm.prototype,`context`,void 0),B([S(`#workspace-upload-input`)],Fm.prototype,`uploadInput`,void 0),B([x()],Fm.prototype,`pendingUpload`,void 0),B([x()],Fm.prototype,`destinationFolder`,void 0),B([x()],Fm.prototype,`overwrite`,void 0),B([x()],Fm.prototype,`createDirs`,void 0),B([x()],Fm.prototype,`formError`,void 0),B([x()],Fm.prototype,`dragActive`,void 0),Fm=B([y(`workspace-files-panel`)],Fm);function Im(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 Lm(e,t){if(e.length===0)return`请至少选择一个要上传的文件。`;for(let n of e)try{vo(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function Rm(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function zm(e){let t=e.selectedFileContent;if(e.selectedFilePath===void 0||e.selectedFilePath===``)return`请选择文件。`;if(t===void 0)return`正在加载 ${e.selectedFilePath}…`;if(t.mediaType!==`image`&&t.binary)return`二进制文件:${t.path} · ${Qm(t.size)}`}function Bm(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function Vm(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Hm(e){return e==null?[]:Array.from(e)}function Um(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function Wm(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`最近 ${String(e.length)} 项`:`${String(t)} 项正在上传`}function Gm(e){let t=e.files.length;switch(e.status){case`completed`:return`已上传 ${String(t)} 个文件`;case`error`:return`${String(t)} 个文件上传失败`;case`cancelled`:return`已取消上传 ${String(t)} 个文件`;case`uploading`:return`正在上传 ${String(t)} 个文件`}}function Km(e){switch(e.status){case`completed`:return`完成`;case`error`:return`失败`;case`cancelled`:return`已取消`;case`uploading`:return Xm(e.percent)}}function qm(e){return e.status===`uploading`?e.percent:1}function Jm(e){switch(e.status){case`pending`:return`等待中`;case`uploading`:return Xm(e.percent);case`completed`:return`完成`;case`error`:return`错误`;case`cancelled`:return`已取消`}}function Ym(e){return e.error===void 0?e.response===void 0?`${e.path} · ${Qm(e.loaded)} / ${Qm(e.total)}`:`已写入 ${e.response.path}`:e.error}function Xm(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function Zm(){Pm(()=>import(`./CodeViewer-
|
|
760
|
+
`]}};B([b({attribute:!1})],Fm.prototype,`context`,void 0),B([S(`#workspace-upload-input`)],Fm.prototype,`uploadInput`,void 0),B([x()],Fm.prototype,`pendingUpload`,void 0),B([x()],Fm.prototype,`destinationFolder`,void 0),B([x()],Fm.prototype,`overwrite`,void 0),B([x()],Fm.prototype,`createDirs`,void 0),B([x()],Fm.prototype,`formError`,void 0),B([x()],Fm.prototype,`dragActive`,void 0),Fm=B([y(`workspace-files-panel`)],Fm);function Im(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 Lm(e,t){if(e.length===0)return`请至少选择一个要上传的文件。`;for(let n of e)try{vo(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function Rm(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function zm(e){let t=e.selectedFileContent;if(e.selectedFilePath===void 0||e.selectedFilePath===``)return`请选择文件。`;if(t===void 0)return`正在加载 ${e.selectedFilePath}…`;if(t.mediaType!==`image`&&t.binary)return`二进制文件:${t.path} · ${Qm(t.size)}`}function Bm(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function Vm(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Hm(e){return e==null?[]:Array.from(e)}function Um(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function Wm(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`最近 ${String(e.length)} 项`:`${String(t)} 项正在上传`}function Gm(e){let t=e.files.length;switch(e.status){case`completed`:return`已上传 ${String(t)} 个文件`;case`error`:return`${String(t)} 个文件上传失败`;case`cancelled`:return`已取消上传 ${String(t)} 个文件`;case`uploading`:return`正在上传 ${String(t)} 个文件`}}function Km(e){switch(e.status){case`completed`:return`完成`;case`error`:return`失败`;case`cancelled`:return`已取消`;case`uploading`:return Xm(e.percent)}}function qm(e){return e.status===`uploading`?e.percent:1}function Jm(e){switch(e.status){case`pending`:return`等待中`;case`uploading`:return Xm(e.percent);case`completed`:return`完成`;case`error`:return`错误`;case`cancelled`:return`已取消`}}function Ym(e){return e.error===void 0?e.response===void 0?`${e.path} · ${Qm(e.loaded)} / ${Qm(e.total)}`:`已写入 ${e.response.path}`:e.error}function Xm(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function Zm(){Pm(()=>import(`./CodeViewer-CWHRo84w.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}function Qm(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`${$m(t)} KB`;let n=t/1024;return n<1024?`${$m(n)} MB`:`${$m(n/1024)} GB`}function $m(e){return e>=10?String(Math.round(e)):e.toFixed(1)}function eh(e){let t=e.submoduleFromCommit,n=e.submoduleToCommit;return t!==void 0&&n!==void 0?`${t} → ${n}`:`commit`}function th(e){let t=e.split(`/`);return t[t.length-1]??e}function nh(e,t=[]){let n=ih(``),r=new Set(t);for(let e of t)oh(n,e).isSubmodule=!0;for(let t of e){if(r.has(t.path)){let e=oh(n,t.path);e.isSubmodule=!0,e.pointer={kind:`file`,name:eh(t),path:t.path,file:t,isSubmodulePointer:!0};continue}let e=t.path.split(`/`).filter(e=>e.length>0),i=e[e.length-1];if(i===void 0)continue;let a=n;for(let t=0;t<e.length-1;t+=1){let n=e[t];n!==void 0&&(a=ah(a,n))}a.files.push({kind:`file`,name:i,path:t.path,file:t})}return sh(n)}function rh(e){let t=[];for(let n of e)n.kind===`directory`&&(t.push(n.path),t.push(...rh(n.children)));return t}function ih(e){return{path:e,directories:new Map,files:[],isSubmodule:!1}}function ah(e,t){let n=e.path.length===0?t:`${e.path}/${t}`,r=e.directories.get(n);if(r!==void 0)return r;let i=ih(n);return e.directories.set(n,i),i}function oh(e,t){let n=e;for(let e of t.split(`/`).filter(e=>e.length>0))n=ah(n,e);return n}function sh(e){let t=[...e.directories.values()].map(e=>({kind:`directory`,name:th(e.path),path:e.path,...e.isSubmodule?{isSubmodule:!0}:{},children:sh(e)})).sort((e,t)=>e.name.localeCompare(t.name)),n=[...e.files].sort((e,t)=>e.name.localeCompare(t.name));return[...e.pointer===void 0?[]:[e.pointer],...t,...n]}function ch(e,t=[]){let n=new Set(t),r=new Map,i=new Map;for(let e of t)i.set(e,[]);let a=[];for(let o of e){if(n.has(o.path)){r.set(o.path,{name:eh(o),file:o});continue}let e=lh(o.path,t);if(e!==void 0){i.get(e)?.push({path:o.path,relativePath:o.path.slice(e.length+1),file:o});continue}a.push(o)}return{submodules:t.map(e=>{let t=r.get(e),n=i.get(e)??[];return{path:e,name:th(e),...t===void 0?{}:{pointer:t},files:[...n].sort((e,t)=>e.relativePath.localeCompare(t.relativePath))}}).sort((e,t)=>e.name.localeCompare(t.name)),files:a}}function lh(e,t){let n;for(let r of t)r!==``&&e.startsWith(`${r}/`)&&(n===void 0||r.length>n.length)&&(n=r);return n}var uh=`pi-web.gitFileView`;function dh(e){return e===`tree`?`tree`:`list`}function fh(e=mh()){if(e===void 0)return`list`;try{return dh(e.getItem(uh))}catch{return`list`}}function ph(e,t=mh()){if(t!==void 0)try{t.setItem(uh,e)}catch{}}function mh(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}var hh={submodules:[],files:[]},gh={nodes:[],listModel:hh,expandablePaths:[]},_h=class extends v{constructor(...e){super(...e),this.view=fh(),this.expandedDirectories=new Set}static{this.styles=[Em,h`
|
|
761
761
|
:host { flex: 1 1 auto; }
|
|
762
762
|
.toolbar-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
|
|
763
763
|
.toolbar .toolbar-actions button { margin-left: 0; }
|
|
@@ -825,7 +825,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
|
|
|
825
825
|
<div class="viewer-header"><strong>${e.path??`差异`}</strong><small>${e.staged?`已暂存`:`未暂存`}${e.truncated?` · 已截断`:``}</small></div>
|
|
826
826
|
<unified-diff-viewer .diff=${e.diff}></unified-diff-viewer>
|
|
827
827
|
</section>
|
|
828
|
-
`}function xh(){Pm(()=>import(`./UnifiedDiffViewer-BZewUESj.js`),[],import.meta.url)}function Sh(e){let t=e.branch??`游离 HEAD`,n=e.ahead??0,r=e.behind??0;return n===0&&r===0?t:`${t} · ↑${String(n)} ↓${String(r)}`}function Ch(e,t){return(t===`unmodified`?e:t).slice(0,1).toUpperCase()}function wh(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Th(){return[{id:`workspace.files`,title:`文件`,icon:Cm(`files`),order:10,render:Eh},{id:`workspace.git`,title:`Git`,icon:Cm(`git`),order:20,visible:({workspace:e})=>e.isGitRepo,render:Oh},{id:`workspace.terminal`,title:`终端`,icon:Cm(`terminal`),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Dh}]}function Eh(e){return g`<workspace-files-panel .context=${e}></workspace-files-panel>`}function Dh(e){return kh(),g`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Oh(e){return g`<workspace-git-panel .context=${e}></workspace-git-panel>`}function kh(){Pm(()=>import(`./TerminalPanel-BOafuuU6.js`),__vite__mapDeps([4,5,6]),import.meta.url)}var Ah={apiVersion:1,name:`PI WEB 核心`,activate:()=>{let e=!vt();return{contributions:{actions:e?dm():dm().filter(e=>e.id!==`view.terminal`),workspacePanels:e?Th():Th().filter(e=>e.id!==`workspace.terminal`)}}}},jh={"--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`},Mh={"--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`},Nh={"--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`},Ph={apiVersion:1,name:`PI WEB 主题`,activate:()=>({contributions:{themes:[{id:`pi-web-dark`,name:`PI WEB 深色`,description:`PI WEB 深色配色。`,order:10,colorScheme:`dark`,tokens:Mh},{id:`pi-web-light`,name:`PI WEB 浅色`,description:`PI WEB 浅色配色。`,order:20,colorScheme:`light`,tokens:Nh},{id:`classic`,name:`PI WEB 经典`,description:`原始 PI WEB 深色配色。`,order:30,colorScheme:`dark`,tokens:jh}],themePairs:[{id:`pi-web`,name:`PI WEB`,description:`跟随系统浅色/深色偏好使用 PI WEB 主题。`,order:10,light:`pi-web-light`,dark:`pi-web-dark`}]}})},Fh=/^[a-z][a-z0-9.-]*$/u,Ih=/^[a-z][a-z0-9.-]*$/u,Lh=new WeakMap,Rh=new WeakMap,zh=class{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{id:t,plugin:n}=e;this.validatePluginId(t);let r=this.parseMachineSpecific(t,e.machineSpecific);if(this.pluginIds.has(t))throw Error(`Duplicate plugin id: ${t}`);if(this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,r))return;this.pluginIds.add(t);let i=n.apiVersion;if(i!==1)throw Error(`Unsupported plugin API version for ${t}: ${String(i)}`);let a=n.activate({apiVersion:1,pluginId:t,html:g,svg:Je}).contributions;for(let n of a.actions??[])this.actions.push(this.qualifyAction(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(t,n,e.machineId,e.sourcePluginId));if(e.machineId===void 0){for(let e of a.themes??[])this.themes.push(this.qualifyTheme(t,e));for(let e of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(t,e));this.gatewayPluginIds.add(t),r&&this.gatewayMachineSpecificPluginIds.add(t)}else e.sourcePluginId!==void 0&&r&&Wh(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=Kh(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=Bh(e,t.pluginId),r=t.enabled?.(n),i=r===!1?t.disabledReason?.(n):void 0,a={id:t.id,pluginId:t.pluginId,localId:t.localId,...t.machineId===void 0?{}:{machineId:t.machineId},title:t.title,run:()=>t.run(n)};return t.description!==void 0&&(a.description=t.description),t.shortcut!==void 0&&(a.shortcut=t.shortcut),t.group!==void 0&&(a.group=t.group),r!==void 0&&(a.enabled=r),i!==void 0&&i!==``&&(a.disabledReason=i),a})}getWorkspacePanels(){return[...this.workspacePanels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}getThemes(){return[...this.themes].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getThemePairs(){return[...this.themePairs].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getWorkspaceLabelItems(e){return[...this.workspaceLabels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.id.localeCompare(t.id)).flatMap(t=>t.visible?.(e)===!1?[]:t.items(e))}qualifyAction(e,t,n,r){let i=this.qualify(e,t.id);return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r){let i=this.qualify(e,t.id),a=t.badge,o=t.visible;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(o?.(Vh(t,e))??!0),...a===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?a(Vh(t,e)):void 0},render:n=>t.render(Vh(n,e))}}qualifyWorkspaceLabelContribution(e,t,n,r){let i=this.qualify(e,t.id),a=t.visible,o=t.items;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(a?.(t)??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?o(t):[]}}qualifyTheme(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id}}qualifyThemePair(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t){this.validateLocalId(t);let n=`${e}:${t}`;if(this.contributionIds.has(n))throw Error(`Duplicate contribution id: ${n}`);return this.contributionIds.add(n),n}qualifyReference(e,t){return this.validateLocalId(t),`${e}:${t}`}isContributionActive(e,t,n,r){return t===void 0?!this.isGatewayPluginHiddenForMachine(e,n):t===n&&!this.isRemotePluginHiddenByGateway(r,t)}isRemoteDuplicateHiddenByGateway(e,t,n){return e!==void 0&&t!==void 0&&this.gatewayPluginIds.has(e)&&!this.gatewayMachineSpecificPluginIds.has(e)&&!n}isRemotePluginHiddenByGateway(e,t){return e===void 0||this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0?!1:this.gatewayPluginIds.has(e)}isGatewayPluginHiddenForMachine(e,t){return t!==`local`&&(this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0)}validatePluginId(e){if(!Fh.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!Ih.test(e))throw Error(`Invalid contribution id: ${e}`)}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${Gh(t)}`);return t}};function Bh(e,t){return Lh.get(e)?.(t)??e}function Vh(e,t){return Rh.get(e)?.(t)??e}function Hh(e,t){return Lh.set(e,t),e}function Uh(e,t){return Rh.set(e,t),e}function Wh(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function Gh(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 Kh(e){return e.state.selectedMachine?.id??`local`}var qh=/^[a-z][a-z0-9.-]*$/u;function Jh(e){return qh.test(e)}var Yh=`machine.`;function Xh(e,t){if(e===``)throw Error(`Machine id is required`);if(!Jh(t))throw Error(`Invalid PI WEB plugin id: ${t}`);return`${Yh}${Zh(e)}.${t}`}function Zh(e){return[...new TextEncoder().encode(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function Qh(e=`pi-web-plugins/manifest.json`,t={}){let n=Ot(e),r=await tg(n);if(r===void 0)return[];let i=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=$h(e.module,n),a=ig(await(t.moduleLoader??eg)(r),r);i.push({id:t.machineId===void 0?e.id:Xh(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){console.warn(`Failed to load PI WEB plugin ${e.module}`,t)}return i}function $h(e,t,n){return e.startsWith(`/`)?n===void 0?Ot(e):Ot(e,n):new URL(e,t).toString()}async function eg(e){return Pm(()=>import(e),[],import.meta.url)}async function tg(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(`Failed to load plugin manifest: ${t.statusText}`);return ng(await t.json())}}function ng(e){if(!og(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);return{plugins:e.plugins.map(e=>{if(!og(e)||typeof e.id!=`string`||e.id===``||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);return{id:e.id,module:e.module,machineSpecific:rg(e.machineSpecific)}})}}function rg(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function ig(e,t){if(!og(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(!ag(n))throw Error(`Plugin module ${t} default export is not a PiWebPlugin`);return n}function ag(e){return og(e)&&e.apiVersion===1&&typeof e.name==`string`&&typeof e.activate==`function`}function og(e){return typeof e==`object`&&!!e}var sg=class{constructor(e,t){this.registerPlugins=e,this.shouldLoadRemotePlugin=t,this.loadedMachineIds=new Set,this.machineLoads=new Map}ensureGatewayLoaded(){return this.gatewayLoad??=this.registerPlugins(`PI WEB 插件`,()=>Qh()),this.gatewayLoad}async loadForMachine(e){if(await this.ensureGatewayLoaded(),e.kind!==`remote`||this.loadedMachineIds.has(e.id))return;let t=this.machineLoads.get(e.id);if(t!==void 0)return t;let n=this.registerPlugins(`来自 ${e.name} 的 PI WEB 插件`,()=>Qh(`api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.shouldLoadRemotePlugin(e.id,e.machineSpecific)})).then(t=>{t&&this.loadedMachineIds.add(e.id)}).finally(()=>{this.machineLoads.delete(e.id)});this.machineLoads.set(e.id,n),await n}},cg=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function lg(){return typeof window>`u`||!(`matchMedia`in window)?[]:cg.map(e=>window.matchMedia(e))}function ug(e,t=dg()){return e.some(e=>e.matches)||fg(t)}function dg(){return typeof navigator>`u`?void 0:navigator}function fg(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var pg=class{constructor(e=mg()){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 mg(){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 hg=`(max-width: 760px)`,gg=`(max-width: 1180px)`,_g=class{constructor(e,t={}){this.host=e,this.onMobileNavigationMediaChange=e=>{this.isMobileNavigationLayout!==e.matches&&(this.isMobileNavigationLayout=e.matches,this.host.requestUpdate())},this.onStackedWorkspaceMediaChange=e=>{this.isStackedWorkspaceLayout!==e.matches&&(this.isStackedWorkspaceLayout=e.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{let e=ug(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??vg(),this.stackedWorkspaceMedia=t.stackedWorkspaceMedia??yg(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??lg(),this.viewportPositionRepairer=t.viewportPositionRepairer??new pg,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=ug(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener(`change`,this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.addEventListener(`change`,this.onStackedWorkspaceMediaChange);for(let e of this.pwaDisplayModeMedia)e.addEventListener(`change`,this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener(`change`,this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.removeEventListener(`change`,this.onStackedWorkspaceMediaChange);for(let e of this.pwaDisplayModeMedia)e.removeEventListener(`change`,this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.normalizedMainView(void 0,!1)}normalizedMainView(e,t){return bg(e,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:t})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function vg(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(hg)}function yg(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(gg)}function bg(e,t){let n=e??(t.isMobileNavigationLayout?`navigation`:`chat`);return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||n===`navigation`||n===`chat`?n:`chat`}var xg=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new qo,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??Sg(),this.documentTarget=t.documentTarget??Cg(),this.isDocumentVisible=t.isDocumentVisible??wg,this.scheduleFrame=t.scheduleFrame??Tg}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 Sg(){return typeof window>`u`?void 0:window}function Cg(){return typeof document>`u`?void 0:document}function wg(){return typeof document>`u`||document.visibilityState===`visible`}function Tg(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 Eg=[`machines`,`projects`,`workspaces`,`sessions`];function Dg(e){return e.selectedProject===void 0?`projects`:e.selectedWorkspace===void 0?`workspaces`:`sessions`}function Og(e,t){if(e!==`none`)return e??Dg(t)}function kg(e,t){return t.isMobileLayout?Og(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Ag(e,t,n){return n.isMobileLayout?Og(e,n.state)===t?`none`:t:e}function jg(e,t,n){return n?t:e}function Mg(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Fg(n)}function Ng(e){return Eg[Eg.indexOf(e)+1]}var Pg=class{hostConnected(){}constructor(e,t,n){this.host=e,this.getState=t,this.isMobileLayout=n,this.collapsedSections=[],e.addController(this)}expandedSection(){return Og(this.expanded,this.getState())}isCollapsed(e){return kg(e,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(e){if(this.isMobileLayout()){this.setExpanded(Ag(this.expanded,e,{isMobileLayout:!0,state:this.getState()}));return}this.setCollapsedSections(Mg(this.collapsedSections,e))}expand(e){if(this.isMobileLayout()){this.setExpanded(jg(this.expanded,e,!0));return}this.setCollapsedSections(this.collapsedSections.filter(t=>t!==e))}advanceAfterSelection(e){if(!this.isMobileLayout())return;let t=Ng(e);t!==void 0&&this.expand(t)}open(e,t){this.isMobileLayout()&&(this.expand(e),t())}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}setCollapsedSections(e){Ig(this.collapsedSections,e)||(this.collapsedSections=e,this.host.requestUpdate())}};function Fg(e){let t=new Set(e);return Eg.filter(e=>t.has(e))}function Ig(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var Lg=class{hostConnected(){}constructor(e){this.host=e,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,e.addController(this)}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(e){return[`shell`,Rg(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...this.workspacePanelCollapsed?[`workspace-panel-collapsed`]:[]].join(` `)}};function Rg(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var zg=`pi-web:panel-sizes:v1`,Bg={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},Vg=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??t_(),this.panelSizes=qg(this.storage)}hostConnected(){}constraints(e){return Hg(e)}panelWidth(e,t){return Kg(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=Kg(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=Zg(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=Qg(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(){Jg(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${e_(Kg(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${e_(Kg(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function Hg(e){return Bg[e]}function Ug(e,t,n){return e===`navigation`?n-t:t-n}function Wg(e,t,n,r,i=Hg(e)){return Kg(e,t+Ug(e,n,r),i)}function Gg(e,t,n,r={}){let i=r.constraints??Hg(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=$g(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return Kg(e,t+a,i)}function Kg(e,t,n=Hg(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function qg(e=t_()){try{let t=e?.getItem(zg);return t==null||t===``?{}:Yg(JSON.parse(t))}catch{return{}}}function Jg(e,t=t_()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(zg);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=Kg(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=Kg(`workspace`,e.workspacePanelWidth)),t.setItem(zg,JSON.stringify(n))}catch{}}function Yg(e){if(!n_(e)||e.version!==1)return{};let t={},n=Xg(e.navigationPanelWidth),r=Xg(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=Kg(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=Kg(`workspace`,r)),t}function Xg(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Zg(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function Qg(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function $g(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 e_(e){return`${String(Math.round(e))}px`}function t_(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function n_(e){return typeof e==`object`&&!!e}function r_(){let e=new URLSearchParams(window.location.search);return{machineId:e.get(`machine`)??void 0,projectId:e.get(`project`)??void 0,workspaceId:e.get(`workspace`)??void 0,sessionId:e.get(`session`)??void 0,tool:a_(e.get(`tool`)),view:o_(e.get(`view`))}}function i_(e,t){let n=new URL(window.location.href);n.searchParams.delete(`machine`),n.searchParams.delete(`project`),n.searchParams.delete(`workspace`),n.searchParams.delete(`session`),n.searchParams.delete(`tool`),n.searchParams.delete(`view`),e.machineId!==void 0&&e.machineId!==``&&e.machineId!==`local`&&n.searchParams.set(`machine`,e.machineId),e.projectId!==void 0&&e.projectId!==``&&n.searchParams.set(`project`,e.projectId),e.workspaceId!==void 0&&e.workspaceId!==``&&n.searchParams.set(`workspace`,e.workspaceId),e.sessionId!==void 0&&e.sessionId!==``&&n.searchParams.set(`session`,e.sessionId),e.tool!==void 0&&n.searchParams.set(`tool`,e.tool),e.view!==void 0&&n.searchParams.set(`view`,e.view),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function a_(e){return e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:s_(e)?e:void 0}function o_(e){return e===`chat`?`chat`:e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:s_(e)?e:void 0}function s_(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function c_(){return u_(new URLSearchParams(window.location.search).get(`settings`))}function l_(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 u_(e){if(e===`general`)return`general`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`}function d_(e,t){return t===void 0?e:e.map(e=>p_(e,t))}function f_(e,t){let n=new Set(Ef(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return d_(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?m_(e):e)}function p_(e,t){if(!Object.hasOwn(t,e.id))return e;let n=t[e.id];return n===void 0?e:n===null?m_(e):{...e,shortcut:n}}function m_(e){let t={...e};return delete t.shortcut,t}function h_(e,t){let n=t.api??eo,r=t.pollIntervalMs??1e3,i=t.setTimeout??v_(),a=t.clearTimeout??y_();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:g_(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function g_(e,t,n,r,i){return __(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&&__(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function __(e){return e.status===`succeeded`||e.status===`failed`}function v_(){return(e,t)=>globalThis.setTimeout(e,t)}function y_(){return e=>{globalThis.clearTimeout(e)}}function b_(e,t=`活动中`,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 x_(e,t=`活动中`,n){let r=b_(e,t,n);if(r!==void 0)return g`<span class="action-activity">${r}</span>`}var S_=0,C_=120;function w_(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?E_():T_(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-S_,f=n.top-c-S_;return[...d<C_&&f>d?[`bottom: ${D_(a-n.top+S_)};`,`max-height: ${D_(Math.max(0,f))};`]:[`top: ${D_(n.bottom+S_)};`,`max-height: ${D_(Math.max(0,d))};`],`right: ${D_(Math.max(0,i-u))};`,`max-width: ${D_(Math.max(0,u-o))};`].join(` `)}function T_(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():E_()}function E_(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function D_(e){return`${String(Math.round(e))}px`}var O_=class{constructor(e){this.host=e,this.menuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this.host)||this.close()},e.addController(this)}hostConnected(){document.addEventListener(`click`,this.onDocumentClick)}hostDisconnected(){document.removeEventListener(`click`,this.onDocumentClick)}isOpen(e){return this.openId===e}toggle(e,t){if(this.openId===e){this.close();return}this.menuStyle=w_(t,{constrainTo:`viewport`}),this.openId=e,this.host.requestUpdate()}close(){this.openId===void 0&&this.menuStyle===``||(this.openId=void 0,this.menuStyle=``,this.host.requestUpdate())}closeIfOpenIdMissing(e){this.openId!==void 0&&!e(this.openId)&&this.close()}closeIf(e){e&&this.close()}closeForEscape(e,t){return e.key!==`Escape`||this.openId!==t?!1:(e.preventDefault(),e.stopPropagation(),this.close(),!0)}},k_=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function A_(e){return e.composedPath().some(e=>j_(e,k_))}function j_(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 M_(e,t){A_(e)||t()}function N_(e,t){return A_(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?F_(e,()=>{I_(e.currentTarget,-1)}):e.key===`ArrowDown`?F_(e,()=>{I_(e.currentTarget,1)}):e.key===`Home`?F_(e,()=>{L_(e.currentTarget,0)}):e.key===`End`?F_(e,()=>{L_(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?F_(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?F_(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&F_(e,t.cancel)}function P_(e,t={}){let n=e.querySelector(`.action-row.selected`)??e.querySelector(`.action-row`)??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return n==null?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}function F_(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function I_(e,t){let n=z_(e),r=V_(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||R_(n,i+t)}function L_(e,t){let n=z_(e);n.length!==0&&R_(n,t<0?n.length-1:t)}function R_(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function z_(e){let t=V_(e)?.getRootNode();return t===void 0||!B_(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function B_(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function V_(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var H_=h`
|
|
828
|
+
`}function xh(){Pm(()=>import(`./UnifiedDiffViewer-DbtJHQ4S.js`),[],import.meta.url)}function Sh(e){let t=e.branch??`游离 HEAD`,n=e.ahead??0,r=e.behind??0;return n===0&&r===0?t:`${t} · ↑${String(n)} ↓${String(r)}`}function Ch(e,t){return(t===`unmodified`?e:t).slice(0,1).toUpperCase()}function wh(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Th(){return[{id:`workspace.files`,title:`文件`,icon:Cm(`files`),order:10,render:Eh},{id:`workspace.git`,title:`Git`,icon:Cm(`git`),order:20,visible:({workspace:e})=>e.isGitRepo,render:Oh},{id:`workspace.terminal`,title:`终端`,icon:Cm(`terminal`),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Dh}]}function Eh(e){return g`<workspace-files-panel .context=${e}></workspace-files-panel>`}function Dh(e){return kh(),g`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Oh(e){return g`<workspace-git-panel .context=${e}></workspace-git-panel>`}function kh(){Pm(()=>import(`./TerminalPanel-CoYwbZrx.js`),__vite__mapDeps([4,5,6]),import.meta.url)}var Ah={apiVersion:1,name:`PI WEB 核心`,activate:()=>{let e=!vt();return{contributions:{actions:e?dm():dm().filter(e=>e.id!==`view.terminal`),workspacePanels:e?Th():Th().filter(e=>e.id!==`workspace.terminal`)}}}},jh={"--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`},Mh={"--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`},Nh={"--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`},Ph={apiVersion:1,name:`PI WEB 主题`,activate:()=>({contributions:{themes:[{id:`pi-web-dark`,name:`PI WEB 深色`,description:`PI WEB 深色配色。`,order:10,colorScheme:`dark`,tokens:Mh},{id:`pi-web-light`,name:`PI WEB 浅色`,description:`PI WEB 浅色配色。`,order:20,colorScheme:`light`,tokens:Nh},{id:`classic`,name:`PI WEB 经典`,description:`原始 PI WEB 深色配色。`,order:30,colorScheme:`dark`,tokens:jh}],themePairs:[{id:`pi-web`,name:`PI WEB`,description:`跟随系统浅色/深色偏好使用 PI WEB 主题。`,order:10,light:`pi-web-light`,dark:`pi-web-dark`}]}})},Fh=/^[a-z][a-z0-9.-]*$/u,Ih=/^[a-z][a-z0-9.-]*$/u,Lh=new WeakMap,Rh=new WeakMap,zh=class{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{id:t,plugin:n}=e;this.validatePluginId(t);let r=this.parseMachineSpecific(t,e.machineSpecific);if(this.pluginIds.has(t))throw Error(`Duplicate plugin id: ${t}`);if(this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,r))return;this.pluginIds.add(t);let i=n.apiVersion;if(i!==1)throw Error(`Unsupported plugin API version for ${t}: ${String(i)}`);let a=n.activate({apiVersion:1,pluginId:t,html:g,svg:Je}).contributions;for(let n of a.actions??[])this.actions.push(this.qualifyAction(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(t,n,e.machineId,e.sourcePluginId));for(let n of a.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(t,n,e.machineId,e.sourcePluginId));if(e.machineId===void 0){for(let e of a.themes??[])this.themes.push(this.qualifyTheme(t,e));for(let e of a.themePairs??[])this.themePairs.push(this.qualifyThemePair(t,e));this.gatewayPluginIds.add(t),r&&this.gatewayMachineSpecificPluginIds.add(t)}else e.sourcePluginId!==void 0&&r&&Wh(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=Kh(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=Bh(e,t.pluginId),r=t.enabled?.(n),i=r===!1?t.disabledReason?.(n):void 0,a={id:t.id,pluginId:t.pluginId,localId:t.localId,...t.machineId===void 0?{}:{machineId:t.machineId},title:t.title,run:()=>t.run(n)};return t.description!==void 0&&(a.description=t.description),t.shortcut!==void 0&&(a.shortcut=t.shortcut),t.group!==void 0&&(a.group=t.group),r!==void 0&&(a.enabled=r),i!==void 0&&i!==``&&(a.disabledReason=i),a})}getWorkspacePanels(){return[...this.workspacePanels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}getThemes(){return[...this.themes].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getThemePairs(){return[...this.themePairs].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getWorkspaceLabelItems(e){return[...this.workspaceLabels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.id.localeCompare(t.id)).flatMap(t=>t.visible?.(e)===!1?[]:t.items(e))}qualifyAction(e,t,n,r){let i=this.qualify(e,t.id);return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r){let i=this.qualify(e,t.id),a=t.badge,o=t.visible;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(o?.(Vh(t,e))??!0),...a===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?a(Vh(t,e)):void 0},render:n=>t.render(Vh(n,e))}}qualifyWorkspaceLabelContribution(e,t,n,r){let i=this.qualify(e,t.id),a=t.visible,o=t.items;return{...t,id:i,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(a?.(t)??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?o(t):[]}}qualifyTheme(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id}}qualifyThemePair(e,t){let n=this.qualify(e,t.id);return{...t,id:n,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t){this.validateLocalId(t);let n=`${e}:${t}`;if(this.contributionIds.has(n))throw Error(`Duplicate contribution id: ${n}`);return this.contributionIds.add(n),n}qualifyReference(e,t){return this.validateLocalId(t),`${e}:${t}`}isContributionActive(e,t,n,r){return t===void 0?!this.isGatewayPluginHiddenForMachine(e,n):t===n&&!this.isRemotePluginHiddenByGateway(r,t)}isRemoteDuplicateHiddenByGateway(e,t,n){return e!==void 0&&t!==void 0&&this.gatewayPluginIds.has(e)&&!this.gatewayMachineSpecificPluginIds.has(e)&&!n}isRemotePluginHiddenByGateway(e,t){return e===void 0||this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0?!1:this.gatewayPluginIds.has(e)}isGatewayPluginHiddenForMachine(e,t){return t!==`local`&&(this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0)}validatePluginId(e){if(!Fh.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!Ih.test(e))throw Error(`Invalid contribution id: ${e}`)}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${Gh(t)}`);return t}};function Bh(e,t){return Lh.get(e)?.(t)??e}function Vh(e,t){return Rh.get(e)?.(t)??e}function Hh(e,t){return Lh.set(e,t),e}function Uh(e,t){return Rh.set(e,t),e}function Wh(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function Gh(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 Kh(e){return e.state.selectedMachine?.id??`local`}var qh=/^[a-z][a-z0-9.-]*$/u;function Jh(e){return qh.test(e)}var Yh=`machine.`;function Xh(e,t){if(e===``)throw Error(`Machine id is required`);if(!Jh(t))throw Error(`Invalid PI WEB plugin id: ${t}`);return`${Yh}${Zh(e)}.${t}`}function Zh(e){return[...new TextEncoder().encode(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function Qh(e=`pi-web-plugins/manifest.json`,t={}){let n=Ot(e),r=await tg(n);if(r===void 0)return[];let i=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=$h(e.module,n),a=ig(await(t.moduleLoader??eg)(r),r);i.push({id:t.machineId===void 0?e.id:Xh(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){console.warn(`Failed to load PI WEB plugin ${e.module}`,t)}return i}function $h(e,t,n){return e.startsWith(`/`)?n===void 0?Ot(e):Ot(e,n):new URL(e,t).toString()}async function eg(e){return Pm(()=>import(e),[],import.meta.url)}async function tg(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(`Failed to load plugin manifest: ${t.statusText}`);return ng(await t.json())}}function ng(e){if(!og(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);return{plugins:e.plugins.map(e=>{if(!og(e)||typeof e.id!=`string`||e.id===``||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);return{id:e.id,module:e.module,machineSpecific:rg(e.machineSpecific)}})}}function rg(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function ig(e,t){if(!og(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(!ag(n))throw Error(`Plugin module ${t} default export is not a PiWebPlugin`);return n}function ag(e){return og(e)&&e.apiVersion===1&&typeof e.name==`string`&&typeof e.activate==`function`}function og(e){return typeof e==`object`&&!!e}var sg=class{constructor(e,t){this.registerPlugins=e,this.shouldLoadRemotePlugin=t,this.loadedMachineIds=new Set,this.machineLoads=new Map}ensureGatewayLoaded(){return this.gatewayLoad??=this.registerPlugins(`PI WEB 插件`,()=>Qh()),this.gatewayLoad}async loadForMachine(e){if(await this.ensureGatewayLoaded(),e.kind!==`remote`||this.loadedMachineIds.has(e.id))return;let t=this.machineLoads.get(e.id);if(t!==void 0)return t;let n=this.registerPlugins(`来自 ${e.name} 的 PI WEB 插件`,()=>Qh(`api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.shouldLoadRemotePlugin(e.id,e.machineSpecific)})).then(t=>{t&&this.loadedMachineIds.add(e.id)}).finally(()=>{this.machineLoads.delete(e.id)});this.machineLoads.set(e.id,n),await n}},cg=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function lg(){return typeof window>`u`||!(`matchMedia`in window)?[]:cg.map(e=>window.matchMedia(e))}function ug(e,t=dg()){return e.some(e=>e.matches)||fg(t)}function dg(){return typeof navigator>`u`?void 0:navigator}function fg(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var pg=class{constructor(e=mg()){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 mg(){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 hg=`(max-width: 760px)`,gg=`(max-width: 1180px)`,_g=class{constructor(e,t={}){this.host=e,this.onMobileNavigationMediaChange=e=>{this.isMobileNavigationLayout!==e.matches&&(this.isMobileNavigationLayout=e.matches,this.host.requestUpdate())},this.onStackedWorkspaceMediaChange=e=>{this.isStackedWorkspaceLayout!==e.matches&&(this.isStackedWorkspaceLayout=e.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{let e=ug(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??vg(),this.stackedWorkspaceMedia=t.stackedWorkspaceMedia??yg(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??lg(),this.viewportPositionRepairer=t.viewportPositionRepairer??new pg,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=ug(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener(`change`,this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.addEventListener(`change`,this.onStackedWorkspaceMediaChange);for(let e of this.pwaDisplayModeMedia)e.addEventListener(`change`,this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener(`change`,this.onMobileNavigationMediaChange),this.stackedWorkspaceMedia?.removeEventListener(`change`,this.onStackedWorkspaceMediaChange);for(let e of this.pwaDisplayModeMedia)e.removeEventListener(`change`,this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.normalizedMainView(void 0,!1)}normalizedMainView(e,t){return bg(e,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:t})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function vg(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(hg)}function yg(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(gg)}function bg(e,t){let n=e??(t.isMobileNavigationLayout?`navigation`:`chat`);return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||n===`navigation`||n===`chat`?n:`chat`}var xg=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new qo,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??Sg(),this.documentTarget=t.documentTarget??Cg(),this.isDocumentVisible=t.isDocumentVisible??wg,this.scheduleFrame=t.scheduleFrame??Tg}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 Sg(){return typeof window>`u`?void 0:window}function Cg(){return typeof document>`u`?void 0:document}function wg(){return typeof document>`u`||document.visibilityState===`visible`}function Tg(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 Eg=[`machines`,`projects`,`workspaces`,`sessions`];function Dg(e){return e.selectedProject===void 0?`projects`:e.selectedWorkspace===void 0?`workspaces`:`sessions`}function Og(e,t){if(e!==`none`)return e??Dg(t)}function kg(e,t){return t.isMobileLayout?Og(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Ag(e,t,n){return n.isMobileLayout?Og(e,n.state)===t?`none`:t:e}function jg(e,t,n){return n?t:e}function Mg(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Fg(n)}function Ng(e){return Eg[Eg.indexOf(e)+1]}var Pg=class{hostConnected(){}constructor(e,t,n){this.host=e,this.getState=t,this.isMobileLayout=n,this.collapsedSections=[],e.addController(this)}expandedSection(){return Og(this.expanded,this.getState())}isCollapsed(e){return kg(e,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(e){if(this.isMobileLayout()){this.setExpanded(Ag(this.expanded,e,{isMobileLayout:!0,state:this.getState()}));return}this.setCollapsedSections(Mg(this.collapsedSections,e))}expand(e){if(this.isMobileLayout()){this.setExpanded(jg(this.expanded,e,!0));return}this.setCollapsedSections(this.collapsedSections.filter(t=>t!==e))}advanceAfterSelection(e){if(!this.isMobileLayout())return;let t=Ng(e);t!==void 0&&this.expand(t)}open(e,t){this.isMobileLayout()&&(this.expand(e),t())}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}setCollapsedSections(e){Ig(this.collapsedSections,e)||(this.collapsedSections=e,this.host.requestUpdate())}};function Fg(e){let t=new Set(e);return Eg.filter(e=>t.has(e))}function Ig(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var Lg=class{hostConnected(){}constructor(e){this.host=e,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,e.addController(this)}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.host.requestUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.host.requestUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.host.requestUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.host.requestUpdate())}shellClass(e){return[`shell`,Rg(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...this.workspacePanelCollapsed?[`workspace-panel-collapsed`]:[]].join(` `)}};function Rg(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var zg=`pi-web:panel-sizes:v1`,Bg={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},Vg=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??t_(),this.panelSizes=qg(this.storage)}hostConnected(){}constraints(e){return Hg(e)}panelWidth(e,t){return Kg(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=Kg(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=Zg(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=Qg(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(){Jg(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${e_(Kg(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${e_(Kg(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function Hg(e){return Bg[e]}function Ug(e,t,n){return e===`navigation`?n-t:t-n}function Wg(e,t,n,r,i=Hg(e)){return Kg(e,t+Ug(e,n,r),i)}function Gg(e,t,n,r={}){let i=r.constraints??Hg(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=$g(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return Kg(e,t+a,i)}function Kg(e,t,n=Hg(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function qg(e=t_()){try{let t=e?.getItem(zg);return t==null||t===``?{}:Yg(JSON.parse(t))}catch{return{}}}function Jg(e,t=t_()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(zg);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=Kg(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=Kg(`workspace`,e.workspacePanelWidth)),t.setItem(zg,JSON.stringify(n))}catch{}}function Yg(e){if(!n_(e)||e.version!==1)return{};let t={},n=Xg(e.navigationPanelWidth),r=Xg(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=Kg(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=Kg(`workspace`,r)),t}function Xg(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Zg(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function Qg(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function $g(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 e_(e){return`${String(Math.round(e))}px`}function t_(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function n_(e){return typeof e==`object`&&!!e}function r_(){let e=new URLSearchParams(window.location.search);return{machineId:e.get(`machine`)??void 0,projectId:e.get(`project`)??void 0,workspaceId:e.get(`workspace`)??void 0,sessionId:e.get(`session`)??void 0,tool:a_(e.get(`tool`)),view:o_(e.get(`view`))}}function i_(e,t){let n=new URL(window.location.href);n.searchParams.delete(`machine`),n.searchParams.delete(`project`),n.searchParams.delete(`workspace`),n.searchParams.delete(`session`),n.searchParams.delete(`tool`),n.searchParams.delete(`view`),e.machineId!==void 0&&e.machineId!==``&&e.machineId!==`local`&&n.searchParams.set(`machine`,e.machineId),e.projectId!==void 0&&e.projectId!==``&&n.searchParams.set(`project`,e.projectId),e.workspaceId!==void 0&&e.workspaceId!==``&&n.searchParams.set(`workspace`,e.workspaceId),e.sessionId!==void 0&&e.sessionId!==``&&n.searchParams.set(`session`,e.sessionId),e.tool!==void 0&&n.searchParams.set(`tool`,e.tool),e.view!==void 0&&n.searchParams.set(`view`,e.view),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function a_(e){return e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:s_(e)?e:void 0}function o_(e){return e===`chat`?`chat`:e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:s_(e)?e:void 0}function s_(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function c_(){return u_(new URLSearchParams(window.location.search).get(`settings`))}function l_(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 u_(e){if(e===`general`)return`general`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`}function d_(e,t){return t===void 0?e:e.map(e=>p_(e,t))}function f_(e,t){let n=new Set(Ef(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return d_(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?m_(e):e)}function p_(e,t){if(!Object.hasOwn(t,e.id))return e;let n=t[e.id];return n===void 0?e:n===null?m_(e):{...e,shortcut:n}}function m_(e){let t={...e};return delete t.shortcut,t}function h_(e,t){let n=t.api??eo,r=t.pollIntervalMs??1e3,i=t.setTimeout??v_(),a=t.clearTimeout??y_();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:g_(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function g_(e,t,n,r,i){return __(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&&__(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function __(e){return e.status===`succeeded`||e.status===`failed`}function v_(){return(e,t)=>globalThis.setTimeout(e,t)}function y_(){return e=>{globalThis.clearTimeout(e)}}function b_(e,t=`活动中`,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 x_(e,t=`活动中`,n){let r=b_(e,t,n);if(r!==void 0)return g`<span class="action-activity">${r}</span>`}var S_=0,C_=120;function w_(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?E_():T_(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-S_,f=n.top-c-S_;return[...d<C_&&f>d?[`bottom: ${D_(a-n.top+S_)};`,`max-height: ${D_(Math.max(0,f))};`]:[`top: ${D_(n.bottom+S_)};`,`max-height: ${D_(Math.max(0,d))};`],`right: ${D_(Math.max(0,i-u))};`,`max-width: ${D_(Math.max(0,u-o))};`].join(` `)}function T_(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():E_()}function E_(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function D_(e){return`${String(Math.round(e))}px`}var O_=class{constructor(e){this.host=e,this.menuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this.host)||this.close()},e.addController(this)}hostConnected(){document.addEventListener(`click`,this.onDocumentClick)}hostDisconnected(){document.removeEventListener(`click`,this.onDocumentClick)}isOpen(e){return this.openId===e}toggle(e,t){if(this.openId===e){this.close();return}this.menuStyle=w_(t,{constrainTo:`viewport`}),this.openId=e,this.host.requestUpdate()}close(){this.openId===void 0&&this.menuStyle===``||(this.openId=void 0,this.menuStyle=``,this.host.requestUpdate())}closeIfOpenIdMissing(e){this.openId!==void 0&&!e(this.openId)&&this.close()}closeIf(e){e&&this.close()}closeForEscape(e,t){return e.key!==`Escape`||this.openId!==t?!1:(e.preventDefault(),e.stopPropagation(),this.close(),!0)}},k_=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function A_(e){return e.composedPath().some(e=>j_(e,k_))}function j_(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 M_(e,t){A_(e)||t()}function N_(e,t){return A_(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?F_(e,()=>{I_(e.currentTarget,-1)}):e.key===`ArrowDown`?F_(e,()=>{I_(e.currentTarget,1)}):e.key===`Home`?F_(e,()=>{L_(e.currentTarget,0)}):e.key===`End`?F_(e,()=>{L_(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?F_(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?F_(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&F_(e,t.cancel)}function P_(e,t={}){let n=e.querySelector(`.action-row.selected`)??e.querySelector(`.action-row`)??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return n==null?!1:(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}function F_(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function I_(e,t){let n=z_(e),r=V_(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||R_(n,i+t)}function L_(e,t){let n=z_(e);n.length!==0&&R_(n,t<0?n.length-1:t)}function R_(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function z_(e){let t=V_(e)?.getRootNode();return t===void 0||!B_(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function B_(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function V_(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var H_=h`
|
|
829
829
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
830
830
|
:host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
831
831
|
section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
|
|
@@ -1040,19 +1040,21 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
|
|
|
1040
1040
|
<button type="button" class="detail-copy" title=${i} aria-label=${i} @click=${()=>{this.copyDetail(e,t)}}>
|
|
1041
1041
|
<span aria-hidden="true">${r?`✓`:`⧉`}</span>
|
|
1042
1042
|
</button>
|
|
1043
|
-
`}async copyDetail(e,t){await q_(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)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuStyle=w_(t,{constrainTo:`viewport`}),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key===`Escape`&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}N_(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=Dm}};B([b({attribute:!1})],V.prototype,`workspaces`,void 0),B([b({attribute:!1})],V.prototype,`selected`,void 0),B([b({type:Boolean,reflect:!0})],V.prototype,`collapsible`,void 0),B([b({type:Boolean,reflect:!0})],V.prototype,`collapsed`,void 0),B([b({attribute:!1})],V.prototype,`workspaceLabelItems`,void 0),B([b({attribute:!1})],V.prototype,`activities`,void 0),B([b({attribute:!1})],V.prototype,`deletingWorkspaceIds`,void 0),B([b({attribute:!1})],V.prototype,`unreadWorkspaceIds`,void 0),B([b({attribute:!1})],V.prototype,`onSelect`,void 0),B([b({attribute:!1})],V.prototype,`onDelete`,void 0),B([b({attribute:!1})],V.prototype,`onToggleCollapsed`,void 0),B([b({attribute:!1})],V.prototype,`onFocusPreviousSection`,void 0),B([b({attribute:!1})],V.prototype,`onFocusNextSection`,void 0),B([b({attribute:!1})],V.prototype,`onCancelKeyboardNavigation`,void 0),B([x()],V.prototype,`openMenuWorkspaceId`,void 0),B([x()],V.prototype,`menuStyle`,void 0),B([x()],V.prototype,`copiedDetailKey`,void 0),V=B([y(`workspace-list`)],V);function iv(e){return`${e.branch??e.label}${e.isMain?` · main`:``}`}function av(e){return e.isGitWorktree&&!e.isMain}function ov(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}function sv(e){return e.slice(-8)}function cv(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?sv(e.id):e.firstMessage}var H=class extends v{constructor(...e){super(...e),this.sessions=[],this.pinnedSessionIds=[],this.statuses={},this.activities={},this.sending={},this.unreadSessionIds=new Set,this.startingCount=0,this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.canCleanup=!1,this.authoritativeSessionPersistence=!1,this.archivedDeleteUnavailableMessage=`请更新并重启此机器上的 Pi-Web 后再删除已归档会话。`,this.cleanupUnavailableMessage=`请更新并重启此机器上的 Pi-Web 后再清理会话。`,this.collapsible=!1,this.collapsed=!1,this.parentLocation=()=>({kind:`unknown`}),this.menuStyle=``,this.archivedExpanded=!1,this.selectionScopes=new Set,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,P_(this.renderRoot,{fallbackSelector:`.section-toggle, h2 button:not([disabled])`})}render(){let e=
|
|
1043
|
+
`}async copyDetail(e,t){await q_(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)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuStyle=w_(t,{constrainTo:`viewport`}),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key===`Escape`&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}N_(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=Dm}};B([b({attribute:!1})],V.prototype,`workspaces`,void 0),B([b({attribute:!1})],V.prototype,`selected`,void 0),B([b({type:Boolean,reflect:!0})],V.prototype,`collapsible`,void 0),B([b({type:Boolean,reflect:!0})],V.prototype,`collapsed`,void 0),B([b({attribute:!1})],V.prototype,`workspaceLabelItems`,void 0),B([b({attribute:!1})],V.prototype,`activities`,void 0),B([b({attribute:!1})],V.prototype,`deletingWorkspaceIds`,void 0),B([b({attribute:!1})],V.prototype,`unreadWorkspaceIds`,void 0),B([b({attribute:!1})],V.prototype,`onSelect`,void 0),B([b({attribute:!1})],V.prototype,`onDelete`,void 0),B([b({attribute:!1})],V.prototype,`onToggleCollapsed`,void 0),B([b({attribute:!1})],V.prototype,`onFocusPreviousSection`,void 0),B([b({attribute:!1})],V.prototype,`onFocusNextSection`,void 0),B([b({attribute:!1})],V.prototype,`onCancelKeyboardNavigation`,void 0),B([x()],V.prototype,`openMenuWorkspaceId`,void 0),B([x()],V.prototype,`menuStyle`,void 0),B([x()],V.prototype,`copiedDetailKey`,void 0),V=B([y(`workspace-list`)],V);function iv(e){return`${e.branch??e.label}${e.isMain?` · main`:``}`}function av(e){return e.isGitWorktree&&!e.isMain}function ov(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}function sv(e){return e.slice(-8)}function cv(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?sv(e.id):e.firstMessage}var lv=new Set([`onSelect`,`onSearch`,`onTogglePin`,`onStart`,`onToggleCollapsed`,`onArchivedCollapsed`,`onFocusPreviousSection`,`onFocusNextSection`,`onCancelKeyboardNavigation`,`onArchive`,`onArchiveWithDescendants`,`onArchiveMany`,`onRestore`,`onDelete`,`onDeleteArchived`,`onDeleteArchivedMany`,`onRename`,`onDetachParent`,`parentLocation`,`onGoToParent`,`onMarkRead`,`onMarkReadMany`,`onReload`,`onCleanup`]),H=class extends v{constructor(...e){super(...e),this.scopeKey=``,this.sessions=[],this.pinnedSessionIds=[],this.statuses={},this.activities={},this.sending={},this.unreadSessionIds=new Set,this.startingCount=0,this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.canCleanup=!1,this.authoritativeSessionPersistence=!1,this.archivedDeleteUnavailableMessage=`请更新并重启此机器上的 Pi-Web 后再删除已归档会话。`,this.cleanupUnavailableMessage=`请更新并重启此机器上的 Pi-Web 后再清理会话。`,this.collapsible=!1,this.collapsed=!1,this.parentLocation=()=>({kind:`unknown`}),this.menuStyle=``,this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set,this.currentVisibleLimit=50,this.archivedVisibleLimit=50,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),this.loadMoreObserver?.disconnect(),this.loadMoreObserver=void 0,super.disconnectedCallback()}willUpdate(e){e.has(`scopeKey`)&&(this.currentVisibleLimit=50,this.archivedVisibleLimit=50),(e.has(`selected`)||e.has(`sessions`)||e.has(`pinnedSessionIds`))&&this.expandVisibleLimitForSelected()}shouldUpdate(e){for(let[t,n]of e)if(!lv.has(String(t))&&!(t===`sessions`&&_v(n,this.sessions))&&!(t===`selected`&&yv(n,this.selected))&&!(t===`statuses`&&bv(n,this.statuses,this.activities,this.sending,this.sessions,this.authoritativeSessionPersistence,`status`))&&!(t===`activities`&&bv(n,this.activities,this.statuses,this.sending,this.sessions,this.authoritativeSessionPersistence,`activity`)))return!0;return!1}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(),this.observeLoadMoreSentinels()}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,P_(this.renderRoot,{fallbackSelector:`.section-toggle, h2 button:not([disabled])`})}render(){let e=jv(this.sessions,this.pinnedSessionIds),t=new Set(e.map(e=>e.session.id)),n=e.map(e=>e.session).filter(e=>mv(e)===`current`),r=Mv(this.sessions.filter(e=>e.archived===!0&&!t.has(e.id)),this.pinnedSessionIds),i=uv(n,this.unreadSessionIds),a=e.slice(0,this.currentVisibleLimit),o=a.map(e=>e.session).filter(e=>mv(e)===`current`),s=r.slice(0,this.archivedVisibleLimit),c=s.map(e=>e.session);return g`
|
|
1044
1044
|
<section>
|
|
1045
|
-
${this.renderHeading(e.length+r.length,n,
|
|
1045
|
+
${this.renderHeading(e.length+r.length,n,i)}
|
|
1046
1046
|
${this.collapsed?null:g`
|
|
1047
1047
|
<div class="list-body">
|
|
1048
|
-
${this.renderCurrentSelectionToolbar(
|
|
1048
|
+
${this.renderCurrentSelectionToolbar(o)}
|
|
1049
1049
|
${this.startingCount>0?this.renderStartingSession():null}
|
|
1050
|
-
${
|
|
1050
|
+
${a.map(e=>this.renderSession(e,`current`))}
|
|
1051
|
+
${this.renderLoadMoreSentinel(`current`,a.length,e.length)}
|
|
1051
1052
|
${r.length>0?g`
|
|
1052
|
-
${this.renderArchivedHeading(r.map(e=>e.session))}
|
|
1053
|
+
${this.renderArchivedHeading(r.map(e=>e.session),c)}
|
|
1053
1054
|
${this.archivedExpanded?g`
|
|
1054
|
-
${this.renderArchivedSelectionToolbar(
|
|
1055
|
-
${
|
|
1055
|
+
${this.renderArchivedSelectionToolbar(c)}
|
|
1056
|
+
${s.map(e=>this.renderSession(e,`archived`))}
|
|
1057
|
+
${this.renderLoadMoreSentinel(`archived`,s.length,r.length)}
|
|
1056
1058
|
`:null}
|
|
1057
1059
|
`:null}
|
|
1058
1060
|
</div>
|
|
@@ -1084,10 +1086,10 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
|
|
|
1084
1086
|
<small>正在等待${e?`新会话`:`会话`}创建</small>
|
|
1085
1087
|
</div>
|
|
1086
1088
|
</div>
|
|
1087
|
-
`}renderArchivedHeading(e){let
|
|
1089
|
+
`}renderArchivedHeading(e,t){let n=this.selectionScopes.has(`archived`);return g`
|
|
1088
1090
|
<h2 class="subheading">
|
|
1089
1091
|
<button class="section-toggle" aria-expanded=${String(this.archivedExpanded)} @click=${()=>{this.toggleArchived()}}><span>${this.archivedExpanded?`▾`:`▸`} 已归档</span></button>
|
|
1090
|
-
${this.archivedExpanded?g`<button class="bulk-select-entry ${
|
|
1092
|
+
${this.archivedExpanded?g`<button class="bulk-select-entry ${n?`selected`:``}" title=${n?`关闭已归档会话选择`:`选择已归档会话`} aria-label=${n?`关闭已归档会话选择`:`选择已归档会话`} aria-expanded=${String(n)} aria-pressed=${String(n)} @click=${()=>{this.toggleSelection(`archived`,t)}}>☑</button>`:null}
|
|
1091
1093
|
<small class="section-count">${e.length}</small>
|
|
1092
1094
|
</h2>
|
|
1093
1095
|
`}renderCurrentSelectionToolbar(e){if(e.length===0||!this.selectionScopes.has(`current`))return null;let t=this.selectedSessions(`current`),n=t.filter(e=>Au(e,this.statuses[e.id],this.sessionPersistenceOptions())),r=t.filter(e=>this.unreadSessionIds.has(e.id)),i=e.length>0&&e.every(e=>this.selectedSessionIds.has(e.id)),a=e.filter(e=>this.selectedSessionIds.has(e.id)).length;return g`
|
|
@@ -1108,45 +1110,49 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
|
|
|
1108
1110
|
<button @click=${()=>{this.closeSelection(`archived`)}}>完成</button>
|
|
1109
1111
|
${this.canDeleteArchived?null:g`<small class="capability-hint">${this.archivedDeleteUnavailableMessage}</small>`}
|
|
1110
1112
|
</div>
|
|
1111
|
-
`}renderSession(e,t
|
|
1113
|
+
`}renderSession(e,t){let{session:n}=e,r=Math.min(e.depth,2),i=mv(n)===t,a=this.selectionScopes.has(t),o=a&&i,s=o&&this.selectedSessionIds.has(n.id),c=this.statuses[n.id],l=this.activities[n.id],u=Ov(n,c,l,this.sending[n.id]===!0),d=kv(n,this.unreadSessionIds),f=this.sessionPersistenceOptions(),p=Au(n,c,f),m=fv(n,c,f),ee=ju(n,c,f),te=p&&this.canReload,ne=this.pinnedSessionIds.includes(n.id),re=n.persisted!==!1,ie=this.openMenuSessionId===n.id?gv(this.sessions,n):0;return g`
|
|
1112
1114
|
<div
|
|
1113
|
-
class="action-row ${this.selected?.id===
|
|
1114
|
-
style=${`--depth:${String(
|
|
1115
|
+
class="action-row ${this.selected?.id===n.id?`selected`:``} ${s?`bulk-selected`:``} ${n.archived===!0?`archived`:``} ${a?`selecting`:``} ${d?`unread`:``} ${ne?`pinned`:``}"
|
|
1116
|
+
style=${`--depth:${String(r)}`}
|
|
1115
1117
|
tabindex="0"
|
|
1116
|
-
title=${
|
|
1117
|
-
@click=${e=>{M_(e,()=>{this.activateSessionRow(
|
|
1118
|
-
@keydown=${e=>{this.handleSessionKeydown(e,
|
|
1118
|
+
title=${n.path}
|
|
1119
|
+
@click=${e=>{M_(e,()=>{this.activateSessionRow(n,t)})}}
|
|
1120
|
+
@keydown=${e=>{this.handleSessionKeydown(e,n,t)}}
|
|
1119
1121
|
>
|
|
1120
|
-
<div class="action-main ${
|
|
1121
|
-
${
|
|
1122
|
-
<span class="action-name-line"><span class="action-name" dir="auto">${this.renderRowMarker(e)}${
|
|
1123
|
-
${this.renderActivity(d
|
|
1122
|
+
<div class="action-main ${a?`selecting`:``}">
|
|
1123
|
+
${o?g`<input class="session-checkbox" type="checkbox" aria-label=${`选择 ${cv(n)}`} .checked=${s} @click=${e=>{e.stopPropagation()}} @change=${()=>{this.toggleSelected(n.id)}}>`:null}
|
|
1124
|
+
<span class="action-name-line"><span class="action-name" dir="auto">${this.renderRowMarker(e)}${ne?g`<span class="pin-indicator" title="已置顶" aria-label="已置顶">★</span>`:null}${cv(n)}</span>${this.renderRowBadges(e)}</span><small>${this.renderSessionMetaPrefix(n,c,l)}${this.renderRelatedSessionsMeta(e)}${String(n.messageCount)} 条消息</small>
|
|
1125
|
+
${this.renderActivity(u,d)}
|
|
1124
1126
|
</div>
|
|
1125
1127
|
<div class="action-menu">
|
|
1126
|
-
<button class="action-menu-toggle" title="会话操作" @click=${e=>{e.stopPropagation(),this.toggleMenu(
|
|
1127
|
-
${this.openMenuSessionId===
|
|
1128
|
+
<button class="action-menu-toggle" title="会话操作" @click=${e=>{e.stopPropagation(),this.toggleMenu(n.id,e.currentTarget)}}>⋯</button>
|
|
1129
|
+
${this.openMenuSessionId===n.id?g`
|
|
1128
1130
|
<div class="action-menu-panel" style=${this.menuStyle}>
|
|
1129
|
-
${
|
|
1130
|
-
${
|
|
1131
|
-
<button title="恢复会话" @click=${()=>{this.openMenuSessionId=void 0,this.onRestore?.(
|
|
1132
|
-
<button class="danger" title=${this.canDeleteArchived?`永久删除已归档会话`:this.archivedDeleteUnavailableMessage} ?disabled=${!this.canDeleteArchived} @click=${()=>{this.openMenuSessionId=void 0,this.confirmDeleteArchived(
|
|
1133
|
-
`:
|
|
1134
|
-
${
|
|
1135
|
-
${
|
|
1136
|
-
${this.unreadSessionIds.has(
|
|
1137
|
-
${
|
|
1138
|
-
<button title="归档会话" @click=${()=>{this.openMenuSessionId=void 0,this.onArchive?.(
|
|
1139
|
-
${
|
|
1131
|
+
${n.archived===!0?g`
|
|
1132
|
+
${re?g`<button title=${ne?`取消置顶会话`:`置顶会话`} @click=${()=>{this.openMenuSessionId=void 0,this.onTogglePin?.(n)}}>${ne?`取消置顶`:`置顶`}</button>`:null}
|
|
1133
|
+
<button title="恢复会话" @click=${()=>{this.openMenuSessionId=void 0,this.onRestore?.(n)}}>恢复</button>
|
|
1134
|
+
<button class="danger" title=${this.canDeleteArchived?`永久删除已归档会话`:this.archivedDeleteUnavailableMessage} ?disabled=${!this.canDeleteArchived} @click=${()=>{this.openMenuSessionId=void 0,this.confirmDeleteArchived(n)}}>删除已归档会话</button>
|
|
1135
|
+
`:ee?g`<button title="删除临时新会话" @click=${()=>{this.openMenuSessionId=void 0,this.onDelete?.(n)}}>删除</button>`:g`
|
|
1136
|
+
${re?g`<button title=${ne?`取消置顶会话`:`置顶会话`} @click=${()=>{this.openMenuSessionId=void 0,this.onTogglePin?.(n)}}>${ne?`取消置顶`:`置顶`}</button>`:null}
|
|
1137
|
+
${m?g`<button title="重命名会话" @click=${()=>{this.renameSession(n)}}>重命名</button>`:null}
|
|
1138
|
+
${this.unreadSessionIds.has(n.id)?g`<button title="将会话标记为已读" @click=${()=>{this.openMenuSessionId=void 0,this.onMarkRead?.(n)}}>标记为已读</button>`:null}
|
|
1139
|
+
${p?g`
|
|
1140
|
+
<button title="归档会话" @click=${()=>{this.openMenuSessionId=void 0,this.onArchive?.(n)}}>归档</button>
|
|
1141
|
+
${ie>0?g`<button title="归档此会话及其后代会话" @click=${()=>{this.openMenuSessionId=void 0,this.confirmArchiveWithDescendants(n,ie)}}>连同后代归档(${ie})</button>`:null}
|
|
1140
1142
|
`:null}
|
|
1141
1143
|
${this.renderGoToParentMenuItem(e)}
|
|
1142
|
-
${
|
|
1143
|
-
${
|
|
1144
|
+
${n.parentSessionPath===void 0?null:g`<button title="从父会话分离" @click=${()=>{this.openMenuSessionId=void 0,this.onDetachParent?.(n)}}>从父会话分离</button>`}
|
|
1145
|
+
${te?g`<button title=${Lo(this.statuses[n.id],this.activities[n.id])?`请先停止当前会话活动,再从磁盘重新加载`:`从磁盘重新加载会话,但不刷新 Pi 运行时资源`} ?disabled=${Lo(this.statuses[n.id],this.activities[n.id])} @click=${()=>{this.openMenuSessionId=void 0,this.onReload?.(n)}}>从磁盘重新加载</button>`:null}
|
|
1144
1146
|
`}
|
|
1145
1147
|
</div>
|
|
1146
1148
|
`:null}
|
|
1147
1149
|
</div>
|
|
1148
1150
|
</div>
|
|
1149
|
-
`}renderRowMarker(e){if(e.hasMissingParent){let t=this.parentLocation(e.session);return g`<span class="tree-marker orphan-marker" title=${$f(t)} aria-label=${Qf(t)}>↳</span>`}return 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>`}renderRelatedSessionsMeta(e){let t=[e.hasMissingParent?Qf(this.parentLocation(e.session)):void 0,
|
|
1151
|
+
`}renderRowMarker(e){if(e.hasMissingParent){let t=this.parentLocation(e.session);return g`<span class="tree-marker orphan-marker" title=${$f(t)} aria-label=${Qf(t)}>↳</span>`}return 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>`}renderRelatedSessionsMeta(e){let t=[e.hasMissingParent?Qf(this.parentLocation(e.session)):void 0,pv(e.session.childSessionsElsewhere)].filter(e=>e!==void 0);return t.length===0?null:`${t.join(` · `)} · `}renderGoToParentMenuItem(e){if(!e.hasMissingParent||this.onGoToParent===void 0)return null;let t=this.parentLocation(e.session);return t.kind===`workspace`?g`<button title=${$f(t)} @click=${()=>{this.openMenuSessionId=void 0,this.onGoToParent?.(e.session,t)}}>前往父会话</button>`:null}handleSessionKeydown(e,t,n){N_(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)&&mv(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}renameSession(e){this.openMenuSessionId=void 0;let t=dv(e);t!==void 0&&this.onRename?.(e,t)}confirmArchiveWithDescendants(e,t){confirm(`归档“${cv(e)}”及其 ${String(t)} 个后代会话?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`永久删除已归档会话“${cv(e)}”?此操作无法撤销。`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;let e=this.selectedSessions(`archived`);e.length!==0&&confirm(`永久删除 ${String(e.length)} 个所选已归档会话?此操作无法撤销。`)&&(this.selectedSessionIds=hv(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=>Au(e,this.statuses[e.id],this.sessionPersistenceOptions()));this.selectedSessionIds=hv(this.selectedSessionIds,e.map(e=>e.id)),this.onArchiveMany?.(e)}toggleSelection(e,t){if(this.selectionScopes.has(e)){this.closeSelection(e);return}this.startSelection(e,t)}startSelection(e,t){this.selectionScopes=new Set([...this.selectionScopes,e]);let n=t.length===1?t[0]:void 0;n!==void 0&&(this.selectedSessionIds=new Set([...this.selectedSessionIds,n.id]))}closeSelection(e){this.selectionScopes=new Set([...this.selectionScopes].filter(t=>t!==e)),this.clearSelection(e)}clearSelection(e){let t=this.sessions.filter(t=>mv(t)===e).map(e=>e.id);this.selectedSessionIds=hv(this.selectedSessionIds,t)}toggleSelected(e){let t=new Set(this.selectedSessionIds);t.has(e)?t.delete(e):t.add(e),this.selectedSessionIds=t}toggleVisibleSelection(e,t){let n=new Set(this.selectedSessionIds);for(let r of e)t?n.add(r.id):n.delete(r.id);this.selectedSessionIds=n}selectedSessions(e){return this.sessions.filter(t=>this.selectedSessionIds.has(t.id)&&mv(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=w_(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?.())}renderLoadMoreSentinel(e,t,n){return t>=n?null:g`
|
|
1152
|
+
<div class="session-load-more-sentinel">
|
|
1153
|
+
<button data-load-scope=${e} @click=${()=>{this.loadMore(e)}}>加载更多(剩余 ${n-t})</button>
|
|
1154
|
+
</div>
|
|
1155
|
+
`}loadMore(e){e===`current`?this.currentVisibleLimit+=50:this.archivedVisibleLimit+=50}observeLoadMoreSentinels(){if(this.loadMoreObserver?.disconnect(),this.loadMoreObserver=void 0,typeof IntersectionObserver>`u`||this.listBody===void 0)return;let e=new IntersectionObserver(e=>{for(let t of e){if(!t.isIntersecting)continue;let e=t.target.getAttribute(`data-load-scope`);e===`current`?this.loadMore(`current`):e===`archived`&&!this.hasMoreCurrentRows()&&this.loadMore(`archived`)}},{root:this.listBody,rootMargin:`0px 0px 160px`});for(let t of this.renderRoot.querySelectorAll(`[data-load-scope]`))e.observe(t);this.loadMoreObserver=e}hasMoreCurrentRows(){return jv(this.sessions,this.pinnedSessionIds).length>this.currentVisibleLimit}expandVisibleLimitForSelected(){let e=this.selected;if(e===void 0)return;let t=jv(this.sessions,this.pinnedSessionIds),n=t.findIndex(t=>t.session.id===e.id);if(n>=0){this.currentVisibleLimit=Math.max(this.currentVisibleLimit,n+1);return}let r=new Set(t.map(e=>e.session.id)),i=Mv(this.sessions.filter(e=>e.archived===!0&&!r.has(e.id)),this.pinnedSessionIds).findIndex(t=>t.session.id===e.id);i<0||(this.currentVisibleLimit=Math.max(this.currentVisibleLimit,t.length),this.archivedVisibleLimit=Math.max(this.archivedVisibleLimit,i+1))}scrollSelectedIntoView(){this.renderRoot.querySelector(`.action-row.selected`)?.scrollIntoView({block:`nearest`})}renderSessionMetaPrefix(e,t,n){return ju(e,t,this.sessionPersistenceOptions())?n?.phase===`active`?`新会话 · 创建中 · `:n?.phase===`error`?`新会话 · 错误 · `:n?.phase===`idle`?`创建完成 · `:`新会话 · `:e.archived===!0?`只读 · `:``}sessionPersistenceOptions(){return{authoritative:this.authoritativeSessionPersistence}}renderActivity(e,t){return x_(e,e===`sending`?`正在发送消息`:`会话活跃`,t?`未读会话活动`:void 0)}static{this.styles=[Dm,h`
|
|
1150
1156
|
h2 { min-height: 30px; }
|
|
1151
1157
|
h2 > .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
|
|
1152
1158
|
h2 > .section-unread-count { flex: 0 0 auto; display: inline; color: var(--pi-accent); font-size: inherit; text-transform: none; }
|
|
@@ -1158,6 +1164,9 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
|
|
|
1158
1164
|
.bulk-row small { display: inline; min-width: 0; color: var(--pi-muted); }
|
|
1159
1165
|
.action-name, .section-selected { text-align: start; unicode-bidi: plaintext; }
|
|
1160
1166
|
.action-row.unread .action-name { color: var(--pi-text-bright); font-weight: 650; }
|
|
1167
|
+
.action-row { content-visibility: auto; contain-intrinsic-size: auto 58px; }
|
|
1168
|
+
.session-load-more-sentinel { display: grid; place-items: center; min-height: 36px; margin: 2px 0 6px; }
|
|
1169
|
+
.session-load-more-sentinel button { padding: 5px 9px; color: var(--pi-muted); font-size: 12px; }
|
|
1161
1170
|
.plain-heading { min-width: 0; }
|
|
1162
1171
|
.session-search { box-sizing: border-box; width: 30px; height: 30px; flex: 0 0 30px; display: grid; place-items: center; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 0; font: 19px/1 system-ui, sans-serif; text-transform: none; }
|
|
1163
1172
|
.session-search:focus-visible { border-color: var(--pi-accent); outline: 2px solid var(--pi-accent); outline-offset: 1px; }
|
|
@@ -1180,7 +1189,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
|
|
|
1180
1189
|
.pending-session-row.starting-session .activity-indicator { flex: 0 0 auto; margin: 0; }
|
|
1181
1190
|
.action-main.selecting { padding-left: calc(32px + var(--depth, 0) * 16px); }
|
|
1182
1191
|
.session-checkbox { position: absolute; top: 9px; left: calc(8px + var(--depth, 0) * 16px); z-index: 2; margin: 0; }
|
|
1183
|
-
`]}};B([b({attribute:!1})],H.prototype,`sessions`,void 0),B([b({attribute:!1})],H.prototype,`pinnedSessionIds`,void 0),B([b({attribute:!1})],H.prototype,`statuses`,void 0),B([b({attribute:!1})],H.prototype,`activities`,void 0),B([b({attribute:!1})],H.prototype,`sending`,void 0),B([b({attribute:!1})],H.prototype,`unreadSessionIds`,void 0),B([b({attribute:!1})],H.prototype,`selected`,void 0),B([b({type:Number})],H.prototype,`startingCount`,void 0),B([b({type:Boolean})],H.prototype,`canStart`,void 0),B([b({type:Boolean})],H.prototype,`canDeleteArchived`,void 0),B([b({type:Boolean})],H.prototype,`canReload`,void 0),B([b({type:Boolean})],H.prototype,`canCleanup`,void 0),B([b({type:Boolean})],H.prototype,`authoritativeSessionPersistence`,void 0),B([b({type:String})],H.prototype,`archivedDeleteUnavailableMessage`,void 0),B([b({type:String})],H.prototype,`cleanupUnavailableMessage`,void 0),B([b({type:Boolean,reflect:!0})],H.prototype,`collapsible`,void 0),B([b({type:Boolean,reflect:!0})],H.prototype,`collapsed`,void 0),B([b({attribute:!1})],H.prototype,`onSelect`,void 0),B([b({attribute:!1})],H.prototype,`onSearch`,void 0),B([b({attribute:!1})],H.prototype,`onTogglePin`,void 0),B([b({attribute:!1})],H.prototype,`onStart`,void 0),B([b({attribute:!1})],H.prototype,`onToggleCollapsed`,void 0),B([b({attribute:!1})],H.prototype,`onArchivedCollapsed`,void 0),B([b({attribute:!1})],H.prototype,`onFocusPreviousSection`,void 0),B([b({attribute:!1})],H.prototype,`onFocusNextSection`,void 0),B([b({attribute:!1})],H.prototype,`onCancelKeyboardNavigation`,void 0),B([b({attribute:!1})],H.prototype,`onArchive`,void 0),B([b({attribute:!1})],H.prototype,`onArchiveWithDescendants`,void 0),B([b({attribute:!1})],H.prototype,`onArchiveMany`,void 0),B([b({attribute:!1})],H.prototype,`onRestore`,void 0),B([b({attribute:!1})],H.prototype,`onDelete`,void 0),B([b({attribute:!1})],H.prototype,`onDeleteArchived`,void 0),B([b({attribute:!1})],H.prototype,`onDeleteArchivedMany`,void 0),B([b({attribute:!1})],H.prototype,`onRename`,void 0),B([b({attribute:!1})],H.prototype,`onDetachParent`,void 0),B([b({attribute:!1})],H.prototype,`parentLocation`,void 0),B([b({attribute:!1})],H.prototype,`onGoToParent`,void 0),B([b({attribute:!1})],H.prototype,`onMarkRead`,void 0),B([b({attribute:!1})],H.prototype,`onMarkReadMany`,void 0),B([b({attribute:!1})],H.prototype,`onReload`,void 0),B([b({attribute:!1})],H.prototype,`onCleanup`,void 0),B([x()],H.prototype,`openMenuSessionId`,void 0),B([x()],H.prototype,`menuStyle`,void 0),B([x()],H.prototype,`archivedExpanded`,void 0),B([x()],H.prototype,`selectionScopes`,void 0),B([x()],H.prototype,`selectedSessionIds`,void 0),H=B([y(`session-list`)],H);function
|
|
1192
|
+
`]}};B([b({attribute:!1})],H.prototype,`scopeKey`,void 0),B([b({attribute:!1})],H.prototype,`sessions`,void 0),B([b({attribute:!1})],H.prototype,`pinnedSessionIds`,void 0),B([b({attribute:!1})],H.prototype,`statuses`,void 0),B([b({attribute:!1})],H.prototype,`activities`,void 0),B([b({attribute:!1})],H.prototype,`sending`,void 0),B([b({attribute:!1})],H.prototype,`unreadSessionIds`,void 0),B([b({attribute:!1})],H.prototype,`selected`,void 0),B([b({type:Number})],H.prototype,`startingCount`,void 0),B([b({type:Boolean})],H.prototype,`canStart`,void 0),B([b({type:Boolean})],H.prototype,`canDeleteArchived`,void 0),B([b({type:Boolean})],H.prototype,`canReload`,void 0),B([b({type:Boolean})],H.prototype,`canCleanup`,void 0),B([b({type:Boolean})],H.prototype,`authoritativeSessionPersistence`,void 0),B([b({type:String})],H.prototype,`archivedDeleteUnavailableMessage`,void 0),B([b({type:String})],H.prototype,`cleanupUnavailableMessage`,void 0),B([b({type:Boolean,reflect:!0})],H.prototype,`collapsible`,void 0),B([b({type:Boolean,reflect:!0})],H.prototype,`collapsed`,void 0),B([b({attribute:!1})],H.prototype,`onSelect`,void 0),B([b({attribute:!1})],H.prototype,`onSearch`,void 0),B([b({attribute:!1})],H.prototype,`onTogglePin`,void 0),B([b({attribute:!1})],H.prototype,`onStart`,void 0),B([b({attribute:!1})],H.prototype,`onToggleCollapsed`,void 0),B([b({attribute:!1})],H.prototype,`onArchivedCollapsed`,void 0),B([b({attribute:!1})],H.prototype,`onFocusPreviousSection`,void 0),B([b({attribute:!1})],H.prototype,`onFocusNextSection`,void 0),B([b({attribute:!1})],H.prototype,`onCancelKeyboardNavigation`,void 0),B([b({attribute:!1})],H.prototype,`onArchive`,void 0),B([b({attribute:!1})],H.prototype,`onArchiveWithDescendants`,void 0),B([b({attribute:!1})],H.prototype,`onArchiveMany`,void 0),B([b({attribute:!1})],H.prototype,`onRestore`,void 0),B([b({attribute:!1})],H.prototype,`onDelete`,void 0),B([b({attribute:!1})],H.prototype,`onDeleteArchived`,void 0),B([b({attribute:!1})],H.prototype,`onDeleteArchivedMany`,void 0),B([b({attribute:!1})],H.prototype,`onRename`,void 0),B([b({attribute:!1})],H.prototype,`onDetachParent`,void 0),B([b({attribute:!1})],H.prototype,`parentLocation`,void 0),B([b({attribute:!1})],H.prototype,`onGoToParent`,void 0),B([b({attribute:!1})],H.prototype,`onMarkRead`,void 0),B([b({attribute:!1})],H.prototype,`onMarkReadMany`,void 0),B([b({attribute:!1})],H.prototype,`onReload`,void 0),B([b({attribute:!1})],H.prototype,`onCleanup`,void 0),B([x()],H.prototype,`openMenuSessionId`,void 0),B([x()],H.prototype,`menuStyle`,void 0),B([x()],H.prototype,`archivedExpanded`,void 0),B([x()],H.prototype,`selectionScopes`,void 0),B([x()],H.prototype,`selectedSessionIds`,void 0),B([x()],H.prototype,`currentVisibleLimit`,void 0),B([x()],H.prototype,`archivedVisibleLimit`,void 0),B([S(`.list-body`)],H.prototype,`listBody`,void 0),H=B([y(`session-list`)],H);function uv(e,t){return e.filter(e=>kv(e,t)).length}function dv(e){let t=globalThis.prompt(`重命名会话`,cv(e))?.trim();return t===void 0||t===``?void 0:t}function fv(e,t,n){return Au(e,t,n)}function pv(e){if(!(e===void 0||e===0))return`其他工作区有 ${String(e)} 个子会话`}function mv(e){return e.archived===!0?`archived`:`current`}function hv(e,t){let n=new Set(t);return new Set([...e].filter(e=>!n.has(e)))}function gv(e,t){let n=new Map;for(let t of e){if(t.parentSessionPath===void 0)continue;let e=z(t.parentSessionPath),r=n.get(e)??[];r.push(t),n.set(e,r)}let r=(e,t)=>{let i=z(e.path);if(t.has(i))return 0;let a=new Set(t);a.add(i);let o=0;for(let e of n.get(i)??[])a.has(z(e.path))||(e.archived!==!0&&(o+=1),o+=r(e,a));return o};return r(t,new Set)}function _v(e,t){return!Array.isArray(e)||e.length!==t.length?!1:t.every((t,n)=>vv(t)===vv(e[n]))}function vv(e){return Sv(e)?JSON.stringify([e.id,e.path,e.cwd,e.name,e.firstMessage,e.messageCount,e.modified,e.archived,e.archivedAt,e.persisted,e.parentSessionPath,e.childSessionsElsewhere]):``}function yv(e,t){return e===void 0||t===void 0?e===t:vv(e)===vv(t)}function bv(e,t,n,r,i,a,o){if(!Cv(e))return!1;for(let s of i){let i=wv(o===`status`?e:n,s.id),c=wv(o===`status`?t:n,s.id),l=Tv(o===`activity`?e:n,s.id),u=Tv(o===`activity`?t:n,s.id);if(xv(s,i,l,r[s.id]===!0,a)!==xv(s,c,u,r[s.id]===!0,a))return!1}return!0}function xv(e,t,n,r,i){return JSON.stringify([Ov(e,t,n,r),n?.phase,ku(e,t,{authoritative:i})])}function Sv(e){return Cv(e)&&typeof e.id==`string`&&typeof e.path==`string`}function Cv(e){return typeof e==`object`&&!!e}function wv(e,t){if(!Cv(e))return;let n=e[t];return Ev(n)?n:void 0}function Tv(e,t){if(!Cv(e))return;let n=e[t];return Dv(n)?n:void 0}function Ev(e){return Cv(e)&&typeof e.sessionId==`string`&&typeof e.isStreaming==`boolean`&&typeof e.isCompacting==`boolean`&&typeof e.isBashRunning==`boolean`&&typeof e.pendingMessageCount==`number`&&Array.isArray(e.queuedMessages)&&Cv(e.tokens)&&typeof e.cost==`number`}function Dv(e){return Cv(e)&&typeof e.sessionId==`string`&&(e.phase===`active`||e.phase===`idle`||e.phase===`error`)&&typeof e.label==`string`&&typeof e.at==`string`}function Ov(e,t,n,r){if(!(qs(e)||e.archived===!0)){if(r)return`sending`;if(Lo(t,n))return`session`}}function kv(e,t){return qs(e)||e.archived===!0?!1:t.has(e.id)}function Av(e){return new Map(e.map(e=>[z(e.path),e]))}function jv(e,t=[]){let n=Av(e),r=new Set;for(let t of e){if(t.archived===!0)continue;r.add(t.id);let e=t.parentSessionPath===void 0?void 0:z(t.parentSessionPath),i=new Set([z(t.path)]);for(;e!==void 0&&!i.has(e);){i.add(e);let t=n.get(e);if(t===void 0)break;r.add(t.id),e=t.parentSessionPath===void 0?void 0:z(t.parentSessionPath)}}return Mv(e.filter(e=>r.has(e.id)),t)}function Mv(e,t=[]){let n=Av(e),r=new Map,i=[];for(let t of e){let e=t.parentSessionPath,a=e===void 0?void 0:n.get(z(e));if(a===void 0){i.push(t);continue}let o=z(a.path),s=r.get(o)??[];s.push(t),r.set(o,s)}let a=new Set(t),o=new Map(e.map((e,t)=>[z(e.path),t])),s=new Map,c=(e,t)=>{if(a.has(e.id))return!0;let n=z(e.path),i=s.get(n);if(i!==void 0)return i;if(t.has(n))return!1;let o=new Set(t);o.add(n);let l=(r.get(n)??[]).some(e=>c(e,o));return s.set(n,l),l},l=(e,t)=>{let n=Number(c(t,new Set))-Number(c(e,new Set));if(n!==0)return n;let r=t.modified.localeCompare(e.modified);return r===0?(o.get(z(e.path))??0)-(o.get(z(t.path))??0):r},u=[],d=(e,t,i)=>{let a=z(e.path);if(i.has(a))return;let o=e.parentSessionPath;u.push({session:e,depth:t,hasMissingParent:o!==void 0&&!n.has(z(o))});let s=new Set(i);s.add(a);for(let e of[...r.get(a)??[]].sort(l))d(e,t+1,s)};for(let e of i.sort(l))d(e,0,new Set);return u}var U=class extends v{constructor(...e){super(...e),this.canCleanup=!0,this.unavailableMessage=`请更新并重启此机器上的 Pi-Web 后再清理会话。`,this.loading=!1,this.running=!1,this.error=``,this.draft={...rp},this.formError=``}willUpdate(e){e.has(`preview`)&&(this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd))}render(){let e=ip(this.draft),t=this.selectedPreview(),n=op({canCleanup:this.canCleanup,draft:this.draft,preview:t,previewRequest:this.previewRequest,loading:this.loading,running:this.running}),r=n?`运行清理`:t!==void 0&&!sp(t)?`至少选择一个项目才能运行清理`:`运行清理前请先预览`;return g`
|
|
1184
1193
|
<div class="backdrop" @mousedown=${()=>{this.onClose?.()}}>
|
|
1185
1194
|
<section role="dialog" aria-modal="true" aria-label="清理会话" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
1186
1195
|
<header>
|
|
@@ -1207,15 +1216,15 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
|
|
|
1207
1216
|
`}renderForm(e){let t=this.loading||this.running,n=ip(this.draft),r=this.preview!==void 0&&n.ok&&ap(n.request)!==ap(this.previewRequest)&&sp(this.preview);return g`
|
|
1208
1217
|
<fieldset ?disabled=${t}>
|
|
1209
1218
|
<label class="toggle-row">
|
|
1210
|
-
<input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:
|
|
1219
|
+
<input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:Nv(e)})}}>
|
|
1211
1220
|
<span>归档空闲超过</span>
|
|
1212
|
-
<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:
|
|
1221
|
+
<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:Pv(e)})}}>
|
|
1213
1222
|
<span>天的未归档会话</span>
|
|
1214
1223
|
</label>
|
|
1215
1224
|
<label class="toggle-row delete-row">
|
|
1216
|
-
<input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:
|
|
1225
|
+
<input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:Nv(e)})}}>
|
|
1217
1226
|
<span>删除已归档超过</span>
|
|
1218
|
-
<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:
|
|
1227
|
+
<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:Pv(e)})}}>
|
|
1219
1228
|
<span>天的已归档会话</span>
|
|
1220
1229
|
</label>
|
|
1221
1230
|
</fieldset>
|
|
@@ -1252,7 +1261,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
|
|
|
1252
1261
|
${t.length===0?g`<p class="hint" role="status">至少选择一个项目才能运行清理。</p>`:null}
|
|
1253
1262
|
`}renderProjectRow(e,t){return g`
|
|
1254
1263
|
<tr class=${t?``:`unselected`}>
|
|
1255
|
-
<td class="select-cell"><input type="checkbox" aria-label=${`清理 ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${t=>{this.setProjectSelected(e.cwd,
|
|
1264
|
+
<td class="select-cell"><input type="checkbox" aria-label=${`清理 ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${t=>{this.setProjectSelected(e.cwd,Nv(t))}}></td>
|
|
1256
1265
|
<th title=${e.cwd} dir="auto">${e.cwd}</th>
|
|
1257
1266
|
<td>${e.archiveCount}</td>
|
|
1258
1267
|
<td>${e.deleteCount}</td>
|
|
@@ -1312,7 +1321,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
|
|
|
1312
1321
|
table { min-width: 560px; }
|
|
1313
1322
|
thead th:first-child, td.select-cell { width: 58px; }
|
|
1314
1323
|
}
|
|
1315
|
-
`}};B([b({type:Boolean})],U.prototype,`canCleanup`,void 0),B([b({type:String})],U.prototype,`unavailableMessage`,void 0),B([b({attribute:!1})],U.prototype,`preview`,void 0),B([b({attribute:!1})],U.prototype,`previewRequest`,void 0),B([b({attribute:!1})],U.prototype,`result`,void 0),B([b({type:Boolean})],U.prototype,`loading`,void 0),B([b({type:Boolean})],U.prototype,`running`,void 0),B([b({type:String})],U.prototype,`error`,void 0),B([b({attribute:!1})],U.prototype,`onPreview`,void 0),B([b({attribute:!1})],U.prototype,`onRun`,void 0),B([b({attribute:!1})],U.prototype,`onClose`,void 0),B([x()],U.prototype,`draft`,void 0),B([x()],U.prototype,`formError`,void 0),B([x()],U.prototype,`selectedProjectCwds`,void 0),U=B([y(`session-cleanup-dialog`)],U);function
|
|
1324
|
+
`}};B([b({type:Boolean})],U.prototype,`canCleanup`,void 0),B([b({type:String})],U.prototype,`unavailableMessage`,void 0),B([b({attribute:!1})],U.prototype,`preview`,void 0),B([b({attribute:!1})],U.prototype,`previewRequest`,void 0),B([b({attribute:!1})],U.prototype,`result`,void 0),B([b({type:Boolean})],U.prototype,`loading`,void 0),B([b({type:Boolean})],U.prototype,`running`,void 0),B([b({type:String})],U.prototype,`error`,void 0),B([b({attribute:!1})],U.prototype,`onPreview`,void 0),B([b({attribute:!1})],U.prototype,`onRun`,void 0),B([b({attribute:!1})],U.prototype,`onClose`,void 0),B([x()],U.prototype,`draft`,void 0),B([x()],U.prototype,`formError`,void 0),B([x()],U.prototype,`selectedProjectCwds`,void 0),U=B([y(`session-cleanup-dialog`)],U);function Nv(e){return e.target instanceof HTMLInputElement&&e.target.checked}function Pv(e){return e.target instanceof HTMLInputElement?e.target.value:``}var Fv=class extends v{constructor(...e){super(...e),this.query=``,this.searching=!1,this.error=``}firstUpdated(){this.searchInput?.focus()}render(){let e=this.query.trim()!==``;return g`
|
|
1316
1325
|
<div class="backdrop" @mousedown=${()=>{this.onClose?.()}}>
|
|
1317
1326
|
<section role="dialog" aria-modal="true" aria-label="搜索会话内容" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
1318
1327
|
<header>
|
|
@@ -1325,7 +1334,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
|
|
|
1325
1334
|
<div class="body">
|
|
1326
1335
|
<label class="search-field">
|
|
1327
1336
|
<span aria-hidden="true">⌕</span>
|
|
1328
|
-
<input type="search" aria-label="搜索用户提问或 AI 回答" .value=${this.query} @input=${e=>{this.onSearch?.(
|
|
1337
|
+
<input type="search" aria-label="搜索用户提问或 AI 回答" .value=${this.query} @input=${e=>{this.onSearch?.(zv(e))}}>
|
|
1329
1338
|
${this.searching?g`<span class="spinner" aria-label="正在搜索"></span>`:null}
|
|
1330
1339
|
</label>
|
|
1331
1340
|
${this.renderStatus(e)}
|
|
@@ -1342,7 +1351,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
|
|
|
1342
1351
|
${e.results.map(e=>g`
|
|
1343
1352
|
<section class="session-group">
|
|
1344
1353
|
<div class="session-heading">
|
|
1345
|
-
<strong dir="auto">${
|
|
1354
|
+
<strong dir="auto">${Rv(e.session)}</strong>
|
|
1346
1355
|
<span>${e.matches.length} 条匹配</span>
|
|
1347
1356
|
</div>
|
|
1348
1357
|
${e.matches.map(t=>this.renderMatch(e.session,t))}
|
|
@@ -1353,7 +1362,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
|
|
|
1353
1362
|
<button class="match-row" @click=${()=>{this.onSelect?.(e,t)}}>
|
|
1354
1363
|
<span class="match-meta"><span class=${`role ${t.role}`}>${n}</span></span>
|
|
1355
1364
|
<span class="excerpts" dir="auto">
|
|
1356
|
-
${t.excerpts.map(e=>g`<span class="excerpt">${
|
|
1365
|
+
${t.excerpts.map(e=>g`<span class="excerpt">${Iv(e)}</span>`)}
|
|
1357
1366
|
</span>
|
|
1358
1367
|
<span class="jump" aria-hidden="true">→</span>
|
|
1359
1368
|
</button>
|
|
@@ -1400,7 +1409,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
|
|
|
1400
1409
|
.body { padding: 12px; }
|
|
1401
1410
|
.match-row { padding-left: 10px; }
|
|
1402
1411
|
}
|
|
1403
|
-
`}};B([b({type:String})],Cv.prototype,`query`,void 0),B([b({attribute:!1})],Cv.prototype,`response`,void 0),B([b({type:Boolean})],Cv.prototype,`searching`,void 0),B([b({type:String})],Cv.prototype,`error`,void 0),B([b({attribute:!1})],Cv.prototype,`onSearch`,void 0),B([b({attribute:!1})],Cv.prototype,`onSelect`,void 0),B([b({attribute:!1})],Cv.prototype,`onClose`,void 0),B([S(`input`)],Cv.prototype,`searchInput`,void 0),Cv=B([y(`session-search-dialog`)],Cv);function wv(e){return g`${Tv(e).map(e=>e.highlighted?g`<mark>${e.text}</mark>`:e.text)}`}function Tv(e){let t=[...e.matchRanges].sort((e,t)=>e.start-t.start),n=[],r=0;for(let i of t){let t=Math.max(r,Math.min(e.text.length,i.start)),a=Math.max(t,Math.min(e.text.length,i.start+i.length));t>r&&n.push({text:e.text.slice(r,t),highlighted:!1}),a>t&&n.push({text:e.text.slice(t,a),highlighted:!0}),r=a}return r<e.text.length&&n.push({text:e.text.slice(r),highlighted:!1}),n}function Ev(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?sv(e.id):e.firstMessage}function Dv(e){return e.target instanceof HTMLInputElement?e.target.value:``}var Ov={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},kv=e=>(...t)=>({_$litDirective$:e,values:t}),Av=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}},{I:jv}=lt,Mv=e=>e,Nv=()=>document.createComment(``),Pv=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new jv(r.insertBefore(Nv(),i),r.insertBefore(Nv(),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=Mv(e).nextSibling;Mv(r).insertBefore(e,i),e=t}}}return n},Fv=(e,t,n=e)=>(e._$AI(t,n),e),Iv={},Lv=(e,t=Iv)=>e._$AH=t,Rv=e=>e._$AH,zv=e=>{e._$AR(),e._$AA.remove()},Bv=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},Vv=kv(class extends Av{constructor(e){if(super(e),e.type!==Ov.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=Rv(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]=Fv(i[d],a[p]),d++,p++;else if(s[f]===o[m])c[m]=Fv(i[f],a[m]),f--,m--;else if(s[d]===o[m])c[m]=Fv(i[d],a[m]),Pv(e,c[m+1],i[d]),d++,m--;else if(s[f]===o[p])c[p]=Fv(i[f],a[p]),Pv(e,i[d],i[f]),f--,p++;else if(l===void 0&&(l=Bv(o,p,m),u=Bv(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=Pv(e,i[d]);Fv(t,a[p]),c[p]=t}else c[p]=Fv(n,a[p]),Pv(e,i[d],n),i[t]=null;p++}else zv(i[f]),f--;else zv(i[d]),d++;for(;p<=m;){let t=Pv(e,c[m+1]);Fv(t,a[p]),c[p++]=t}for(;d<=f;){let e=i[d++];e!==null&&zv(e)}return this.ut=o,Lv(e,c),Ye}}),Hv=`pi-web:chat-groups:`,Uv={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(Gv(e));return t===null||t===``?void 0:Kv(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(Gv(e),JSON.stringify(t))}catch{}}},Wv=class{constructor(e=Uv){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&&Jv(i,this.openGroupKeys)&&Jv(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 Gv(e){return`${Hv}${e}`}function Kv(e){if(Array.isArray(e))return{open:qv(e),closedDefaultOpen:[]};if(Yv(e))return{open:Array.isArray(e.open)?qv(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?qv(e.closedDefaultOpen):[]}}function qv(e){return e.filter(e=>typeof e==`string`)}function Jv(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Yv(e){return typeof e==`object`&&!!e}function Xv(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=>ey(e,t)),s=e.parts.filter(t=>!ey(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(Qv(t)){let e=$v(s);n.push({kind:`tool-image`,message:t,index:c,...e===void 0?{}:{toolName:e}})}else n.push({kind:`message`,message:t,index:c})}}),o(),n}function Zv(e){if(e.every(e=>e.source===`compaction`))return`${String(e.length)} 条历史压缩摘要`;if(e.every(e=>e.source===`branch_summary`))return`${String(e.length)} 条分支摘要`;let t=e.reduce((e,t)=>(e[t.role]=(e[t.role]??0)+1,e),{}),n={user:`用户`,assistant:`助手`,tool:`工具`,system:`系统`,bash:`命令`,skill:`技能`},r=Object.entries(t).map(([e,t])=>`${String(t)} ${n[e]??e}`).join(` · `);return`${String(e.length)} 个事件${r===``?``:` · ${r}`}`}function Qv(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function $v(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function ey(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 ty(e,t){let n=ry(oy(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function ny(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=iy(r,t.markerOffset);return}e.scrollTop=ay(e.scrollHeight,t.distanceFromBottom)}function ry(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 iy(e,t){return e-t}function ay(e,t){return Math.max(0,e-t)}function oy(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 sy=600,cy=1;function ly(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:uy(e)||dy(e)}function uy(e){return e.scrollTop<(e.topThreshold??Math.max(sy,e.clientHeight))}function dy(e){return e.scrollHeight<=e.clientHeight+cy}var fy=`pi-web:chat-scroll:`,py=180,my=48,hy=2,gy={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)}},_y={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},vy=class{constructor(e=gy,t=_y){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=py){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=hy){if(e===``||t===void 0||!xy(t))return`skipped`;try{if(Cy(t,r))return this.storage.setItem(yy(e),JSON.stringify({mode:`bottom`})),`saved`;let i=Ty(t,n);if(i===void 0)return`skipped`;let a=wy(t,i);return this.storage.setItem(yy(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||!xy(t))return{status:`skipped`};let i=Dy(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(yy(e));if(t===null||t===``)return;let n=JSON.parse(t);return by(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!xy(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function yy(e){return`${fy}${e}`}function by(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 xy(e){return e.clientHeight>0&&e.scrollHeight>0}function Sy(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function Cy(e,t=my){return Sy(e)<t}function wy(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:Oy(t)??``,offset:t.getBoundingClientRect().top-n}}function Ty(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(Oy(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 Ey(e,t){let n=e.getBoundingClientRect();return t.find(e=>{let t=e.getBoundingClientRect();return t.bottom>=n.top&&t.top<=n.bottom})}function Dy(e,t){return e.find(e=>Oy(e)===t)}function Oy(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}var ky=e=>e??_,Ay=class extends v{constructor(...e){super(...e),this.draftSessionId=``,this.answers={},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=Qc(e.questions,this.answers),n=$c(e.questions,this.answers);return g`
|
|
1412
|
+
`}};B([b({type:String})],Fv.prototype,`query`,void 0),B([b({attribute:!1})],Fv.prototype,`response`,void 0),B([b({type:Boolean})],Fv.prototype,`searching`,void 0),B([b({type:String})],Fv.prototype,`error`,void 0),B([b({attribute:!1})],Fv.prototype,`onSearch`,void 0),B([b({attribute:!1})],Fv.prototype,`onSelect`,void 0),B([b({attribute:!1})],Fv.prototype,`onClose`,void 0),B([S(`input`)],Fv.prototype,`searchInput`,void 0),Fv=B([y(`session-search-dialog`)],Fv);function Iv(e){return g`${Lv(e).map(e=>e.highlighted?g`<mark>${e.text}</mark>`:e.text)}`}function Lv(e){let t=[...e.matchRanges].sort((e,t)=>e.start-t.start),n=[],r=0;for(let i of t){let t=Math.max(r,Math.min(e.text.length,i.start)),a=Math.max(t,Math.min(e.text.length,i.start+i.length));t>r&&n.push({text:e.text.slice(r,t),highlighted:!1}),a>t&&n.push({text:e.text.slice(t,a),highlighted:!0}),r=a}return r<e.text.length&&n.push({text:e.text.slice(r),highlighted:!1}),n}function Rv(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?sv(e.id):e.firstMessage}function zv(e){return e.target instanceof HTMLInputElement?e.target.value:``}var Bv={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},Vv=e=>(...t)=>({_$litDirective$:e,values:t}),Hv=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}},{I:Uv}=lt,Wv=e=>e,Gv=()=>document.createComment(``),Kv=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new Uv(r.insertBefore(Gv(),i),r.insertBefore(Gv(),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=Wv(e).nextSibling;Wv(r).insertBefore(e,i),e=t}}}return n},qv=(e,t,n=e)=>(e._$AI(t,n),e),Jv={},Yv=(e,t=Jv)=>e._$AH=t,Xv=e=>e._$AH,Zv=e=>{e._$AR(),e._$AA.remove()},Qv=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},$v=Vv(class extends Hv{constructor(e){if(super(e),e.type!==Bv.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=Xv(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]=qv(i[d],a[p]),d++,p++;else if(s[f]===o[m])c[m]=qv(i[f],a[m]),f--,m--;else if(s[d]===o[m])c[m]=qv(i[d],a[m]),Kv(e,c[m+1],i[d]),d++,m--;else if(s[f]===o[p])c[p]=qv(i[f],a[p]),Kv(e,i[d],i[f]),f--,p++;else if(l===void 0&&(l=Qv(o,p,m),u=Qv(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=Kv(e,i[d]);qv(t,a[p]),c[p]=t}else c[p]=qv(n,a[p]),Kv(e,i[d],n),i[t]=null;p++}else Zv(i[f]),f--;else Zv(i[d]),d++;for(;p<=m;){let t=Kv(e,c[m+1]);qv(t,a[p]),c[p++]=t}for(;d<=f;){let e=i[d++];e!==null&&Zv(e)}return this.ut=o,Yv(e,c),Ye}}),ey=`pi-web:chat-groups:`,ty={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(ry(e));return t===null||t===``?void 0:iy(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(ry(e),JSON.stringify(t))}catch{}}},ny=class{constructor(e=ty){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&&oy(i,this.openGroupKeys)&&oy(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 ry(e){return`${ey}${e}`}function iy(e){if(Array.isArray(e))return{open:ay(e),closedDefaultOpen:[]};if(sy(e))return{open:Array.isArray(e.open)?ay(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?ay(e.closedDefaultOpen):[]}}function ay(e){return e.filter(e=>typeof e==`string`)}function oy(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function sy(e){return typeof e==`object`&&!!e}function cy(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=>fy(e,t)),s=e.parts.filter(t=>!fy(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(uy(t)){let e=dy(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 ly(e){if(e.every(e=>e.source===`compaction`))return`${String(e.length)} 条历史压缩摘要`;if(e.every(e=>e.source===`branch_summary`))return`${String(e.length)} 条分支摘要`;let t=e.reduce((e,t)=>(e[t.role]=(e[t.role]??0)+1,e),{}),n={user:`用户`,assistant:`助手`,tool:`工具`,system:`系统`,bash:`命令`,skill:`技能`},r=Object.entries(t).map(([e,t])=>`${String(t)} ${n[e]??e}`).join(` · `);return`${String(e.length)} 个事件${r===``?``:` · ${r}`}`}function uy(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function dy(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function fy(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 py(e,t){let n=hy(vy(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function my(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=gy(r,t.markerOffset);return}e.scrollTop=_y(e.scrollHeight,t.distanceFromBottom)}function hy(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 gy(e,t){return e-t}function _y(e,t){return Math.max(0,e-t)}function vy(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 yy=600,by=1;function xy(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:Sy(e)||Cy(e)}function Sy(e){return e.scrollTop<(e.topThreshold??Math.max(yy,e.clientHeight))}function Cy(e){return e.scrollHeight<=e.clientHeight+by}var wy=`pi-web:chat-scroll:`,Ty=180,Ey=48,Dy=2,Oy={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)}},ky={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},Ay=class{constructor(e=Oy,t=ky){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=Ty){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=Dy){if(e===``||t===void 0||!Ny(t))return`skipped`;try{if(Fy(t,r))return this.storage.setItem(jy(e),JSON.stringify({mode:`bottom`})),`saved`;let i=Ly(t,n);if(i===void 0)return`skipped`;let a=Iy(t,i);return this.storage.setItem(jy(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||!Ny(t))return{status:`skipped`};let i=zy(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(jy(e));if(t===null||t===``)return;let n=JSON.parse(t);return My(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!Ny(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function jy(e){return`${wy}${e}`}function My(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 Ny(e){return e.clientHeight>0&&e.scrollHeight>0}function Py(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function Fy(e,t=Ey){return Py(e)<t}function Iy(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:By(t)??``,offset:t.getBoundingClientRect().top-n}}function Ly(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(By(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 Ry(e,t){let n=e.getBoundingClientRect(),r=0,i=t.length;for(;r<i;){let e=Math.floor((r+i)/2),a=t[e];a===void 0||a.getBoundingClientRect().bottom<n.top?r=e+1:i=e}let a=Math.max(0,r-1);for(let e=a;e<t.length;e+=1){let r=t[e];if(r===void 0)continue;let i=r.getBoundingClientRect();if(i.top>n.bottom)return;if(i.bottom>=n.top&&i.top<=n.bottom)return r}}function zy(e,t){return e.find(e=>By(e)===t)}function By(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}var Vy=e=>e??_,Hy=class extends v{constructor(...e){super(...e),this.draftSessionId=``,this.answers={},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=Qc(e.questions,this.answers),n=$c(e.questions,this.answers);return g`
|
|
1404
1413
|
<article class="card open-card" aria-labelledby="ask-user-heading">
|
|
1405
1414
|
<header class="card-header">
|
|
1406
1415
|
<h2 id="ask-user-heading">问题</h2>
|
|
@@ -1425,7 +1434,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
|
|
|
1425
1434
|
<fieldset
|
|
1426
1435
|
id=${this.questionFieldsetId(n)}
|
|
1427
1436
|
class=${`question${i?` answered`:``}`}
|
|
1428
|
-
aria-describedby=${
|
|
1437
|
+
aria-describedby=${Vy(a)}
|
|
1429
1438
|
tabindex="-1"
|
|
1430
1439
|
>
|
|
1431
1440
|
<legend>
|
|
@@ -1675,7 +1684,7 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
|
|
|
1675
1684
|
.confirmation-actions { justify-content: flex-end; }
|
|
1676
1685
|
.primary-action { min-height: 42px; }
|
|
1677
1686
|
}
|
|
1678
|
-
`}};B([b({attribute:!1})],
|
|
1687
|
+
`}};B([b({attribute:!1})],Hy.prototype,`ask`,void 0),B([b({attribute:!1})],Hy.prototype,`outcome`,void 0),B([b({attribute:!1})],Hy.prototype,`draftSessionId`,void 0),B([b({attribute:!1})],Hy.prototype,`onSubmit`,void 0),B([x()],Hy.prototype,`answers`,void 0),B([x()],Hy.prototype,`confirmingPartialSubmit`,void 0),B([x()],Hy.prototype,`submitting`,void 0),Hy=B([y(`ask-user-card`)],Hy);var Uy=class extends v{constructor(...e){super(...e),this.positionPercent=0,this.loadedPercent=100}render(){let e=Wy(this.positionPercent),t=Wy(this.loadedPercent),n=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return g`
|
|
1679
1688
|
<div
|
|
1680
1689
|
class="meter"
|
|
1681
1690
|
style=${`--position:${e.toFixed(2)}%;`}
|
|
@@ -1698,14 +1707,14 @@ import{$ as e,A as t,J as n,P as r,Q as i,S as a,X as o,Z as s,d as c,f as l,j a
|
|
|
1698
1707
|
.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); }
|
|
1699
1708
|
.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)); }
|
|
1700
1709
|
.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%); }
|
|
1701
|
-
`}};B([b({type:Number})],
|
|
1702
|
-
]`).replace(`lheading`,
|
|
1703
|
-
`),n=t.length-1;for(;n>=0
|
|
1704
|
-
`)}function
|
|
1710
|
+
`}};B([b({type:Number})],Uy.prototype,`positionPercent`,void 0),B([b({type:Number})],Uy.prototype,`loadedPercent`,void 0),Uy=B([y(`conversation-meter`)],Uy);function Wy(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}var Gy=class extends Hv{constructor(e){if(super(e),this.it=_,e.type!==Bv.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===Ye)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:[]}}};Gy.directiveName=`unsafeHTML`,Gy.resultType=1;var Ky=Vv(Gy);function qy(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Jy=qy();function Yy(e){Jy=e}var Xy={exec:()=>null};function Zy(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function W(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace($y.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var Qy=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),$y={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:Zy(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Zy(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Zy(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Zy(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Zy(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:Zy(e=>RegExp(`^ {0,${e}}>`))},eb=/^(?:[ \t]*(?:\n|$))+/,tb=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,nb=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,rb=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,ib=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ab=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,ob=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,sb=W(ob).replace(/bull/g,ab).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(),cb=W(ob).replace(/bull/g,ab).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(),lb=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,ub=/^[^\n]+/,db=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,fb=W(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,db).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),pb=W(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,ab).getRegex(),mb=`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`,hb=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,gb=W(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n+|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n+|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n+|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,hb).replace(`tag`,mb).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),_b=e=>W(lb).replace(`hr`,rb).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`,mb).getRegex(),vb=_b(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),yb=_b(/ {0,3}(?:[*+-]|\d{1,9}[.)])[ \t]+[^ \t\n]/),bb={blockquote:W(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,yb).getRegex(),code:tb,def:fb,fences:nb,heading:ib,hr:rb,html:gb,lheading:sb,list:pb,newline:eb,paragraph:vb,table:Xy,text:ub},xb=W(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,rb).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`,mb).getRegex(),Sb={...bb,lheading:cb,table:xb,paragraph:W(lb).replace(`hr`,rb).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,xb).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`,mb).getRegex()},Cb={...bb,html:W(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,hb).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:Xy,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:W(lb).replace(`hr`,rb).replace(`heading`,` *#{1,6} *[^
|
|
1711
|
+
]`).replace(`lheading`,sb).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},wb=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Tb=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Eb=/^( {2,}|\\)\n(?!\s*$)/,Db=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Ob=/[\p{P}\p{S}]/u,kb=/[\s\p{P}\p{S}]/u,Ab=/[^\s\p{P}\p{S}]/u,jb=W(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,kb).getRegex(),Mb=/(?!~)[\p{P}\p{S}]/u,Nb=/(?!~)[\s\p{P}\p{S}]/u,Pb=/(?:[^\s\p{P}\p{S}]|~)/u,Fb=W(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,Qy?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),Ib=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Lb=W(Ib,`u`).replace(/punct/g,Ob).getRegex(),Rb=W(Ib,`u`).replace(/punct/g,Mb).getRegex(),zb=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,Bb=W(zb,`gu`).replace(/notPunctSpace/g,Ab).replace(/punctSpace/g,kb).replace(/punct/g,Ob).getRegex(),Vb=W(zb,`gu`).replace(/notPunctSpace/g,Pb).replace(/punctSpace/g,Nb).replace(/punct/g,Mb).getRegex(),Hb=W(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,Ab).replace(/punctSpace/g,kb).replace(/punct/g,Ob).getRegex(),Ub=W(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,Ob).getRegex(),Wb=W(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Ab).replace(/punctSpace/g,kb).replace(/punct/g,Ob).getRegex(),Gb=W(/\\(punct)/,`gu`).replace(/punct/g,Ob).getRegex(),Kb=W(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace(`scheme`,/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(`email`,/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),qb=W(hb).replace(`(?:-->|$)`,`-->`).getRegex(),Jb=W(`^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,qb).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Yb=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Xb=W(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,Yb).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Zb=W(/^!?\[(label)\]\[(ref)\]/).replace(`label`,Yb).replace(`ref`,db).getRegex(),Qb=W(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,db).getRegex(),$b=W(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,Zb).replace(`nolink`,Qb).getRegex(),ex=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,tx={_backpedal:Xy,anyPunctuation:Gb,autolink:Kb,blockSkip:Fb,br:Eb,code:Tb,del:Xy,delLDelim:Xy,delRDelim:Xy,emStrongLDelim:Lb,emStrongRDelimAst:Bb,emStrongRDelimUnd:Hb,escape:wb,link:Xb,nolink:Qb,punctuation:jb,reflink:Zb,reflinkSearch:$b,tag:Jb,text:Db,url:Xy},nx={...tx,link:W(/^!?\[(label)\]\((.*?)\)/).replace(`label`,Yb).getRegex(),reflink:W(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,Yb).getRegex()},rx={...tx,emStrongRDelimAst:Vb,emStrongLDelim:Rb,delLDelim:Ub,delRDelim:Wb,url:W(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,ex).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:W(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,ex).getRegex()},ix={...rx,br:W(Eb).replace(`{2,}`,`*`).getRegex(),text:W(rx.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},ax={normal:bb,gfm:Sb,pedantic:Cb},ox={normal:tx,gfm:rx,breaks:ix,pedantic:nx},sx={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},cx=e=>sx[e];function lx(e,t){if(t){if($y.escapeTest.test(e))return e.replace($y.escapeReplace,cx)}else if($y.escapeTestNoEncode.test(e))return e.replace($y.escapeReplaceNoEncode,cx);return e}function ux(e){try{e=encodeURI(e).replace($y.percentDecode,`%`)}catch{return null}return e}function dx(e,t){let n=e.replace($y.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split($y.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($y.slashPipe,`|`);return n}function fx(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 px(e){let t=e.split(`
|
|
1712
|
+
`),n=t.length-1;for(;n>=0&&$y.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
|
|
1713
|
+
`)}function mx(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 hx(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 gx(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 _x(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
1705
1714
|
`).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(`
|
|
1706
|
-
`)}var
|
|
1707
|
-
`),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:
|
|
1708
|
-
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=
|
|
1715
|
+
`)}var vx=class{options;rules;lexer;constructor(e){this.options=e||Jy}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]:px(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=_x(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=fx(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:fx(t[0],`
|
|
1716
|
+
`),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:fx(t[0],`
|
|
1717
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=fx(t[0],`
|
|
1709
1718
|
`).split(`
|
|
1710
1719
|
`),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(`
|
|
1711
1720
|
`),c=s.replace(this.rules.other.blockquoteSetextReplace,`
|
|
@@ -1716,20 +1725,20 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
1716
1725
|
`),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+`
|
|
1717
1726
|
`+e.join(`
|
|
1718
1727
|
`),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(`
|
|
1719
|
-
`);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=
|
|
1728
|
+
`);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=hx(t[2].split(`
|
|
1720
1729
|
`,1)[0],t[1].length),l=e.split(`
|
|
1721
1730
|
`,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+`
|
|
1722
1731
|
`,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(`
|
|
1723
1732
|
`,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+=`
|
|
1724
1733
|
`+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+=`
|
|
1725
1734
|
`+l}u=!l.trim(),r+=p+`
|
|
1726
|
-
`,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=
|
|
1727
|
-
`),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
|
|
1728
|
-
`):[],a={type:`table`,raw:
|
|
1729
|
-
`),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(
|
|
1735
|
+
`,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=px(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:fx(t[0],`
|
|
1736
|
+
`),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=dx(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
|
|
1737
|
+
`):[],a={type:`table`,raw:fx(t[0],`
|
|
1738
|
+
`),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(dx(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:fx(t[0],`
|
|
1730
1739
|
`),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)===`
|
|
1731
|
-
`?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=
|
|
1732
|
-
`),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(
|
|
1740
|
+
`?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=fx(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=mx(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)),gx(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 gx(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}}}},yx=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Jy,this.options.tokenizer=this.options.tokenizer||new vx,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:$y,block:ax.normal,inline:ox.normal};this.options.pedantic?(t.block=ax.pedantic,t.inline=ox.pedantic):this.options.gfm&&(t.block=ax.gfm,this.options.breaks?t.inline=ox.breaks:t.inline=ox.gfm),this.tokenizer.rules=t}static get rules(){return{block:ax,inline:ox}}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($y.carriageReturn,`
|
|
1741
|
+
`),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($y.tabCharGlobal,` `).replace($y.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+=`
|
|
1733
1742
|
`: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(`
|
|
1734
1743
|
`)?``:`
|
|
1735
1744
|
`)+i.raw,n.text+=`
|
|
@@ -1742,9 +1751,9 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
1742
1751
|
`+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(`
|
|
1743
1752
|
`)?``:`
|
|
1744
1753
|
`)+i.raw,n.text+=`
|
|
1745
|
-
`+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)}},
|
|
1746
|
-
`;return r?`<pre><code class="language-`+
|
|
1747
|
-
`:`<pre><code>`+(n?i:
|
|
1754
|
+
`+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)}},bx=class{options;parser;constructor(e){this.options=e||Jy}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match($y.notSpaceStart)?.[0],i=e.replace($y.endingNewline,``)+`
|
|
1755
|
+
`;return r?`<pre><code class="language-`+lx(r)+`">`+(n?i:lx(i,!0))+`</code></pre>
|
|
1756
|
+
`:`<pre><code>`+(n?i:lx(i,!0))+`</code></pre>
|
|
1748
1757
|
`}blockquote({tokens:e}){return`<blockquote>
|
|
1749
1758
|
${this.parser.parse(e)}</blockquote>
|
|
1750
1759
|
`}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
@@ -1760,8 +1769,8 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
1760
1769
|
`}tablerow({text:e}){return`<tr>
|
|
1761
1770
|
${e}</tr>
|
|
1762
1771
|
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
1763
|
-
`}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>${
|
|
1764
|
-
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+
|
|
1772
|
+
`}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>${lx(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=ux(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+lx(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=ux(e);if(i===null)return lx(n);e=i;let a=`<img src="${e}" alt="${lx(n)}"`;return t&&(a+=` title="${lx(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:lx(e.text)}},xx=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}},Sx=class e{options;renderer;textRenderer;constructor(e){this.options=e||Jy,this.options.renderer=this.options.renderer||new bx,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new xx}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}},Cx=class{options;block;constructor(e){this.options=e||Jy}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?yx.lex:yx.lexInline}provideParser(e=this.block){return e?Sx.parse:Sx.parseInline}},wx=new class{defaults=qy();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=Sx;Renderer=bx;TextRenderer=xx;Lexer=yx;Tokenizer=vx;Hooks=Cx;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 bx(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 vx(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 Cx;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];Cx.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&Cx.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 yx.lex(e,t??this.defaults)}parser(e,t){return Sx.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?yx.lex:yx.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?Sx.parse:Sx.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?yx.lex:yx.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?Sx.parse:Sx.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+=`
|
|
1773
|
+
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+lx(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function G(e,t){return wx.parse(e,t)}G.options=G.setOptions=function(e){return wx.setOptions(e),G.defaults=wx.defaults,Yy(G.defaults),G},G.getDefaults=qy,G.defaults=Jy,G.use=function(...e){return wx.use(...e),G.defaults=wx.defaults,Yy(G.defaults),G},G.walkTokens=function(e,t){return wx.walkTokens(e,t)},G.parseInline=wx.parseInline,G.Parser=Sx,G.parser=Sx.parse,G.Renderer=bx,G.TextRenderer=xx,G.Lexer=yx,G.lexer=yx.lex,G.Tokenizer=vx,G.Hooks=Cx,G.parse=G,G.options,G.setOptions,G.use,G.walkTokens,G.parseInline,Sx.parse,yx.lex;var Tx=new G.Renderer;Tx.html=({text:e})=>kx(e);var Ex=300,Dx=new Map;function Ox(e){let t=Dx.get(e);if(t!==void 0)return t;let n=jx(G.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:Tx}));if(Dx.set(e,n),Dx.size>Ex){let e=Dx.keys().next().value;e!==void 0&&Dx.delete(e)}return n}function kx(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}var Ax=`table-scroll`;function jx(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`)&&!Nx(t.value)&&e.removeAttribute(t.name)}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),Mx(t.content),t.innerHTML}function Mx(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(Ax)===!0)return;let t=document.createElement(`div`);t.className=Ax,t.setAttribute(`role`,`region`),t.setAttribute(`aria-label`,`表格`),t.setAttribute(`tabindex`,`0`),e.before(t),t.append(e)})}function Nx(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}var Px=h`
|
|
1765
1774
|
:host { display: block; }
|
|
1766
1775
|
.formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
|
|
1767
1776
|
p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
|
|
@@ -1787,18 +1796,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1787
1796
|
th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
|
|
1788
1797
|
th { background: var(--pi-surface); }
|
|
1789
1798
|
mark[data-search-highlight] { border-radius: 3px; background: color-mix(in srgb, var(--pi-warning) 42%, var(--pi-warning-surface)); color: var(--pi-text-bright, inherit); padding: 0 1px; box-shadow: 0 0 0 1px var(--pi-warning-border); }
|
|
1790
|
-
`,
|
|
1799
|
+
`,Fx=class extends v{constructor(...e){super(...e),this.text=``,this.highlight=``,this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`.code-copy-button`);if(!(t instanceof HTMLButtonElement))return;let n=t.closest(`.code-block-wrapper`);if(!(n instanceof HTMLElement))return;let r=n.querySelector(`pre code`);r instanceof HTMLElement&&this.copyCode(r.textContent,t)}}render(){return g`<div class="formatted" dir="auto" @click=${this.onFormattedClick}>${Ky(Ox(this.text))}</div>`}updated(){this.enhanceCodeBlocks(),this.applyHighlight()}applyHighlight(){let e=this.renderRoot.querySelector(`.formatted`);if(!(e instanceof HTMLElement))return;e.querySelectorAll(`mark[data-search-highlight]`).forEach(e=>{e.replaceWith(document.createTextNode(e.textContent))}),e.normalize();let t=this.highlight.trim();if(t===``)return;let n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),r=[];for(let e=n.nextNode();e!==null;e=n.nextNode())e instanceof Text&&e.parentElement?.closest(`.code-copy-button`)===null&&r.push(e);for(let e of r)Ix(e,t)}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=`复制代码块`,n.setAttribute(`aria-label`,`复制代码块`);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 q_(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`?`已复制代码块`:t===`failed`?`复制代码块失败`:`复制代码块`;e.title=r,e.setAttribute(`aria-label`,r)}static{this.styles=Px}};B([b()],Fx.prototype,`text`,void 0),B([b()],Fx.prototype,`highlight`,void 0),Fx=B([y(`formatted-text`)],Fx);function Ix(e,t){let n=e.data,r=[...n.matchAll(new RegExp(Lx(t),`giu`))];if(r.length===0)return;let i=0,a=document.createDocumentFragment();for(let e of r){let t=e.index;t>i&&a.append(n.slice(i,t));let r=document.createElement(`mark`);r.dataset.searchHighlight=``,r.textContent=e[0],a.append(r),i=t+e[0].length}i<n.length&&a.append(n.slice(i)),e.replaceWith(a)}function Lx(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}var Rx=180,zx=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=Vx(e.args),n=Ux(e.details),r=e.preview,i=n??r?.diff,a=i===void 0?void 0:Wx(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=Bx(e,t);return g`
|
|
1791
1800
|
<section class=${`tool-card ${e.status}`}>
|
|
1792
1801
|
<div class="tool-header">
|
|
1793
1802
|
<div class="tool-title">
|
|
1794
|
-
<span class="status-icon" aria-hidden="true">${
|
|
1803
|
+
<span class="status-icon" aria-hidden="true">${Jx(e.status)}</span>
|
|
1795
1804
|
<strong>${e.toolName}</strong>
|
|
1796
1805
|
${this.renderHeaderTarget(l)}
|
|
1797
1806
|
</div>
|
|
1798
1807
|
<div class="tool-meta">
|
|
1799
|
-
${
|
|
1808
|
+
${Hx(e)===void 0?null:g`<span>${Hx(e)}</span>`}
|
|
1800
1809
|
${a===void 0?null:g`<span class="diff-stats"><b class="added">+${a.added}</b><span>/</span><b class="removed">-${a.removed}</b></span>`}
|
|
1801
|
-
<span class="status-label">${
|
|
1810
|
+
<span class="status-label">${Yx(e.status)}</span>
|
|
1802
1811
|
</div>
|
|
1803
1812
|
</div>
|
|
1804
1813
|
|
|
@@ -1823,7 +1832,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1823
1832
|
`}
|
|
1824
1833
|
</details>
|
|
1825
1834
|
`}renderDiffBody(e,t,n){let r=e.split(`
|
|
1826
|
-
`),i=!this.showFullDiff&&r.length>
|
|
1835
|
+
`),i=!this.showFullDiff&&r.length>Rx,a=i?r.slice(0,Rx):r;return g`
|
|
1827
1836
|
<details class="diff-details" ?open=${this.diffOpen} @toggle=${e=>{this.onDiffToggle(e)}}>
|
|
1828
1837
|
<summary>
|
|
1829
1838
|
<span>${t}</span>
|
|
@@ -1834,7 +1843,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1834
1843
|
<span>${i?`显示 ${String(a.length)} / ${String(r.length)} 行`:`完整 diff`}</span>
|
|
1835
1844
|
<button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?`已复制`:`复制 diff`}</button>
|
|
1836
1845
|
</div>
|
|
1837
|
-
<pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${
|
|
1846
|
+
<pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${Gx(e)}>${e}</span>`)}</code></pre>
|
|
1838
1847
|
${i?g`
|
|
1839
1848
|
<button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
|
|
1840
1849
|
显示全部 ${String(r.length)} 行 diff
|
|
@@ -1885,24 +1894,24 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1885
1894
|
.diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
|
|
1886
1895
|
.diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
|
|
1887
1896
|
.show-more { justify-self: start; }
|
|
1888
|
-
`}};B([b({attribute:!1})],
|
|
1889
|
-
`))
|
|
1897
|
+
`}};B([b({attribute:!1})],zx.prototype,`execution`,void 0),B([x()],zx.prototype,`showFullDiff`,void 0),B([x()],zx.prototype,`copied`,void 0),B([x()],zx.prototype,`diffOpen`,void 0),zx=B([y(`tool-execution-view`)],zx);function Bx(e,t){if(t!==void 0&&t!==``)return{label:`文件`,text:t};let n=Qx(e.args,`command`);if(n!==void 0&&n!==``)return{label:`命令`,text:n};if(e.summary!==``)return{label:`输入`,text:e.summary}}function Vx(e){return Qx(e,`path`)??Qx(e,`file_path`)}function Hx(e){if(e.toolName!==`edit`)return;let t=Zx(e.args,`edits`);if(Array.isArray(t))return`${String(t.length)} 处编辑`;if(typeof Zx(e.args,`oldText`)==`string`&&typeof Zx(e.args,`newText`)==`string`)return`1 处编辑`}function Ux(e){return Qx(e,`diff`)}function Wx(e){let t=0,n=0;for(let r of e.split(`
|
|
1898
|
+
`))Kx(r)?t++:qx(r)&&n++;return{added:t,removed:n}}function Gx(e){return Kx(e)?`added`:qx(e)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`+++`)||e.startsWith(`---`)?`file`:e.startsWith(`diff `)||e.startsWith(`index `)?`meta`:`context`}function Kx(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)}function qx(e){return e.startsWith(`-`)&&!e.startsWith(`---`)}function Jx(e){return e===`success`?`✓`:e===`error`?`✖`:e===`running`?`●`:`○`}function Yx(e){return e===`success`?`完成`:e===`error`?`失败`:e===`running`?`运行中`:`等待中`}function Xx(e){return typeof e==`object`&&!!e}function Zx(e,t){return Xx(e)?e[t]:void 0}function Qx(e,t){let n=Zx(e,t);return typeof n==`string`?n:void 0}var $x=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`medium`}),eS=new Intl.DateTimeFormat(void 0,{timeStyle:`short`});function tS(e){return g`
|
|
1890
1899
|
<svg class=${`notification-icon notification-disclosure-icon${e?``:` expanded`}`} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1891
1900
|
<path d="m9 18 6-6-6-6"></path>
|
|
1892
1901
|
</svg>
|
|
1893
|
-
`}function
|
|
1902
|
+
`}function nS(){return g`
|
|
1894
1903
|
<svg class="notification-icon notification-close-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1895
1904
|
<path d="M6 6l12 12"></path>
|
|
1896
1905
|
<path d="M18 6 6 18"></path>
|
|
1897
1906
|
</svg>
|
|
1898
|
-
`}function
|
|
1907
|
+
`}function rS(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 iS(e){return aS(e,0,100)}function aS(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function oS(e,t){return[e.length===0?void 0:{source:`client`,heading:`等待会话启动后发送`,detail:`后端会话就绪后将自动发送`,messages:e},t.length===0?void 0:{source:`server`,heading:`排队中的消息`,detail:`${String(t.length)} 条待处理`,messages:t}].filter(e=>e!==void 0)}function sS(e){return{src:`data:${e.mimeType};base64,${e.data}`,alt:`附加图片`}}function cS(e){return e===void 0||e===``?`工具输出`:`${e} 输出`}var lS={user:`用户`,assistant:`助手`,tool:`工具`,system:`系统`,bash:`命令`,skill:`技能`};function uS(e){return lS[e]}function dS(e){return`m:${String(e)}`}function fS(e){return`g:${String(e)}`}function pS(e){return`e:${String(e)}`}function mS(e){return`g:${String(e)}`}function hS(e){return e?`msg event-group live`:`msg event-group`}function gS(e){return e?`实时事件`:`事件`}function _S(e,t,n){return e.source===`server`&&t&&n}function vS(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 yS(e){let t=e.meta?.timestamp,n=[t===void 0?void 0:bS(t),xS(e)].filter(e=>e!==void 0&&e!==``);return n.length===0?`没有可用的 Pi 消息元数据`:n.join(` · `)}function bS(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return $x.format(t)}function xS(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.canClearServerQueue=!1,this.warningsVisible=!0,this.pinnedToBottom=!0,this.zoomedImage=void 0,this.collapsedNotificationTargetKeys=new Set,this.disclosures=new ny,this.scrollController=new Ay,this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.transcriptStructureKey=``,this.primaryArticleElements=[],this.articleElements=[],this.scrollAnchorElementIndex=[],this.scrollMarkerElements=[],this.scrollMarkerElementById=new Map,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.handleToggleWarnings=()=>{this.onToggleWarnings?.()}}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.saveScrollPosition(),this.scrollController.dispose(),this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.loadMoreCheckFrame!==void 0&&cancelAnimationFrame(this.loadMoreCheckFrame),this.scrollToBottomFrame!==void 0&&cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToOpenAskFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenAskFrame),this.scrollToOpenAskFrame=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),this.clearTranscriptElementIndex(),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!=`string`||e===``||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.disclosures.syncSession(this.sessionId),this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0,this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this.prependRestoreToken+=1,this.clearTranscriptElementIndex(),this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0),this.scrollToOpenAskFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenAskFrame),this.scrollToOpenAskFrame=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),this.liveTailContentChanged(e)&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){let t=this.isPrependingMessages(e)?this.capturePrependScrollAnchor():void 0;super.update(e),this.syncTranscriptElementIndex(),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`));!e.has(`sessionId`)&&t&&this.pinnedToBottom?this.scrollToOpenAsk():!e.has(`sessionId`)&&this.liveTailContentChanged(e)&&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`))&&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()}liveTailContentChanged(e){return e.has(`messages`)||e.has(`pendingAsk`)||e.has(`pendingMessageCount`)||e.has(`clientQueuedMessages`)}syncImageZoomDialog(){let e=this.imageZoomDialog;e!==void 0&&(this.zoomedImage!==void 0&&!e.open?e.showModal():this.zoomedImage===void 0&&e.open&&e.close())}notificationTargetChanged(e){let t=this.notificationInbox;return!rS(e)||t===void 0?e!==t:Fd(e)!==Fd(t)}render(){let e=this.groupedMessages();return g`
|
|
1899
1908
|
${this.renderTopNotices()}
|
|
1900
1909
|
${this.renderNotificationLiveRegions()}
|
|
1901
1910
|
<div class="chat-wrap">
|
|
1902
1911
|
${this.renderConversationRail()}
|
|
1903
1912
|
<div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${e=>{this.onWheel(e)}} @touchstart=${e=>{this.onTouchStart(e)}} @touchmove=${e=>{this.onTouchMove(e)}}>
|
|
1904
1913
|
${this.renderHistoryBoundary()}
|
|
1905
|
-
${
|
|
1914
|
+
${$v(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))}
|
|
1906
1915
|
${this.renderQueuedMessages()}
|
|
1907
1916
|
${this.renderSessionActivity()}
|
|
1908
1917
|
${this.renderOpenAsk()}
|
|
@@ -1931,7 +1940,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1931
1940
|
aria-expanded=${String(!a)}
|
|
1932
1941
|
aria-controls="session-notification-list"
|
|
1933
1942
|
@click=${()=>{this.toggleNotificationTray(e,a)}}
|
|
1934
|
-
>${
|
|
1943
|
+
>${tS(a)}</button>
|
|
1935
1944
|
</div>
|
|
1936
1945
|
</header>
|
|
1937
1946
|
<div class="notification-list" id="session-notification-list" ?hidden=${a}>
|
|
@@ -1943,7 +1952,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1943
1952
|
<div class="notification-metadata">
|
|
1944
1953
|
<strong class="notification-severity">${n}</strong>
|
|
1945
1954
|
<span aria-hidden="true">·</span>
|
|
1946
|
-
<time datetime=${t.receivedAt}>${
|
|
1955
|
+
<time datetime=${t.receivedAt}>${eS.format(new Date(t.receivedAt))}</time>
|
|
1947
1956
|
</div>
|
|
1948
1957
|
<p class="notification-message" dir="auto">${t.message}</p>
|
|
1949
1958
|
${r===void 0?null:g`<p class="notification-truncated">${r}</p>`}
|
|
@@ -1954,15 +1963,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1954
1963
|
title="关闭通知"
|
|
1955
1964
|
?disabled=${e.pendingDismissedIds.has(t.id)||e.dismissAllPending||this.onDismissNotification===void 0}
|
|
1956
1965
|
@click=${()=>{this.dismissNotification(t.id)}}
|
|
1957
|
-
>${
|
|
1966
|
+
>${nS()}</button>
|
|
1958
1967
|
</article>
|
|
1959
1968
|
`})}
|
|
1960
1969
|
</div>
|
|
1961
1970
|
</section>
|
|
1962
1971
|
`}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`
|
|
1963
|
-
<div class="visually-hidden notification-live" aria-live="polite" aria-atomic="false">${
|
|
1964
|
-
<div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${
|
|
1965
|
-
`}toggleNotificationTray(e,t){this.collapsedNotificationTargetKeys=Ld(this.collapsedNotificationTargetKeys,e,!t)}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=Pd(t.notifications,e),r=Fd(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=Fd(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===Fd(r)&&jd(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||Fd(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}jd(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}renderWarnings(){let e=
|
|
1972
|
+
<div class="visually-hidden notification-live" aria-live="polite" aria-atomic="false">${$v(t,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${Ad(e)}</span>`)}</div>
|
|
1973
|
+
<div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${$v(n,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${Ad(e)}</span>`)}</div>
|
|
1974
|
+
`}toggleNotificationTray(e,t){this.collapsedNotificationTargetKeys=Ld(this.collapsedNotificationTargetKeys,e,!t)}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=Pd(t.notifications,e),r=Fd(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=Fd(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===Fd(r)&&jd(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||Fd(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}jd(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}renderWarnings(){let e=vS(this.status);return!this.warningsVisible||e.length===0?null:g`
|
|
1966
1975
|
<aside class="session-warnings" role="alert" aria-live="polite">
|
|
1967
1976
|
${this.onToggleWarnings===void 0?null:g`
|
|
1968
1977
|
<div class="session-warnings-controls">
|
|
@@ -2009,7 +2018,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2009
2018
|
<img class="image-zoom-full" src=${this.zoomedImage.src} alt=${this.zoomedImage.alt} />
|
|
2010
2019
|
`}
|
|
2011
2020
|
</dialog>
|
|
2012
|
-
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=
|
|
2021
|
+
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=cy(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase===`active`}renderActivityDock(){if(this.isSendingPrompt)return g`
|
|
2013
2022
|
<div class="activity-dock active" aria-live="polite">
|
|
2014
2023
|
<span class="dot"></span>
|
|
2015
2024
|
<span class="activity-text">正在发送你的消息…</span>
|
|
@@ -2019,7 +2028,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2019
2028
|
<span class="dot"></span>
|
|
2020
2029
|
<span class="activity-text">${this.activityText(e)}</span>
|
|
2021
2030
|
</div>
|
|
2022
|
-
`}renderQueuedMessages(){let e=this.status?.queuedMessages??[];return g`${
|
|
2031
|
+
`}renderQueuedMessages(){let e=this.status?.queuedMessages??[];return g`${oS(this.clientQueuedMessages,e).map(e=>this.renderQueuedMessageList(e))}`}renderQueuedMessageList(e){let t=_S(e,this.canClearServerQueue,this.onClearServerQueue!==void 0);return g`
|
|
2023
2032
|
<aside class="queued-messages" aria-live="polite">
|
|
2024
2033
|
<div class="queued-header">
|
|
2025
2034
|
<div class="queued-heading">
|
|
@@ -2050,7 +2059,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2050
2059
|
<span>代理正在总结较早的上下文。压缩完成前,新提示词将进入队列。</span>
|
|
2051
2060
|
${this.pendingMessageCount>0?g`<small>${this.pendingMessageCount} 条消息正在排队</small>`:null}
|
|
2052
2061
|
</aside>
|
|
2053
|
-
`:null}activityState(){let e=this.status;return e===void 0?this.activity?.label:e.isCompacting?`compacting`:e.isBashRunning?`bash`:e.isStreaming?`running`:e.pendingMessageCount>0?`queued`:`idle`}activityText(e){let t=this.activity;if(t===void 0)return
|
|
2062
|
+
`:null}activityState(){let e=this.status;return e===void 0?this.activity?.label:e.isCompacting?`compacting`:e.isBashRunning?`bash`:e.isStreaming?`running`:e.pendingMessageCount>0?`queued`:`idle`}activityText(e){let t=this.activity;if(t===void 0)return SS(e);if(e!==`idle`&&t.phase===`idle`)return e;let n=SS(t.label,t.phase);return t.detail!==void 0&&t.detail!==``?`${n}:${t.detail}`:n}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?iS(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 iS(aS(this.currentConversationIndex??t,0,e-1)/(e-1)*100)}renderHistoryBoundary(){let e=this.historyRangeLabel();return this.loadingMore?g`<div class="history-boundary"><span>正在加载较早消息…</span>${e}</div>`:this.hasMore?g`
|
|
2054
2063
|
<div class="history-boundary">
|
|
2055
2064
|
<button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>加载较早消息</button>
|
|
2056
2065
|
<span>向上滚动以加载较早消息</span>
|
|
@@ -2062,7 +2071,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2062
2071
|
${n||r?null:this.renderMessageHeader(e,String(t))}
|
|
2063
2072
|
${e.parts.map(t=>this.renderPart(t,e))}
|
|
2064
2073
|
</article>
|
|
2065
|
-
`}renderToolImageOutput(e,t,n){let r=
|
|
2074
|
+
`}renderToolImageOutput(e,t,n){let r=cS(n);return g`
|
|
2066
2075
|
${this.renderScrollMarker(this.messageScrollMarkerId(t))}
|
|
2067
2076
|
<article class="msg tool-image-output" data-index=${t} data-scroll-anchor-id=${this.messageAnchorKey(t)}>
|
|
2068
2077
|
${this.renderMessageHeader(e,String(t),r)}
|
|
@@ -2070,10 +2079,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2070
2079
|
</article>
|
|
2071
2080
|
`}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`
|
|
2072
2081
|
${this.renderScrollMarker(this.groupScrollMarkerId(n))}
|
|
2073
|
-
<details class=${
|
|
2082
|
+
<details class=${hS(r)} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${a} @toggle=${e=>{this.onGroupToggle(i,e,r)}}>
|
|
2074
2083
|
<summary>
|
|
2075
|
-
<b class="label">${
|
|
2076
|
-
<span>${
|
|
2084
|
+
<b class="label">${gS(r)}</b>
|
|
2085
|
+
<span>${ly(e)}</span>
|
|
2077
2086
|
</summary>
|
|
2078
2087
|
${a?this.renderMessageGroupBody(e,t):null}
|
|
2079
2088
|
</details>
|
|
@@ -2086,7 +2095,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2086
2095
|
</section>
|
|
2087
2096
|
`})}
|
|
2088
2097
|
</div>
|
|
2089
|
-
`}renderScrollMarker(e){return g`<span class="scroll-marker" data-marker-id=${e} aria-hidden="true"></span>`}renderMessageHeader(e,t,n=
|
|
2098
|
+
`}renderScrollMarker(e){return g`<span class="scroll-marker" data-marker-id=${e} aria-hidden="true"></span>`}renderMessageHeader(e,t,n=uS(e.role)){let r=this.messageMetaLabel(e),i=this.expandedMetaKey===t;return g`
|
|
2090
2099
|
<div class="msg-header">
|
|
2091
2100
|
<b class="label">${n}</b>
|
|
2092
2101
|
<div class="msg-header-trailing">
|
|
@@ -2096,13 +2105,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2096
2105
|
</div>
|
|
2097
2106
|
`}renderMessageActions(e,t){if(!this.isCopyableMessage(e))return null;let n=this.copiedMessageKey===t;return g`
|
|
2098
2107
|
<div class="msg-actions" aria-label="消息操作">
|
|
2099
|
-
<button type="button" class="msg-action" title=${n?`已复制`:`复制消息`} aria-label=${`${n?`已复制`:`复制`}${
|
|
2108
|
+
<button type="button" class="msg-action" title=${n?`已复制`:`复制消息`} aria-label=${`${n?`已复制`:`复制`}${uS(e.role)}消息`} @click=${n=>{this.copyMessage(e,t,n)}}>
|
|
2100
2109
|
<span aria-hidden="true">${n?`✓`:`⧉`}</span>
|
|
2101
2110
|
</button>
|
|
2102
2111
|
</div>
|
|
2103
2112
|
`}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(`
|
|
2104
2113
|
|
|
2105
|
-
`);return this.messageCopyTextCache.set(e,n),n}async copyMessage(e,t,n){n.stopPropagation(),await q_(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=
|
|
2114
|
+
`);return this.messageCopyTextCache.set(e,n),n}async copyMessage(e,t,n){n.stopPropagation(),await q_(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=yS(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>思考</summary><formatted-text .text=${e.text}></formatted-text></details>`;if(e.type===`skillInvocation`)return g`
|
|
2106
2115
|
<details class="part skill-invocation">
|
|
2107
2116
|
<summary><b>[skill]</b> ${e.name}</summary>
|
|
2108
2117
|
<small>${e.location}</small>
|
|
@@ -2119,36 +2128,36 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2119
2128
|
.outcome=${e.outcome}
|
|
2120
2129
|
.draftSessionId=${this.askDraftSessionId}
|
|
2121
2130
|
></ask-user-card>
|
|
2122
|
-
`;if(e.type===`image`){let{src:t,alt:n}=
|
|
2131
|
+
`;if(e.type===`image`){let{src:t,alt:n}=sS(e);return g`<img class="part chat-image" src=${t} alt=${n} loading="lazy" role="button" tabindex="0" title="点击放大" @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`
|
|
2123
2132
|
<details class="part" ?open=${e.isError}>
|
|
2124
2133
|
<summary>${e.isError?`✖`:`✓`} ${e.toolName} result</summary>
|
|
2125
2134
|
<formatted-text .text=${e.text}></formatted-text>
|
|
2126
2135
|
</details>
|
|
2127
|
-
`: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&&ly({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||Cy(e)}isAtBottom(){let e=this.chat;return!e||Sy(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)}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)}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())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 ty(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(ny(i,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=i.scrollTop,n+=1,n<30){requestAnimationFrame(r);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};r()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){let e=this.sessionId;this.scrollController.scheduleSave(e,e=>{this.sessionId===e&&this.saveScrollPosition(e)})}scheduleConversationRailUpdate(){this.conversationRailFrame===void 0&&(this.conversationRailFrame=requestAnimationFrame(()=>{this.conversationRailFrame=void 0,this.updateConversationRailPosition()}))}updateConversationRailPosition(){if(!this.messages.length||this.messageTotal<=0){this.currentConversationIndex=void 0;return}let e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),n=Number(t?.dataset.index);if(Number.isFinite(n)){this.currentConversationIndex=qx(n,0,Math.max(0,e-1));return}this.currentConversationIndex=qx(this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,0,Math.max(0,e-1))}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(`.scroll-marker`))}scrollMarkerAt(e){return this.scrollMarkers().find(t=>t.dataset.markerId===e)}firstVisibleArticle(){let e=this.chat;if(e!==void 0)return Ey(e,Array.from(this.renderRoot.querySelectorAll(`article.msg`)))??Ey(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 $x(e)}groupRenderKey(e){return eS(e)}groupAnchorKey(e){return eS(e)}eventAnchorKey(e){return tS(e)}messageScrollMarkerId(e){return $x(e)}groupScrollMarkerId(e){return nS(e)}static{this.styles=Om}};B([b({attribute:!1})],K.prototype,`messages`,void 0),B([b()],K.prototype,`sessionId`,void 0),B([b({type:Number})],K.prototype,`messageStart`,void 0),B([b({type:Number})],K.prototype,`messageEnd`,void 0),B([b({type:Number})],K.prototype,`messageTotal`,void 0),B([b({type:Boolean})],K.prototype,`hasMore`,void 0),B([b({type:Boolean})],K.prototype,`loadingMore`,void 0),B([b({type:Boolean})],K.prototype,`isSendingPrompt`,void 0),B([b({type:Boolean})],K.prototype,`isCompacting`,void 0),B([b({type:Number})],K.prototype,`pendingMessageCount`,void 0),B([b({attribute:!1})],K.prototype,`clientQueuedMessages`,void 0),B([b({attribute:!1})],K.prototype,`status`,void 0),B([b({attribute:!1})],K.prototype,`activity`,void 0),B([b({attribute:!1})],K.prototype,`pendingAsk`,void 0),B([b({attribute:!1})],K.prototype,`askDraftSessionId`,void 0),B([b({attribute:!1})],K.prototype,`onSubmitAsk`,void 0),B([b({attribute:!1})],K.prototype,`notificationInbox`,void 0),B([b({type:Boolean})],K.prototype,`canClearServerQueue`,void 0),B([b({attribute:!1})],K.prototype,`onClearServerQueue`,void 0),B([b({attribute:!1})],K.prototype,`onDismissWarning`,void 0),B([b({attribute:!1})],K.prototype,`onDismissNotification`,void 0),B([b({attribute:!1})],K.prototype,`onDismissAllNotifications`,void 0),B([b({type:Boolean})],K.prototype,`warningsVisible`,void 0),B([b({attribute:!1})],K.prototype,`onToggleWarnings`,void 0),B([b({attribute:!1})],K.prototype,`onLoadMore`,void 0),B([S(`.chat`)],K.prototype,`chat`,void 0),B([S(`dialog.image-zoom`)],K.prototype,`imageZoomDialog`,void 0),B([x()],K.prototype,`pinnedToBottom`,void 0),B([x()],K.prototype,`zoomedImage`,void 0),B([x()],K.prototype,`expandedMetaKey`,void 0),B([x()],K.prototype,`copiedMessageKey`,void 0),B([x()],K.prototype,`currentConversationIndex`,void 0),B([x()],K.prototype,`collapsedNotificationTargetKeys`,void 0),B([x()],K.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),B([x()],K.prototype,`loadMoreRequested`,void 0),K=B([y(`chat-view`)],K);function uS(e,t){return t===`idle`?`空闲`:t===void 0?{"agent running":`代理正在运行`,"bash complete":`命令执行完成`,"bash failed":`命令执行失败`,"branch summary aborted":`分支汇总已终止`,compacting:`正在压缩上下文`,"compaction complete":`上下文压缩完成`,"compaction failed":`上下文压缩失败`,"duplicate queued message ignored":`已忽略重复的排队消息`,error:`发生错误`,"extension error":`扩展错误`,idle:`空闲`,"message complete":`消息处理完成`,"message queued":`消息已排队`,"message queued during compaction":`压缩期间消息已排队`,"message started":`消息开始处理`,"navigating session tree":`正在切换会话树`,"prompt accepted":`消息已接收`,"receiving response":`正在接收回复`,"reload failed":`重新加载失败`,"reloading resources":`正在重新加载资源`,"resources reloaded":`资源已重新加载`,running:`代理正在运行`,"running bash":`正在运行命令`,"running tool":`正在运行工具`,"session tree navigated":`已切换会话树`,"steering queued":`插队消息已排队`,"stop failed":`停止失败`,stopped:`已停止`,"summarizing branch":`正在汇总分支`,"tool complete":`工具执行完成`,"tool failed":`工具执行失败`,"tree navigation cancelled":`会话树切换已取消`,"turn complete":`本轮已完成`,"updating session":`正在更新会话`,queued:`正在排队`}[e]??e:uS(e)}var dS=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function fS(e){return typeof e==`string`&&dS.has(e)}function pS(e){switch(e){case`image/jpeg`:return`jpg`;case`image/png`:return`png`;case`image/gif`:return`gif`;case`image/webp`:return`webp`;default:return`bin`}}var mS=`application/octet-stream`,hS=`读取附件失败。`;async function gS(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(bS(i,e))}catch{r=hS}return{attachments:n,...r===void 0?{}:{error:r}}}function _S(e){return e.kind===`image`&&fS(e.mimeType)}function vS(e){return e.every(e=>_S(e))}function yS(e,t){return vS(t)?e:`folder`}function bS(e,t){return fS(e.type)?{kind:`image`,name:SS(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:SS(e),mimeType:xS(e),data:t,size:e.size}}function xS(e){let t=e.type.trim();return t===``?mS:t}function SS(e){return e.name===``?fS(e.type)?`pasted-image.${pS(e.type)}`:`pasted-file.bin`:e.name}var CS=`pi-web:attachment-delivery`;function wS(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function TS(e=wS()){try{return e?.getItem(CS)===`folder`?`folder`:`inline`}catch{return`inline`}}function ES(e,t=wS()){try{t?.setItem(CS,e)}catch{}}var DS=`(pointer: coarse), (max-width: 760px)`,OS=`pi-web.promptEnterPreference`;function kS(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(DS):void 0}function AS(e){return e===`send`||e===`newline`?e:`auto`}function jS(e=IS()){if(e===void 0)return`auto`;try{return AS(e.getItem(OS))}catch{return`auto`}}function MS(e,t=IS()){if(t!==void 0)try{t.setItem(OS,e)}catch{}}function NS(e=kS(),t=jS()){return t===`send`||t!==`newline`&&e?.matches!==!0}function PS(e,t,n=kS()){return e?n?.matches!==!0||t:!1}function FS(e,t=kS(),n=jS()){let r=NS(t,n);return e?!r:r}function IS(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function LS(){return Je`
|
|
2136
|
+
`: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&&xy({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||Fy(e)}isAtBottom(){let e=this.chat;return!e||Py(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)}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)}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())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 py(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(my(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=aS(n,0,Math.max(0,e-1));return}this.currentConversationIndex=aS(this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,0,Math.max(0,e-1))}scrollMarkers(){return this.scrollMarkerElements}scrollMarkerAt(e){return this.scrollMarkerElementById.get(e)}firstVisibleArticle(){let e=this.chat;if(e!==void 0)return Ry(e,this.primaryArticleElements)??Ry(e,this.articles())}articles(){return this.articleElements}scrollAnchorElements(){return this.scrollAnchorElementIndex}syncTranscriptElementIndex(){let e=this.currentTranscriptStructureKey();e!==this.transcriptStructureKey&&(this.transcriptStructureKey=e,this.primaryArticleElements=Array.from(this.renderRoot.querySelectorAll(`article.msg`)),this.articleElements=Array.from(this.renderRoot.querySelectorAll(`article.msg, details.msg`)),this.scrollAnchorElementIndex=Array.from(this.renderRoot.querySelectorAll(`[data-scroll-anchor-id]`)),this.scrollMarkerElements=Array.from(this.renderRoot.querySelectorAll(`.scroll-marker`)),this.scrollMarkerElementById=new Map(this.scrollMarkerElements.flatMap(e=>{let t=e.dataset.markerId;return t===void 0?[]:[[t,e]]})))}currentTranscriptStructureKey(){let e=this.groupedMessages(),t=e.map((t,n)=>{if(t.kind!==`group`)return[t.kind,t.index];let r=this.isLiveTailGroup(e,n),i=this.groupDisclosureKey(t.startIndex,t.endIndex,r);return[t.kind,t.startIndex,t.endIndex,this.disclosures.isOpen(i,r)]});return JSON.stringify([this.sessionId,this.messageStart,t,this.hasMore,this.loadingMore,this.pendingAsk?.askId])}clearTranscriptElementIndex(){this.transcriptStructureKey=``,this.primaryArticleElements=[],this.articleElements=[],this.scrollAnchorElementIndex=[],this.scrollMarkerElements=[],this.scrollMarkerElementById.clear()}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 dS(e)}groupRenderKey(e){return fS(e)}groupAnchorKey(e){return fS(e)}eventAnchorKey(e){return pS(e)}messageScrollMarkerId(e){return dS(e)}groupScrollMarkerId(e){return mS(e)}static{this.styles=Om}};B([b({attribute:!1})],K.prototype,`messages`,void 0),B([b()],K.prototype,`sessionId`,void 0),B([b({type:Number})],K.prototype,`messageStart`,void 0),B([b({type:Number})],K.prototype,`messageEnd`,void 0),B([b({type:Number})],K.prototype,`messageTotal`,void 0),B([b({type:Boolean})],K.prototype,`hasMore`,void 0),B([b({type:Boolean})],K.prototype,`loadingMore`,void 0),B([b({type:Boolean})],K.prototype,`isSendingPrompt`,void 0),B([b({type:Boolean})],K.prototype,`isCompacting`,void 0),B([b({type:Number})],K.prototype,`pendingMessageCount`,void 0),B([b({attribute:!1})],K.prototype,`clientQueuedMessages`,void 0),B([b({attribute:!1})],K.prototype,`status`,void 0),B([b({attribute:!1})],K.prototype,`activity`,void 0),B([b({attribute:!1})],K.prototype,`pendingAsk`,void 0),B([b({attribute:!1})],K.prototype,`askDraftSessionId`,void 0),B([b({attribute:!1})],K.prototype,`onSubmitAsk`,void 0),B([b({attribute:!1})],K.prototype,`notificationInbox`,void 0),B([b({type:Boolean})],K.prototype,`canClearServerQueue`,void 0),B([b({attribute:!1})],K.prototype,`onClearServerQueue`,void 0),B([b({attribute:!1})],K.prototype,`onDismissWarning`,void 0),B([b({attribute:!1})],K.prototype,`onDismissNotification`,void 0),B([b({attribute:!1})],K.prototype,`onDismissAllNotifications`,void 0),B([b({type:Boolean})],K.prototype,`warningsVisible`,void 0),B([b({attribute:!1})],K.prototype,`onToggleWarnings`,void 0),B([b({attribute:!1})],K.prototype,`onLoadMore`,void 0),B([S(`.chat`)],K.prototype,`chat`,void 0),B([S(`dialog.image-zoom`)],K.prototype,`imageZoomDialog`,void 0),B([x()],K.prototype,`pinnedToBottom`,void 0),B([x()],K.prototype,`zoomedImage`,void 0),B([x()],K.prototype,`expandedMetaKey`,void 0),B([x()],K.prototype,`copiedMessageKey`,void 0),B([x()],K.prototype,`currentConversationIndex`,void 0),B([x()],K.prototype,`collapsedNotificationTargetKeys`,void 0),B([x()],K.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),B([x()],K.prototype,`loadMoreRequested`,void 0),K=B([y(`chat-view`)],K);function SS(e,t){return t===`idle`?`空闲`:t===void 0?{"agent running":`代理正在运行`,"bash complete":`命令执行完成`,"bash failed":`命令执行失败`,"branch summary aborted":`分支汇总已终止`,compacting:`正在压缩上下文`,"compaction complete":`上下文压缩完成`,"compaction failed":`上下文压缩失败`,"duplicate queued message ignored":`已忽略重复的排队消息`,error:`发生错误`,"extension error":`扩展错误`,idle:`空闲`,"message complete":`消息处理完成`,"message queued":`消息已排队`,"message queued during compaction":`压缩期间消息已排队`,"message started":`消息开始处理`,"navigating session tree":`正在切换会话树`,"prompt accepted":`消息已接收`,"receiving response":`正在接收回复`,"reload failed":`重新加载失败`,"reloading resources":`正在重新加载资源`,"resources reloaded":`资源已重新加载`,running:`代理正在运行`,"running bash":`正在运行命令`,"running tool":`正在运行工具`,"session tree navigated":`已切换会话树`,"steering queued":`插队消息已排队`,"stop failed":`停止失败`,stopped:`已停止`,"summarizing branch":`正在汇总分支`,"tool complete":`工具执行完成`,"tool failed":`工具执行失败`,"tree navigation cancelled":`会话树切换已取消`,"turn complete":`本轮已完成`,"updating session":`正在更新会话`,queued:`正在排队`}[e]??e:SS(e)}var CS=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function wS(e){return typeof e==`string`&&CS.has(e)}function TS(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 ES=`application/octet-stream`,DS=`读取附件失败。`;async function OS(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(MS(i,e))}catch{r=DS}return{attachments:n,...r===void 0?{}:{error:r}}}function kS(e){return e.kind===`image`&&wS(e.mimeType)}function AS(e){return e.every(e=>kS(e))}function jS(e,t){return AS(t)?e:`folder`}function MS(e,t){return wS(e.type)?{kind:`image`,name:PS(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:PS(e),mimeType:NS(e),data:t,size:e.size}}function NS(e){let t=e.type.trim();return t===``?ES:t}function PS(e){return e.name===``?wS(e.type)?`pasted-image.${TS(e.type)}`:`pasted-file.bin`:e.name}var FS=`pi-web:attachment-delivery`;function IS(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function LS(e=IS()){try{return e?.getItem(FS)===`folder`?`folder`:`inline`}catch{return`inline`}}function RS(e,t=IS()){try{t?.setItem(FS,e)}catch{}}var zS=`(pointer: coarse), (max-width: 760px)`,BS=`pi-web.promptEnterPreference`;function VS(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(zS):void 0}function HS(e){return e===`send`||e===`newline`?e:`auto`}function US(e=JS()){if(e===void 0)return`auto`;try{return HS(e.getItem(BS))}catch{return`auto`}}function WS(e,t=JS()){if(t!==void 0)try{t.setItem(BS,e)}catch{}}function GS(e=VS(),t=US()){return t===`send`||t!==`newline`&&e?.matches!==!0}function KS(e,t,n=VS()){return e?n?.matches!==!0||t:!1}function qS(e,t=VS(),n=US()){let r=GS(t,n);return e?!r:r}function JS(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function YS(){return Je`
|
|
2128
2137
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2129
2138
|
<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>
|
|
2130
2139
|
</svg>
|
|
2131
|
-
`}function
|
|
2140
|
+
`}function XS(){return Je`
|
|
2132
2141
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2133
2142
|
<path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
|
|
2134
2143
|
<path d="M21 3 11.5 12.5"></path>
|
|
2135
2144
|
</svg>
|
|
2136
|
-
`}function
|
|
2145
|
+
`}function ZS(){return Je`
|
|
2137
2146
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2138
2147
|
<path d="M4 7h11"></path>
|
|
2139
2148
|
<path d="M4 12h7"></path>
|
|
2140
2149
|
<path d="M4 17h7"></path>
|
|
2141
2150
|
<path d="m15 14 5 3-5 3z"></path>
|
|
2142
2151
|
</svg>
|
|
2143
|
-
`}function
|
|
2152
|
+
`}function QS(){return XS()}function $S(){return Je`
|
|
2144
2153
|
<svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2145
2154
|
<rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
|
|
2146
2155
|
</svg>
|
|
2147
|
-
`}function
|
|
2156
|
+
`}function eC(e){let t=Math.max(e.total,1),n=t>1?1.2:0,r=(18-n*(t-1))/t;return Je`
|
|
2148
2157
|
<svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2149
2158
|
${Array.from({length:t},(i,a)=>{let o=3+a*(r+n),s=4+(a+1)/t*12,c=20-s;return Je`<rect class=${a<e.filled?`gauge-bar gauge-bar-active`:`gauge-bar`} x=${o} y=${c} width=${r} height=${s} rx="1"></rect>`})}
|
|
2150
2159
|
</svg>
|
|
2151
|
-
`}var
|
|
2160
|
+
`}var tC=Vv(class extends Hv{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===Bv.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){}}),nC=h`
|
|
2152
2161
|
:host { display: block; }
|
|
2153
2162
|
.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: 8px; background: var(--pi-surface); box-shadow: 0 10px 30px var(--pi-shadow); }
|
|
2154
2163
|
button { display: grid; grid-template-columns: minmax(120px, 1fr) auto; gap: 4px 10px; width: 100%; border: 0; border-bottom: 1px solid var(--pi-border); border-radius: 0; background: transparent; color: var(--pi-text); padding: 8px 10px; text-align: left; cursor: pointer; }
|
|
@@ -2156,22 +2165,22 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2156
2165
|
button.selected, button:hover { background: var(--pi-selection-bg); }
|
|
2157
2166
|
span { color: var(--pi-muted); font-size: 12px; }
|
|
2158
2167
|
small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
2159
|
-
`,
|
|
2168
|
+
`,rC=class extends v{constructor(...e){super(...e),this.items=[],this.selectedIndex=0}render(){return this.items.length?g`
|
|
2160
2169
|
<div class="menu">
|
|
2161
2170
|
${this.items.map((e,t)=>g`
|
|
2162
|
-
<button class=${t===this.selectedIndex?`selected`:``} ${
|
|
2171
|
+
<button class=${t===this.selectedIndex?`selected`:``} ${tC(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
|
|
2163
2172
|
<strong>${e.insertText}</strong>
|
|
2164
2173
|
<span>${e.detail}</span>
|
|
2165
2174
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
2166
2175
|
</button>
|
|
2167
2176
|
`)}
|
|
2168
2177
|
</div>
|
|
2169
|
-
`:null}static{this.styles=
|
|
2178
|
+
`:null}static{this.styles=nC}};B([b({attribute:!1})],rC.prototype,`items`,void 0),B([b({type:Number})],rC.prototype,`selectedIndex`,void 0),B([b({attribute:!1})],rC.prototype,`onPick`,void 0),rC=B([y(`autocomplete-menu`)],rC);var q=class extends v{constructor(...e){super(...e),this.disabled=!1,this.machineId=`local`,this.workspaceScopedFileSuggestions=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.availableThinkingLevels=[],this.draft=``,this.currentInputMode={kind:`normal`},this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=LS(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new s,this.readOnlyCompartment=new s,this.mobilePromptEnterMedia=VS(),this.explicitShiftKeyActive=!1}willUpdate(e){if(!e.has(`sessionId`)&&!e.has(`machineId`))return;let t=e.has(`sessionId`)?e.get(`sessionId`):this.sessionId,n=aC(e.has(`machineId`)?e.get(`machineId`):this.machineId,t);n!==void 0&&Vc(n,this.draft);let r=aC(this.machineId,this.sessionId);this.draft=r===void 0?``:Bc(r),this.currentInputMode=du(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has(`status`)&&e.size===1?!iC(e.get(`status`),this.status):!0}firstUpdated(){this.createEditor()}updated(e){e.has(`disabled`)&&this.updateEditorDisabledState(),(e.has(`sessionId`)||e.has(`machineId`))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){let e=this.currentInputMode.kind===`shell`?this.currentInputMode:void 0,t=e!==void 0,n=this.canSteer||this.isCompacting,r=this.disabled||this.sending;return g`
|
|
2170
2179
|
<footer class=${t?`shell-mode`:``} @paste=${e=>{this.handlePaste(e)}} @dragover=${e=>{this.handleDragOver(e)}} @drop=${e=>{this.handleDrop(e)}}>
|
|
2171
2180
|
<div class="editor-wrap">
|
|
2172
2181
|
<div class=${`markdown-editor${this.disabled?` markdown-editor-disabled`:``}`} aria-label="给 pi 发送消息" aria-disabled=${this.disabled?`true`:`false`}></div>
|
|
2173
2182
|
<input class="attachment-input" type="file" multiple hidden @change=${e=>{this.handleFileInput(e)}} />
|
|
2174
|
-
<button class="editor-attach icon-button" ?disabled=${r} title="附加文件" aria-label="附加文件" @click=${()=>{this.attachmentInput?.click()}}>${
|
|
2183
|
+
<button class="editor-attach icon-button" ?disabled=${r} title="附加文件" aria-label="附加文件" @click=${()=>{this.attachmentInput?.click()}}>${YS()}</button>
|
|
2175
2184
|
${t?g`<div class="mode-hint">终端命令${e.excludeFromContext?` · 已排除上下文`:``}</div>`:null}
|
|
2176
2185
|
${this.isCompacting&&!t?g`<div class="mode-hint">正在压缩历史 · 消息将排队发送</div>`:null}
|
|
2177
2186
|
${this.renderAttachments()}
|
|
@@ -2179,20 +2188,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2179
2188
|
</div>
|
|
2180
2189
|
<div class="actions">
|
|
2181
2190
|
${this.renderCompactStatus()}
|
|
2182
|
-
<button class="icon-button send-button" ?disabled=${r} title=${n?`当前活动结束后排队发送`:`发送`} aria-label=${n?`排队发送`:`发送`} @click=${()=>{this.send(`followUp`)}}>${n?
|
|
2183
|
-
${this.canSteer&&!this.isCompacting?g`<button class="icon-button steer-button" ?disabled=${r} title="在下次模型调用前引导当前回复" aria-label="引导当前回复" @click=${()=>{this.send(`steer`)}}>${
|
|
2184
|
-
<button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?`停止当前工作并清空排队消息`:`当前没有运行任务`} aria-label="停止" @click=${()=>this.onStop?.()}>${
|
|
2191
|
+
<button class="icon-button send-button" ?disabled=${r} title=${n?`当前活动结束后排队发送`:`发送`} aria-label=${n?`排队发送`:`发送`} @click=${()=>{this.send(`followUp`)}}>${n?ZS():XS()}</button>
|
|
2192
|
+
${this.canSteer&&!this.isCompacting?g`<button class="icon-button steer-button" ?disabled=${r} title="在下次模型调用前引导当前回复" aria-label="引导当前回复" @click=${()=>{this.send(`steer`)}}>${QS()}</button>`:null}
|
|
2193
|
+
<button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?`停止当前工作并清空排队消息`:`当前没有运行任务`} aria-label="停止" @click=${()=>this.onStop?.()}>${$S()}</button>
|
|
2185
2194
|
</div>
|
|
2186
2195
|
</footer>
|
|
2187
|
-
`}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=
|
|
2196
|
+
`}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=aC(this.machineId,this.sessionId);t!==void 0&&Vc(t,e);let n=this.editor;if(n!==void 0){let t=n.state.doc.toString();n.dispatch({...t===e?{}:{changes:{from:0,to:t.length,insert:e}},selection:i.cursor(e.length)})}this.requestVersion+=1,this.currentInputMode=du(e),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??`无模型`;return g`
|
|
2188
2197
|
<div class="compact-status" aria-label="会话状态">
|
|
2189
2198
|
<button class="select-model" title="选择模型" @click=${()=>this.onSelectModel?.()}>${e.model?.provider!==void 0&&e.model.provider!==``?`${e.model.provider}/`:``}${t}</button>
|
|
2190
|
-
<button class="select-thinking icon-button" title=${`思考级别:${Ho(e.thinkingLevel)}`} aria-label=${`思考级别:${Ho(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${
|
|
2199
|
+
<button class="select-thinking icon-button" title=${`思考级别:${Ho(e.thinkingLevel)}`} aria-label=${`思考级别:${Ho(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${eC(Wo(e.thinkingLevel,this.availableThinkingLevels))}</button>
|
|
2191
2200
|
</div>
|
|
2192
|
-
`}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=
|
|
2201
|
+
`}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=AS(this.attachments),t=this.effectiveAttachmentDelivery();return g`
|
|
2193
2202
|
<div class="attachments" aria-label="待发送附件">
|
|
2194
2203
|
${this.attachments.map(e=>g`
|
|
2195
|
-
<div class=${`attachment-chip ${
|
|
2204
|
+
<div class=${`attachment-chip ${kS(e)?`attachment-chip-image`:`attachment-chip-file`}`} title=${e.name}>
|
|
2196
2205
|
${this.renderAttachmentPreview(e)}
|
|
2197
2206
|
<button type="button" class="attachment-remove" title="移除附件" aria-label=${`移除 ${e.name}`} @click=${()=>{this.removeAttachment(e.id)}}>×</button>
|
|
2198
2207
|
</div>
|
|
@@ -2207,10 +2216,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2207
2216
|
`:null}
|
|
2208
2217
|
${this.attachmentError===void 0?null:g`<div class="attachment-error">${this.attachmentError}</div>`}
|
|
2209
2218
|
</div>
|
|
2210
|
-
`}renderAttachmentPreview(e){return
|
|
2211
|
-
<div class="attachment-file-preview" aria-hidden="true">${
|
|
2219
|
+
`}renderAttachmentPreview(e){return kS(e)?g`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:g`
|
|
2220
|
+
<div class="attachment-file-preview" aria-hidden="true">${dC(e.name)}</div>
|
|
2212
2221
|
<span class="attachment-file-name">${e.name}</span>
|
|
2213
|
-
`}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;if(t===`inline`&&!
|
|
2222
|
+
`}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;if(t===`inline`&&!AS(this.attachments)){e.target.value=`folder`;return}this.attachmentDelivery=t,RS(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e)}async handlePaste(e){let t=cC(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&lC(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=cC(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}async handleFileInput(e){if(!(e.target instanceof HTMLInputElement)||e.target.files===null)return;let t=Array.from(e.target.files);e.target.value=``,await this.addAttachmentFiles(t)}async addAttachmentFiles(e){this.attachmentError=void 0;let{attachments:t,error:n}=await OS(e,fC);t.length>0&&(this.attachments=[...this.attachments,...t.map(e=>({id:`attachment-${String(++this.attachmentSeq)}`,...e}))]),n!==void 0&&(this.attachmentError=n)}currentAttachments(){return this.attachments.map(e=>uC(e))}effectiveAttachmentDelivery(){return jS(this.attachmentDelivery,this.attachments)}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new p({parent:this.editorHost,state:e.create({doc:this.draft,extensions:[m(),ne(),t(),u.of(` `),r(a,{fallback:!0}),p.lineWrapping,p.contentAttributes.of(e=>hC(e.state.sliceDoc(0,e.state.selection.main.head))),p.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),o(`给 pi 发送消息... 使用 / 输入命令,@ 输入已跟踪文件,@ 空格显示所有文件`),this.editableCompartment.of(p.editable.of(!this.disabled)),this.readOnlyCompartment.of(e.readOnly.of(this.disabled)),p.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),n.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:`ArrowDown`,run:()=>this.moveCompletion(1)},{key:`ArrowUp`,run:()=>this.moveCompletion(-1)},{key:`Escape`,run:()=>this.closeCompletions()},{key:`Tab`,run:e=>this.handleEditorTab(e)},{key:`Shift-Tab`,run:e=>l.shift?.(e)??!1},{key:`Backspace`,run:e=>ee(e)},...c,...d])]})}))}syncEditorDoc(){let e=this.editor;if(!e)return;let t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:i.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(p.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(e.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;let t=aC(this.machineId,this.sessionId);t!==void 0&&Vc(t,this.draft);let n=du(this.draft);pu(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(oC);if(t!==this.requestVersion)return;this.completions=n.filter(t=>t.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(t=>({kind:`command`,replaceFrom:e.from,replaceTo:e.to,insertText:`/${t.name}`,detail:t.source,...t.description===void 0?{}:{description:t.description}}))}else if(e.kind===`file`&&this.cwd!==void 0&&this.cwd!==``){let n=await I.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(sC);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=ou(t.path,e.quoted===!0,t.path.endsWith(`/`)?e.allPrefix:void 0);return{kind:`file`,replaceFrom:e.from,replaceTo:e.to,insertText:n,detail:t.kind,...t.path.endsWith(`/`)&&n.endsWith(`"`)?{cursorOffset:n.length-1}:{}}})}}currentTrigger(){return au(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.completions.length?(this.completions=[],!0):!1}handleEditorKeyDown(e,t){if(e.key===`Shift`)return this.explicitShiftKeyActive=!0,!1;if(e.key!==`Enter`)return this.explicitShiftKeyActive=!1,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;let n=KS(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 qS(t,this.mobilePromptEnterMedia,US())?(this.send(this.canSteer||this.isCompacting?`followUp`:void 0),!0):te(e)||f(e)}handleEditorTab(e){if(this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.currentTrigger()?.kind===`file`?(this.refreshCompletions(),!0):l.run?.(e)??!1}pick(e){let t=this.editor;if(!t)return;let n=e.kind===`file`&&(e.insertText.endsWith(`/`)||e.cursorOffset!==void 0)?``:` `,r=e.replaceFrom+(e.cursorOffset??e.insertText.length)+n.length,a=e.insertText.endsWith(`"`)&&this.draft.slice(e.replaceTo).startsWith(`"`)?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:a,insert:`${e.insertText}${n}`},selection:i.cursor(r),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending)return;let t=this.draft.trim(),n=this.attachments;if(t===``&&n.length===0)return;let r=this.canSteer||this.isCompacting?e:void 0,i=n.length>0?this.currentAttachments():void 0,a=this.effectiveAttachmentDelivery();this.resetComposer(),this.onSend?.(t,r,i,i===void 0?void 0:a)}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=aC(this.machineId,this.sessionId);e!==void 0&&Hc(e),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=Am}};B([b({type:Boolean})],q.prototype,`disabled`,void 0),B([b()],q.prototype,`sessionId`,void 0),B([b()],q.prototype,`cwd`,void 0),B([b()],q.prototype,`machineId`,void 0),B([b()],q.prototype,`projectId`,void 0),B([b()],q.prototype,`workspaceId`,void 0),B([b({type:Boolean})],q.prototype,`workspaceScopedFileSuggestions`,void 0),B([b({type:Boolean})],q.prototype,`canSteer`,void 0),B([b({type:Boolean})],q.prototype,`isCompacting`,void 0),B([b({type:Boolean})],q.prototype,`canStop`,void 0),B([b({attribute:!1})],q.prototype,`status`,void 0),B([b({type:Boolean})],q.prototype,`sending`,void 0),B([b({attribute:!1})],q.prototype,`onSend`,void 0),B([b({attribute:!1})],q.prototype,`onStop`,void 0),B([b({attribute:!1})],q.prototype,`onSelectModel`,void 0),B([b({attribute:!1})],q.prototype,`onSelectThinking`,void 0),B([b({attribute:!1})],q.prototype,`availableThinkingLevels`,void 0),B([S(`.markdown-editor`)],q.prototype,`editorHost`,void 0),B([S(`.attachment-input`)],q.prototype,`attachmentInput`,void 0),B([x()],q.prototype,`currentInputMode`,void 0),B([x()],q.prototype,`completions`,void 0),B([x()],q.prototype,`selectedIndex`,void 0),B([x()],q.prototype,`attachments`,void 0),B([x()],q.prototype,`attachmentDelivery`,void 0),B([x()],q.prototype,`attachmentError`,void 0),q=B([y(`prompt-editor`)],q);function iC(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 aC(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return Ko(e,t)}function oC(){return[]}function sC(){return[]}function cC(e){return e===null?[]:Array.from(e.files)}function lC(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function uC(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 dC(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`文件`}function fC(e){return new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>{n(r.error??Error(`读取文件失败`))},r.onload=()=>{let e=r.result;if(typeof e!=`string`){n(Error(`文件读取结果异常`));return}let i=e.indexOf(`,`);t(i===-1?e:e.slice(i+1))},r.readAsDataURL(e)})}var pC={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},mC={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function hC(e){return du(e).kind===`normal`?pC:mC}function gC(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 _C(e){return!Number.isFinite(e)||e===0?`$0`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function vC(e,t){if(!Number.isInteger(e)||e<=0)return;let n=`${String(e)} 条警告`;return{countText:String(e),accessibleLabel:t?`最小化 ${n}`:`在警告区域显示 ${n}`}}var yC=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">尚无会话状态</div>`;let t=e.contextUsage,n=t?t.percent==null?`上下文 ${gC(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${gC(t.contextWindow)}`:`上下文未知`,r=e.tokens,i=vC(this.warningCount,this.warningsExpanded);return g`
|
|
2214
2223
|
<div class="bar">
|
|
2215
2224
|
${i===void 0||this.onToggleWarnings===void 0?null:g`
|
|
2216
2225
|
<button
|
|
@@ -2225,13 +2234,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2225
2234
|
<span>${i.countText}</span>
|
|
2226
2235
|
</button>
|
|
2227
2236
|
`}
|
|
2228
|
-
<span>↑${
|
|
2229
|
-
<span>↓${
|
|
2237
|
+
<span>↑${gC(r.input)}</span>
|
|
2238
|
+
<span>↓${gC(r.output)}</span>
|
|
2230
2239
|
<span class="context">${n}</span>
|
|
2231
|
-
<span>${
|
|
2240
|
+
<span>${_C(e.cost)}</span>
|
|
2232
2241
|
${e.pendingMessageCount>0?g`<span>${String(e.pendingMessageCount)} 条排队中</span>`:null}
|
|
2233
2242
|
</div>
|
|
2234
|
-
`}static{this.styles=km}};B([b({attribute:!1})],
|
|
2243
|
+
`}static{this.styles=km}};B([b({attribute:!1})],yC.prototype,`status`,void 0),B([b({type:Number})],yC.prototype,`warningCount`,void 0),B([b({type:Boolean})],yC.prototype,`warningsExpanded`,void 0),B([b({attribute:!1})],yC.prototype,`onToggleWarnings`,void 0),yC=B([y(`status-bar`)],yC);var bC=h`
|
|
2235
2244
|
:host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
2236
2245
|
.backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
|
|
2237
2246
|
section { width: min(720px, calc(100vw - 40px)); max-height: min(640px, calc(100vh - 40px)); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
|
|
@@ -2245,7 +2254,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2245
2254
|
.options button.selected, .options button:hover { background: var(--pi-selection-bg); }
|
|
2246
2255
|
small { display: block; margin-top: 4px; color: var(--pi-muted); }
|
|
2247
2256
|
.empty { padding: 24px; color: var(--pi-muted); text-align: center; }
|
|
2248
|
-
`,
|
|
2257
|
+
`,xC=class extends v{constructor(...e){super(...e),this.title=`选择`,this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=``}render(){let e=this.filteredOptions();return g`
|
|
2249
2258
|
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
2250
2259
|
<section @mousedown=${e=>{e.stopPropagation()}}>
|
|
2251
2260
|
<header>
|
|
@@ -2255,7 +2264,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2255
2264
|
${this.searchable?g`<input placeholder="搜索" .value=${this.query} @input=${e=>{this.handleSearchInput(e)}} @keydown=${e=>{this.handleKeyDown(e)}}>`:null}
|
|
2256
2265
|
<div class="options" @keydown=${e=>{this.handleKeyDown(e)}} tabindex="0">
|
|
2257
2266
|
${e.map((e,t)=>g`
|
|
2258
|
-
<button class=${t===this.selectedIndex?`selected`:``} ${
|
|
2267
|
+
<button class=${t===this.selectedIndex?`selected`:``} ${tC(t===this.selectedIndex,e.value)} @click=${()=>this.onPick?.(e.value)}>
|
|
2259
2268
|
<span>${e.label}</span>
|
|
2260
2269
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
2261
2270
|
</button>
|
|
@@ -2264,7 +2273,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2264
2273
|
</div>
|
|
2265
2274
|
</section>
|
|
2266
2275
|
</div>
|
|
2267
|
-
`}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?`input`:`.options`)?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;let e=this.filteredOptions().findIndex(e=>e.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){let e=this.query.trim().toLowerCase();return e===``?this.options:this.options.filter(t=>`${t.label} ${t.description??``} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){let t=this.filteredOptions();if(e.key===`Escape`)e.preventDefault(),this.onCancel?.();else if(e.key===`ArrowDown`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key===`ArrowUp`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key===`Enter`){e.preventDefault();let n=t[this.selectedIndex];n&&this.onPick?.(n.value)}}static{this.styles=
|
|
2276
|
+
`}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?`input`:`.options`)?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;let e=this.filteredOptions().findIndex(e=>e.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){let e=this.query.trim().toLowerCase();return e===``?this.options:this.options.filter(t=>`${t.label} ${t.description??``} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){let t=this.filteredOptions();if(e.key===`Escape`)e.preventDefault(),this.onCancel?.();else if(e.key===`ArrowDown`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key===`ArrowUp`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key===`Enter`){e.preventDefault();let n=t[this.selectedIndex];n&&this.onPick?.(n.value)}}static{this.styles=bC}};B([b()],xC.prototype,`title`,void 0),B([b({type:Boolean})],xC.prototype,`searchable`,void 0),B([b({attribute:!1})],xC.prototype,`options`,void 0),B([b({attribute:!1})],xC.prototype,`selectedValue`,void 0),B([b({attribute:!1})],xC.prototype,`onPick`,void 0),B([b({attribute:!1})],xC.prototype,`onCancel`,void 0),B([x()],xC.prototype,`selectedIndex`,void 0),B([x()],xC.prototype,`query`,void 0),xC=B([y(`command-picker`)],xC);var SC=h`
|
|
2268
2277
|
:host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
2269
2278
|
.backdrop { --palette-top: min(12dvh, 90px); --palette-bottom: max(20px, env(safe-area-inset-bottom)); display: grid; align-items: start; justify-items: center; width: 100%; height: 100dvh; background: var(--pi-overlay); padding: var(--palette-top) 20px var(--palette-bottom); box-sizing: border-box; overflow: hidden; }
|
|
2270
2279
|
section { width: min(720px, 100%); max-height: min(640px, calc(100dvh - var(--palette-top) - var(--palette-bottom))); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
|
|
@@ -2282,7 +2291,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2282
2291
|
.group { grid-column: 1 / -1; font-size: 12px; }
|
|
2283
2292
|
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; }
|
|
2284
2293
|
.empty { padding: 24px; color: var(--pi-muted); text-align: center; }
|
|
2285
|
-
`,
|
|
2294
|
+
`,CC=class extends v{constructor(...e){super(...e),this.actions=[],this.queryText=``,this.selectedIndex=0}render(){let e=this.filteredActions();return g`
|
|
2286
2295
|
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
2287
2296
|
<section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
2288
2297
|
<header>
|
|
@@ -2295,7 +2304,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2295
2304
|
</header>
|
|
2296
2305
|
<div class="options">
|
|
2297
2306
|
${e.length===0?g`<div class="empty">未找到操作。</div>`:e.map((e,t)=>g`
|
|
2298
|
-
<button class=${`${t===this.selectedIndex?`selected`:``} ${e.enabled===!1?`disabled`:``}`} ?disabled=${e.enabled===!1} title=${e.disabledReason??e.title} ${
|
|
2307
|
+
<button class=${`${t===this.selectedIndex?`selected`:``} ${e.enabled===!1?`disabled`:``}`} ?disabled=${e.enabled===!1} title=${e.disabledReason??e.title} ${tC(t===this.selectedIndex,e.id)} @click=${()=>{this.run(e)}}>
|
|
2299
2308
|
<span class="main">
|
|
2300
2309
|
<strong>${e.title}</strong>
|
|
2301
2310
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
@@ -2308,7 +2317,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2308
2317
|
</div>
|
|
2309
2318
|
</section>
|
|
2310
2319
|
</div>
|
|
2311
|
-
`}firstUpdated(){this.input?.focus()}updated(e){if(!e.has(`actions`)&&!e.has(`queryText`))return;let t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){return
|
|
2320
|
+
`}firstUpdated(){this.input?.focus()}updated(e){if(!e.has(`actions`)&&!e.has(`queryText`))return;let t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){return wC(this.actions,this.queryText)}handleKeyDown(e){let t=this.filteredActions();if(e.key===`Escape`)e.preventDefault(),this.onCancel?.();else if(e.key===`ArrowDown`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key===`ArrowUp`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key===`Enter`){e.preventDefault();let n=t[this.selectedIndex];n!==void 0&&this.run(n)}}run(e){e.enabled!==!1&&this.onRun?.(e)}static{this.styles=SC}};B([b({attribute:!1})],CC.prototype,`actions`,void 0),B([b({attribute:!1})],CC.prototype,`onRun`,void 0),B([b({attribute:!1})],CC.prototype,`onCancel`,void 0),B([S(`input`)],CC.prototype,`input`,void 0),B([x()],CC.prototype,`queryText`,void 0),B([x()],CC.prototype,`selectedIndex`,void 0),CC=B([y(`action-palette`)],CC);function wC(e,t){let n=t.trim().toLowerCase();return e.filter(e=>e.enabled!==!1||e.disabledReason!==void 0).filter(e=>n===``||[e.title,e.description??``,e.disabledReason??``,e.group??``,e.shortcut??``].join(` `).toLowerCase().includes(n))}var TC=class extends v{render(){let e=this.state;return e===void 0?null:g`
|
|
2312
2321
|
<div class="backdrop" @mousedown=${()=>{this.cancel()}}>
|
|
2313
2322
|
<section @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
2314
2323
|
<header>
|
|
@@ -2331,13 +2340,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2331
2340
|
<div class="actions"><button @click=${()=>{this.cancel()}}>取消</button><button class="primary" ?disabled=${e.saving===!0} @click=${()=>{this.onSaveApiKey?.()}}>${e.saving===!0?`正在保存…`:`保存 API key`}</button></div>
|
|
2332
2341
|
</div>
|
|
2333
2342
|
`;case`oauth`:return this.renderOAuth(e);case`logout`:return g`<div class="options">${e.providers.length===0?g`<div class="empty">没有已保存的凭据。环境变量和 models.json 设置不会变化。</div>`:e.providers.map(e=>g`
|
|
2334
|
-
<button @click=${()=>{this.onLogoutProvider?.(e.id)}}><span>${e.name}</span><small>${e.id} · ${
|
|
2343
|
+
<button @click=${()=>{this.onLogoutProvider?.(e.id)}}><span>${e.name}</span><small>${e.id} · ${DC(e.authType)}</small></button>
|
|
2335
2344
|
`)}</div>`}}renderProviderButton(e){return g`
|
|
2336
2345
|
<button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
|
|
2337
|
-
<span>${e.name}${e.status.source===void 0?null:g` <em>${
|
|
2338
|
-
<small>${e.id} · ${
|
|
2346
|
+
<span>${e.name}${e.status.source===void 0?null:g` <em>${kC(e)}</em>`}</span>
|
|
2347
|
+
<small>${e.id} · ${DC(e.authType)}</small>
|
|
2339
2348
|
</button>
|
|
2340
|
-
`}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=
|
|
2349
|
+
`}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=EC(n?.promptType);return g`
|
|
2341
2350
|
<div class="form">
|
|
2342
2351
|
${t.auth===void 0?g`<p>正在启动登录流程…</p>`:g`
|
|
2343
2352
|
<p>打开此授权链接:</p>
|
|
@@ -2367,10 +2376,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2367
2376
|
`)}</div>
|
|
2368
2377
|
`}
|
|
2369
2378
|
${e.error!==void 0&&e.error!==``?g`<div class="error-text">${e.error}</div>`:null}
|
|
2370
|
-
${t.status===`error`||t.status===`cancelled`?g`<div class="error-text">${t.error??
|
|
2379
|
+
${t.status===`error`||t.status===`cancelled`?g`<div class="error-text">${t.error??AC(t.status)}</div><div class="actions"><button @click=${()=>{this.cancel()}}>关闭</button></div>`:null}
|
|
2371
2380
|
${n===void 0&&r===void 0&&t.status===`running`?g`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>取消</button></div>`:null}
|
|
2372
2381
|
</div>
|
|
2373
|
-
`}focusInputIfNeeded(){let e=
|
|
2382
|
+
`}focusInputIfNeeded(){let e=OC(this.state);if(e===void 0){this.lastFocusedInputKey=void 0;return}e!==this.lastFocusedInputKey&&(this.lastFocusedInputKey=e,this.input?.focus())}handleKeyDown(e){if(e.key===`Escape`){e.preventDefault(),this.cancel();return}if(e.key!==`Enter`)return;let t=this.state;t?.step===`apiKey`?(e.preventDefault(),this.onSaveApiKey?.()):t?.step===`oauth`&&t.flow.prompt!==void 0&&(e.preventDefault(),this.onOAuthRespond?.())}cancel(){this.state?.step===`oauth`?this.onOAuthCancel?.():this.onCancel?.()}static{this.styles=[bC,h`
|
|
2374
2383
|
.form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
|
|
2375
2384
|
.form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
|
|
2376
2385
|
.form a { color: var(--pi-accent); overflow-wrap: anywhere; }
|
|
@@ -2388,13 +2397,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2388
2397
|
.inline-options button { display: grid; gap: 2px; text-align: left; }
|
|
2389
2398
|
.inline-options small { color: var(--pi-muted); }
|
|
2390
2399
|
em { color: var(--pi-success); font-style: normal; font-size: 12px; }
|
|
2391
|
-
`]}};B([b({attribute:!1})],
|
|
2400
|
+
`]}};B([b({attribute:!1})],TC.prototype,`state`,void 0),B([b({attribute:!1})],TC.prototype,`onChooseMethod`,void 0),B([b({attribute:!1})],TC.prototype,`onSelectProvider`,void 0),B([b({attribute:!1})],TC.prototype,`onApiKeyInput`,void 0),B([b({attribute:!1})],TC.prototype,`onSaveApiKey`,void 0),B([b({attribute:!1})],TC.prototype,`onLogoutProvider`,void 0),B([b({attribute:!1})],TC.prototype,`onOAuthInput`,void 0),B([b({attribute:!1})],TC.prototype,`onOAuthRespond`,void 0),B([b({attribute:!1})],TC.prototype,`onOAuthCancel`,void 0),B([b({attribute:!1})],TC.prototype,`onCancel`,void 0),B([S(`input`)],TC.prototype,`input`,void 0),TC=B([y(`auth-dialog`)],TC);function EC(e){return e===`secret`?`password`:`text`}function DC(e){return e===`oauth`?`订阅`:`API key`}function OC(e){if(e?.step===`apiKey`)return`api-key:${e.provider.authType}:${e.provider.id}`;if(e?.step===`oauth`&&e.flow.prompt!==void 0)return`oauth:${e.flow.flowId}:${e.flow.prompt.requestId}`}function kC(e){if(e.status.source===void 0)return``;switch(e.status.source){case`stored`:return`✓ 已配置`;case`environment`:return`✓ 环境变量${e.status.label===void 0?``:`: ${e.status.label}`}`;case`runtime`:return`✓ 运行时`;case`fallback`:return`✓ 自定义 key`;case`models_json_key`:return`✓ models.json key`;case`models_json_command`:return`✓ models.json command`;default:return``}}function AC(e){return e===`cancelled`?`已取消`:e===`error`?`错误`:e}var jC=class extends v{constructor(...e){super(...e),this.mode=`login`,this.loading=!1,this.error=``,this.currentPassword=``,this.password=``,this.confirmPassword=``,this.localError=``}render(){return g`
|
|
2392
2401
|
<div class="backdrop">
|
|
2393
|
-
<section role="dialog" aria-modal="true" aria-label=${
|
|
2402
|
+
<section role="dialog" aria-modal="true" aria-label=${MC(this.mode)} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
2394
2403
|
<header>
|
|
2395
2404
|
<div>
|
|
2396
2405
|
<span class="eyebrow">普通模式</span>
|
|
2397
|
-
<h1>${
|
|
2406
|
+
<h1>${MC(this.mode)}</h1>
|
|
2398
2407
|
</div>
|
|
2399
2408
|
${this.mode===`change`?g`<button class="close-button" title="关闭" aria-label="关闭" @click=${()=>this.onCancel?.()}>×</button>`:null}
|
|
2400
2409
|
</header>
|
|
@@ -2402,17 +2411,17 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2402
2411
|
${this.mode===`change`?g`
|
|
2403
2412
|
<label>
|
|
2404
2413
|
<span>当前密码</span>
|
|
2405
|
-
<input type="password" .value=${this.currentPassword} autocomplete="current-password" @input=${e=>{this.currentPassword=
|
|
2414
|
+
<input type="password" .value=${this.currentPassword} autocomplete="current-password" @input=${e=>{this.currentPassword=PC(e),this.localError=``}}>
|
|
2406
2415
|
</label>
|
|
2407
2416
|
`:null}
|
|
2408
2417
|
<label>
|
|
2409
2418
|
<span>${this.mode===`login`?`密码`:`新密码`}</span>
|
|
2410
|
-
<input type="password" .value=${this.password} autocomplete=${this.mode===`login`?`current-password`:`new-password`} @input=${e=>{this.password=
|
|
2419
|
+
<input type="password" .value=${this.password} autocomplete=${this.mode===`login`?`current-password`:`new-password`} @input=${e=>{this.password=PC(e),this.localError=``}}>
|
|
2411
2420
|
</label>
|
|
2412
2421
|
${this.mode===`login`?null:g`
|
|
2413
2422
|
<label>
|
|
2414
2423
|
<span>确认密码</span>
|
|
2415
|
-
<input type="password" .value=${this.confirmPassword} autocomplete="new-password" @input=${e=>{this.confirmPassword=
|
|
2424
|
+
<input type="password" .value=${this.confirmPassword} autocomplete="new-password" @input=${e=>{this.confirmPassword=PC(e),this.localError=``}}>
|
|
2416
2425
|
</label>
|
|
2417
2426
|
`}
|
|
2418
2427
|
${this.message()===``?null:g`<p class="message">${this.message()}</p>`}
|
|
@@ -2423,7 +2432,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2423
2432
|
</form>
|
|
2424
2433
|
</section>
|
|
2425
2434
|
</div>
|
|
2426
|
-
`}submitLabel(){return this.mode===`setup`?`设置并进入`:this.mode===`change`?`保存密码`:`进入`}message(){return this.localError||this.error}async submit(e){e.preventDefault();let t={currentPassword:this.currentPassword,password:this.password,confirmPassword:this.confirmPassword},n=
|
|
2435
|
+
`}submitLabel(){return this.mode===`setup`?`设置并进入`:this.mode===`change`?`保存密码`:`进入`}message(){return this.localError||this.error}async submit(e){e.preventDefault();let t={currentPassword:this.currentPassword,password:this.password,confirmPassword:this.confirmPassword},n=NC(this.mode,t);if(n!==void 0){this.localError=n;return}this.localError=``,await this.onSubmit?.(t)}handleKeyDown(e){e.key!==`Escape`||this.mode!==`change`||(e.preventDefault(),e.stopPropagation(),this.onCancel?.())}static{this.styles=h`
|
|
2427
2436
|
:host { position: fixed; inset: 0; z-index: 40; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
2428
2437
|
.backdrop { box-sizing: border-box; width: 100%; height: 100dvh; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-bg); }
|
|
2429
2438
|
section { width: min(420px, 100%); border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-surface); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
|
|
@@ -2441,7 +2450,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2441
2450
|
.close-button { width: 34px; height: 34px; display: grid; place-items: center; border: 0; background: transparent; color: var(--pi-muted); padding: 0; font-size: 24px; }
|
|
2442
2451
|
.message { margin: 0; border: 1px solid var(--pi-danger-border); border-radius: 8px; background: var(--pi-danger-surface); color: var(--pi-danger); padding: 10px; }
|
|
2443
2452
|
footer { display: flex; justify-content: flex-end; gap: 8px; }
|
|
2444
|
-
`}};B([b()],
|
|
2453
|
+
`}};B([b()],jC.prototype,`mode`,void 0),B([b({type:Boolean})],jC.prototype,`loading`,void 0),B([b()],jC.prototype,`error`,void 0),B([b({attribute:!1})],jC.prototype,`onSubmit`,void 0),B([b({attribute:!1})],jC.prototype,`onCancel`,void 0),B([x()],jC.prototype,`currentPassword`,void 0),B([x()],jC.prototype,`password`,void 0),B([x()],jC.prototype,`confirmPassword`,void 0),B([x()],jC.prototype,`localError`,void 0),jC=B([y(`normal-auth-dialog`)],jC);function MC(e){return e===`setup`?`设置进入密码`:e===`change`?`修改进入密码`:`输入密码`}function NC(e,t){if(e===`change`&&(t.currentPassword??``)===``)return`请输入当前密码。`;if(t.password===``)return`请输入密码。`;if(e!==`login`&&t.password!==(t.confirmPassword??``))return`两次输入的密码不一致。`}function PC(e){return e.target instanceof HTMLInputElement?e.target.value:``}var FC=class extends v{constructor(...e){super(...e),this.machineId=`local`,this.path=``,this.createMissing=!0,this.suggestions=[],this.selected=0,this.loading=!1,this.requestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}firstUpdated(){this.pathInput?.focus()}async loadSuggestions(){let e=++this.requestId;this.loading=!0;try{let t=await I.projectDirectories(this.path,this.machineId);if(e!==this.requestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.requestId&&(this.suggestions=[])}finally{e===this.requestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.loadSuggestions()}pick(e){this.setPath(e.path)}submit(){this.path.trim()!==``&&this.onSubmit?.(this.path,this.createMissing)}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}onKeyDown(e){if(e.key===`Escape`)e.preventDefault(),this.onCancel?.();else if(e.key===`Enter`)e.preventDefault(),this.submit();else if(e.key===`ArrowDown`)e.preventDefault(),this.selected=Math.min(this.selected+1,Math.max(0,this.suggestions.length-1));else if(e.key===`ArrowUp`)e.preventDefault(),this.selected=Math.max(0,this.selected-1);else if(e.key===`Tab`){let t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return g`
|
|
2445
2454
|
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
2446
2455
|
<section @click=${e=>{e.stopPropagation()}}>
|
|
2447
2456
|
<header>
|
|
@@ -2491,7 +2500,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2491
2500
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
2492
2501
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
2493
2502
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
2494
|
-
`}};B([b({attribute:!1})],
|
|
2503
|
+
`}};B([b({attribute:!1})],FC.prototype,`onSubmit`,void 0),B([b({attribute:!1})],FC.prototype,`onCancel`,void 0),B([b()],FC.prototype,`machineId`,void 0),B([x()],FC.prototype,`path`,void 0),B([x()],FC.prototype,`createMissing`,void 0),B([x()],FC.prototype,`suggestions`,void 0),B([x()],FC.prototype,`selected`,void 0),B([x()],FC.prototype,`loading`,void 0),B([S(`input`)],FC.prototype,`pathInput`,void 0),FC=B([y(`project-dialog`)],FC);var IC=class extends v{constructor(...e){super(...e),this.error=``,this.url=``,this.name=``,this.token=``,this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=``}firstUpdated(){this.urlInput?.focus()}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;let t=e.target.value,n=LC(t);(!this.nameEdited||this.name.trim()===``||this.name===this.previousSuggestedName)&&(this.name=n),this.previousSuggestedName=n,this.url=t}handleNameInput(e){e.target instanceof HTMLInputElement&&(this.nameEdited=!0,this.name=e.target.value)}handleTokenInput(e){e.target instanceof HTMLInputElement&&(this.token=e.target.value)}handleKeyDown(e){if(e.key===`Escape`){e.preventDefault(),this.onCancel?.();return}e.key===`Enter`&&e.target instanceof HTMLInputElement&&e.target.name===`baseUrl`&&RC(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===``||RC(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?RC(this.url):void 0,n=this.validInput()!==void 0&&!this.submitting;return g`
|
|
2495
2504
|
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
2496
2505
|
<section @click=${e=>{e.stopPropagation()}}>
|
|
2497
2506
|
<form @submit=${e=>{this.handleSubmit(e)}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
@@ -2546,7 +2555,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2546
2555
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
2547
2556
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
2548
2557
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
2549
|
-
`}};B([b({attribute:!1})],
|
|
2558
|
+
`}};B([b({attribute:!1})],IC.prototype,`onSubmit`,void 0),B([b({attribute:!1})],IC.prototype,`onCancel`,void 0),B([b()],IC.prototype,`error`,void 0),B([x()],IC.prototype,`url`,void 0),B([x()],IC.prototype,`name`,void 0),B([x()],IC.prototype,`token`,void 0),B([x()],IC.prototype,`submitting`,void 0),B([S(`input[name='baseUrl']`)],IC.prototype,`urlInput`,void 0),B([S(`input[name='name']`)],IC.prototype,`nameInput`,void 0),IC=B([y(`machine-dialog`)],IC);function LC(e){let t=e.trim();if(t===``)return``;let n=zC(t)??zC(`http://${t.replace(/^\/+/u,``)}`);return n!==void 0&&n.hostname!==``?n.hostname.replace(/^\[(.*)\]$/u,`$1`):BC(t)}function RC(e){let t=e.trim();if(t===``)return`必须填写远程 PI WEB URL。`;let n;try{n=new URL(t)}catch{return`请输入包含 http:// 或 https:// 的有效 URL。`}if(n.protocol!==`http:`&&n.protocol!==`https:`)return`请使用 http:// 或 https:// URL。`;if(n.username!==``||n.password!==``)return`机器 URL 中不要包含凭据。`;if(n.search!==``||n.hash!==``)return`不要包含查询字符串或片段。`}function zC(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:void 0}catch{return}}function BC(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 VC={availability:`error`,error:`error`,success:`success`,security:`warning`,warning:`warning`,info:`info`};function HC(e){return e.tone??VC[e.type]}var UC=class extends v{constructor(...e){super(...e),this.heading=``,this.description=``,this.actionLabel=``,this.actionTitle=``,this.actionDisabled=!1,this.notices=[]}render(){return g`
|
|
2550
2559
|
<section class="panel" aria-label=${this.heading||`设置面板`}>
|
|
2551
2560
|
<header class="section-heading">
|
|
2552
2561
|
<div class="heading-copy">
|
|
@@ -2569,7 +2578,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2569
2578
|
<div class="notice-stack" aria-label="设置通知">
|
|
2570
2579
|
${this.notices.map(e=>this.renderNotice(e))}
|
|
2571
2580
|
</div>
|
|
2572
|
-
`}renderNotice(e){let t=
|
|
2581
|
+
`}renderNotice(e){let t=HC(e),n=e.role??WC(t),r=e.title;return g`
|
|
2573
2582
|
<article class=${`notice ${t}`} role=${n}>
|
|
2574
2583
|
${r===void 0||r===``?_:g`<strong class="notice-title">${r}</strong>`}
|
|
2575
2584
|
<div class="notice-content">${e.content}</div>
|
|
@@ -2602,13 +2611,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2602
2611
|
.section-heading { display: grid; gap: 12px; }
|
|
2603
2612
|
.heading-actions { justify-self: start; }
|
|
2604
2613
|
}
|
|
2605
|
-
`}};B([b()],
|
|
2606
|
-
`):``}}function
|
|
2607
|
-
`)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function
|
|
2608
|
-
`).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!
|
|
2614
|
+
`}};B([b()],UC.prototype,`heading`,void 0),B([b({attribute:!1})],UC.prototype,`description`,void 0),B([b()],UC.prototype,`actionLabel`,void 0),B([b()],UC.prototype,`actionTitle`,void 0),B([b({type:Boolean})],UC.prototype,`actionDisabled`,void 0),B([b({attribute:!1})],UC.prototype,`notices`,void 0),B([b({attribute:!1})],UC.prototype,`onAction`,void 0),UC=B([y(`settings-panel-frame`)],UC);function WC(e){switch(e){case`error`:return`alert`;case`success`:return`status`;case`warning`:case`info`:return`note`}}function GC(){return{host:``,port:``,allowedHostsMode:`list`,allowedHostsText:``}}function KC(){return{allowedPathsText:``,uploadDefaultFolder:``}}function qC(){return{command:``,dir:``}}function JC(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(`
|
|
2615
|
+
`):``}}function YC(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
|
|
2616
|
+
`)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``}}function XC(e){return{command:e.agent?.command??``,dir:e.agent?.dir??``}}function ZC(e){let t=e.command.trim(),n=e.dir.trim();return{agent:{...t===``?{}:{command:t},...n===``?{}:{dir:n}}}}function QC(e,t){let n=ZC(e).agent??{},r=t.agent??{};return n.command===r.command&&n.dir===r.dir}function $C(e,t={}){let n=tw(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(`端口必须是 1 到 65535 之间的整数。`);n.port=e}return n.allowedHosts=e.allowedHostsMode===`all`||nw(e.allowedHostsText),n}function ew(e){let t=rw(e.allowedPathsText),n=iw(e.uploadDefaultFolder);return{pathAccess:{allowedPaths:t},uploads:n===``?{}:{defaultFolder:n}}}function tw(e){return{...e.shortcuts===void 0?{}:{shortcuts:e.shortcuts},...e.plugins===void 0?{}:{plugins:e.plugins},...e.normalAuth===void 0?{}:{normalAuth:e.normalAuth},...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 nw(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e!==``)}function rw(e){let t=e.split(`
|
|
2617
|
+
`).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!aw(e));if(n!==void 0)throw Error(`允许的外部路径必须是绝对路径或以 ~ 开头:${n}`);return t}function iw(e){let t=e.trim();if(t===``)return``;if(ow(t))throw Error(`上传默认文件夹必须是工作区相对路径。`);let n=t.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(n.length===0)return``;if(n.some(e=>e===`..`))throw Error(`上传默认文件夹不能包含路径穿越。`);return n.join(`/`)}function aw(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)||e.startsWith(`/`)||e.startsWith(`\\`)||/^[A-Za-z]:[\\/]/u.test(e)}function ow(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function sw(e){return g`网关服务器字段用于编辑当前本地网关;文件访问和上传默认值用于编辑 ${e}。`}var J=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=GC(),this.machineDraft=KC(),this.gatewayLocalError=``,this.machineLocalError=``}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.gatewayDraft=JC(this.configResponse.config),this.gatewayLocalError=``),e.has(`machineConfigResponse`)&&this.machineConfigResponse!==void 0&&(this.machineDraft=YC(this.machineConfigResponse.config),this.machineLocalError=``)}render(){return g`
|
|
2609
2618
|
<settings-panel-frame
|
|
2610
2619
|
heading="通用配置"
|
|
2611
|
-
.description=${
|
|
2620
|
+
.description=${sw(this.targetLabel)}
|
|
2612
2621
|
actionLabel="重新加载"
|
|
2613
2622
|
.actionDisabled=${this.loading||this.machineLoading}
|
|
2614
2623
|
.notices=${this.panelNotices()}
|
|
@@ -2637,7 +2646,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2637
2646
|
<span>主机地址</span>
|
|
2638
2647
|
${this.renderOverrideBadge(`host`)}
|
|
2639
2648
|
</span>
|
|
2640
|
-
<input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:
|
|
2649
|
+
<input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:uw(e)})}}>
|
|
2641
2650
|
<small>Web 服务器应绑定的地址。留空则使用 PI WEB 默认值。</small>
|
|
2642
2651
|
</label>
|
|
2643
2652
|
|
|
@@ -2646,7 +2655,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2646
2655
|
<span>端口</span>
|
|
2647
2656
|
${this.renderOverrideBadge(`port`)}
|
|
2648
2657
|
</span>
|
|
2649
|
-
<input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:
|
|
2658
|
+
<input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:uw(e)})}}>
|
|
2650
2659
|
<small>TCP 端口,范围 1 到 65535。留空则使用 PI WEB 默认值。</small>
|
|
2651
2660
|
</label>
|
|
2652
2661
|
|
|
@@ -2655,11 +2664,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2655
2664
|
<span>允许的主机名</span>
|
|
2656
2665
|
${this.renderOverrideBadge(`allowedHosts`)}
|
|
2657
2666
|
</span>
|
|
2658
|
-
<select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode
|
|
2667
|
+
<select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:dw(e)===`all`?`all`:`list`})}}>
|
|
2659
2668
|
<option value="list">仅允许列出的主机名</option>
|
|
2660
2669
|
<option value="all">允许所有主机名</option>
|
|
2661
2670
|
</select>
|
|
2662
|
-
<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:
|
|
2671
|
+
<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:fw(e)})}}></textarea>
|
|
2663
2672
|
<small>每行输入一个主机名,或选择“允许所有主机名”写入 <code>true</code>。</small>
|
|
2664
2673
|
</div>
|
|
2665
2674
|
|
|
@@ -2689,7 +2698,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2689
2698
|
<span class="field-heading">
|
|
2690
2699
|
<span>外部文件系统根目录</span>
|
|
2691
2700
|
</span>
|
|
2692
|
-
<textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs /opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:
|
|
2701
|
+
<textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs /opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:fw(e)})}}></textarea>
|
|
2693
2702
|
<small>${this.targetLabel} 上允许用于绝对路径 <code>@</code> 补全和工作区外文件读取的目录。每行输入一个绝对路径、Windows 绝对路径或以 <code>~</code> 开头的路径。留空则默认禁止外部路径。</small>
|
|
2694
2703
|
</label>
|
|
2695
2704
|
|
|
@@ -2697,7 +2706,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2697
2706
|
<span class="field-heading">
|
|
2698
2707
|
<span>默认上传文件夹</span>
|
|
2699
2708
|
</span>
|
|
2700
|
-
<input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${po} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:
|
|
2709
|
+
<input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${po} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:uw(e)})}}>
|
|
2701
2710
|
<small>${this.targetLabel} 上手动上传文件使用的工作区相对目录。留空则使用 PI WEB 默认值 <code>${po}</code>。</small>
|
|
2702
2711
|
</label>
|
|
2703
2712
|
|
|
@@ -2715,18 +2724,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2715
2724
|
<dl>
|
|
2716
2725
|
<div><dt>主机地址</dt><dd>${e.host??g`<span class="muted">默认 127.0.0.1</span>`}</dd></div>
|
|
2717
2726
|
<div><dt>端口</dt><dd>${e.port??g`<span class="muted">默认 8504</span>`}</dd></div>
|
|
2718
|
-
<div><dt>允许的主机名</dt><dd>${
|
|
2727
|
+
<div><dt>允许的主机名</dt><dd>${cw(e.allowedHosts)}</dd></div>
|
|
2719
2728
|
</dl>
|
|
2720
2729
|
</section>
|
|
2721
2730
|
`}renderMachineEffectiveConfig(){let e=this.machineConfigResponse?.effectiveConfig??{};return g`
|
|
2722
2731
|
<section class="effective-card" aria-label="所选机器最终生效的文件访问和上传摘要">
|
|
2723
2732
|
<h3>所选机器的生效配置</h3>
|
|
2724
2733
|
<dl>
|
|
2725
|
-
<div><dt>外部根目录</dt><dd>${
|
|
2734
|
+
<div><dt>外部根目录</dt><dd>${lw(e.pathAccess?.allowedPaths)}</dd></div>
|
|
2726
2735
|
<div><dt>上传文件夹</dt><dd>${e.uploads?.defaultFolder??g`<span class="muted">默认 ${`.pi-web/uploads`}</span>`}</dd></div>
|
|
2727
2736
|
</dl>
|
|
2728
2737
|
</section>
|
|
2729
|
-
`}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(
|
|
2738
|
+
`}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.($C(this.gatewayDraft,this.configResponse?.config??{}))}catch(e){this.gatewayLocalError=pw(e)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError=``;try{await this.onSaveMachineConfig?.(ew(this.machineDraft))}catch(e){this.machineLocalError=pw(e)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=``}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=``}static{this.styles=h`
|
|
2730
2739
|
:host { display: block; }
|
|
2731
2740
|
.card-heading { display: grid; gap: 6px; min-width: 0; }
|
|
2732
2741
|
h3, p { margin: 0; }
|
|
@@ -2757,10 +2766,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2757
2766
|
@media (max-width: 760px) {
|
|
2758
2767
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
2759
2768
|
}
|
|
2760
|
-
`}};B([b({attribute:!1})],J.prototype,`configResponse`,void 0),B([b({attribute:!1})],J.prototype,`machineConfigResponse`,void 0),B([b({type:Boolean})],J.prototype,`loading`,void 0),B([b({type:Boolean})],J.prototype,`machineLoading`,void 0),B([b({type:Boolean})],J.prototype,`saving`,void 0),B([b()],J.prototype,`error`,void 0),B([b()],J.prototype,`machineError`,void 0),B([b()],J.prototype,`savedMessage`,void 0),B([b()],J.prototype,`targetLabel`,void 0),B([b({attribute:!1})],J.prototype,`onReload`,void 0),B([b({attribute:!1})],J.prototype,`onReloadMachine`,void 0),B([b({attribute:!1})],J.prototype,`onSave`,void 0),B([b({attribute:!1})],J.prototype,`onSaveMachineConfig`,void 0),B([x()],J.prototype,`gatewayDraft`,void 0),B([x()],J.prototype,`machineDraft`,void 0),B([x()],J.prototype,`gatewayLocalError`,void 0),B([x()],J.prototype,`machineLocalError`,void 0),J=B([y(`settings-general-panel`)],J);function
|
|
2769
|
+
`}};B([b({attribute:!1})],J.prototype,`configResponse`,void 0),B([b({attribute:!1})],J.prototype,`machineConfigResponse`,void 0),B([b({type:Boolean})],J.prototype,`loading`,void 0),B([b({type:Boolean})],J.prototype,`machineLoading`,void 0),B([b({type:Boolean})],J.prototype,`saving`,void 0),B([b()],J.prototype,`error`,void 0),B([b()],J.prototype,`machineError`,void 0),B([b()],J.prototype,`savedMessage`,void 0),B([b()],J.prototype,`targetLabel`,void 0),B([b({attribute:!1})],J.prototype,`onReload`,void 0),B([b({attribute:!1})],J.prototype,`onReloadMachine`,void 0),B([b({attribute:!1})],J.prototype,`onSave`,void 0),B([b({attribute:!1})],J.prototype,`onSaveMachineConfig`,void 0),B([x()],J.prototype,`gatewayDraft`,void 0),B([x()],J.prototype,`machineDraft`,void 0),B([x()],J.prototype,`gatewayLocalError`,void 0),B([x()],J.prototype,`machineLocalError`,void 0),J=B([y(`settings-general-panel`)],J);function cw(e){return e===!0?`任意 host`:Array.isArray(e)?e.length===0?g`<span class="muted">未列出</span>`:e.join(`, `):g`<span class="muted">未设置</span>`}function lw(e){return e===void 0||e.length===0?g`<span class="muted">已禁止外部路径</span>`:e.join(`, `)}function uw(e){return e.target instanceof HTMLInputElement?e.target.value:``}function dw(e){return e.target instanceof HTMLSelectElement?e.target.value:``}function fw(e){return e.target instanceof HTMLTextAreaElement?e.target.value:``}function pw(e){return e instanceof Error?e.message:String(e)}function mw(e){return{spawnSessions:e}}function hw(e){return{subsessions:e}}function gw(e){return{askUser:e}}function _w(e,t){let n=e?.effectiveConfig.agent;if(n?.command===void 0||n.dir===void 0||t===void 0)return`unavailable`;let r=[`PI_WEB_AGENT_SESSION_DIR`,...Wt(n.command)?[`PI_CODING_AGENT_SESSION_DIR`]:[]];return n.command===t.command&&n.dir===t.dir&&bw(t.sessionDirEnvKeys,r)?`active`:`restart-required`}function vw(e,t){return e?.agentDirSource===`pi-web`?!0:e?.agentDirSource===`pi-compatibility`?Wt(t.trim()||`pi`):e?.agentDir===!0}function yw(e,t){let n={...e.envOverrides,spawnSessions:t.envOverrides.spawnSessions,subsessions:t.envOverrides.subsessions,askUser:t.envOverrides.askUser,agentCommand:t.envOverrides.agentCommand,agentDir:t.envOverrides.agentDir,agentSessionDir:t.envOverrides.agentSessionDir};return t.envOverrides.agentDirSource===void 0?delete n.agentDirSource:n.agentDirSource=t.envOverrides.agentDirSource,{...e,config:{...e.config,...t.config},effectiveConfig:{...e.effectiveConfig,...t.effectiveConfig},envOverrides:n}}function bw(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var xw=class extends v{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`本机(本地网关)`,this.agentProfileSupport={state:`supported`},this.agentDraft=qC(),this.agentDraftDirty=!1,this.agentLocalError=``}willUpdate(e){if(e.has(`configResponse`)){if(this.configResponse===void 0){this.agentDraft=qC(),this.agentDraftDirty=!1,this.agentLocalError=``;return}(!this.agentDraftDirty||QC(this.agentDraft,this.configResponse.config))&&(this.agentDraft=XC(this.configResponse.config),this.agentDraftDirty=!1,this.agentLocalError=``)}}render(){let e=this.configResponse,t=e?.envOverrides.spawnSessions===!0,n=e?.effectiveConfig.spawnSessions!==!1,r=e?.envOverrides.subsessions===!0,i=e?.effectiveConfig.subsessions===!0&&n,a=e?.effectiveConfig.askUser!==void 0,o=e?.envOverrides.askUser===!0,s=e?.effectiveConfig.askUser===!0,c=e?.envOverrides.agentCommand===!0,l=this.agentProfileSupport.state===`supported`,u=c?e.effectiveConfig.agent?.command??this.agentDraft.command:this.agentDraft.command,d=vw(e?.envOverrides,u),f=e?.envOverrides.agentDir===!0,p=e?.effectiveConfig.agent,m=_w(e,this.activeAgentProfile);return g`
|
|
2761
2770
|
<settings-panel-frame
|
|
2762
2771
|
heading="会话守护进程"
|
|
2763
|
-
.description=${
|
|
2772
|
+
.description=${Tw(this.targetLabel)}
|
|
2764
2773
|
actionLabel="重新加载"
|
|
2765
2774
|
.actionDisabled=${this.loading}
|
|
2766
2775
|
.notices=${this.panelNotices(e)}
|
|
@@ -2786,7 +2795,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2786
2795
|
.value=${this.agentDraft.command}
|
|
2787
2796
|
placeholder="pi"
|
|
2788
2797
|
?disabled=${this.loading||this.saving||!l||c}
|
|
2789
|
-
@input=${e=>{this.updateAgentDraft({command:
|
|
2798
|
+
@input=${e=>{this.updateAgentDraft({command:Cw(e)})}}
|
|
2790
2799
|
>
|
|
2791
2800
|
<small>设置诊断和更新检查所用的 Pi 兼容配套 CLI。内嵌会话运行时仍使用 PI WEB 捆绑的 Pi SDK。</small>
|
|
2792
2801
|
</label>
|
|
@@ -2803,7 +2812,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2803
2812
|
.value=${this.agentDraft.dir}
|
|
2804
2813
|
placeholder="~/.pi/agent 或 ~/agent-profiles/work"
|
|
2805
2814
|
?disabled=${this.loading||this.saving||!l||d}
|
|
2806
|
-
@input=${e=>{this.updateAgentDraft({dir:
|
|
2815
|
+
@input=${e=>{this.updateAgentDraft({dir:Cw(e)})}}
|
|
2807
2816
|
>
|
|
2808
2817
|
<small>选择 PI WEB 读取的 Pi 兼容认证、模型、设置和会话目录。备用命令会与其所需状态目录一并保存。</small>
|
|
2809
2818
|
</label>
|
|
@@ -2868,7 +2877,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2868
2877
|
<div><dt>期望状态目录</dt><dd>${p?.dir??g`<span class="muted">不可用</span>`}</dd></div>
|
|
2869
2878
|
<div><dt>当前命令</dt><dd>${this.activeAgentProfile?.command??g`<span class="muted">不可用</span>`}</dd></div>
|
|
2870
2879
|
<div><dt>当前状态目录</dt><dd>${this.activeAgentProfile?.dir??g`<span class="muted">不可用</span>`}</dd></div>
|
|
2871
|
-
<div><dt>配置档案状态</dt><dd>${
|
|
2880
|
+
<div><dt>配置档案状态</dt><dd>${Sw(m)}</dd></div>
|
|
2872
2881
|
<div><dt>派生会话</dt><dd>${n?`已启用`:g`<span class="muted">已禁用</span>`}</dd></div>
|
|
2873
2882
|
<div><dt>子会话</dt><dd>${i?`已启用`:g`<span class="muted">已禁用</span>`}</dd></div>
|
|
2874
2883
|
<div><dt>代理提问</dt><dd>${a?s?`已启用`:g`<span class="muted">已禁用</span>`:g`<span class="muted">不可用</span>`}</dd></div>
|
|
@@ -2876,7 +2885,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2876
2885
|
</section>
|
|
2877
2886
|
`}
|
|
2878
2887
|
</settings-panel-frame>
|
|
2879
|
-
`}panelNotices(e){let t=[],n=this.agentLocalError||this.error;return n!==``&&t.push({type:`error`,content:n}),this.savedMessage!==``&&t.push({type:`success`,content:this.savedMessage}),
|
|
2888
|
+
`}panelNotices(e){let t=[],n=this.agentLocalError||this.error;return n!==``&&t.push({type:`error`,content:n}),this.savedMessage!==``&&t.push({type:`success`,content:this.savedMessage}),_w(e,this.activeAgentProfile)===`restart-required`&&t.push({type:`warning`,title:`${this.targetLabel} 需要重启`,content:g`更改这些设置后,请在该机器上运行 <code>pi-web restart</code>,或重启其会话守护进程服务。`}),t}renderUnavailableConfigState(){return g`<div class="loading-card">${this.loading?`正在加载配置…`:`配置不可用,请重新加载。`}</div>`}async saveAgentProfile(e){e.preventDefault(),this.agentLocalError=``;try{await this.onSave?.(ZC(this.agentDraft))}catch(e){this.agentLocalError=ww(e)}}updateAgentDraft(e){this.agentDraft={...this.agentDraft,...e},this.agentDraftDirty=!0,this.agentLocalError=``}async toggleSpawnSessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(mw(t))}async toggleSubsessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(hw(t))}async toggleAskUser(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(gw(t))}static{this.styles=h`
|
|
2880
2889
|
:host { display: block; }
|
|
2881
2890
|
h3 { margin: 0; font-size: 13px; line-height: 1.3; }
|
|
2882
2891
|
button, input { font: inherit; }
|
|
@@ -2921,10 +2930,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2921
2930
|
@media (max-width: 760px) {
|
|
2922
2931
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
2923
2932
|
}
|
|
2924
|
-
`}};B([b({attribute:!1})],
|
|
2933
|
+
`}};B([b({attribute:!1})],xw.prototype,`configResponse`,void 0),B([b({type:Boolean})],xw.prototype,`loading`,void 0),B([b({type:Boolean})],xw.prototype,`saving`,void 0),B([b()],xw.prototype,`error`,void 0),B([b()],xw.prototype,`savedMessage`,void 0),B([b()],xw.prototype,`targetLabel`,void 0),B([b({attribute:!1})],xw.prototype,`activeAgentProfile`,void 0),B([b({attribute:!1})],xw.prototype,`agentProfileSupport`,void 0),B([b({attribute:!1})],xw.prototype,`onReload`,void 0),B([b({attribute:!1})],xw.prototype,`onSave`,void 0),B([x()],xw.prototype,`agentDraft`,void 0),B([x()],xw.prototype,`agentDraftDirty`,void 0),B([x()],xw.prototype,`agentLocalError`,void 0),xw=B([y(`settings-sessiond-panel`)],xw);function Sw(e){return e===`active`?`已生效`:e===`restart-required`?`需要重启`:g`<span class="muted">不可用</span>`}function Cw(e){return e.target instanceof HTMLInputElement?e.target.value:``}function ww(e){return e instanceof Error?e.message:String(e)}function Tw(e){return`这些设置会影响 ${e} 上长生命周期的会话运行时。更改会立即保存,但只有在该机器的会话守护进程重启后才会生效。`}function Ew(e){return e===void 0?{id:`local`,name:`本机`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function Dw(e){return e.kind===`local`?`${e.name}(本地网关)`:`${e.name}(远程机器)`}function Ow(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?T(t,w.piPackagesManage)?{state:`supported`}:{state:`unsupported`,message:jw(e)}:{state:`unknown`}}function kw(e){return`${e.state}:${e.message??``}`}function Aw(e){return e?.state===`unsupported`}function jw(e){return`${e.name} 不支持 Pi 包管理。请更新并重启该机器上的 PI WEB,然后重试。`}function Mw(e){return e.kind===`local`}function Nw(e){return e.trim()}function Pw(e){if(Nw(e)===``)return`请输入 Pi 支持的包来源,例如 npm:@scope/package、Git/URL 来源或本地路径。`}function Fw(e){return e.scope===`project`?`项目范围`:`用户范围`}function Iw(e){return e.filtered?`已被当前 Pi 包设置过滤`:`可用于此 PI WEB 进程`}function Lw(e){return e.installedPath??`Pi 未报告安装路径`}function Rw(e){return e.scope===`user`}function zw(e){if(!Rw(e))return`此处会列出项目范围的 Pi 包,但 PI WEB 只能在此界面安全更新用户范围的 Pi 包。`}function Bw(e){return e.length>0&&e.every(Rw)}function Vw(e){if(e.length===0)return`尚未配置 Pi 包。`;if(!Bw(e))return`列表中包含项目范围的 Pi 包,无法全部更新;请逐个更新用户范围的包。`}function Hw(e,t,n){return e?.kind===t?n===void 0||e.source===n:!1}function Uw(e,t=Ew(void 0)){return`Pi 包${e===`install`?`已安装`:e===`remove`?`已移除`:`已更新`}${t.kind===`local`?``:`(${t.name})`}。请在 ${t.kind===`local`?`每个空闲的 PI WEB 会话`:`${t.name} 上每个空闲的 PI WEB 会话`} 中输入 /reload,重新发现 Pi 运行时资源:扩展、技能、提示词模板、主题以及上下文/系统提示文件。对于 ${t.kind===`local`?`PI WEB 浏览器插件变更`:`${t.name} 提供的 PI WEB 浏览器插件变更`},请另外重新加载浏览器页面。`}function Ww(e,t){let n=e.trim();return t.kind===`remote`?Gw(n)?jw(t):n===`Remote machine timeout`?`联系 ${t.name} 进行 Pi 包管理时超时。包操作可能仍在远端运行;重试前请重新加载包列表。`:n===`Remote machine unavailable`?`无法连接 ${t.name} 进行 Pi 包管理。请检查机器连接后重试。`:n:n}function Gw(e){return e===`Not Found`||/route\s+(GET|POST):?\/api\/pi-packages\b.*not found/iu.test(e)||/cannot\s+(GET|POST)\s+.*\/api\/pi-packages\b/iu.test(e)}var Kw=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=Dw(t),r=this.packageManagementUnavailable,i=this.packagesResponse!==void 0&&!r;return g`
|
|
2925
2934
|
<settings-panel-frame
|
|
2926
2935
|
heading="Pi 包"
|
|
2927
|
-
.description=${
|
|
2936
|
+
.description=${qw(n)}
|
|
2928
2937
|
actionLabel="重新加载"
|
|
2929
2938
|
actionTitle=${r?this.packageManagementUnavailableMessage(n):`从 ${n} 重新加载 Pi 包`}
|
|
2930
2939
|
.actionDisabled=${this.loading||this.isOperating||r}
|
|
@@ -2941,12 +2950,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2941
2950
|
<label for="package-source">Pi 包来源</label>
|
|
2942
2951
|
<div class="install-row">
|
|
2943
2952
|
<input id="package-source" .value=${this.installSource} ?disabled=${this.isOperating} placeholder="npm:@scope/package、Git URL 或本地路径" @input=${e=>{this.updateInstallSource(e)}}>
|
|
2944
|
-
<button type="submit" title="安装此 Pi 包" ?disabled=${this.isOperating}>${
|
|
2953
|
+
<button type="submit" title="安装此 Pi 包" ?disabled=${this.isOperating}>${Hw(this.operation,`install`)?`正在安装…`:`安装`}</button>
|
|
2945
2954
|
</div>
|
|
2946
2955
|
${this.validationMessage===``?null:g`<div class="field-error">${this.validationMessage}</div>`}
|
|
2947
2956
|
<small>安装操作在 ${e} 上运行并使用 Pi 的默认包位置,等同于 <code>pi install <source></code>。PI WEB 不会要求你选择安装位置。</small>
|
|
2948
2957
|
</form>
|
|
2949
|
-
`}renderPackageList(e,t){let n=
|
|
2958
|
+
`}renderPackageList(e,t){let n=Dw(t),r=this.packageManagementUnavailable?this.packageManagementUnavailableMessage(n):Vw(e),i=r!==void 0&&e.length>0;return g`
|
|
2950
2959
|
<section class="package-section" aria-label="已配置的 Pi 包">
|
|
2951
2960
|
<div class="package-toolbar">
|
|
2952
2961
|
<div>
|
|
@@ -2954,7 +2963,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2954
2963
|
<p>此列表来自 ${n} 上的 Pi 包管理器设置。</p>
|
|
2955
2964
|
</div>
|
|
2956
2965
|
<button class="secondary" title=${r??`更新所有用户范围的 Pi 包`} ?disabled=${this.isOperating||r!==void 0} @click=${()=>{this.updatePackage()}}>
|
|
2957
|
-
${
|
|
2966
|
+
${Hw(this.operation,`update-all`)?`正在更新…`:`全部更新`}
|
|
2958
2967
|
</button>
|
|
2959
2968
|
</div>
|
|
2960
2969
|
${i?g`<div class="action-note">${r}</div>`:null}
|
|
@@ -2965,12 +2974,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2965
2974
|
<div class="package-list">
|
|
2966
2975
|
${e.map(e=>this.renderPackage(e))}
|
|
2967
2976
|
</div>
|
|
2968
|
-
`}renderPackage(e){let t=
|
|
2977
|
+
`}renderPackage(e){let t=Dw(this.packageTarget),n=this.packageManagementUnavailable,r=n?this.packageManagementUnavailableMessage(t):zw(e),i=n?this.packageManagementUnavailableMessage(t):`移除此 Pi 包`,a=Hw(this.operation,`update`,e.source),o=Hw(this.operation,`remove`,e.source);return g`
|
|
2969
2978
|
<article class=${`package-card${e.filtered?` filtered`:``}`}>
|
|
2970
2979
|
<div class="package-main">
|
|
2971
2980
|
<strong>${e.source}</strong>
|
|
2972
|
-
<small>${
|
|
2973
|
-
<small>安装路径:<code>${
|
|
2981
|
+
<small>${Fw(e)} · ${Iw(e)}</small>
|
|
2982
|
+
<small>安装路径:<code>${Lw(e)}</code></small>
|
|
2974
2983
|
${r===void 0?null:g`<small class="action-note">${r}</small>`}
|
|
2975
2984
|
</div>
|
|
2976
2985
|
<div class="package-actions">
|
|
@@ -2978,7 +2987,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2978
2987
|
<button class="danger" title=${i} ?disabled=${this.isOperating||n} @click=${()=>{this.removePackage(e)}}>${o?`正在移除…`:`移除`}</button>
|
|
2979
2988
|
</div>
|
|
2980
2989
|
</article>
|
|
2981
|
-
`}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=
|
|
2990
|
+
`}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=Pw(this.installSource);if(t!==void 0){this.validationMessage=t;return}let n=Nw(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??Ew(void 0)}get packageManagementUnavailable(){return Aw(this.managementSupport)}packageManagementUnavailableMessage(e){return this.managementSupport?.message??`${e} 不支持 Pi 包管理。`}get isOperating(){return this.operation!==void 0}static{this.styles=h`
|
|
2982
2991
|
:host { display: block; }
|
|
2983
2992
|
.package-toolbar { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
2984
2993
|
.package-toolbar > div, .package-main { display: grid; gap: 6px; min-width: 0; }
|
|
@@ -3013,10 +3022,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3013
3022
|
.package-actions { justify-self: start; flex-wrap: wrap; }
|
|
3014
3023
|
.package-main strong, .package-main small { white-space: normal; }
|
|
3015
3024
|
}
|
|
3016
|
-
`}};B([b({attribute:!1})],
|
|
3025
|
+
`}};B([b({attribute:!1})],Kw.prototype,`packagesResponse`,void 0),B([b({type:Boolean})],Kw.prototype,`loading`,void 0),B([b({attribute:!1})],Kw.prototype,`operation`,void 0),B([b({attribute:!1})],Kw.prototype,`targetMachine`,void 0),B([b({attribute:!1})],Kw.prototype,`managementSupport`,void 0),B([b()],Kw.prototype,`error`,void 0),B([b()],Kw.prototype,`operationMessage`,void 0),B([b({attribute:!1})],Kw.prototype,`onReload`,void 0),B([b({attribute:!1})],Kw.prototype,`onInstallPackage`,void 0),B([b({attribute:!1})],Kw.prototype,`onRemovePackage`,void 0),B([b({attribute:!1})],Kw.prototype,`onUpdatePackage`,void 0),B([x()],Kw.prototype,`installSource`,void 0),B([x()],Kw.prototype,`validationMessage`,void 0),Kw=B([y(`settings-packages-panel`)],Kw);function qw(e){return g`管理 <strong>${e}</strong> 上的 Pi 包。你可以安装、移除和更新所选机器上由 Pi 管理的包。Pi 包可提供扩展、技能、提示词模板、主题、上下文/系统提示文件以及 PI WEB 浏览器插件。`}var Jw=class extends v{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`本机(本地网关)`}render(){let e=this.pluginsResponse?.plugins??[],t=this.pluginsResponse!==void 0;return g`
|
|
3017
3026
|
<settings-panel-frame
|
|
3018
3027
|
heading="PI WEB 插件"
|
|
3019
|
-
.description=${
|
|
3028
|
+
.description=${Yw(this.targetLabel)}
|
|
3020
3029
|
actionLabel="重新加载"
|
|
3021
3030
|
actionTitle=${`从 ${this.targetLabel} 重新加载 PI WEB 插件`}
|
|
3022
3031
|
.actionDisabled=${this.loading}
|
|
@@ -3034,7 +3043,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3034
3043
|
<article class=${`plugin-card${e.enabled?``:` disabled`}`}>
|
|
3035
3044
|
<div class="plugin-main">
|
|
3036
3045
|
<strong>${e.id}</strong>
|
|
3037
|
-
<small>${
|
|
3046
|
+
<small>${Xw(e.source)} · ${Zw(e.scope)}${e.machineSpecific?` · 机器专属`:``}</small>
|
|
3038
3047
|
<small>${n}</small>
|
|
3039
3048
|
</div>
|
|
3040
3049
|
<label class="toggle">
|
|
@@ -3062,10 +3071,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3062
3071
|
.plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
3063
3072
|
.toggle { justify-self: start; }
|
|
3064
3073
|
}
|
|
3065
|
-
`}};B([b({attribute:!1})],
|
|
3074
|
+
`}};B([b({attribute:!1})],Jw.prototype,`pluginsResponse`,void 0),B([b({attribute:!1})],Jw.prototype,`configResponse`,void 0),B([b({type:Boolean})],Jw.prototype,`loading`,void 0),B([b({type:Boolean})],Jw.prototype,`saving`,void 0),B([b()],Jw.prototype,`error`,void 0),B([b()],Jw.prototype,`savedMessage`,void 0),B([b()],Jw.prototype,`targetLabel`,void 0),B([b({attribute:!1})],Jw.prototype,`onReload`,void 0),B([b({attribute:!1})],Jw.prototype,`onTogglePlugin`,void 0),Jw=B([y(`settings-plugins-panel`)],Jw);function Yw(e){return g`启用或禁用 <strong>${e}</strong> 上发现的 PI WEB 浏览器插件。这与安装 Pi 包相互独立;请重新加载浏览器标签页以应用插件运行时更改。`}function Xw(e){return e===`bundled`?`内置`:e===`local`?`本地`:e===`dev`?`开发`:e}function Zw(e){switch(e){case`bundled`:return`内置范围`;case`local`:return`本地范围`;case`user`:return`用户范围`;case`project`:return`项目范围`}}var Qw={capture:!0},$w=[{value:`auto`,label:`自动/默认`,description:`桌面环境按 Enter 发送;移动设备、粗略指针或窄屏环境按 Enter 换行。`},{value:`send`,label:`Enter 发送消息`,description:`Enter 发送聊天消息;支持时 Shift+Enter 插入新行。`},{value:`newline`,label:`Enter 插入新行`,description:`Enter 插入换行;支持时 Shift+Enter 发送聊天消息。`}];function eT(){return g`按操作编辑应用快捷键。输入 <code>mod+k</code> 或 <code>mod+g p</code> 这类快捷键,也可以从键盘录制、设为无或恢复默认。快捷键冲突时,自定义快捷键优先于默认值;同级按操作 ID 排序,较短快捷键会遮蔽相同前缀的较长序列。`}var tT=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=US(),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=Af(e);if(n===void 0){this.localError=`请按字母、数字、标点、功能键或导航键。按 Esc 取消录制。`;return}if(t.tokens.length===0&&!jf(n)){this.localError=`快捷键请以 Ctrl/⌘ 或 Alt 开始,以免捕获正常输入。`;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=aT(this.actions),t=this.shortcutResolutions();return g`
|
|
3066
3075
|
<settings-panel-frame
|
|
3067
3076
|
heading="键盘快捷键"
|
|
3068
|
-
.description=${
|
|
3077
|
+
.description=${eT()}
|
|
3069
3078
|
actionLabel="重新加载"
|
|
3070
3079
|
.actionDisabled=${this.loading}
|
|
3071
3080
|
.notices=${this.panelNotices()}
|
|
@@ -3096,7 +3105,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3096
3105
|
<p>选择当前浏览器中 Enter 键的行为。支持时 Shift+Enter 执行相反操作;为避免误发送,会忽略触摸键盘的自动大写状态。</p>
|
|
3097
3106
|
</div>
|
|
3098
3107
|
<div class="prompt-enter-options" role="radiogroup" aria-label="聊天输入框中的 Enter 和 Shift Enter 行为">
|
|
3099
|
-
${
|
|
3108
|
+
${$w.map(e=>g`
|
|
3100
3109
|
<label class="prompt-enter-option">
|
|
3101
3110
|
<input
|
|
3102
3111
|
type="radio"
|
|
@@ -3113,8 +3122,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3113
3122
|
`)}
|
|
3114
3123
|
</div>
|
|
3115
3124
|
</section>
|
|
3116
|
-
`}updatePromptEnterPreference(e){this.promptEnterPreference=e,
|
|
3117
|
-
<article class=${
|
|
3125
|
+
`}updatePromptEnterPreference(e){this.promptEnterPreference=e,WS(e)}renderShortcutRow(e,t){let n=this.configResponse?.config.shortcuts,r=sT(e.id,n),i=uT(e,n),a=this.shortcutInputText(e),o=a.trim()===``?void 0:Df(a),s=o?.ok===!0?o.shortcut:lT(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=iT(t);return g`
|
|
3126
|
+
<article class=${nT(t)}>
|
|
3118
3127
|
<div class="shortcut-main">
|
|
3119
3128
|
<strong>${e.title}</strong>
|
|
3120
3129
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
@@ -3124,8 +3133,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3124
3133
|
<div class="shortcut-editor">
|
|
3125
3134
|
<div class="shortcut-status">
|
|
3126
3135
|
${s!==void 0&&s!==``?g`<kbd>${kf(s)}</kbd>`:g`<span class="unassigned">${i===`disabled`?`已禁用`:`未分配`}</span>`}
|
|
3127
|
-
<small class=${u}>${
|
|
3128
|
-
${f===void 0?null:g`<small class=${
|
|
3136
|
+
<small class=${u}>${dT(u)}${l?` · 未保存`:``}</small>
|
|
3137
|
+
${f===void 0?null:g`<small class=${rT(t)}>${f}</small>`}
|
|
3129
3138
|
</div>
|
|
3130
3139
|
<label class="shortcut-input-label">
|
|
3131
3140
|
<span>快捷键</span>
|
|
@@ -3138,7 +3147,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3138
3147
|
autocapitalize="off"
|
|
3139
3148
|
spellcheck="false"
|
|
3140
3149
|
?disabled=${this.saving}
|
|
3141
|
-
@input=${t=>{this.updateDraft(e.id,
|
|
3150
|
+
@input=${t=>{this.updateDraft(e.id,fT(t))}}
|
|
3142
3151
|
>
|
|
3143
3152
|
</label>
|
|
3144
3153
|
${d===``?null:g`<small class="recording-hint">${d}</small>`}
|
|
@@ -3150,7 +3159,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3150
3159
|
</div>
|
|
3151
3160
|
</div>
|
|
3152
3161
|
</article>
|
|
3153
|
-
`}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=
|
|
3162
|
+
`}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=sT(e.id,this.configResponse?.config.shortcuts);return n===null?``:n??e.shortcut??``}recordingHint(e){let t=this.recording;return t?.actionId===e?t.tokens.length===0?`正在录制:请按 Ctrl/⌘ 或 Alt 加一个按键。按 Esc 取消。`:`正在录制:${kf(t.tokens.join(` `))}。继续按键可添加序列,或等待录制完成。`:``}updateDraft(e,t){this.drafts={[e]:t},this.localError=``}async saveShortcut(e){this.stopRecording();let t=Df(this.shortcutInputText(e).trim());if(!t.ok){this.localError=t.message;return}this.localError=``,await this.saveShortcutPreference(e.id,t.shortcut)}async setShortcutNone(e){this.stopRecording(),this.localError=``,await this.saveShortcutPreference(e,null)}async resetShortcut(e){this.stopRecording(),this.localError=``,await this.saveShortcutPreference(e,void 0)}async saveShortcutPreference(e,t){let n={...this.configResponse?.config??{}},r=n.shortcuts??{},i=t===void 0?cT(r,e):{...r,[e]:t};Object.keys(i).length===0?delete n.shortcuts:n.shortcuts=i,await this.onSave?.(n)}shortcutResolutions(){return new Map(Ef(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=Df(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()},Cf)}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,Qw),!0)}removeRecordingListener(){this.recordingListenerActive&&=(window.removeEventListener(`keydown`,this.onRecordKeyDown,Qw),!1)}static{this.styles=h`
|
|
3154
3163
|
:host { display: block; }
|
|
3155
3164
|
h3, p { margin: 0; }
|
|
3156
3165
|
h3 { font-size: 13px; line-height: 1.3; }
|
|
@@ -3206,7 +3215,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3206
3215
|
.shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
3207
3216
|
.shortcut-status, .shortcut-actions { justify-content: flex-start; }
|
|
3208
3217
|
}
|
|
3209
|
-
`}};B([b({attribute:!1})],
|
|
3218
|
+
`}};B([b({attribute:!1})],tT.prototype,`actions`,void 0),B([b({attribute:!1})],tT.prototype,`configResponse`,void 0),B([b({type:Boolean})],tT.prototype,`loading`,void 0),B([b({type:Boolean})],tT.prototype,`saving`,void 0),B([b()],tT.prototype,`error`,void 0),B([b()],tT.prototype,`savedMessage`,void 0),B([b({attribute:!1})],tT.prototype,`onReload`,void 0),B([b({attribute:!1})],tT.prototype,`onSave`,void 0),B([x()],tT.prototype,`drafts`,void 0),B([x()],tT.prototype,`localError`,void 0),B([x()],tT.prototype,`promptEnterPreference`,void 0),B([x()],tT.prototype,`recording`,void 0),tT=B([y(`settings-shortcuts-panel`)],tT);function nT(e){return e?.active===!1?`shortcut-row shadowed`:e?.active===!0&&e.shadows.length>0?`shortcut-row shadowing`:`shortcut-row`}function rT(e){return e?.active===!1?`conflict shadowed`:`conflict shadowing`}function iT(e){if(e===void 0)return;if(!e.active)return`被“${e.shadowedBy?.action.title??`另一项操作`}”覆盖`;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)} 项`:``;return`覆盖 ${String(t)} 项操作:${n}${r}`}function aT(e){let t=new Map;for(let n of[...e].sort(oT)){let e=n.group??`其他`;t.set(e,[...t.get(e)??[],n])}return[...t.entries()].map(([e,t])=>({name:e,actions:t}))}function oT(e,t){return(e.group??`其他`).localeCompare(t.group??`其他`)||e.title.localeCompare(t.title)}function sT(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function cT(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function lT(e,t){let n=sT(e.id,t);if(n!==null)return n??e.shortcut}function uT(e,t){let n=sT(e.id,t);return n===null?`disabled`:n===void 0?e.shortcut===void 0||e.shortcut===``?`unassigned`:`default`:`custom`}function dT(e){switch(e){case`default`:return`默认`;case`custom`:return`配置覆盖`;case`disabled`:return`配置禁用`;case`unassigned`:return`无默认值`}}function fT(e){return e.target instanceof HTMLInputElement?e.target.value:``}async function pT(e){let[t,n]=await Promise.allSettled([e.loadConfig(),e.loadPlugins()]),r={error:``},i=[];return t.status===`fulfilled`?r.config=t.value:i.push(`配置:${hT(t.reason)}`),n.status===`fulfilled`?r.plugins=n.value:i.push(`PI WEB 插件:${hT(n.reason)}`),i.length>0&&(r.error=`加载设置失败:${i.join(`;`)}`),r}async function mT(e,t,n){if(Aw(n))return{error:n.message??`${Dw(e)} 不支持 Pi 包管理。`,skipped:!0};try{return{packagesResponse:await t(e.id),error:``}}catch(t){return{error:`从 ${Dw(e)} 加载 Pi 包失败:${Ww(hT(t),e)}`}}}function hT(e){return e instanceof Error?e.message:String(e)}function gT(e,t){return{...e,config:_T(e.config,t.config),effectiveConfig:_T(e.effectiveConfig,t.effectiveConfig)}}function _T(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 vT(e){return e===void 0?{id:`local`,name:`本机`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function Y(e){return e.kind===`local`?`${e.name}(本地网关)`:`${e.name}(远程机器)`}function yT(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?T(t,w.selectedMachineSettings)?{state:`supported`}:{state:`unsupported`,message:wT(e)}:{state:`unknown`}}function bT(e,t){return e.kind===`local`?{state:`supported`}:t?.ok===!0?T(t,w.agentProfileConfig)?{state:`supported`}:{state:`unsupported`,message:`${e.name} 不支持 Pi 兼容代理配置档案设置。请更新并重启该机器上的 PI WEB,然后重试。`}:{state:`unknown`,message:`无法确认 ${e.name} 是否支持 Pi 兼容代理配置档案。更改配置档案前请重新加载机器状态。`}}function xT(e){return`${e.state}:${e.message??``}`}function ST(e){return e?.state===`unsupported`}function CT(e){return e?.state===`supported`}function wT(e){return`${e.name} 不支持所选机器设置。请更新并重启该机器上的 PI WEB,然后重试。`}function TT(e,t){let n=e.trim();return t.kind===`remote`?ET(n)?wT(t):n===`Remote machine timeout`?`联系 ${t.name} 获取所选机器设置时超时。操作可能仍在远端运行;请重新加载后再重试。`:n===`Remote machine unavailable`?`无法连接 ${t.name} 以获取所选机器设置。请检查机器连接后重试。`:n:n}function ET(e){return e===`Not Found`||/route\s+(GET|PUT):?\/api\/(config|plugins)\b.*not found/iu.test(e)||/cannot\s+(GET|PUT)\s+.*\/api\/(config|plugins)\b/iu.test(e)}function DT(e,t,n){let r=e.plugins??{},i=r[t]??{};return{plugins:{...r,[t]:{...i,enabled:n}}}}function OT(e,t){return{...e,config:kT(e.config,t.config),effectiveConfig:kT(e.effectiveConfig,t.effectiveConfig)}}function kT(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.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`)&&vT(e.get(`machine`)).id!==t.id){this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t),this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t);return}e.has(`machineRuntime`)&&(this.selectedMachineSettingsSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetAccessStateForTargetChange(),this.isConnected&&this.loadAccessConfigForTarget(t),this.resetSessiondStateForTargetChange(),this.isConnected&&this.loadSessiondConfigForTarget(t),this.resetPluginStateForTargetChange(),this.isConnected&&this.loadPluginsForTarget(t)),this.packageManagementSupportNeedsReload(e.get(`machineRuntime`),t)&&(this.resetPackageStateForTargetChange(),this.isConnected&&this.loadPackagesForTarget(t)))}render(){return g`
|
|
3210
3219
|
<div class="backdrop" @mousedown=${()=>this.onClose?.()}>
|
|
3211
3220
|
<section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB 设置" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
3212
3221
|
<header class="settings-header">
|
|
@@ -3301,7 +3310,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3301
3310
|
<strong>${t}</strong>
|
|
3302
3311
|
<small>${n}</small>
|
|
3303
3312
|
</button>
|
|
3304
|
-
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await
|
|
3313
|
+
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await pT({loadConfig:()=>Wa.config(),loadPlugins:()=>Ka.plugins()});if(!this.isCurrentLoad(e))return;t.config!==void 0&&(this.configResponse=t.config),t.plugins!==void 0&&(this.pluginsResponse=t.plugins),this.error=t.error}finally{this.isCurrentLoad(e)&&(this.loading=!1)}}async loadAccessConfigForTarget(e=this.settingsTarget()){let t=++this.accessLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(ST(n)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=n.message??`${Y(e)} 不支持所选机器设置。`;return}this.accessLoading=!0,this.accessError=``;try{let n=await Wa.config(e.id);if(!this.isCurrentAccessLoad(t,e))return;this.accessConfigResponse=n}catch(n){this.isCurrentAccessLoad(t,e)&&(this.accessError=`从 ${Y(e)} 加载文件访问/上传配置失败:${TT(AT(n),e)}`)}finally{this.isCurrentAccessLoad(t,e)&&(this.accessLoading=!1)}}async reloadSessiondState(e=this.settingsTarget()){await Promise.all([this.loadSessiondConfigForTarget(e),this.onRefreshMachineRuntime?.(e.id)])}async loadSessiondConfigForTarget(e=this.settingsTarget()){let t=++this.sessiondLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(ST(n)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=n.message??`${Y(e)} 不支持所选机器设置。`;return}this.sessiondLoading=!0,this.sessiondError=``;try{let n=await Wa.config(e.id);if(!this.isCurrentSessiondLoad(t,e))return;this.sessiondConfigResponse=n}catch(n){this.isCurrentSessiondLoad(t,e)&&(this.sessiondError=`从 ${Y(e)} 加载会话守护进程配置失败:${TT(AT(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(ST(n)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=n.message??`${Y(e)} 不支持所选机器设置。`;return}this.pluginLoading=!0,this.pluginError=``;try{let[n,r]=await Promise.allSettled([Wa.config(e.id),Ka.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let i=[];n.status===`fulfilled`?this.selectedPluginConfigResponse=n.value:i.push(`配置:${TT(AT(n.reason),e)}`),r.status===`fulfilled`?this.selectedPluginsResponse=r.value:i.push(`PI WEB 插件:${TT(AT(r.reason),e)}`),this.pluginError=i.length===0?``:`从 ${Y(e)} 加载 PI WEB 插件设置失败:${i.join(`;`)}`}finally{this.isCurrentPluginLoad(t,e)&&(this.pluginLoading=!1)}}async loadPackagesForTarget(e=this.packageTarget()){let t=++this.packageLoadRequestSeq;this.packageLoading=!0,this.packageError=``,this.packageMessage=``;try{let n=await mT(e,e=>Ja.packages(e),this.packageManagementSupport(e));if(!this.isCurrentPackageLoad(t,e))return;this.packagesResponse=n.packagesResponse,this.packageError=n.error}finally{this.isCurrentPackageLoad(t,e)&&(this.packageLoading=!1)}}async togglePlugin(e,t){if(this.saving)return;let n=this.settingsTarget(),r=this.selectedMachineSettingsSupport(n);if(ST(r)){this.pluginError=r.message??`${Y(n)} 不支持所选机器设置。`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`尚未加载 ${Y(n)} 的插件配置。更改插件启用状态前请重新加载。`;return}let i=DT(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await Wa.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=OT(this.configResponse,e),this.onConfigSaved?.(this.configResponse.effectiveConfig));let t=await this.refreshPluginsForTarget(n);if(!this.isCurrentSettingsTarget(n))return;t!==void 0&&(this.pluginError=t),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(n)&&(this.pluginError=`在 ${Y(n)} 上保存 PI WEB 插件配置失败:${TT(AT(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await Wa.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`保存配置失败:${AT(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(ST(n)){this.accessError=n.message??`${Y(t)} 不支持所选机器设置。`;return}this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await Wa.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=gT(this.configResponse,n),this.onConfigSaved?.(this.configResponse.effectiveConfig)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.accessError=`在 ${Y(t)} 上保存文件访问/上传配置失败:${TT(AT(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(ST(n)){this.sessiondError=n.message??`${Y(t)} 不支持所选机器设置。`;return}if(e.agent!==void 0){let e=this.agentProfileSettingsSupport(t);if(!CT(e)){this.sessiondError=e.message??`${Y(t)} 不支持 Pi 兼容代理配置档案设置。`;return}}this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await Wa.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=yw(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`在 ${Y(t)} 上保存会话守护进程配置失败:${TT(AT(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`安装 Pi 包`,t,()=>Ja.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`移除 Pi 包`,n,()=>Ja.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},`更新 Pi 包`,t,()=>Ja.update(e,t.id))}async runPiPackageMutation(e,t,n,r){let i=this.packageManagementSupport(n);if(Aw(i))throw this.packageError=i.message??`${Dw(n)} 不支持 Pi 包管理。`,Error(this.packageError);if(this.saving)throw Error(`已有设置操作正在运行。`);let a=++this.packageMutationSeq;this.packageLoadRequestSeq+=1,this.packageLoading=!1,this.saving=!0,this.packageOperation=e,this.packageError=``,this.packageMessage=``;try{let e=await r();if(!this.isCurrentPackageMutation(a,n))return;this.packagesResponse={packages:e.packages};let t=Mw(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(a,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=Uw(e.action,n)}catch(e){throw this.isCurrentPackageMutation(a,n)&&(this.packageError=`在 ${Dw(n)} 上${t}失败:${Ww(AT(e),n)}`),e}finally{this.packageMutationSeq===a&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await Ka.plugins();return}catch(e){return`刷新网关 PI WEB 插件失败:${AT(e)}`}}async refreshPluginsForTarget(e){try{let t=await Ka.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`配置已保存,但从 ${Y(e)} 刷新 PI WEB 插件失败:${TT(AT(t),e)}`}}settingsTarget(){return vT(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return yT(e,this.machineRuntime)}agentProfileSettingsSupport(e=this.settingsTarget()){return bT(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){let n=yT(t,e),r=this.selectedMachineSettingsSupport(t);return xT(n)!==xT(r)}packageManagementSupport(e=this.packageTarget()){return Ow(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){let n=Ow(t,e),r=this.packageManagementSupport(t);return kw(n)===kw(r)?!1:n.state===`unsupported`||r.state===`unsupported`}isCurrentLoad(e){return e===this.loadRequestSeq}isCurrentAccessLoad(e,t){return e===this.accessLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentSessiondLoad(e,t){return e===this.sessiondLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPluginLoad(e,t){return e===this.pluginLoadRequestSeq&&this.isCurrentSettingsTarget(t)}isCurrentPackageLoad(e,t){return e===this.packageLoadRequestSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageMutation(e,t){return e===this.packageMutationSeq&&this.isCurrentPackageTarget(t)}isCurrentPackageTarget(e){return this.packageTarget().id===e.id}isCurrentSettingsTarget(e){return this.settingsTarget().id===e.id}resetAccessStateForTargetChange(){this.accessLoadRequestSeq+=1,this.accessLoading=!1,this.accessError=``,this.accessConfigResponse=void 0,this.savedMessage=``}resetSessiondStateForTargetChange(){this.sessiondLoadRequestSeq+=1,this.sessiondLoading=!1,this.sessiondError=``,this.sessiondConfigResponse=void 0,this.savedMessage=``}resetPluginStateForTargetChange(){this.pluginLoadRequestSeq+=1,this.pluginLoading=!1,this.pluginError=``,this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.savedMessage=``}resetPackageStateForTargetChange(){let e=this.packageOperation!==void 0;this.packageLoadRequestSeq+=1,this.packageMutationSeq+=1,this.packageLoading=!1,this.packageOperation=void 0,this.packageMessage=``,this.packageError=``,this.packagesResponse=void 0,e&&(this.saving=!1)}showSavedMessage(){this.savedMessage=`配置已保存。`,this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage===`配置已保存。`&&(this.savedMessage=``),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}static{this.styles=h`
|
|
3305
3314
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
3306
3315
|
.backdrop { box-sizing: border-box; width: 100%; height: 100dvh; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-overlay); overflow: hidden; }
|
|
3307
3316
|
.settings-shell { width: min(980px, 100%); max-height: min(760px, 100%); min-height: min(620px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr); border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
|
|
@@ -3328,7 +3337,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3328
3337
|
.settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
|
|
3329
3338
|
.settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
|
|
3330
3339
|
}
|
|
3331
|
-
`}};B([b({attribute:!1})],X.prototype,`section`,void 0),B([b({attribute:!1})],X.prototype,`actions`,void 0),B([b({attribute:!1})],X.prototype,`machine`,void 0),B([b({attribute:!1})],X.prototype,`machineRuntime`,void 0),B([b({attribute:!1})],X.prototype,`onNavigate`,void 0),B([b({attribute:!1})],X.prototype,`onClose`,void 0),B([b({attribute:!1})],X.prototype,`onConfigSaved`,void 0),B([b({attribute:!1})],X.prototype,`onRefreshMachineRuntime`,void 0),B([x()],X.prototype,`configResponse`,void 0),B([x()],X.prototype,`accessConfigResponse`,void 0),B([x()],X.prototype,`sessiondConfigResponse`,void 0),B([x()],X.prototype,`pluginsResponse`,void 0),B([x()],X.prototype,`selectedPluginConfigResponse`,void 0),B([x()],X.prototype,`selectedPluginsResponse`,void 0),B([x()],X.prototype,`packagesResponse`,void 0),B([x()],X.prototype,`loading`,void 0),B([x()],X.prototype,`accessLoading`,void 0),B([x()],X.prototype,`sessiondLoading`,void 0),B([x()],X.prototype,`pluginLoading`,void 0),B([x()],X.prototype,`packageLoading`,void 0),B([x()],X.prototype,`saving`,void 0),B([x()],X.prototype,`packageOperation`,void 0),B([x()],X.prototype,`error`,void 0),B([x()],X.prototype,`accessError`,void 0),B([x()],X.prototype,`sessiondError`,void 0),B([x()],X.prototype,`pluginError`,void 0),B([x()],X.prototype,`packageError`,void 0),B([x()],X.prototype,`savedMessage`,void 0),B([x()],X.prototype,`packageMessage`,void 0),X=B([y(`settings-dialog`)],X);function
|
|
3340
|
+
`}};B([b({attribute:!1})],X.prototype,`section`,void 0),B([b({attribute:!1})],X.prototype,`actions`,void 0),B([b({attribute:!1})],X.prototype,`machine`,void 0),B([b({attribute:!1})],X.prototype,`machineRuntime`,void 0),B([b({attribute:!1})],X.prototype,`onNavigate`,void 0),B([b({attribute:!1})],X.prototype,`onClose`,void 0),B([b({attribute:!1})],X.prototype,`onConfigSaved`,void 0),B([b({attribute:!1})],X.prototype,`onRefreshMachineRuntime`,void 0),B([x()],X.prototype,`configResponse`,void 0),B([x()],X.prototype,`accessConfigResponse`,void 0),B([x()],X.prototype,`sessiondConfigResponse`,void 0),B([x()],X.prototype,`pluginsResponse`,void 0),B([x()],X.prototype,`selectedPluginConfigResponse`,void 0),B([x()],X.prototype,`selectedPluginsResponse`,void 0),B([x()],X.prototype,`packagesResponse`,void 0),B([x()],X.prototype,`loading`,void 0),B([x()],X.prototype,`accessLoading`,void 0),B([x()],X.prototype,`sessiondLoading`,void 0),B([x()],X.prototype,`pluginLoading`,void 0),B([x()],X.prototype,`packageLoading`,void 0),B([x()],X.prototype,`saving`,void 0),B([x()],X.prototype,`packageOperation`,void 0),B([x()],X.prototype,`error`,void 0),B([x()],X.prototype,`accessError`,void 0),B([x()],X.prototype,`sessiondError`,void 0),B([x()],X.prototype,`pluginError`,void 0),B([x()],X.prototype,`packageError`,void 0),B([x()],X.prototype,`savedMessage`,void 0),B([x()],X.prototype,`packageMessage`,void 0),X=B([y(`settings-dialog`)],X);function AT(e){return e instanceof Error?e.message:String(e)}var jT=h`
|
|
3332
3341
|
:host { display: flex; flex-direction: column; min-height: 0; color: var(--pi-text); background: var(--pi-bg); font: 13px system-ui, sans-serif; container-type: inline-size; }
|
|
3333
3342
|
header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
|
|
3334
3343
|
.workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
|
|
@@ -3387,7 +3396,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3387
3396
|
.image-preview img { display: block; max-width: 100%; max-height: 100%; object-fit: contain; border: 1px solid var(--pi-border-muted); border-radius: 8px; background-color: var(--pi-surface); background-image: linear-gradient(45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(-45deg, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 25%, transparent 25%), linear-gradient(45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%), linear-gradient(-45deg, transparent 75%, color-mix(in srgb, var(--pi-border-muted) 45%, transparent) 75%); background-position: 0 0, 0 8px, 8px -8px, -8px 0; background-size: 16px 16px; box-shadow: 0 8px 24px var(--pi-shadow-soft); }
|
|
3388
3397
|
pre { margin: 0; padding: 10px; overflow: auto; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
3389
3398
|
p { margin: 10px; }
|
|
3390
|
-
`,
|
|
3399
|
+
`,MT=class extends v{constructor(...e){super(...e),this.tool=`core:workspace.files`,this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>void 0,this.workspaceHeaderCanScrollLeft=!1,this.workspaceHeaderCanScrollRight=!1,this.onWorkspaceHeaderScroll=()=>{this.updateWorkspaceHeaderScrollState()}}firstUpdated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}updated(){this.observeWorkspaceHeaderStrip(),this.updateWorkspaceHeaderScrollState()}disconnectedCallback(){this.workspaceHeaderResizeObserver?.disconnect(),this.workspaceHeaderResizeObserver=void 0,this.observedWorkspaceHeaderStrip=void 0,super.disconnectedCallback()}render(){if(this.workspace===void 0)return this.renderEmptyState(this.emptyState??{title:`选择工作区`,body:`选择工作区来查看文件、Git 或终端。`});let e=this.panelContext;if(e===void 0)return this.renderEmptyState({title:`工作区工具不可用`,body:`请尝试重新选择工作区。`});let t=this.panels,n=t.find(e=>e.id===this.tool)??t[0];return g`
|
|
3391
3400
|
${this.hideToolTabs?null:g`
|
|
3392
3401
|
<header>
|
|
3393
3402
|
<div class=${this.workspaceHeaderFrameClass()}>
|
|
@@ -3417,32 +3426,32 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3417
3426
|
<h2>${e.title}</h2>
|
|
3418
3427
|
${e.body===void 0?null:g`<p>${e.body}</p>`}
|
|
3419
3428
|
</section>
|
|
3420
|
-
`}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?` can-scroll-left`:``}${this.workspaceHeaderCanScrollRight?` can-scroll-right`:``}`}observeWorkspaceHeaderStrip(){let e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>`u`)&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){let e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=e!==void 0&&e.scrollLeft>1,r=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==n&&(this.workspaceHeaderCanScrollLeft=n),this.workspaceHeaderCanScrollRight!==r&&(this.workspaceHeaderCanScrollRight=r)}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=
|
|
3429
|
+
`}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?` can-scroll-left`:``}${this.workspaceHeaderCanScrollRight?` can-scroll-right`:``}`}observeWorkspaceHeaderStrip(){let e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>`u`)&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){let e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=e!==void 0&&e.scrollLeft>1,r=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==n&&(this.workspaceHeaderCanScrollLeft=n),this.workspaceHeaderCanScrollRight!==r&&(this.workspaceHeaderCanScrollRight=r)}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=jT}};B([b({attribute:!1})],MT.prototype,`workspace`,void 0),B([b({attribute:!1})],MT.prototype,`panelContext`,void 0),B([b({attribute:!1})],MT.prototype,`emptyState`,void 0),B([b()],MT.prototype,`tool`,void 0),B([b({attribute:!1})],MT.prototype,`panels`,void 0),B([b({type:Boolean})],MT.prototype,`hideToolTabs`,void 0),B([b({attribute:!1})],MT.prototype,`onSelectTool`,void 0),B([S(`.workspace-header-strip`)],MT.prototype,`workspaceHeaderStrip`,void 0),B([x()],MT.prototype,`workspaceHeaderCanScrollLeft`,void 0),B([x()],MT.prototype,`workspaceHeaderCanScrollRight`,void 0),MT=B([y(`workspace-panel`)],MT);var NT=class extends v{constructor(...e){super(...e),this.machines=[],this.canScrollLeft=!1,this.canScrollRight=!1,this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){let e=PT(this.machines),t=FT(this.machine),n=LT(this.project),r=zT(this.workspace),i=VT(this.session);return g`
|
|
3421
3430
|
<nav class=${this.contextBarClass()} aria-label="当前位置">
|
|
3422
3431
|
<span class="context-bar-label">位置</span>
|
|
3423
3432
|
<ol class="context-items" @scroll=${this.onContextScroll}>
|
|
3424
3433
|
${e?g`
|
|
3425
3434
|
<li class="context-item">
|
|
3426
|
-
<button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${
|
|
3435
|
+
<button type="button" class=${this.machine===void 0?`context-chip empty`:`context-chip`} title=${IT(this.machine)} aria-label=${`机器:${t}。打开机器选择。`} @click=${()=>{this.onOpenSection?.(`machines`)}}>
|
|
3427
3436
|
<span class="context-kind">机器</span>
|
|
3428
3437
|
<span class="context-value">${t}</span>
|
|
3429
3438
|
</button>
|
|
3430
3439
|
</li>
|
|
3431
3440
|
`:null}
|
|
3432
3441
|
<li class="context-item">
|
|
3433
|
-
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${
|
|
3442
|
+
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${RT(this.project)} aria-label=${`项目:${n}。打开项目选择。`} @click=${()=>{this.onOpenSection?.(`projects`)}}>
|
|
3434
3443
|
<span class="context-kind">项目</span>
|
|
3435
3444
|
<span class="context-value">${n}</span>
|
|
3436
3445
|
</button>
|
|
3437
3446
|
</li>
|
|
3438
3447
|
<li class="context-item">
|
|
3439
|
-
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${
|
|
3448
|
+
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${BT(this.workspace)} aria-label=${`工作区:${r}。打开工作区选择。`} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
|
|
3440
3449
|
<span class="context-kind">工作区</span>
|
|
3441
3450
|
<span class="context-value">${r}</span>
|
|
3442
3451
|
</button>
|
|
3443
3452
|
</li>
|
|
3444
3453
|
<li class="context-item">
|
|
3445
|
-
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${
|
|
3454
|
+
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${HT(this.session)} aria-label=${`会话:${i}。打开会话选择。`} @click=${()=>{this.onOpenSection?.(`sessions`)}}>
|
|
3446
3455
|
<span class="context-kind">会话</span>
|
|
3447
3456
|
<span class="context-value">${i}</span>
|
|
3448
3457
|
</button>
|
|
@@ -3482,7 +3491,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3482
3491
|
.context-kind { display: none; }
|
|
3483
3492
|
.context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
|
|
3484
3493
|
button { cursor: pointer; }
|
|
3485
|
-
`}};B([b({attribute:!1})],
|
|
3494
|
+
`}};B([b({attribute:!1})],NT.prototype,`machines`,void 0),B([b({attribute:!1})],NT.prototype,`machine`,void 0),B([b({attribute:!1})],NT.prototype,`project`,void 0),B([b({attribute:!1})],NT.prototype,`workspace`,void 0),B([b({attribute:!1})],NT.prototype,`session`,void 0),B([b({attribute:!1})],NT.prototype,`refreshControl`,void 0),B([b({attribute:!1})],NT.prototype,`onOpenSection`,void 0),B([b({attribute:!1})],NT.prototype,`onShowActions`,void 0),B([S(`.context-items`)],NT.prototype,`contextItems`,void 0),B([x()],NT.prototype,`canScrollLeft`,void 0),B([x()],NT.prototype,`canScrollRight`,void 0),NT=B([y(`app-context-bar`)],NT);function PT(e){return e.length>1}function FT(e){return e===void 0?`未选择机器`:`${e.name}${e.kind===`remote`?` · 远程`:``}`}function IT(e){return e===void 0?`未选择机器`:e.baseUrl??e.name}function LT(e){return e?.name??`未选择项目`}function RT(e){return e===void 0?`未选择项目`:`${e.name} — ${e.path}`}function zT(e){return e===void 0?`未选择工作区`:`${e.label}${e.isMain?` · 主工作区`:``} · ${e.path}`}function BT(e){return e===void 0?`未选择工作区`:`${e.label}${e.isMain?` · 主工作区`:``} — ${e.path}`}function VT(e){let t=e?.name?.trim(),n=e?.firstMessage.trim();return t!==void 0&&t!==``?t:n!==void 0&&n!==``?n:e===void 0?`未选择会话`:sv(e.id)}function HT(e){return e===void 0?`未选择会话`:e.path}var UT=class extends v{constructor(...e){super(...e),this.tabs=[],this.selectedView=`chat`,this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.mobileTabsResizeObserver?.disconnect(),this.mobileTabsResizeObserver=void 0,this.observedMobileTabs=void 0,super.disconnectedCallback()}firstUpdated(){this.observeMobileTabs(),this.updateScrollState()}updated(){this.observeMobileTabs(),this.updateScrollState()}render(){let e=this.fallbackLabels();return g`
|
|
3486
3495
|
<div class=${this.frameClass()}>
|
|
3487
3496
|
<div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
|
|
3488
3497
|
${this.tabs.map(t=>{let n=this.selectedView===t.id;return g`
|
|
@@ -3521,12 +3530,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3521
3530
|
.tab-label { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; }
|
|
3522
3531
|
.tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
|
|
3523
3532
|
}
|
|
3524
|
-
`}};B([b({attribute:!1})],
|
|
3533
|
+
`}};B([b({attribute:!1})],UT.prototype,`tabs`,void 0),B([b({attribute:!1})],UT.prototype,`selectedView`,void 0),B([b({attribute:!1})],UT.prototype,`onSelect`,void 0),B([S(`.mobile-tabs`)],UT.prototype,`mobileTabs`,void 0),B([x()],UT.prototype,`canScrollLeft`,void 0),B([x()],UT.prototype,`canScrollRight`,void 0),UT=B([y(`app-mobile-main-tabs`)],UT);var WT=class extends v{constructor(...e){super(...e),this.machines=[],this.statuses={},this.activities={},this.unreadMachineIds=new Set,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=GT(e,this.statuses),n=e.name;return g`
|
|
3525
3534
|
<div class="machine-switcher">
|
|
3526
3535
|
<button
|
|
3527
3536
|
type="button"
|
|
3528
3537
|
class="machine-switcher-button"
|
|
3529
|
-
title=${
|
|
3538
|
+
title=${qT(e)}
|
|
3530
3539
|
aria-label=${this.machineSwitcherAriaLabel(e)}
|
|
3531
3540
|
aria-expanded=${String(this.open)}
|
|
3532
3541
|
@click=${e=>{this.toggleMenu(e.currentTarget)}}
|
|
@@ -3537,7 +3546,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3537
3546
|
<span class="machine-switcher-kicker">机器</span>
|
|
3538
3547
|
<span class="machine-switcher-label">${n}</span>
|
|
3539
3548
|
</span>
|
|
3540
|
-
<span class=${`machine-status ${t}`}>${
|
|
3549
|
+
<span class=${`machine-status ${t}`}>${KT(t)}</span>
|
|
3541
3550
|
<span class="machine-chevron" aria-hidden="true">▾</span>
|
|
3542
3551
|
</button>
|
|
3543
3552
|
${this.open?g`
|
|
@@ -3546,18 +3555,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3546
3555
|
</div>
|
|
3547
3556
|
`:null}
|
|
3548
3557
|
</div>
|
|
3549
|
-
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=
|
|
3558
|
+
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=GT(e,this.statuses),r=W_(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return g`
|
|
3550
3559
|
<div class=${`machine-option ${t?`selected`:``} ${r?``:`no-actions`}`}>
|
|
3551
3560
|
<button
|
|
3552
3561
|
type="button"
|
|
3553
3562
|
class="machine-option-main"
|
|
3554
|
-
title=${
|
|
3563
|
+
title=${qT(e)}
|
|
3555
3564
|
data-machine-id=${e.id}
|
|
3556
3565
|
@click=${()=>{this.select(e)}}
|
|
3557
3566
|
@keydown=${e=>{this.handleMachineOptionKeydown(e)}}
|
|
3558
3567
|
>
|
|
3559
3568
|
<span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
|
|
3560
|
-
<small>${e.kind===`local`?`本地 PI WEB`:e.baseUrl??`远程 PI WEB`} · ${
|
|
3569
|
+
<small>${e.kind===`local`?`本地 PI WEB`:e.baseUrl??`远程 PI WEB`} · ${KT(n)}</small>
|
|
3561
3570
|
</button>
|
|
3562
3571
|
${r?g`
|
|
3563
3572
|
<div class="machine-option-actions">
|
|
@@ -3577,7 +3586,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3577
3586
|
</div>
|
|
3578
3587
|
`:null}
|
|
3579
3588
|
</div>
|
|
3580
|
-
`}renderActivity(e){let t=
|
|
3589
|
+
`}renderActivity(e){let t=GT(e,this.statuses),n=t===`offline`||t===`error`?void 0:Ms(this.activities[e.id]),r=this.unreadMachineIds.has(e.id)?`此机器上有未读会话`:void 0;return b_(n,n===`terminal`?`机器终端活动中`:`机器活动中`,r)}selectedMachine(){return this.selected??this.machines.find(e=>e.id===`local`)??this.machines[0]}machineSwitcherAriaLabel(e){return`机器:${e.name}。切换机器。`}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=JT(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=JT(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=w_(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`
|
|
3581
3590
|
:host { min-width: 0; display: block; }
|
|
3582
3591
|
.machine-switcher { min-width: 0; }
|
|
3583
3592
|
.machine-switcher-button { box-sizing: border-box; width: 100%; min-width: 0; display: flex; align-items: center; gap: 6px; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 8px; cursor: pointer; text-align: left; }
|
|
@@ -3613,10 +3622,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3613
3622
|
.machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
|
|
3614
3623
|
.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); }
|
|
3615
3624
|
@keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
|
|
3616
|
-
`}};B([b({attribute:!1})],
|
|
3625
|
+
`}};B([b({attribute:!1})],WT.prototype,`machines`,void 0),B([b({attribute:!1})],WT.prototype,`selected`,void 0),B([b({attribute:!1})],WT.prototype,`statuses`,void 0),B([b({attribute:!1})],WT.prototype,`activities`,void 0),B([b({attribute:!1})],WT.prototype,`unreadMachineIds`,void 0),B([b({attribute:!1})],WT.prototype,`onSelect`,void 0),B([b({attribute:!1})],WT.prototype,`onRemove`,void 0),B([b({attribute:!1})],WT.prototype,`onFocusNextSection`,void 0),B([b({attribute:!1})],WT.prototype,`onCancelKeyboardNavigation`,void 0),B([x()],WT.prototype,`open`,void 0),B([x()],WT.prototype,`menuStyle`,void 0),B([x()],WT.prototype,`openActionsMachineId`,void 0),B([x()],WT.prototype,`actionMenuStyle`,void 0),WT=B([y(`machine-switcher`)],WT);function GT(e,t){return t[e.id]?.status??e.status??`unknown`}function KT(e){return e===`online`?`在线`:e===`offline`?`离线`:e===`error`?`错误`:`未知`}function qT(e){return e.baseUrl??e.name}function JT(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: ${YT(t.bottom)};`,`left: ${YT(r)};`,`width: ${YT(n)};`,`max-height: ${YT(i)};`].join(` `)}function YT(e){return`${String(Math.round(e))}px`}var Z=class extends v{constructor(...e){super(...e),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.pinnedSessionIds=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.unreadSessionIds=new Set,this.unreadPresence=Tp,this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.startingSessionCount=0,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.canCleanupSessions=!1,this.authoritativeSessionPersistence=!1,this.archivedDeleteUnavailableMessage=`请更新并重启此机器上的 Pi-Web 后再删除已归档会话。`,this.cleanupUnavailableMessage=`请更新并重启此机器上的 Pi-Web 后再清理会话。`}async focusSection(e){switch(await this.updateComplete,e){case`machines`:return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case`projects`:return await this.focusNavigableSection(this.projectList);case`workspaces`:return await this.focusNavigableSection(this.workspaceList);case`sessions`:return await this.focusNavigableSection(this.sessionList)}}render(){return g`
|
|
3617
3626
|
<header>
|
|
3618
3627
|
<strong>PI WEB</strong>
|
|
3619
|
-
${
|
|
3628
|
+
${QT(this.machines)?g`
|
|
3620
3629
|
<machine-switcher
|
|
3621
3630
|
.machines=${this.machines}
|
|
3622
3631
|
.selected=${this.selectedMachine}
|
|
@@ -3634,7 +3643,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3634
3643
|
<button title="显示操作" aria-label="显示操作" @click=${()=>{this.onShowActions?.()}}>操作</button>
|
|
3635
3644
|
</div>
|
|
3636
3645
|
</header>
|
|
3637
|
-
${this.compact&&
|
|
3646
|
+
${this.compact&&QT(this.machines)?g`
|
|
3638
3647
|
<machine-list
|
|
3639
3648
|
.machines=${this.machines}
|
|
3640
3649
|
.selected=${this.selectedMachine}
|
|
@@ -3682,6 +3691,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3682
3691
|
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
3683
3692
|
></workspace-list>
|
|
3684
3693
|
<session-list
|
|
3694
|
+
.scopeKey=${XT(this.selectedMachine?.id,this.selectedWorkspace?.id)}
|
|
3685
3695
|
.sessions=${this.sessions}
|
|
3686
3696
|
.pinnedSessionIds=${this.pinnedSessionIds}
|
|
3687
3697
|
.statuses=${this.sessionStatuses}
|
|
@@ -3714,7 +3724,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3714
3724
|
.onDeleteArchivedMany=${e=>this.onDeleteArchivedSessions?.(e)}
|
|
3715
3725
|
.onRename=${(e,t)=>this.onRenameSession?.(e,t)}
|
|
3716
3726
|
.onDetachParent=${e=>this.onDetachParentSession?.(e)}
|
|
3717
|
-
.parentLocation=${this.parentSessionLocation??
|
|
3727
|
+
.parentLocation=${this.parentSessionLocation??ZT}
|
|
3718
3728
|
.onGoToParent=${this.onGoToParentSession===void 0?void 0:(e,t)=>this.onGoToParentSession?.(e,t)}
|
|
3719
3729
|
.onMarkRead=${e=>this.onMarkSessionRead?.(e)}
|
|
3720
3730
|
.onMarkReadMany=${e=>this.onMarkSessionsRead?.(e)}
|
|
@@ -3724,7 +3734,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3724
3734
|
.onFocusNextSection=${()=>{this.focusNextFrom(`sessions`)}}
|
|
3725
3735
|
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
3726
3736
|
></session-list>
|
|
3727
|
-
`}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t
|
|
3737
|
+
`}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=$T(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(eE(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
|
|
3728
3738
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
|
|
3729
3739
|
:host([compact]) { flex: 1 1 auto; }
|
|
3730
3740
|
header { flex: 0 0 auto; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
|
|
@@ -3747,7 +3757,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3747
3757
|
:host([compact]) workspace-list[collapsed],
|
|
3748
3758
|
:host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
3749
3759
|
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
3750
|
-
`}};B([b({attribute:!1})],Z.prototype,`machines`,void 0),B([b({attribute:!1})],Z.prototype,`selectedMachine`,void 0),B([b({attribute:!1})],Z.prototype,`machineStatuses`,void 0),B([b({attribute:!1})],Z.prototype,`machineActivities`,void 0),B([b({attribute:!1})],Z.prototype,`projects`,void 0),B([b({attribute:!1})],Z.prototype,`selectedProject`,void 0),B([b({attribute:!1})],Z.prototype,`workspaces`,void 0),B([b({attribute:!1})],Z.prototype,`selectedWorkspace`,void 0),B([b({attribute:!1})],Z.prototype,`sessions`,void 0),B([b({attribute:!1})],Z.prototype,`pinnedSessionIds`,void 0),B([b({attribute:!1})],Z.prototype,`selectedSession`,void 0),B([b({attribute:!1})],Z.prototype,`workspaceActivities`,void 0),B([b({attribute:!1})],Z.prototype,`sessionActivities`,void 0),B([b({attribute:!1})],Z.prototype,`sessionStatuses`,void 0),B([b({attribute:!1})],Z.prototype,`sendingPrompts`,void 0),B([b({attribute:!1})],Z.prototype,`unreadSessionIds`,void 0),B([b({attribute:!1})],Z.prototype,`unreadPresence`,void 0),B([b({attribute:!1})],Z.prototype,`workspacesByProjectId`,void 0),B([b({attribute:!1})],Z.prototype,`deletingWorkspaceIds`,void 0),B([b({attribute:!1})],Z.prototype,`workspaceLabelItems`,void 0),B([b({attribute:!1})],Z.prototype,`refreshControl`,void 0),B([b({type:Boolean,reflect:!0})],Z.prototype,`collapsible`,void 0),B([b({type:Boolean,reflect:!0})],Z.prototype,`compact`,void 0),B([b({type:Boolean})],Z.prototype,`machinesCollapsed`,void 0),B([b({type:Boolean})],Z.prototype,`projectsCollapsed`,void 0),B([b({type:Boolean})],Z.prototype,`workspacesCollapsed`,void 0),B([b({type:Boolean})],Z.prototype,`sessionsCollapsed`,void 0),B([b({type:Number})],Z.prototype,`startingSessionCount`,void 0),B([b({type:Boolean})],Z.prototype,`canStartSession`,void 0),B([b({type:Boolean})],Z.prototype,`canDeleteArchivedSessions`,void 0),B([b({type:Boolean})],Z.prototype,`canReloadSessions`,void 0),B([b({type:Boolean})],Z.prototype,`canCleanupSessions`,void 0),B([b({type:Boolean})],Z.prototype,`authoritativeSessionPersistence`,void 0),B([b({type:String})],Z.prototype,`archivedDeleteUnavailableMessage`,void 0),B([b({type:String})],Z.prototype,`cleanupUnavailableMessage`,void 0),B([b({attribute:!1})],Z.prototype,`onShowActions`,void 0),B([b({attribute:!1})],Z.prototype,`onToggleMachines`,void 0),B([b({attribute:!1})],Z.prototype,`onToggleProjects`,void 0),B([b({attribute:!1})],Z.prototype,`onToggleWorkspaces`,void 0),B([b({attribute:!1})],Z.prototype,`onToggleSessions`,void 0),B([b({attribute:!1})],Z.prototype,`onSelectProject`,void 0),B([b({attribute:!1})],Z.prototype,`onCloseProject`,void 0),B([b({attribute:!1})],Z.prototype,`onSelectWorkspace`,void 0),B([b({attribute:!1})],Z.prototype,`onDeleteWorkspace`,void 0),B([b({attribute:!1})],Z.prototype,`onStartSession`,void 0),B([b({attribute:!1})],Z.prototype,`onSelectSession`,void 0),B([b({attribute:!1})],Z.prototype,`onSearchSessions`,void 0),B([b({attribute:!1})],Z.prototype,`onToggleSessionPin`,void 0),B([b({attribute:!1})],Z.prototype,`onArchiveSession`,void 0),B([b({attribute:!1})],Z.prototype,`onArchiveSessionWithDescendants`,void 0),B([b({attribute:!1})],Z.prototype,`onArchiveSessions`,void 0),B([b({attribute:!1})],Z.prototype,`onRestoreSession`,void 0),B([b({attribute:!1})],Z.prototype,`onDeleteCachedNewSession`,void 0),B([b({attribute:!1})],Z.prototype,`onDeleteArchivedSession`,void 0),B([b({attribute:!1})],Z.prototype,`onDeleteArchivedSessions`,void 0),B([b({attribute:!1})],Z.prototype,`onRenameSession`,void 0),B([b({attribute:!1})],Z.prototype,`onDetachParentSession`,void 0),B([b({attribute:!1})],Z.prototype,`parentSessionLocation`,void 0),B([b({attribute:!1})],Z.prototype,`onGoToParentSession`,void 0),B([b({attribute:!1})],Z.prototype,`onMarkSessionRead`,void 0),B([b({attribute:!1})],Z.prototype,`onMarkSessionsRead`,void 0),B([b({attribute:!1})],Z.prototype,`onReloadSession`,void 0),B([b({attribute:!1})],Z.prototype,`onCleanupSessions`,void 0),B([b({attribute:!1})],Z.prototype,`onArchivedCollapsed`,void 0),B([b({attribute:!1})],Z.prototype,`onSelectMachine`,void 0),B([b({attribute:!1})],Z.prototype,`onRemoveMachine`,void 0),B([b({attribute:!1})],Z.prototype,`onFocusNavigationTarget`,void 0),B([b({attribute:!1})],Z.prototype,`onCancelKeyboardNavigation`,void 0),B([S(`machine-list`)],Z.prototype,`machineList`,void 0),B([S(`machine-switcher`)],Z.prototype,`machineSwitcher`,void 0),B([S(`project-list`)],Z.prototype,`projectList`,void 0),B([S(`workspace-list`)],Z.prototype,`workspaceList`,void 0),B([S(`session-list`)],Z.prototype,`sessionList`,void 0),Z=B([y(`app-navigation-panel`)],Z);var
|
|
3760
|
+
`}};B([b({attribute:!1})],Z.prototype,`machines`,void 0),B([b({attribute:!1})],Z.prototype,`selectedMachine`,void 0),B([b({attribute:!1})],Z.prototype,`machineStatuses`,void 0),B([b({attribute:!1})],Z.prototype,`machineActivities`,void 0),B([b({attribute:!1})],Z.prototype,`projects`,void 0),B([b({attribute:!1})],Z.prototype,`selectedProject`,void 0),B([b({attribute:!1})],Z.prototype,`workspaces`,void 0),B([b({attribute:!1})],Z.prototype,`selectedWorkspace`,void 0),B([b({attribute:!1})],Z.prototype,`sessions`,void 0),B([b({attribute:!1})],Z.prototype,`pinnedSessionIds`,void 0),B([b({attribute:!1})],Z.prototype,`selectedSession`,void 0),B([b({attribute:!1})],Z.prototype,`workspaceActivities`,void 0),B([b({attribute:!1})],Z.prototype,`sessionActivities`,void 0),B([b({attribute:!1})],Z.prototype,`sessionStatuses`,void 0),B([b({attribute:!1})],Z.prototype,`sendingPrompts`,void 0),B([b({attribute:!1})],Z.prototype,`unreadSessionIds`,void 0),B([b({attribute:!1})],Z.prototype,`unreadPresence`,void 0),B([b({attribute:!1})],Z.prototype,`workspacesByProjectId`,void 0),B([b({attribute:!1})],Z.prototype,`deletingWorkspaceIds`,void 0),B([b({attribute:!1})],Z.prototype,`workspaceLabelItems`,void 0),B([b({attribute:!1})],Z.prototype,`refreshControl`,void 0),B([b({type:Boolean,reflect:!0})],Z.prototype,`collapsible`,void 0),B([b({type:Boolean,reflect:!0})],Z.prototype,`compact`,void 0),B([b({type:Boolean})],Z.prototype,`machinesCollapsed`,void 0),B([b({type:Boolean})],Z.prototype,`projectsCollapsed`,void 0),B([b({type:Boolean})],Z.prototype,`workspacesCollapsed`,void 0),B([b({type:Boolean})],Z.prototype,`sessionsCollapsed`,void 0),B([b({type:Number})],Z.prototype,`startingSessionCount`,void 0),B([b({type:Boolean})],Z.prototype,`canStartSession`,void 0),B([b({type:Boolean})],Z.prototype,`canDeleteArchivedSessions`,void 0),B([b({type:Boolean})],Z.prototype,`canReloadSessions`,void 0),B([b({type:Boolean})],Z.prototype,`canCleanupSessions`,void 0),B([b({type:Boolean})],Z.prototype,`authoritativeSessionPersistence`,void 0),B([b({type:String})],Z.prototype,`archivedDeleteUnavailableMessage`,void 0),B([b({type:String})],Z.prototype,`cleanupUnavailableMessage`,void 0),B([b({attribute:!1})],Z.prototype,`onShowActions`,void 0),B([b({attribute:!1})],Z.prototype,`onToggleMachines`,void 0),B([b({attribute:!1})],Z.prototype,`onToggleProjects`,void 0),B([b({attribute:!1})],Z.prototype,`onToggleWorkspaces`,void 0),B([b({attribute:!1})],Z.prototype,`onToggleSessions`,void 0),B([b({attribute:!1})],Z.prototype,`onSelectProject`,void 0),B([b({attribute:!1})],Z.prototype,`onCloseProject`,void 0),B([b({attribute:!1})],Z.prototype,`onSelectWorkspace`,void 0),B([b({attribute:!1})],Z.prototype,`onDeleteWorkspace`,void 0),B([b({attribute:!1})],Z.prototype,`onStartSession`,void 0),B([b({attribute:!1})],Z.prototype,`onSelectSession`,void 0),B([b({attribute:!1})],Z.prototype,`onSearchSessions`,void 0),B([b({attribute:!1})],Z.prototype,`onToggleSessionPin`,void 0),B([b({attribute:!1})],Z.prototype,`onArchiveSession`,void 0),B([b({attribute:!1})],Z.prototype,`onArchiveSessionWithDescendants`,void 0),B([b({attribute:!1})],Z.prototype,`onArchiveSessions`,void 0),B([b({attribute:!1})],Z.prototype,`onRestoreSession`,void 0),B([b({attribute:!1})],Z.prototype,`onDeleteCachedNewSession`,void 0),B([b({attribute:!1})],Z.prototype,`onDeleteArchivedSession`,void 0),B([b({attribute:!1})],Z.prototype,`onDeleteArchivedSessions`,void 0),B([b({attribute:!1})],Z.prototype,`onRenameSession`,void 0),B([b({attribute:!1})],Z.prototype,`onDetachParentSession`,void 0),B([b({attribute:!1})],Z.prototype,`parentSessionLocation`,void 0),B([b({attribute:!1})],Z.prototype,`onGoToParentSession`,void 0),B([b({attribute:!1})],Z.prototype,`onMarkSessionRead`,void 0),B([b({attribute:!1})],Z.prototype,`onMarkSessionsRead`,void 0),B([b({attribute:!1})],Z.prototype,`onReloadSession`,void 0),B([b({attribute:!1})],Z.prototype,`onCleanupSessions`,void 0),B([b({attribute:!1})],Z.prototype,`onArchivedCollapsed`,void 0),B([b({attribute:!1})],Z.prototype,`onSelectMachine`,void 0),B([b({attribute:!1})],Z.prototype,`onRemoveMachine`,void 0),B([b({attribute:!1})],Z.prototype,`onFocusNavigationTarget`,void 0),B([b({attribute:!1})],Z.prototype,`onCancelKeyboardNavigation`,void 0),B([S(`machine-list`)],Z.prototype,`machineList`,void 0),B([S(`machine-switcher`)],Z.prototype,`machineSwitcher`,void 0),B([S(`project-list`)],Z.prototype,`projectList`,void 0),B([S(`workspace-list`)],Z.prototype,`workspaceList`,void 0),B([S(`session-list`)],Z.prototype,`sessionList`,void 0),Z=B([y(`app-navigation-panel`)],Z);function XT(e,t){return JSON.stringify([e??``,t??``])}var ZT=()=>({kind:`unknown`});function QT(e){return e.length>1}function $T(e,t){let n=tE(t);return n[n.indexOf(e)-1]}function eE(e,t){let n=tE(t);return n[n.indexOf(e)+1]??`chat`}function tE(e){return Eg.filter(t=>t!==`machines`||QT(e))}var nE=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),rE=420,iE=4,Q=class extends v{constructor(...e){super(...e),this.side=`navigation`,this.collapsed=!1,this.resizable=!1,this.controls=``,this.resizeLabel=`调整面板宽度`,this.expandLabel=`展开面板`,this.collapseLabel=`折叠面板`,this.lastTapAt=0}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){let e=this.collapsed?this.expandLabel:this.collapseLabel;return g`
|
|
3751
3761
|
${this.renderResizeHandle()}
|
|
3752
3762
|
<button
|
|
3753
3763
|
type="button"
|
|
@@ -3777,7 +3787,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3777
3787
|
@dblclick=${e=>{this.onResizeDoubleClick(e)}}
|
|
3778
3788
|
@keydown=${e=>{this.onResizeKeyDown(e)}}
|
|
3779
3789
|
></div>
|
|
3780
|
-
`}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)<=
|
|
3790
|
+
`}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)<=iE)&&(t.moved=!0,this.commitPanelWidth(Wg(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||!nE.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=Gg(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<=rE){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 Kg(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(Kg(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=Hg(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=h`
|
|
3781
3791
|
: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; }
|
|
3782
3792
|
:host([side="navigation"]) { grid-column: 2; }
|
|
3783
3793
|
:host([side="workspace"]) { grid-column: 4; }
|
|
@@ -3796,7 +3806,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3796
3806
|
@media (max-width: 760px) {
|
|
3797
3807
|
:host([side="navigation"]) { display: none; }
|
|
3798
3808
|
}
|
|
3799
|
-
`}};B([b({reflect:!0})],Q.prototype,`side`,void 0),B([b({type:Boolean,reflect:!0})],Q.prototype,`collapsed`,void 0),B([b({type:Boolean})],Q.prototype,`resizable`,void 0),B([b({type:Number})],Q.prototype,`panelWidth`,void 0),B([b({type:Number})],Q.prototype,`minWidth`,void 0),B([b({type:Number})],Q.prototype,`maxWidth`,void 0),B([b()],Q.prototype,`controls`,void 0),B([b()],Q.prototype,`resizeLabel`,void 0),B([b()],Q.prototype,`expandLabel`,void 0),B([b()],Q.prototype,`collapseLabel`,void 0),B([b({attribute:!1})],Q.prototype,`onToggle`,void 0),B([b({attribute:!1})],Q.prototype,`onResizeStart`,void 0),B([b({attribute:!1})],Q.prototype,`onResize`,void 0),B([b({attribute:!1})],Q.prototype,`onResizeEnd`,void 0),B([b({attribute:!1})],Q.prototype,`onReset`,void 0),Q=B([y(`app-panel-edge-control`)],Q);var
|
|
3809
|
+
`}};B([b({reflect:!0})],Q.prototype,`side`,void 0),B([b({type:Boolean,reflect:!0})],Q.prototype,`collapsed`,void 0),B([b({type:Boolean})],Q.prototype,`resizable`,void 0),B([b({type:Number})],Q.prototype,`panelWidth`,void 0),B([b({type:Number})],Q.prototype,`minWidth`,void 0),B([b({type:Number})],Q.prototype,`maxWidth`,void 0),B([b()],Q.prototype,`controls`,void 0),B([b()],Q.prototype,`resizeLabel`,void 0),B([b()],Q.prototype,`expandLabel`,void 0),B([b()],Q.prototype,`collapseLabel`,void 0),B([b({attribute:!1})],Q.prototype,`onToggle`,void 0),B([b({attribute:!1})],Q.prototype,`onResizeStart`,void 0),B([b({attribute:!1})],Q.prototype,`onResize`,void 0),B([b({attribute:!1})],Q.prototype,`onResizeEnd`,void 0),B([b({attribute:!1})],Q.prototype,`onReset`,void 0),Q=B([y(`app-panel-edge-control`)],Q);var aE=class extends v{constructor(...e){super(...e),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){let e=`完整重载页面`;return g`
|
|
3800
3810
|
<button
|
|
3801
3811
|
class="app-refresh-button"
|
|
3802
3812
|
title=${e}
|
|
@@ -3815,7 +3825,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3815
3825
|
:host, :host * { -webkit-user-select: none; user-select: none; }
|
|
3816
3826
|
.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; }
|
|
3817
3827
|
.app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
3818
|
-
`}};B([b({attribute:!1})],
|
|
3828
|
+
`}};B([b({attribute:!1})],aE.prototype,`onReload`,void 0),aE=B([y(`app-refresh-control`)],aE);var oE=h`
|
|
3819
3829
|
/* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
|
|
3820
3830
|
:host { --pi-app-safe-area-bottom: 0px; position: fixed; top: 0; right: 0; left: 0; display: block; height: 100dvh; box-sizing: border-box; overflow: hidden; padding: env(safe-area-inset-top) env(safe-area-inset-right) var(--pi-app-safe-area-bottom) env(safe-area-inset-left); color: var(--pi-text); background: var(--pi-bg); font: 14px system-ui, sans-serif; }
|
|
3821
3831
|
:host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
|
|
@@ -3914,7 +3924,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3914
3924
|
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
3915
3925
|
.empty { margin: auto; color: var(--pi-muted); }
|
|
3916
3926
|
.error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
|
|
3917
|
-
`,JT=900*1e3,YT=750,XT=[1e3,3e3,8e3,15e3,3e4],ZT={capture:!0},QT=`auto:on`,$T=`auto:off`,eE=`theme:`,tE=ns(`core:workspace.files`),nE=ns(`core:workspace.git`),rE=ns(`core:workspace.terminal`),iE=320,aE=2,oE=`(min-width: 1181px)`,$=class extends v{constructor(...e){super(...e),this.state=Io(),this.apiScope=cE(),this.sessionUnread=new _p({onChange:e=>{this.syncUnreadPresence(),L(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(L(this.state),this.state.sessions),this.unreadPresence=Tp,this.unreadConnected=!1,this.notifications=new qd(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new $u(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Bu,{socket:new hu(this.apiScope),notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},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.projectActivityOwnership=new Fs(()=>this.state,e=>{this.setState(e)},{api:Qa,onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Jo(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new Zo(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)},{scope:this.apiScope}),this.workspaces=new tf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new $d),this.projects=new Ds(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new ws(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebStatusController=new Ls(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}),this.files=new hs(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Cs(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Tf,this.realtime=new gu(this.apiScope),this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new sf,this.terminalSelection=new bf,this.appShell=new _g(this),this.browserResume=new xg({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new Lg(this),this.panelResize=new Vg(this),this.navigationSections=new Pg(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=sE(),this.pluginLoads=new sg((e,t)=>this.registerExternalPlugins(e,t),(e,t)=>this.plugins.shouldLoadRemotePlugin(e,t)),this.themePreference=Kp()??Hp,this.activeThemeId=Vp,this.isRefreshingApp=!1,this.sessionSearchDialogOpen=!1,this.settingsSection=c_(),this.normalAuthLoading=!0,this.normalAuthError=``,this.shortcutConfig={},this.workspaceUploadDefaultFolder=go(void 0),this.sessionWarningVisibility=Fp(),this.authenticatedAppRunning=!1,this.normalAuthInitSeq=0,this.onPopState=()=>void this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)}),this.onPageShow=()=>{this.renegotiateUnreadMachines(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.previousStackedWorkspaceLayout=this.appShell.isStackedWorkspaceLayout,this.onKeyDown=e=>{this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.parentSessionLocationFor=e=>Zf(e,{workspaces:this.state.workspaces,workspacesByProjectId:this.state.workspacesByProjectId,projects:this.state.projects}),this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleSubmitAsk=(e,t)=>this.sessions.submitAsk(e,t),this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=Bp(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.normalizeMainViewForLayoutChange(),this.syncSessionWarningVisibility()}updated(){this.committedChatIdentity=dE(this.state),this.syncSelectedSessionReadState()}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=Lp(this.sessionWarningVisibility,e===void 0?void 0:Ko(L(this.state),e.id),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=uE(e,t);await this.updateComplete,!(!this.unreadConnected||dE(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(L(this.state),this.state.sessions);_E(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncUnreadPresence(){let e=Ep({machineIds:this.state.machines.map(e=>e.id),projectionFor:e=>this.sessionUnread.projection(e),selectedMachineId:L(this.state),projects:this.state.projects,workspaces:this.state.workspaces,workspacesByProjectId:this.state.workspacesByProjectId});Mp(e,this.unreadPresence)||(this.unreadPresence=e)}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=uE(e,t);return dE(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isChatObscured()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isChatObscured(){return this.settingsSection!==void 0||this.sessionCleanupDialog!==void 0||this.state.actionPaletteOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.treeDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.state.authDialog!==void 0}connectedCallback(){super.connectedCallback(),this.normalAuthInitSeq+=1,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,ZT),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.initializeNormalAuth(this.normalAuthInitSeq)}startAuthenticatedApp(){!this.isConnected||this.authenticatedAppRunning||(this.authenticatedAppRunning=!0,this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},JT),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()}))}async initializeNormalAuth(e){if(this.apiScope===`management`){if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthStatus={configured:!0,authenticated:!0},this.normalAuthLoading=!1,this.startAuthenticatedApp();return}this.normalAuthLoading=!0,this.normalAuthError=``;try{let t=await Ga.status();if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthStatus=t,t.authenticated&&this.startAuthenticatedApp()}catch(t){if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthError=`检查普通模式密码失败:${CE(t)}`}finally{this.isConnected&&e===this.normalAuthInitSeq&&(this.normalAuthLoading=!1)}}disconnectedCallback(){this.normalAuthInitSeq+=1,this.authenticatedAppRunning=!1,this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.unreadRuntimeRefreshes.clear(),this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,ZT),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.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.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!gE(this.state,e))return;let t=this.state;this.state={...this.state,...e},dE(t)!==dE(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),fE(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.syncUnreadPresence(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),pE(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=r_();await this.machines.loadMachines(e.machineId);let t=this.routeForSelectedMachine(e),n=this.state.machineStatuses[t.machineId??`local`];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,n)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.workspaces.refreshSelectedProjectTopology()])}schedulePiWebStatusRefresh(e=YT){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 refreshWorkspaceActivity(e=L(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){let e=this.state.machines.length===0?[L(this.state)]:this.state.machines.filter(e=>hE(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}async loadClientConfig(){try{this.applyClientConfig((await Wa.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEB config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=go(e)}async submitNormalAuth(e){let t=this.normalAuthDialogMode??this.normalAuthGateMode();if(!(t===void 0||this.normalAuthLoading)){this.normalAuthLoading=!0,this.normalAuthError=``;try{t===`setup`?await Ga.setup(e.password):t===`change`?await Ga.changePassword(e.currentPassword??``,e.password):await Ga.login(e.password);let n=await Ga.status();this.normalAuthStatus=n,this.normalAuthDialogMode=void 0,n.authenticated&&this.startAuthenticatedApp()}catch(e){this.normalAuthError=CE(e)}finally{this.normalAuthLoading=!1}}}normalAuthGateMode(){if(this.apiScope!==`management`&&this.normalAuthStatus?.authenticated!==!0)return this.normalAuthStatus?.configured===!0?`login`:`setup`}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),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.git`?await this.git.refreshGit():t===`core:workspace.terminal`&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(r_(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=L(this.state),a=e.projectId===void 0||e.projectId===``?bE():n,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=a.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);let n=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith(`machine.`)===!0&&await n,!this.isCurrentRouteRestore(o))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:this.appShell.normalizedMainView(r??e.view,e.sessionId!==void 0),selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),e.projectId===void 0||e.projectId===``){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}let i=this.state.projects.find(t=>t.id===e.projectId);if(!i){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(i,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),L(this.state)!==i&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?bE():{selectedFilePath:is(tE,`file`),selectedDiffPath:is(nE,`diff`),selectedTerminalId:is(rE,`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){i_(e,{replace:!0}),as(tE,`file`,void 0,{replace:!0}),as(nE,`diff`,void 0,{replace:!0}),as(rE,`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=SE(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>=XT.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??`远程机器`,i=this.state.machineStatuses[n]?.error??(this.state.error===``?void 0:this.state.error),a=t.exhausted===!0?`${r} 仍不可用。`:`${r} 暂不可用,正在重新连接…`;this.setState({error:`${a}${i===void 0?``:` ${i}`}`})}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){let n=e.machineId??`local`;if(this.state.selectedMachine?.id===n)return;let r=this.state.machines.find(e=>e.id===n);r!==void 0&&await this.machines.selectMachine(r,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??`local`)===(this.state.selectedMachine?.id??`local`)&&e.workspaceId!==void 0&&e.workspaceId!==``&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e===`core:workspace.files`&&await this.files.refreshFiles(),e===`core:workspace.files`&&t!==void 0&&await this.files.restoreFile(t),e===`core:workspace.git`&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await TE(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}normalizeMainViewForLayoutChange(){let e=this.previousStackedWorkspaceLayout,t=this.appShell.isStackedWorkspaceLayout;if(this.previousStackedWorkspaceLayout=t,e||!t)return;let n=this.appShell.normalizedMainView(this.state.mainView,this.state.selectedSession!==void 0);n!==this.state.mainView&&(this.setState({mainView:n}),this.updateUrl({replace:!0}))}updateUrl(e){this.rememberCurrentMachineNavigation(),i_({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(lf(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(lf(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){i_(uf(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){as(tE,`file`,e.selectedFilePath,{replace:!0}),as(nE,`diff`,e.selectedDiffPath,{replace:!0}),as(rE,`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)??cf(e.id);if(await this.restoreRouteFor(uf(r),!1,r.surface,r.view),!(n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(r)){this.machineNavigation.remember(r),this.writeMachineNavigationSnapshotToUrl(r);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==``}openWorkspaceTool(e){e===`core:workspace.terminal`&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool(`core:workspace.terminal`)}terminalCommandRunsForOrigin(e,t=L(this.state)){let n=xE(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=h_(e,{api:{runTerminalCommand:(e,n)=>eo.runTerminalCommand(e,n,t),listCommandRuns:e=>eo.listCommandRuns(e,t),getCommandRun:e=>eo.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:`找不到用于运行终端命令的机器`});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){as(rE,`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(),this.git.updatePolling()}openSettings(e=`general`){this.settingsSection=e,l_(e)}closeSettings(){this.settingsSection=void 0,l_(void 0)}navigateSettings(e){this.settingsSection=e,l_(e)}restoreSettingsRoute(){this.settingsSection=c_()}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})),this.sessions.updatePolling(),t.selectedWorkspace!==void 0&&(this.sessions.refreshPinnedSessions(t.selectedWorkspace.path,L(this.state)),this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));this.sessionUnread.retainMachines(e);for(let t of e){let e=this.state.machineRuntimes[t];if(e===void 0)continue;let n=this.unreadRuntimeRefreshes.has(t)||!e.ok?`unknown`:T(e,w.sessionsUnread)?`supported`:`unsupported`;this.sessionUnread.setCapability(t,n)&&this.sessionUnread.refresh(t)}}async renegotiateUnreadMachines(){if(!this.unreadConnected)return;let e=new Set(this.state.machines.map(e=>e.id));e.add(L(this.state)),await Promise.all([...e].map(async e=>{await this.renegotiateUnreadMachine(e)}))}renegotiateUnreadMachine(e){let t=this.unreadRuntimeRefreshes.get(e);if(t!==void 0)return t;this.sessionUnread.setCapability(e,`unknown`);let n=!1,r=Promise.resolve().then(async()=>{n=await this.machines.refreshMachineRuntime(e)!==void 0});this.unreadRuntimeRefreshes.set(e,r);let i=()=>{this.unreadRuntimeRefreshes.get(e)===r&&(this.unreadRuntimeRefreshes.delete(e),this.unreadConnected&&(n?this.syncSessionUnreadMachines():this.sessionUnread.setCapability(e,`unknown`)))};return r.then(i,i),r}connectRealtime(){let e=L(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.renegotiateUnreadMachine(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t),this.refreshWorkspaceActivity(e)},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new gu(this.apiScope);e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=L(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>mE(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity):yE(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){if(this.apiScope===`management`)return;let t=L(this.state);try{let n=await eo.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=vE(e),r=vE(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&(this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebStatus:void 0}),this.sessions.updatePolling(),this.git.updatePolling(),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
|
|
3927
|
+
`,sE=900*1e3,cE=750,lE=[1e3,3e3,8e3,15e3,3e4],uE={capture:!0},dE=`auto:on`,fE=`auto:off`,pE=`theme:`,mE=ns(`core:workspace.files`),hE=ns(`core:workspace.git`),gE=ns(`core:workspace.terminal`),_E=320,vE=2,yE=`(min-width: 1181px)`,$=class extends v{constructor(...e){super(...e),this.state=Io(),this.apiScope=xE(),this.sessionUnread=new _p({onChange:e=>{this.syncUnreadPresence(),L(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(L(this.state),this.state.sessions),this.unreadPresence=Tp,this.unreadConnected=!1,this.notifications=new qd(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new $u(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Bu,{socket:new hu(this.apiScope),notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},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.projectActivityOwnership=new Fs(()=>this.state,e=>{this.setState(e)},{api:Qa,onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Jo(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.auth=new Zo(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)},{scope:this.apiScope}),this.workspaces=new tf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new $d),this.projects=new Ds(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new ws(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebStatusController=new Ls(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}),this.files=new hs(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Cs(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Tf,this.realtime=new gu(this.apiScope),this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new sf,this.terminalSelection=new bf,this.appShell=new _g(this),this.browserResume=new xg({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new Lg(this),this.panelResize=new Vg(this),this.navigationSections=new Pg(this,()=>this.state,()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.refreshingWorkspaceDeletionRuns=!1,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.plugins=bE(),this.pluginLoads=new sg((e,t)=>this.registerExternalPlugins(e,t),(e,t)=>this.plugins.shouldLoadRemotePlugin(e,t)),this.themePreference=Kp()??Hp,this.activeThemeId=Vp,this.isRefreshingApp=!1,this.sessionSearchDialogOpen=!1,this.settingsSection=c_(),this.normalAuthLoading=!0,this.normalAuthError=``,this.shortcutConfig={},this.workspaceUploadDefaultFolder=go(void 0),this.sessionWarningVisibility=Fp(),this.authenticatedAppRunning=!1,this.normalAuthInitSeq=0,this.onPopState=()=>void this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)}),this.onPageShow=()=>{this.renegotiateUnreadMachines(),this.appShell.repairViewportPosition(),this.retryPendingRemoteRouteRestoreSoon()},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.previousStackedWorkspaceLayout=this.appShell.isStackedWorkspaceLayout,this.onKeyDown=e=>{this.settingsSection!==void 0||this.state.treeDialog!==void 0||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.parentSessionLocationFor=e=>Zf(e,{workspaces:this.state.workspaces,workspacesByProjectId:this.state.workspacesByProjectId,projects:this.state.projects}),this.handleSendPrompt=(e,t,n,r)=>{this.sendPrompt(e,t,n,r)},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleSubmitAsk=(e,t)=>this.sessions.submitAsk(e,t),this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=Bp(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleSelectThinking=()=>{this.openThinkingDialog()}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.normalizeMainViewForLayoutChange(),this.syncSessionWarningVisibility()}updated(){this.committedChatIdentity=wE(this.state),this.syncSelectedSessionReadState()}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=Lp(this.sessionWarningVisibility,e===void 0?void 0:Ko(L(this.state),e.id),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=CE(e,t);await this.updateComplete,!(!this.unreadConnected||wE(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(L(this.state),this.state.sessions);AE(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncUnreadPresence(){let e=Ep({machineIds:this.state.machines.map(e=>e.id),projectionFor:e=>this.sessionUnread.projection(e),selectedMachineId:L(this.state),projects:this.state.projects,workspaces:this.state.workspaces,workspacesByProjectId:this.state.workspacesByProjectId});Mp(e,this.unreadPresence)||(this.unreadPresence=e)}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=CE(e,t);return wE(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isChatObscured()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isChatObscured(){return this.settingsSection!==void 0||this.sessionCleanupDialog!==void 0||this.state.actionPaletteOpen||this.state.projectDialogOpen||this.state.machineDialogOpen||this.state.commandDialog!==void 0||this.state.treeDialog!==void 0||this.state.modelDialog!==void 0||this.state.thinkingDialog!==void 0||this.state.themeDialog!==void 0||this.state.authDialog!==void 0}connectedCallback(){super.connectedCallback(),this.normalAuthInitSeq+=1,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,uE),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.initializeNormalAuth(this.normalAuthInitSeq)}startAuthenticatedApp(){!this.isConnected||this.authenticatedAppRunning||(this.authenticatedAppRunning=!0,this.connectRealtime(),this.renegotiateUnreadMachines(),this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},sE),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()}))}async initializeNormalAuth(e){if(this.apiScope===`management`){if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthStatus={configured:!0,authenticated:!0},this.normalAuthLoading=!1,this.startAuthenticatedApp();return}this.normalAuthLoading=!0,this.normalAuthError=``;try{let t=await Ga.status();if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthStatus=t,t.authenticated&&this.startAuthenticatedApp()}catch(t){if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthError=`检查普通模式密码失败:${IE(t)}`}finally{this.isConnected&&e===this.normalAuthInitSeq&&(this.normalAuthLoading=!1)}}disconnectedCallback(){this.normalAuthInitSeq+=1,this.authenticatedAppRunning=!1,this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.unreadRuntimeRefreshes.clear(),this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),window.removeEventListener(`pageshow`,this.onPageShow),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,uE),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.notifications.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.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.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!kE(this.state,e))return;let t=this.state;this.state={...this.state,...e},wE(t)!==wE(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),TE(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.syncUnreadPresence(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),EE(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=r_();await this.machines.loadMachines(e.machineId);let t=this.routeForSelectedMachine(e),n=this.state.machineStatuses[t.machineId??`local`];t!==e&&this.replaceRouteAndClearWorkspaceQuery(t),await this.projects.loadProjects(),await this.withChatScrollTransition(()=>this.restoreRouteFor(t,!1)),this.shouldDeferRemoteRouteRestore(t,n)?this.deferRemoteRouteRestore(t):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){await this.renegotiateUnreadMachines(),await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns(),this.workspaces.refreshSelectedProjectTopology()])}schedulePiWebStatusRefresh(e=cE){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 refreshWorkspaceActivity(e=L(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){let e=this.state.machines.length===0?[L(this.state)]:this.state.machines.filter(e=>OE(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}async loadClientConfig(){try{this.applyClientConfig((await Wa.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEB config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=go(e)}async submitNormalAuth(e){let t=this.normalAuthDialogMode??this.normalAuthGateMode();if(!(t===void 0||this.normalAuthLoading)){this.normalAuthLoading=!0,this.normalAuthError=``;try{t===`setup`?await Ga.setup(e.password):t===`change`?await Ga.changePassword(e.currentPassword??``,e.password):await Ga.login(e.password);let n=await Ga.status();this.normalAuthStatus=n,this.normalAuthDialogMode=void 0,n.authenticated&&this.startAuthenticatedApp()}catch(e){this.normalAuthError=IE(e)}finally{this.normalAuthLoading=!1}}}normalAuthGateMode(){if(this.apiScope!==`management`&&this.normalAuthStatus?.authenticated!==!0)return this.normalAuthStatus?.configured===!0?`login`:`setup`}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),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.git`?await this.git.refreshGit():t===`core:workspace.terminal`&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(r_(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=L(this.state),a=e.projectId===void 0||e.projectId===``?NE():n,o=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=a.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);let n=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith(`machine.`)===!0&&await n,!this.isCurrentRouteRestore(o))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:this.appShell.normalizedMainView(r??e.view,e.sessionId!==void 0),selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),e.projectId===void 0||e.projectId===``){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}let i=this.state.projects.find(t=>t.id===e.projectId);if(!i){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(i,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(o))return;this.setState({selectedFilePath:a.selectedFilePath,selectedDiffPath:a.selectedDiffPath,selectedTerminalId:a.selectedTerminalId}),a.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(a.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,a.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0),L(this.state)!==i&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?NE():{selectedFilePath:is(mE,`file`),selectedDiffPath:is(hE,`diff`),selectedTerminalId:is(gE,`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){i_(e,{replace:!0}),as(mE,`file`,void 0,{replace:!0}),as(hE,`diff`,void 0,{replace:!0}),as(gE,`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=FE(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>=lE.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??`远程机器`,i=this.state.machineStatuses[n]?.error??(this.state.error===``?void 0:this.state.error),a=t.exhausted===!0?`${r} 仍不可用。`:`${r} 暂不可用,正在重新连接…`;this.setState({error:`${a}${i===void 0?``:` ${i}`}`})}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){let n=e.machineId??`local`;if(this.state.selectedMachine?.id===n)return;let r=this.state.machines.find(e=>e.id===n);r!==void 0&&await this.machines.selectMachine(r,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??`local`)===(this.state.selectedMachine?.id??`local`)&&e.workspaceId!==void 0&&e.workspaceId!==``&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e===`core:workspace.files`&&await this.files.refreshFiles(),e===`core:workspace.files`&&t!==void 0&&await this.files.restoreFile(t),e===`core:workspace.git`&&await this.git.refreshGit()}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await RE(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}normalizeMainViewForLayoutChange(){let e=this.previousStackedWorkspaceLayout,t=this.appShell.isStackedWorkspaceLayout;if(this.previousStackedWorkspaceLayout=t,e||!t)return;let n=this.appShell.normalizedMainView(this.state.mainView,this.state.selectedSession!==void 0);n!==this.state.mainView&&(this.setState({mainView:n}),this.updateUrl({replace:!0}))}updateUrl(e){this.rememberCurrentMachineNavigation(),i_({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(lf(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(lf(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){i_(uf(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){as(mE,`file`,e.selectedFilePath,{replace:!0}),as(hE,`diff`,e.selectedDiffPath,{replace:!0}),as(gE,`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)??cf(e.id);if(await this.restoreRouteFor(uf(r),!1,r.surface,r.view),!(n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(r)){this.machineNavigation.remember(r),this.writeMachineNavigationSnapshotToUrl(r);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==``}openWorkspaceTool(e){e===`core:workspace.terminal`&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool(`core:workspace.terminal`)}terminalCommandRunsForOrigin(e,t=L(this.state)){let n=PE(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=h_(e,{api:{runTerminalCommand:(e,n)=>eo.runTerminalCommand(e,n,t),listCommandRuns:e=>eo.listCommandRuns(e,t),getCommandRun:e=>eo.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:`找不到用于运行终端命令的机器`});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){as(gE,`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(),this.git.updatePolling()}openSettings(e=`general`){this.settingsSection=e,l_(e)}closeSettings(){this.settingsSection=void 0,l_(void 0)}navigateSettings(e){this.settingsSection=e,l_(e)}restoreSettingsRoute(){this.settingsSection=c_()}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})),this.sessions.updatePolling(),t.selectedWorkspace!==void 0&&(this.sessions.refreshPinnedSessions(t.selectedWorkspace.path,L(this.state)),this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));this.sessionUnread.retainMachines(e);for(let t of e){let e=this.state.machineRuntimes[t];if(e===void 0)continue;let n=this.unreadRuntimeRefreshes.has(t)||!e.ok?`unknown`:T(e,w.sessionsUnread)?`supported`:`unsupported`;this.sessionUnread.setCapability(t,n)&&this.sessionUnread.refresh(t)}}async renegotiateUnreadMachines(){if(!this.unreadConnected)return;let e=new Set(this.state.machines.map(e=>e.id));e.add(L(this.state)),await Promise.all([...e].map(async e=>{await this.renegotiateUnreadMachine(e)}))}renegotiateUnreadMachine(e){let t=this.unreadRuntimeRefreshes.get(e);if(t!==void 0)return t;this.sessionUnread.setCapability(e,`unknown`);let n=!1,r=Promise.resolve().then(async()=>{n=await this.machines.refreshMachineRuntime(e)!==void 0});this.unreadRuntimeRefreshes.set(e,r);let i=()=>{this.unreadRuntimeRefreshes.get(e)===r&&(this.unreadRuntimeRefreshes.delete(e),this.unreadConnected&&(n?this.syncSessionUnreadMachines():this.sessionUnread.setCapability(e,`unknown`)))};return r.then(i,i),r}connectRealtime(){let e=L(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.renegotiateUnreadMachine(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t),this.refreshWorkspaceActivity(e)},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new gu(this.apiScope);e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=L(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>DE(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity):ME(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){if(this.apiScope===`management`)return;let t=L(this.state);try{let n=await eo.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=jE(e),r=jE(t);n&&!r&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&(this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.sessionCleanupDialog=void 0,this.setState({piWebStatus:void 0}),this.sessions.updatePolling(),this.git.updatePolling(),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e===`core:workspace.files`&&this.files.refreshFiles(),e===`core:workspace.git`&&this.git.refreshGit()}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
|
|
3918
3928
|
<workspace-panel
|
|
3919
3929
|
id="workspace-panel"
|
|
3920
3930
|
.workspace=${e}
|
|
@@ -3960,7 +3970,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3960
3970
|
.onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
|
|
3961
3971
|
.onReset=${()=>{this.resetResizablePanel(`workspace`)}}
|
|
3962
3972
|
></app-panel-edge-control>
|
|
3963
|
-
`}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-
|
|
3973
|
+
`}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-vE-_E);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(yE).matches}measuredPanelWidth(e){let t=(e===`navigation`?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return t===void 0||t<=0?void 0:t}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){let e=this.selectedMachineRuntime();return e?.ok!==!0||T(e,w.sessionsDeleteArchived)}canReloadSessions(){let e=this.selectedMachineRuntime();return e?.ok===!0&&T(e,w.sessionsReload)}canClearServerQueue(){let e=this.selectedMachineRuntime();return e?.ok===!0&&T(e,w.sessionsClearQueue)}canCleanupSessions(){let e=this.selectedMachineRuntime();return this.apiScope===`management`&&this.state.selectedProject===void 0?!1:e?.ok===!0&&T(e,w.sessionsCleanup)}hasAuthoritativeSessionPersistence(){return Du(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=L(this.state)){if(e===`local`)return!0;let t=this.state.machineRuntimes[e];return t?.ok===!0&&T(t,w.workspaceFileSuggestions)}archivedDeleteUnavailableMessage(){return`请更新并重启 ${this.state.selectedMachine?.name??`此机器`} 上的 Pi-Web 后再删除已归档会话。`}sessionCleanupUnavailableMessage(){return fp(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[L(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:``}}openSessionSearchDialog(){this.sessions.searchSessions(``),this.sessionSearchDialogOpen=!0}closeSessionSearchDialog(){this.sessionSearchDialogOpen=!1,this.sessions.searchSessions(``)}async selectSessionSearchMatch(e,t){let n=this.state.sessionSearchQuery.trim();this.sessionSearchDialogOpen=!1,await this.selectNavigationItem(`sessions`,`chat`,()=>this.sessions.selectSearchMatch(e,t,n))}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){let t=this.sessionCleanupRequestForCurrentProject(e);if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}let n=L(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let e=await $a.cleanupPreview(t,n);if(L(this.state)!==n)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:e,previewRequest:t,result:void 0,loading:!1,error:``}}catch(e){L(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`预览清理失败:${IE(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupRequestForCurrentProject(e),n=this.sessionCleanupDialog;if(n?.preview===void 0||ap(n.previewRequest)!==ap(t)){this.sessionCleanupDialog={...n??{},error:`运行清理前请先预览。`};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...n,error:this.sessionCleanupUnavailableMessage(),running:!1};return}let r=L(this.state);this.sessionCleanupDialog={...n,running:!0,error:``};try{let e=await $a.cleanup(t,r);if(L(this.state)!==r)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:e,previewRequest:t,result:e,running:!1,error:``},await this.sessions.applySessionCleanupResult(e,r)}catch(e){L(this.state)===r&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`运行清理失败:${IE(e)}`})}}sessionCleanupRequestForCurrentProject(e){if(this.apiScope!==`management`)return e;let t=this.state.selectedProject,n=t===void 0?[]:this.state.workspaces.filter(e=>e.projectId===t.id).map(e=>e.path),r=e.projectCwds??n,i=new Set(n);return{...e,projectId:t?.id??``,projectCwds:r.filter(e=>i.has(e))}}renderNavigationPanel(){return g`
|
|
3964
3974
|
<app-navigation-panel
|
|
3965
3975
|
.machines=${this.state.machines}
|
|
3966
3976
|
.selectedMachine=${this.state.selectedMachine}
|
|
@@ -4031,14 +4041,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4031
4041
|
.onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
|
|
4032
4042
|
.onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
|
|
4033
4043
|
></app-navigation-panel>
|
|
4034
|
-
`}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await n()},i),i()&&await this.focusNavigationTarget(t)}async goToParentSession(e){e.kind===`workspace`&&await this.selectNavigationItem(`sessions`,`chat`,async()=>{let t=this.state.workspaces.find(t=>t.id===e.workspaceId);if(t!==void 0){await this.workspaces.selectWorkspace(t,{sessionId:e.sessionId});return}let n=this.state.projects.find(t=>t.id===e.projectId);n!==void 0&&await this.workspaces.selectProject(n,{workspaceId:e.workspaceId,sessionId:e.sessionId})})}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}async startSessionAndOpenChat(e=()=>!0){this.sessions.startSession().catch(t=>{e()&&this.setState({error:String(t)})}),e()&&await this.focusChatComposer()}async focusNavigationTarget(e){if(e===`chat`){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e===`machines`&&!
|
|
4044
|
+
`}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq;await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await n()},i),i()&&await this.focusNavigationTarget(t)}async goToParentSession(e){e.kind===`workspace`&&await this.selectNavigationItem(`sessions`,`chat`,async()=>{let t=this.state.workspaces.find(t=>t.id===e.workspaceId);if(t!==void 0){await this.workspaces.selectWorkspace(t,{sessionId:e.sessionId});return}let n=this.state.projects.find(t=>t.id===e.projectId);n!==void 0&&await this.workspaces.selectProject(n,{workspaceId:e.workspaceId,sessionId:e.sessionId})})}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}async startSessionAndOpenChat(e=()=>!0){this.sessions.startSession().catch(t=>{e()&&this.setState({error:String(t)})}),e()&&await this.focusChatComposer()}async focusNavigationTarget(e){if(e===`chat`){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e===`machines`&&!QT(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 RE(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!==`chat`&&this.selectMainView(`chat`),await this.updateComplete,await RE(),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}closeSessionTreeNavigator(){this.sessions.closeTreeDialog(),this.focusChatComposer()}renderSessionTreeNavigator(e){return e.treeDialog===void 0?null:g`
|
|
4035
4045
|
<session-tree-navigator
|
|
4036
4046
|
.tree=${e.treeDialog}
|
|
4037
4047
|
.onNavigate=${(e,t)=>this.navigateSessionTree(e,t)}
|
|
4038
4048
|
.onAbort=${()=>this.sessions.abortTreeNavigation()}
|
|
4039
4049
|
.onCancel=${()=>{this.closeSessionTreeNavigator()}}
|
|
4040
4050
|
></session-tree-navigator>
|
|
4041
|
-
`}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:`正在加载项目…`,body:`正在查找你已添加到 PI WEB 的项目。`}:e===void 0?this.state.projects.length===0?{title:`还没有项目`,body:`使用“操作 → 添加项目”添加文件夹。选择工作区后,工作区工具会显示在这里。`}:{title:`选择项目`,body:`从侧边栏选择一个项目,然后选择工作区来查看文件、Git 或终端。`}:this.state.isLoadingWorkspaces?{title:`正在加载工作区…`,body:`正在为 ${e.name} 准备工作区工具。`}:this.state.workspaces.length===0?{title:`未找到工作区`,body:`${e.name} 没有可用工作区。请尝试重新选择该项目,或重新添加它。`}:{title:`选择工作区`,body:`选择 ${e.name} 中的工作区,以查看文件、Git 或终端。`}}sessionEmptyMessage(){return this.state.isLoadingProjects?`正在加载项目…`:this.state.selectedWorkspace===void 0?this.state.selectedProject===void 0?this.state.projects.length===0?`添加项目以启动会话。`:`选择项目和工作区以开始会话。`:`选择工作区以启动会话。`:`选择或启动会话。`}mobilePanelBadge(e){let t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}mobilePanelIcon(e){switch(e.id){case`core:workspace.files`:return`files`;case`core:workspace.git`:return`git`;case`core:workspace.terminal`:return`terminal`;default:return}}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){let t=lE(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:n=>Qa.workspaceFile(e.projectId,e.id,n,t),readOptionalFile:n=>Qa.optionalWorkspaceFile(e.projectId,e.id,n,t),listFiles:n=>Qa.workspaceTree(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await Qa.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await Qa.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await Qa.moveWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){let t=lE(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return Uh({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),prompt:this.createPromptEditor(),terminal:{open:t=>{this.openRuntimeTerminal(n,e,t)},runCommand:t=>a.runCommand({...t,workspace:e})},openTerminal:t=>{this.openRuntimeTerminal(n,e,t)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:a},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:_o(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onCreateFile:e=>{this.files.createFile(e)},onCreateDirectory:e=>{this.files.createDirectory(e)},onMoveSelectedPath:e=>{this.files.moveSelectedPath(e)},onDeleteSelectedPath:()=>{this.files.deleteSelectedPath()},onDownloadSelectedFile:()=>{this.files.downloadSelectedFile()},onExpandDir:e=>{this.files.expandDir(e)},onSelectDirectory:e=>{this.files.selectDirectory(e)},onSelectFile:e=>{this.files.selectFile(e)},onStartWorkspaceUpload:(e,t)=>this.files.startWorkspaceUpload(e,t),onCancelWorkspaceUpload:e=>{this.files.cancelWorkspaceUpload(e)},onClearWorkspaceUpload:e=>{this.files.clearWorkspaceUpload(e)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:e=>{this.git.selectDiff(e)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(`core`)}getActions(){return f_(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.normalAuthActions(),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}normalAuthActions(){return this.apiScope===`management`?[]:[{id:`app.normal-auth.change-password`,title:`修改普通模式密码`,description:`更改进入普通模式所需的本地密码`,group:`偏好设置`,enabled:this.normalAuthStatus?.authenticated===!0,run:()=>{this.normalAuthDialogMode=`change`,this.normalAuthError=``}}]}sessionActions(){return[{id:`app.sessions.cleanup`,title:`清理会话`,description:`预览并手动清理所选机器上的空闲或已归档会话`,group:`会话`,...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.reset-navigation-panel-size`,title:`重置导航面板宽度`,description:`将导航面板恢复为默认宽度`,group:`视图`,run:()=>{this.resetResizablePanel(`navigation`)}},{id:`app.layout.reset-workspace-panel-size`,title:`重置工作区面板宽度`,description:`将工作区面板恢复为默认宽度`,group:`视图`,run:()=>{this.resetResizablePanel(`workspace`)}},{id:`app.layout.reset-panel-sizes`,title:`重置面板宽度`,description:`将所有侧边面板恢复为默认宽度`,group:`视图`,run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:`app.navigation.focus-machines`,title:`聚焦机器`,description:`将键盘焦点移到机器选择器`,shortcut:`mod+g m`,group:`导航`,run:()=>this.focusNavigationSection(`machines`)},{id:`app.navigation.focus-projects`,title:`聚焦项目`,description:`将键盘焦点移到项目列表`,shortcut:`mod+g p`,group:`导航`,run:()=>this.focusNavigationSection(`projects`)},{id:`app.navigation.focus-workspaces`,title:`聚焦工作区`,description:`将键盘焦点移到工作区列表`,shortcut:`mod+g w`,group:`导航`,run:()=>this.focusNavigationSection(`workspaces`)},{id:`app.navigation.focus-sessions`,title:`聚焦会话`,description:`将键盘焦点移到会话列表`,shortcut:`mod+g s`,group:`导航`,run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){return this.pluginLoads.ensureGatewayLoaded().then(()=>void 0)}async loadPluginsForSelectedMachine(){let e=this.state.selectedMachine;e?.kind===`remote`&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){await this.pluginLoads.loadForMachine(e)}async registerExternalPlugins(e,t){try{let e=await t();for(let t of e)try{this.plugins.register(t)}catch(e){console.warn(`Failed to register PI WEB plugin ${t.id}`,e)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(t){return console.warn(`Failed to load ${e}`,t),!1}}createPromptEditor(){return{insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){let e=t=>Hh({state:this.state,prompt:this.createPromptEditor(),piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:e=>{this.openSettings(e)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},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(),refreshGit:()=>this.git.refreshGit(),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:()=>this.sessions.stopActiveWork()},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!nf(e)){this.setState({error:`只能删除辅助 Git 工作树`});return}if(cm(this.state,e))return;let t=e.branch??e.label;if(!confirm(`删除工作区 ${t}?\n\n此操作将运行 git worktree remove 并删除:\n${e.path}\n\n不会删除 Git 分支。`))return;let n=L(this.state);try{let t=await Qa.deleteWorkspace(e.projectId,e.id,n);if(L(this.state)!==n)return;this.recordWorkspaceDeletionRun(t,n);let r=await this.workspaceForCommandRun(t);if(L(this.state)!==n)return;r!==void 0&&this.openRuntimeTerminal(n,r,{terminalId:t.terminalId})}catch(e){L(this.state)===n&&this.setState({error:`启动工作区删除失败:${CE(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=lm(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(am(t.id));if(L(this.state)!==e)return;let r=om(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))um(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(um);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=xE(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=lm(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:wE(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&(this.setState({error:`工作区删除失败。请查看终端输出。`}),this.updateWorkspaceDeletionPolling())}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(`移除 ${e.name}?\n\n这只会从当前 PI WEB 网关移除它。`))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:`操作失败:${n}`})})}async openModelDialog(){let e=await this.sessions.listModels(),t=this.state.status?.model?.provider,n=this.state.status?.model?.id;this.setState({modelDialog:{title:`选择模型`,...t!==void 0&&n!==void 0?{selectedValue:`${t}/${n}`}:{},options:e.map(e=>{let r=e.provider??``,i=e.id??``,a=r===t&&i===n;return{value:`${r}/${i}`,label:`${i}${a?` ✓ 当前`:``}`,description:r}})}})}async pickModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?$T:QT;this.setState({themeDialog:{title:`选择主题`,selectedValue:n===void 0?r:`${eE}${n}`,options:[{value:r,label:`自动 ${this.themePreference.auto?`✓ 开启`:`关闭`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${eE}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===QT||e===$T){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===QT},this.applyPreferredTheme(!0);return}if(!e.startsWith(eE))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,Jp(t),e&&qp(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Yp({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return Zp(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?`当所选主题有配对主题时,跟随系统明暗偏好。`:e.selectedThemePair===void 0?`已开启,但所选主题没有明暗配对,因此会保持当前主题。`:`已开启 · ${e.selectedThemePair.name} 跟随系统${this.systemPrefersLight()?`浅色`:`深色`}偏好。`}themeOptionLabel(e,t){let n=[...e.id===t?[`已选择`]:[],...e.id===this.activeThemeId&&e.id!==t?[`生效中`]:[]];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(`自动配对`),e.description!==void 0&&t.push(e.description),t.join(` · `)}async openThinkingDialog(){let e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??`off`;this.setState({thinkingDialog:{title:`选择思考级别`,selectedValue:t,options:e.map(e=>{let n=Uo(e);return{value:e,label:`${Ho(e)}${e===t?` ✓ 当前`:``}`,...n===void 0?{}:{description:n}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==``&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t,n,r){!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,n,r)}renderChatView(e,t){return g`
|
|
4051
|
+
`}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:`正在加载项目…`,body:`正在查找你已添加到 PI WEB 的项目。`}:e===void 0?this.state.projects.length===0?{title:`还没有项目`,body:`使用“操作 → 添加项目”添加文件夹。选择工作区后,工作区工具会显示在这里。`}:{title:`选择项目`,body:`从侧边栏选择一个项目,然后选择工作区来查看文件、Git 或终端。`}:this.state.isLoadingWorkspaces?{title:`正在加载工作区…`,body:`正在为 ${e.name} 准备工作区工具。`}:this.state.workspaces.length===0?{title:`未找到工作区`,body:`${e.name} 没有可用工作区。请尝试重新选择该项目,或重新添加它。`}:{title:`选择工作区`,body:`选择 ${e.name} 中的工作区,以查看文件、Git 或终端。`}}sessionEmptyMessage(){return this.state.isLoadingProjects?`正在加载项目…`:this.state.selectedWorkspace===void 0?this.state.selectedProject===void 0?this.state.projects.length===0?`添加项目以启动会话。`:`选择项目和工作区以开始会话。`:`选择工作区以启动会话。`:`选择或启动会话。`}mobilePanelBadge(e){let t=this.state.selectedWorkspace;if(t!==void 0)return e.badge?.(this.createWorkspacePanelContext(t))}mobilePanelIcon(e){switch(e.id){case`core:workspace.files`:return`files`;case`core:workspace.git`:return`git`;case`core:workspace.terminal`:return`terminal`;default:return}}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){let t=SE(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:n=>Qa.workspaceFile(e.projectId,e.id,n,t),readOptionalFile:n=>Qa.optionalWorkspaceFile(e.projectId,e.id,n,t),listFiles:n=>Qa.workspaceTree(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await Qa.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await Qa.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await Qa.moveWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){let t=SE(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i,n);return Uh({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,n),prompt:this.createPromptEditor(),terminal:{open:t=>{this.openRuntimeTerminal(n,e,t)},runCommand:t=>a.runCommand({...t,workspace:e})},openTerminal:t=>{this.openRuntimeTerminal(n,e,t)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:a},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,workspaceUploadDefaultFolder:_o(e.effectiveConfig,this.workspaceUploadDefaultFolder),onRefreshFiles:()=>{this.files.refreshFiles()},onCreateFile:e=>{this.files.createFile(e)},onCreateDirectory:e=>{this.files.createDirectory(e)},onMoveSelectedPath:e=>{this.files.moveSelectedPath(e)},onDeleteSelectedPath:()=>{this.files.deleteSelectedPath()},onDownloadSelectedFile:()=>{this.files.downloadSelectedFile()},onExpandDir:e=>{this.files.expandDir(e)},onSelectDirectory:e=>{this.files.selectDirectory(e)},onSelectFile:e=>{this.files.selectFile(e)},onStartWorkspaceUpload:(e,t)=>this.files.startWorkspaceUpload(e,t),onCancelWorkspaceUpload:e=>{this.files.cancelWorkspaceUpload(e)},onClearWorkspaceUpload:e=>{this.files.clearWorkspaceUpload(e)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:e=>{this.git.selectDiff(e)},onSelectTerminal:(e,t)=>{this.selectTerminal(e,t)}},r)};return r(`core`)}getActions(){return f_(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.normalAuthActions(),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}normalAuthActions(){return this.apiScope===`management`?[]:[{id:`app.normal-auth.change-password`,title:`修改普通模式密码`,description:`更改进入普通模式所需的本地密码`,group:`偏好设置`,enabled:this.normalAuthStatus?.authenticated===!0,run:()=>{this.normalAuthDialogMode=`change`,this.normalAuthError=``}}]}sessionActions(){return[{id:`app.sessions.cleanup`,title:`清理会话`,description:`预览并手动清理所选机器上的空闲或已归档会话`,group:`会话`,...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.reset-navigation-panel-size`,title:`重置导航面板宽度`,description:`将导航面板恢复为默认宽度`,group:`视图`,run:()=>{this.resetResizablePanel(`navigation`)}},{id:`app.layout.reset-workspace-panel-size`,title:`重置工作区面板宽度`,description:`将工作区面板恢复为默认宽度`,group:`视图`,run:()=>{this.resetResizablePanel(`workspace`)}},{id:`app.layout.reset-panel-sizes`,title:`重置面板宽度`,description:`将所有侧边面板恢复为默认宽度`,group:`视图`,run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:`app.navigation.focus-machines`,title:`聚焦机器`,description:`将键盘焦点移到机器选择器`,shortcut:`mod+g m`,group:`导航`,run:()=>this.focusNavigationSection(`machines`)},{id:`app.navigation.focus-projects`,title:`聚焦项目`,description:`将键盘焦点移到项目列表`,shortcut:`mod+g p`,group:`导航`,run:()=>this.focusNavigationSection(`projects`)},{id:`app.navigation.focus-workspaces`,title:`聚焦工作区`,description:`将键盘焦点移到工作区列表`,shortcut:`mod+g w`,group:`导航`,run:()=>this.focusNavigationSection(`workspaces`)},{id:`app.navigation.focus-sessions`,title:`聚焦会话`,description:`将键盘焦点移到会话列表`,shortcut:`mod+g s`,group:`导航`,run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){return this.pluginLoads.ensureGatewayLoaded().then(()=>void 0)}async loadPluginsForSelectedMachine(){let e=this.state.selectedMachine;e?.kind===`remote`&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){await this.pluginLoads.loadForMachine(e)}async registerExternalPlugins(e,t){try{let e=await t();for(let t of e)try{this.plugins.register(t)}catch(e){console.warn(`Failed to register PI WEB plugin ${t.id}`,e)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(t){return console.warn(`Failed to load ${e}`,t),!1}}createPromptEditor(){return{insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){let e=t=>Hh({state:this.state,prompt:this.createPromptEditor(),piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:e=>{this.openSettings(e)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},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(),refreshGit:()=>this.git.refreshGit(),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:()=>this.sessions.stopActiveWork()},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!nf(e)){this.setState({error:`只能删除辅助 Git 工作树`});return}if(cm(this.state,e))return;let t=e.branch??e.label;if(!confirm(`删除工作区 ${t}?\n\n此操作将运行 git worktree remove 并删除:\n${e.path}\n\n不会删除 Git 分支。`))return;let n=L(this.state);try{let t=await Qa.deleteWorkspace(e.projectId,e.id,n);if(L(this.state)!==n)return;this.recordWorkspaceDeletionRun(t,n);let r=await this.workspaceForCommandRun(t);if(L(this.state)!==n)return;r!==void 0&&this.openRuntimeTerminal(n,r,{terminalId:t.terminalId})}catch(e){L(this.state)===n&&this.setState({error:`启动工作区删除失败:${IE(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=lm(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(am(t.id));if(L(this.state)!==e)return;let r=om(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))um(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(um);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=PE(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=lm(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:LE(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&(this.setState({error:`工作区删除失败。请查看终端输出。`}),this.updateWorkspaceDeletionPolling())}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(`移除 ${e.name}?\n\n这只会从当前 PI WEB 网关移除它。`))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:`操作失败:${n}`})})}async openModelDialog(){let e=await this.sessions.listModels(),t=this.state.status?.model?.provider,n=this.state.status?.model?.id;this.setState({modelDialog:{title:`选择模型`,...t!==void 0&&n!==void 0?{selectedValue:`${t}/${n}`}:{},options:e.map(e=>{let r=e.provider??``,i=e.id??``,a=r===t&&i===n;return{value:`${r}/${i}`,label:`${i}${a?` ✓ 当前`:``}`,description:r}})}})}async pickModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?fE:dE;this.setState({themeDialog:{title:`选择主题`,selectedValue:n===void 0?r:`${pE}${n}`,options:[{value:r,label:`自动 ${this.themePreference.auto?`✓ 开启`:`关闭`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${pE}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===dE||e===fE){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===dE},this.applyPreferredTheme(!0);return}if(!e.startsWith(pE))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,Jp(t),e&&qp(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Yp({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return Zp(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?`当所选主题有配对主题时,跟随系统明暗偏好。`:e.selectedThemePair===void 0?`已开启,但所选主题没有明暗配对,因此会保持当前主题。`:`已开启 · ${e.selectedThemePair.name} 跟随系统${this.systemPrefersLight()?`浅色`:`深色`}偏好。`}themeOptionLabel(e,t){let n=[...e.id===t?[`已选择`]:[],...e.id===this.activeThemeId&&e.id!==t?[`生效中`]:[]];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(`自动配对`),e.description!==void 0&&t.push(e.description),t.join(` · `)}async openThinkingDialog(){let e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??`off`;this.setState({thinkingDialog:{title:`选择思考级别`,selectedValue:t,options:e.map(e=>{let n=Uo(e);return{value:e,label:`${Ho(e)}${e===t?` ✓ 当前`:``}`,...n===void 0?{}:{description:n}}})}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==``&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t,n,r){!(n!==void 0&&n.length>0)&&t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t,n,r)}renderChatView(e,t){return g`
|
|
4042
4052
|
<chat-view .sessionId=${t.id} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .searchTarget=${e.sessionSearchTarget} .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} .askDraftSessionId=${Ko(L(e),t.id)} .onSubmitAsk=${this.handleSubmitAsk} .notificationInbox=${Od(e.selectedNotificationInbox)} .canClearServerQueue=${this.canClearServerQueue()} .onClearServerQueue=${this.handleClearServerQueue} .onDismissWarning=${this.handleDismissWarning} .onDismissNotification=${this.handleDismissNotification} .onDismissAllNotifications=${this.handleDismissAllNotifications} .warningsVisible=${!this.sessionWarningVisibility.collapsed} .onToggleWarnings=${this.handleToggleWarnings} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
|
|
4043
4053
|
`}renderStatusBar(e){let t=this.sessionWarningVisibility.warningCount;return g`
|
|
4044
4054
|
<status-bar .status=${e.status} .warningCount=${t} .warningsExpanded=${t>0&&!this.sessionWarningVisibility.collapsed} .onToggleWarnings=${this.handleToggleWarnings}></status-bar>
|
|
@@ -4059,7 +4069,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4059
4069
|
.selectedView=${this.state.mainView}
|
|
4060
4070
|
.onSelect=${e=>{this.selectMainView(e)}}
|
|
4061
4071
|
></app-mobile-main-tabs>
|
|
4062
|
-
`}mobileMainTabs(){let e=
|
|
4072
|
+
`}mobileMainTabs(){let e=uv(this.state.sessions,this.unreadSessionIds);return[{id:`navigation`,label:`会话`,icon:`navigation`,className:`navigation-tab`,...e===0?{}:{badge:e,badgeLabel:`${String(e)} unread`,badgeTone:`unread`}},{id:`chat`,label:`聊天`,icon:`chat`},...this.visibleWorkspacePanels().map(e=>{let t=e.icon??this.mobilePanelIcon(e);return{id:e.id,label:e.title,...t===void 0?{}:{icon:t},badge:this.mobilePanelBadge(e)}})]}renderAppRefresh(){return g`<app-refresh-control .onReload=${()=>{this.hardReloadApp()}}></app-refresh-control>`}render(){let e=this.state,t=this.normalAuthGateMode();return this.apiScope===`normal`&&(t!==void 0||this.normalAuthStatus===void 0)?this.renderNormalAuthDialog(t??`login`):g`
|
|
4063
4073
|
<div class=${this.panelCollapse.shellClass(e.mainView)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints(`navigation`),workspace:this.resizablePanelConstraints(`workspace`)})}>
|
|
4064
4074
|
<aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
|
|
4065
4075
|
${this.renderNavigationPanelEdgeControl()}
|
|
@@ -4098,4 +4108,4 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4098
4108
|
.onSubmit=${e=>{this.submitNormalAuth(e)}}
|
|
4099
4109
|
.onCancel=${()=>{this.normalAuthDialogMode=void 0,this.normalAuthError=``}}
|
|
4100
4110
|
></normal-auth-dialog>
|
|
4101
|
-
`}static{this.styles=
|
|
4111
|
+
`}static{this.styles=oE}};B([x()],$.prototype,`state`,void 0),B([S(`chat-view`)],$.prototype,`chatView`,void 0),B([S(`prompt-editor`)],$.prototype,`promptEditor`,void 0),B([S(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),B([S(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),B([S(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),B([x()],$.prototype,`unreadSessionIds`,void 0),B([x()],$.prototype,`unreadPresence`,void 0),B([x()],$.prototype,`activeThemeId`,void 0),B([x()],$.prototype,`isRefreshingApp`,void 0),B([x()],$.prototype,`sessionCleanupDialog`,void 0),B([x()],$.prototype,`sessionSearchDialogOpen`,void 0),B([x()],$.prototype,`settingsSection`,void 0),B([x()],$.prototype,`normalAuthStatus`,void 0),B([x()],$.prototype,`normalAuthLoading`,void 0),B([x()],$.prototype,`normalAuthError`,void 0),B([x()],$.prototype,`normalAuthDialogMode`,void 0),B([x()],$.prototype,`shortcutConfig`,void 0),B([x()],$.prototype,`workspaceUploadDefaultFolder`,void 0),$=B([y(`pi-web-app`)],$);function bE(){let e=new zh;return e.register({id:`core`,plugin:Ah}),e.register({id:`themes`,plugin:Ph}),e}function xE(){let e=vt()?`management`:`normal`;return Nt(e),e}function SE(e){let t=e.selectedMachine;return t===void 0?{id:`local`,name:`本机`,kind:`local`}:{id:t.id,name:t.name,kind:t.kind}}function CE(e,t){return JSON.stringify([e,t.id,t.cwd])}function wE(e){let t=e.selectedSession;return t===void 0?void 0:CE(L(e),t)}function TE(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function EE(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function DE(e,t){return OE(e,t)}function OE(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function kE(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function AE(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function jE(e){return Lo(e.status,e.activity)}function ME(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function NE(){return{}}function PE(e,t){return JSON.stringify([e,t])}function FE(e){return lE[Math.min(e,lE.length-1)]??3e4}function IE(e){return e instanceof Error?e.message:String(e)}function LE(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function RE(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}export{h as _,B as a,lo as c,x as d,b as f,g,Ye as h,q_ as i,eo as l,v as m,Hv as n,Sf as o,y as p,Bv as r,xf as s,Vv as t,S as u};
|