@chainingintention/pi-web-cn 1.202609.10 → 1.202609.11
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-vh-rj4PA.js → CodeViewer-CZHnKRwQ.js} +1 -1
- package/dist/client/assets/{TerminalPanel-Bb2lTnwP.js → TerminalPanel-B_EaRPHY.js} +1 -1
- package/dist/client/assets/{index-D4FYxEQo.js → index-Bv1v-Jz7.js} +292 -292
- package/dist/client/index.html +1 -1
- package/dist/server/plugins/pluginBackendProxyRoutes.js +7 -7
- package/dist/server/plugins/pluginBackendProxyRoutes.js.map +1 -1
- package/dist/server/requestCancellation.js +15 -1
- package/dist/server/requestCancellation.js.map +1 -1
- package/dist/server/sessiond/sessionProxyRoutes.js +22 -25
- package/dist/server/sessiond/sessionProxyRoutes.js.map +1 -1
- package/dist/server/sessions/sessionNameGenerator.js +3 -2
- package/dist/server/sessions/sessionNameGenerator.js.map +1 -1
- package/dist/server/terminalProxyRoutes.js +20 -17
- package/dist/server/terminalProxyRoutes.js.map +1 -1
- package/dist/server/workspaces/workspaceDeletionRoutes.js +3 -3
- package/dist/server/workspaces/workspaceDeletionRoutes.js.map +1 -1
- package/dist/sessiond/sessionDaemonClient.js +18 -16
- package/dist/sessiond/sessionDaemonClient.js.map +1 -1
- package/dist/sessiond/sessionDaemonErrors.js +49 -0
- package/dist/sessiond/sessionDaemonErrors.js.map +1 -0
- package/package.json +7 -7
|
@@ -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-CZHnKRwQ.js","./vendor-editor-core-vUi74DnD.js","./vendor-editor-languages-DoaXUodB.js","./vendor-editor-legacy-CYBnW6ZU.js","./TerminalPanel-B_EaRPHY.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),_=qe(2),Je=Symbol.for(`lit-noChange`),v=Symbol.for(`lit-nothing`),Ye=new WeakMap,Xe=Pe.createTreeWalker(Pe,129);function Ze(e,t){if(!Le(e)||!e.hasOwnProperty(`raw`))throw Error(`invalid template strings array`);return ke===void 0?t:ke.createHTML(t)}var Qe=(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[Ze(e,a+(e[n]||`<?>`)+(t===2?`</svg>`:t===3?`</math>`:``)),r]},$e=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]=Qe(t,n);if(this.el=e.createElement(l,r),Xe.currentNode=this.el.content,n===2||n===3){let e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;(i=Xe.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]===`.`?it:r[1]===`?`?at:r[1]===`@`?ot:rt}),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()),Xe.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 et(e,t,n=e,r){if(t===Je)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=et(e,i._$AS(e,t.values),i,r)),t}var tt=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);Xe.currentNode=r;let i=Xe.nextNode(),a=0,o=0,s=n[0];for(;s!==void 0;){if(a===s.index){let t;s.type===2?t=new nt(i,i.nextSibling,this,e):s.type===1?t=new s.ctor(i,s.name,s.strings,this,e):s.type===6&&(t=new st(i,this,e)),this._$AV.push(t),s=n[++o]}a!==s?.index&&(i=Xe.nextNode(),a++)}return Xe.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++}},nt=class e{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(e,t,n,r){this.type=2,this._$AH=v,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=n,this.options=r,this._$Cv=r?.isConnected??!0}get parentNode(){let e=this._$AA.parentNode,t=this._$AM;return t!==void 0&&e?.nodeType===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=et(this,e,t),Ie(e)?e===v||e==null||e===``?(this._$AH!==v&&this._$AR(),this._$AH=v):e!==this._$AH&&e!==Je&&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!==v&&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=$e.createElement(Ze(n.h,n.h[0]),this.options)),n);if(this._$AH?._$AD===r)this._$AH.p(t);else{let e=new tt(r,this),n=e.u(this.options);e.p(t),this.T(n),this._$AH=e}}_$AC(e){let t=Ye.get(e.strings);return t===void 0&&Ye.set(e.strings,t=new $e(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))}},rt=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,n,r,i){this.type=1,this._$AH=v,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=i,n.length>2||n[0]!==``||n[1]!==``?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=v}_$AI(e,t=this,n,r){let i=this.strings,a=!1;if(i===void 0)e=et(this,e,t,0),a=!Ie(e)||e!==this._$AH&&e!==Je,a&&(this._$AH=e);else{let r=e,o,s;for(e=i[0],o=0;o<i.length-1;o++)s=et(this,r[n+o],t,o),s===Je&&(s=this._$AH[o]),a||=!Ie(s)||s!==this._$AH[o],s===v?e=v:e!==v&&(e+=(s??``)+i[o+1]),this._$AH[o]=s}a&&!r&&this.j(e)}j(e){e===v?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??``)}},it=class extends rt{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===v?void 0:e}},at=class extends rt{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==v)}},ot=class extends rt{constructor(e,t,n,r,i){super(e,t,n,r,i),this.type=5}_$AI(e,t=this){if((e=et(this,e,t,0)??v)===Je)return;let n=this._$AH,r=e===v&&n!==v||e.capture!==n.capture||e.once!==n.once||e.passive!==n.passive,i=e!==v&&(n===v||r);r&&this.element.removeEventListener(this.name,this,n),i&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){typeof this._$AH==`function`?this._$AH.call(this.options?.host??this.element,e):this._$AH.handleEvent(e)}},st=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){et(this,e)}},ct={M:Ae,P:je,A:Me,C:1,L:Qe,R:tt,D:Re,V:et,I:nt,H:rt,N:at,U:ot,B:it,F:st},lt=Ee.litHtmlPolyfillSupport;lt?.($e,nt),(Ee.litHtmlVersions??=[]).push(`3.3.3`);var ut=(e,t,n)=>{let r=n?.renderBefore??t,i=r._$litPart$;if(i===void 0){let e=n?.renderBefore??null;r._$litPart$=i=new nt(t.insertBefore(Fe(),e),e,void 0,n??{})}return i._$AI(e),i},dt=globalThis,y=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=ut(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Je}};y._$litElement$=!0,y.finalized=!0,dt.litElementHydrateSupport?.({LitElement:y});var ft=dt.litElementPolyfillSupport;ft?.({LitElement:y}),(dt.litElementVersions??=[]).push(`4.2.2`);var b=e=>(t,n)=>{n===void 0?customElements.define(e,t):n.addInitializer(()=>{customElements.define(e,t)})},pt={attribute:!0,type:String,converter:Se,reflect:!1,hasChanged:Ce},mt=(e=pt,t,n)=>{let{kind:r,metadata:i}=n,a=globalThis.litPropertyMetadata.get(i);if(a===void 0&&globalThis.litPropertyMetadata.set(i,a=new Map),r===`setter`&&((e=Object.create(e)).wrapped=!0),a.set(n.name,e),r===`accessor`){let{name:r}=n;return{set(n){let i=t.get.call(this);t.set.call(this,n),this.requestUpdate(r,i,e,!0,n)},init(t){return t!==void 0&&this.C(r,void 0,e,t),t}}}if(r===`setter`){let{name:r}=n;return function(n){let i=this[r];t.call(this,n),this.requestUpdate(r,i,e,!0,n)}}throw Error(`Unsupported decorator location: `+r)};function x(e){return(t,n)=>typeof n==`object`?mt(e,t,n):((e,t,n)=>{let r=t.hasOwnProperty(n);return t.constructor.createProperty(n,e),r?Object.getOwnPropertyDescriptor(t,n):void 0})(e,t,n)}function S(e){return x({...e,state:!0,attribute:!1})}var ht=(e,t,n)=>(n.configurable=!0,n.enumerable=!0,Reflect.decorate&&typeof t!=`object`&&Object.defineProperty(e,t,n),n);function C(e,t){return(n,r,i)=>{let a=t=>t.renderRoot?.querySelector(e)??null;if(t){let{get:e,set:t}=typeof r==`object`?n:i??(()=>{let e=Symbol();return{get(){return this[e]},set(t){this[e]=t}}})();return ht(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 ht(n,r,{get(){return a(this)}})}}var gt=`management`;function _t(e=Tt()){return wt(e)===gt}function vt(e=Et()){return _t(e?.search)?`management`:`normal`}function yt(e,t=Et(),n=`management`){return St(e,t,n,!0)}function bt(e,t=Et(),n=`management`){return St(e,t,n,!1)}function xt(e){if(e!==`management`||globalThis.history===void 0)return;let t=Et();t===void 0||Ct(t)?.token===void 0||(t.searchParams.delete(`token`),globalThis.history.replaceState(globalThis.history.state,``,`${t.pathname}${t.search}${t.hash}`))}function St(e,t,n,r){if(n===`normal`||t===void 0)return e;let i=Ct(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 Ct(e){if(e===void 0)return;let t=wt(e.search),n=e.searchParams.get(`token`)?.trim();if(t===gt)return{embed:t,...n===void 0||n===``?{}:{token:n}}}function wt(e){if(e===void 0||e===``)return;let t=new URLSearchParams(e).get(`embed`)?.trim();return t===``?void 0:t}function Tt(){return typeof window>`u`?void 0:window.location.search}function Et(){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 Dt(e,t=kt()){let n=new URL(t.viteBaseUrl,t.documentBaseUrl);return new URL(At(e),n).toString()}function Ot(e,t=kt()){let n=new URL(Dt(e,t));if(n.protocol===`http:`)n.protocol=`ws:`;else if(n.protocol===`https:`)n.protocol=`wss:`;else throw Error(`Cannot create a WebSocket URL from ${n.protocol}`);return n.toString()}function kt(){return{viteBaseUrl:`./`,documentBaseUrl:typeof document>`u`?`http://localhost/`:document.baseURI}}function At(e){return e.startsWith(`/`)?`.${e}`:e}var jt=class extends Error{constructor(e,t,n={}){super(e,n),this.status=t,this.name=`HttpRequestError`}},Mt=vt();function Nt(e){Mt=e}function Pt(e){return Dt(yt(e,void 0,Mt))}async function w(e,t,n){let r=new Headers(n?.headers);n?.body!==void 0&&!r.has(`content-type`)&&r.set(`content-type`,`application/json`);let i=await fetch(Pt(e),{...n,headers:r});if(!i.ok)throw new jt(It(await i.json().catch(()=>({})))??i.statusText,i.status);return xt(Mt),t(await i.json())}async function Ft(e,t){let n=await fetch(Pt(e));if(n.status===204){xt(Mt);return}if(n.status!==404){if(!n.ok){let e=await n.json().catch(()=>({}));throw Error(It(e)??n.statusText)}return xt(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 T={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`,pluginLifecycle:`plugins.lifecycle`},Rt=1e3,zt=32*1024,Bt=8*1024,Vt=1e3,Ht=4e3,Ut=1e3,Wt=4e3,Gt=1e4,Kt=new Set([`schemaVersion`,`revision`,`command`,`dir`,`sessionDirEnvKeys`]),qt=/^sha256:[0-9a-f]{64}$/u,Jt=/^[A-Za-z0-9_][A-Za-z0-9._+-]*$/u,Yt=new Set([`PI_WEB_AGENT_SESSION_DIR`,`PI_CODING_AGENT_SESSION_DIR`]);function Xt(e){if(!tn(e)||Object.keys(e).some(e=>!Kt.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`||!qt.test(n))&&!(typeof r!=`string`||!Zt(r))&&!(typeof i!=`string`||!Qt(i))&&en(a)&&new Set(a).size===a.length&&!(a[0]!==`PI_WEB_AGENT_SESSION_DIR`||a.some(e=>!Yt.has(e))))return Object.freeze({schemaVersion:t,revision:n,command:r,dir:i,sessionDirEnvKeys:Object.freeze([...a])})}function Zt(e){return e!==e.trim()||/[\s;&|`$<>]/u.test(e)?!1:Qt(e)?!e.endsWith(`/`)&&!e.endsWith(`\\`):Jt.test(e)}function Qt(e){if(e===``||e!==e.trim()||$t(e))return!1;let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function $t(e){for(let t of e){let e=t.charCodeAt(0);if(e<32||e===127)return!0}return!1}function en(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function tn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var nn=Object.values(T),rn=new Set(nn);T.sessionsDeleteArchived,T.sessionsBulkMutations,T.sessionsCleanup,T.sessionsReload,T.sessionsClearQueue,T.sessionsPersistedState,T.sessionsNotifications,T.sessionsUnread,T.sessionsAskUser,T.promptAttachments,T.workspaceFileSuggestions,T.piPackagesManage,T.selectedMachineSettings,T.agentProfileConfig,T.pluginLifecycle,T.sessionsDeleteArchived,T.sessionsBulkMutations,T.sessionsCleanup,T.sessionsReload,T.sessionsClearQueue,T.sessionsPersistedState,T.sessionsNotifications,T.sessionsUnread,T.sessionsAskUser,T.promptAttachments,T.sessionsDeleteArchived,T.sessionsBulkMutations,T.sessionsCleanup,T.sessionsReload,T.sessionsClearQueue,T.sessionsPersistedState,T.sessionsNotifications,T.sessionsUnread,T.sessionsAskUser,T.promptAttachments,T.workspaceFileSuggestions,T.piPackagesManage,T.selectedMachineSettings,T.agentProfileConfig,T.pluginLifecycle;function an(e){return typeof e==`string`&&rn.has(e)}function on(e){if(!(!Array.isArray(e)||!e.every(e=>typeof e==`string`)))return e.filter(an)}var sn={working:`core:working`,terminal:`core:terminal`,unread:`core:unread`};function cn(e){if(!dn(e))return;let t=e.epochId,n=e.revision,r=e.generatedAt,i=ln(e.machine),a=ln(e.unattributed),o=un(e.projects),s=un(e.workspaces);if(!(typeof t!=`string`||t===``)&&!(typeof n!=`number`||!Number.isFinite(n))&&!(typeof r!=`string`||r===``)&&!(i===void 0||a===void 0||o===void 0||s===void 0))return{epochId:t,revision:n,machine:i,projects:o,workspaces:s,unattributed:a,generatedAt:r}}function ln(e){if(!dn(e))return;let t=new Map;for(let[n,r]of Object.entries(e))typeof r==`boolean`&&t.set(n,r);return Object.fromEntries(t)}function un(e){if(!dn(e))return;let t=new Map;for(let[n,r]of Object.entries(e)){let e=ln(r);e!==void 0&&t.set(n,e)}return Object.fromEntries(t)}function dn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function fn(e){return typeof e==`object`&&!!e}function E(e){if(!fn(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 pn(e){if(!Array.isArray(e))throw Error(`Expected array response`);return e}function mn(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`))throw Error(`Expected string array field: ${t}`);return e}function hn(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};let t=E(e);return{messages:pn(t.messages),start:k(t,`start`),total:k(t,`total`)}}function gn(e){let t=E(e);return j(_n)(t.machines)}function _n(e){let t=E(e),n=bn(t,`kind`),r=O(t,`baseUrl`),i=xn(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 vn(e){let t=E(e),n=xn(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:Sa(t.web)},...t.sessiond===void 0?{}:{sessiond:Sa(t.sessiond)},...r===void 0?{}:{error:r}}}function yn(e){let t=E(e),n=O(t,`error`);return{machineId:D(t,`machineId`),ok:A(t,`ok`),checkedAt:D(t,`checkedAt`),...N(`packageName`,O(t,`packageName`)),...N(`generatedAt`,O(t,`generatedAt`)),...t.components===void 0?{}:{components:ba(t.components)},...t.capabilities===void 0?{}:{capabilities:Oa(t.capabilities)},...n===void 0?{}:{error:n}}}function bn(e,t){let n=D(e,t);if(n!==`local`&&n!==`remote`)throw Error(`Expected machine kind field: ${t}`);return n}function xn(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 Sn(e){let t=E(e);return{id:D(t,`id`),name:D(t,`name`),path:D(t,`path`),createdAt:D(t,`createdAt`)}}function Cn(e){let t=E(e),n=O(t,`branch`),r=wn(t.provider),i=Tn(t.removal);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`),...r===void 0?{}:{provider:r},...i===void 0?{}:{removal:i},...N(`effectiveConfig`,On(t.effectiveConfig))}}function wn(e){if(e===void 0)return;let t=E(e),n=E(t.capabilities),r=t.metadata===void 0?void 0:En(t.metadata,`workspace provider metadata`);return{pluginId:D(t,`pluginId`),capabilities:{request:A(n,`request`),remove:A(n,`remove`)},...r===void 0?{}:{metadata:r}}}function Tn(e){if(e===void 0)return;let t=E(e);return{actionLabel:D(t,`actionLabel`),confirmation:D(t,`confirmation`),precondition:D(t,`precondition`)}}function En(e,t){let n=Dn(e,t);if(typeof n!=`object`||!n||Array.isArray(n))throw Error(`Expected JSON object: ${t}`);return n}function Dn(e,t){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(Array.isArray(e))return e.map(e=>Dn(e,t));if(fn(e))return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Dn(n,t)]));throw Error(`Expected JSON value: ${t}`)}function On(e){if(e!==void 0){if(!fn(e)||Array.isArray(e))throw Error(`Invalid workspace effectiveConfig field`);return{...N(`uploads`,Qi(e.uploads)),...N(`attachments`,$i(e.attachments))}}}function kn(e){let t=E(e),n=O(t,`name`),r=ga(t.persisted,`persisted`),i=O(t,`parentSessionPath`),a=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},...t.archived===!0?{archived:!0}:{},...a===void 0?{}:{archivedAt:a}}}function An(e){let t=E(e);return{configured:A(t,`configured`),authenticated:A(t,`authenticated`)}}function jn(e){return{path:D(E(e),`path`)}}function Mn(e){let t=E(e);if(t.deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0,path:D(t,`path`)}}function Nn(e){return{sessionIds:mn(E(e).sessionIds,`sessionIds`)}}function Pn(e){return{pinned:A(E(e),`pinned`)}}function Fn(e){let t=E(e);return{results:j(In)(t.results),matchCount:k(t,`matchCount`),truncated:A(t,`truncated`)}}function In(e){let t=E(e);return{session:kn(t.session),matches:j(Ln)(t.matches)}}function Ln(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(Rn)(t.excerpts),occurrenceCount:k(t,`occurrenceCount`)}}function Rn(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 zn(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid session warning severity`);return e}function Bn(e){if(e!==void 0)return{id:D(E(e),`id`)}}function Vn(e){let t=E(e),n=Bn(t.dismiss);return{severity:zn(t.severity),message:D(t,`message`),...N(`source`,O(t,`source`)),...N(`path`,O(t,`path`)),...n===void 0?{}:{dismiss:n}}}function Hn(e){return e===void 0?{}:{warnings:j(Vn)(e)}}function Un(e){let t=E(e);return{value:Sr(t,`value`,128),label:Sr(t,`label`,Vt),...N(`detail`,Cr(t,`detail`,Vt))}}function Wn(e){let t=E(e),n=zr(t.options,Un,12,`options`);er(n.map(e=>e.value),`ask option value`),ga(t.allowOther,`allowOther`);let r=ga(t.multiple,`multiple`);return{id:Sr(t,`id`,128),question:Sr(t,`question`,Vt),...N(`detail`,Cr(t,`detail`,Vt)),options:n,allowOther:!0,...r===void 0?{}:{multiple:r}}}function Gn(e){let t=E(e),n=zr(t.questions,Wn,20,`questions`);if(n.length===0)throw Error(`Pending ask has no questions`);return er(n.map(e=>e.id),`ask question id`),{askId:Sr(t,`askId`,128),askedAt:M(t,`askedAt`),questions:n}}function Kn(e){return e===void 0?{}:{pendingAsk:Gn(e)}}function qn(e){let t=E(e);if(t.type!==`ask.opened`)throw Error(`Invalid ask opened event type`);return{type:`ask.opened`,ask:Gn(t.ask)}}function Jn(e){let t=E(e);if(t.type!==`ask.closed`)throw Error(`Invalid ask closed event type`);return{type:`ask.closed`,askId:Sr(t,`askId`,128),reason:Yn(t.reason)}}function Yn(e){if(e!==`submitted`&&e!==`superseded`&&e!==`cancelled`)throw Error(`Invalid ask close reason`);return e}function Xn(e){let t=E(e),n=Wn(t.question),r=zr(t.values,Br,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=Cr(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 Zn(e){let t=E(e),n=zr(t.questions,Xn,20,`questions`),r=Vr(t,`answeredCount`),i=mn(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:Sr(t,`askId`,128),reason:Yn(t.reason),askedAt:M(t,`askedAt`),closedAt:M(t,`closedAt`),questions:n,answeredCount:r,unansweredIds:i,summary:M(t,`summary`)}}function Qn(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:Zn(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Ask close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:dr(t.sessionStatus)}}function $n(e){let t=E(e),n=t.result;if(n!==`closed`&&n!==`stale`)throw Error(`Invalid dialog close result`);let r=t.outcome===void 0?void 0:lr(t.outcome);if(n===`closed`!=(r!==void 0))throw Error(`Dialog close response outcome mismatch`);return{result:n,...r===void 0?{}:{outcome:r},sessionStatus:dr(t.sessionStatus)}}function er(e,t){if(new Set(e).size!==e.length)throw Error(`Duplicate ${t}`)}function tr(e){if(e!==`confirm`&&e!==`select`&&e!==`input`)throw Error(`Invalid extension dialog kind`);return e}function nr(e){if(e!==`answered`&&e!==`cancelled`&&e!==`timeout`&&e!==`aborted`&&e!==`session-ended`)throw Error(`Invalid extension dialog close reason`);return e}function rr(e){if(typeof e==`boolean`||typeof e==`string`&&e.length<=4e3)return e;throw Error(`Invalid extension dialog answer`)}function ir(e){let t=Br(e);if(t.length>1e3)throw Error(`String field exceeds limit: option`);return t}function ar(e){let t=E(e),n=tr(t.kind),r=t.options===void 0?void 0:zr(t.options,ir,24,`options`);if(r!==void 0&&er(r,`dialog option`),n===`select`&&(r===void 0||r.length===0))throw Error(`Select dialog has no options`);return{dialogId:Sr(t,`dialogId`,128),kind:n,title:Sr(t,`title`,Ut),...N(`message`,Cr(t,`message`,Ut)),...r===void 0?{}:{options:r},...N(`placeholder`,Cr(t,`placeholder`,Ut)),askedAt:M(t,`askedAt`),...N(`timeoutAt`,ur(t,`timeoutAt`)),runScoped:A(t,`runScoped`)}}function or(e){if(e===void 0)return{};let t=j(ar)(e);return er(t.map(e=>e.dialogId),`dialog id`),{pendingDialogs:t}}function sr(e){let t=E(e);if(t.type!==`dialog.opened`)throw Error(`Invalid dialog opened event type`);return{type:`dialog.opened`,dialog:ar(t.dialog)}}function cr(e){let t=E(e);if(t.type!==`dialog.closed`)throw Error(`Invalid dialog closed event type`);let n=nr(t.reason),r=t.answer===void 0?void 0:rr(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog closed event answer mismatch`);return{type:`dialog.closed`,dialogId:Sr(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r}}}function lr(e){let t=E(e),n=nr(t.reason),r=t.answer===void 0?void 0:rr(t.answer);if(n===`answered`!=(r!==void 0))throw Error(`Dialog outcome answer mismatch`);return{dialogId:Sr(t,`dialogId`,128),reason:n,...r===void 0?{}:{answer:r},askedAt:M(t,`askedAt`),closedAt:M(t,`closedAt`)}}function ur(e,t){let n=O(e,t);if(n!==void 0){if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}}function dr(e){let t=E(e);return{sessionId:D(t,`sessionId`),...N(`persisted`,ga(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(ei)(t.queuedMessages),...N(`messageCount`,eo(t,`messageCount`)),tokens:ti(t.tokens),cost:k(t,`cost`),...ri(t.model),...Ci(t.contextUsage),...N(`thinkingLevel`,O(t,`thinkingLevel`)),...Hn(t.warnings),...Kn(t.pendingAsk),...or(t.pendingDialogs)}}function fr(e){let t=E(e);return{seq:k(t,`seq`),partial:t.partial??null}}function pr(e){let t=E(e),n=Vr(t,`catalogRevision`),r=zr(t.sessions,yr,Rt,`sessions`);if(br(r),xr(r),r.some(e=>e.completionOrder>n))throw Error(`Session unread completion order exceeds catalog revision`);return{catalogId:Sr(t,`catalogId`,512),catalogRevision:n,sessions:r}}function mr(e){let t=E(e);if(t.type!==`sessions.unread`)throw Error(`Invalid session unread event type`);let n=Sr(t,`sessionId`,512),r=Sr(t,`cwd`,zt),i=wr(t,`catalogRevision`),a=t.unread===null?null:yr(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:Sr(t,`catalogId`,512),catalogRevision:i,sessionId:n,cwd:r,unread:a}}function hr(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`,...N(`startupToken`,n),activity:gr(t.activity)}}function gr(e){let t=E(e);return{sessionId:M(t,`sessionId`),phase:vr(t,`phase`),label:M(t,`label`),...N(`detail`,O(t,`detail`)),at:M(t,`at`),...N(`startup`,_r(t))}}function _r(e){let t=e.startup;if(t!==void 0){if(typeof t!=`boolean`)throw Error(`Expected optional boolean field: startup`);return t}}function vr(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 yr(e){let t=E(e),n=Sr(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:Sr(t,`sessionId`,512),cwd:Sr(t,`cwd`,zt),completionOrder:wr(t,`completionOrder`),completedAt:n}}function br(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 xr(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 Sr(e,t,n){let r=M(e,t);if(r.length>n)throw Error(`String field exceeds limit: ${t}`);return r}function Cr(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 wr(e,t){let n=Vr(e,t);if(n===0)throw Error(`Expected positive safe integer field: ${t}`);return n}function Tr(e){let t=E(e),n=Mr(t.summary),r=zr(t.notifications,Nr,100,`notifications`);if(Hr(r),Ur(r),n.retainedCount!==r.length)throw Error(`Notification snapshot retained count mismatch`);if(n.highestSeverity!==Gr(r))throw Error(`Notification snapshot severity mismatch`);let i=Pr(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:M(t,`daemonInstanceId`),catalogRevision:Vr(t,`catalogRevision`),summary:n,notifications:r,dismissThrough:i}}function Er(e){let t=E(e);if(t.type!==`notifications.inbox`)throw Error(`Invalid notification inbox event type`);let n=Mr(t.summary),r=Pr(t.dismissThrough);if(r.overflowWatermark<n.discardedCount)throw Error(`Notification event overflow cutoff mismatch`);let i=Fr(t.delta);if(i.kind===`cleared`&&!Wr(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:M(t,`daemonInstanceId`),catalogRevision:Vr(t,`catalogRevision`),summary:n,dismissThrough:r,delta:i}}function Dr(e){let t=E(e),n=j(Ar)(t.notices),r=n.map(e=>e.id);if(new Set(r).size!==r.length)throw Error(`Duplicate server notice id`);return{daemonInstanceId:M(t,`daemonInstanceId`),revision:Vr(t,`revision`),notices:n}}function Or(e){let t=E(e);if(t.type!==`notices.updated`)throw Error(`Invalid server notice event type`);return{type:`notices.updated`,snapshot:Dr(t.snapshot)}}function kr(e){let t=E(e);if(t.type!==`models.changed`)throw Error(`Invalid model scope event type`);return{type:`models.changed`,revision:Vr(t,`revision`)}}function Ar(e){let t=E(e),n=M(t,`createdAt`);if(!Number.isFinite(Date.parse(n)))throw Error(`Invalid server notice creation time`);let r=O(t,`source`),i=t.context===void 0?void 0:En(t.context,`server notice context`);return{id:M(t,`id`),severity:jr(t.severity),message:D(t,`message`),createdAt:n,...N(`source`,r),...N(`context`,i)}}function jr(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid server notice severity`);return e}function Mr(e){let t=E(e),n=Vr(t,`retainedCount`);if(n>100)throw Error(`Notification retained count exceeds limit`);let r=Vr(t,`discardedCount`),i=Lr(t.highestSeverity);if(n===0!=(i===void 0))throw Error(`Notification summary severity mismatch`);return{sessionId:M(t,`sessionId`),cwd:M(t,`cwd`),inboxRevision:Vr(t,`inboxRevision`),retainedCount:n,discardedCount:r,...i===void 0?{}:{highestSeverity:i}}}function Nr(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=Vr(t,`order`);if(i===0)throw Error(`Invalid notification order`);return{id:M(t,`id`),message:n,truncated:A(t,`truncated`),severity:Ir(t.severity),receivedAt:r,order:i}}function Pr(e){let t=E(e);return{order:Vr(t,`order`),overflowWatermark:Vr(t,`overflowWatermark`)}}function Fr(e){let t=E(e);switch(t.kind){case`added`:{let e=O(t,`evictedNotificationId`);return{kind:`added`,notification:Nr(t.notification),...e===void 0?{}:{evictedNotificationId:e}}}case`dismissed`:{let e=zr(t.notificationIds,Br,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:Rr(t.reason)};case`resync`:return{kind:`resync`};default:throw Error(`Invalid notification inbox delta`)}}function Ir(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid notification severity`);return e}function Lr(e){return e===void 0?void 0:Ir(e)}function Rr(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 zr(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 Br(e){if(typeof e!=`string`||e===``)throw Error(`Expected non-empty string`);return e}function M(e,t){let n=D(e,t);if(n===``)throw Error(`Expected non-empty string field: ${t}`);return n}function Vr(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 Hr(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 Ur(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 Wr(e){return e.retainedCount===0&&e.discardedCount===0}function Gr(e){let t;for(let n of e){if(n.severity===`error`)return`error`;n.severity===`warning`?t=`warning`:t??=`info`}return t}function Kr(e){let t=E(e),n=t.skippedBusySessionIds===void 0?void 0:mn(t.skippedBusySessionIds,`skippedBusySessionIds`);return{generatedAt:D(t,`generatedAt`),thresholds:Zr(t.thresholds),projects:j(Qr)(t.projects),totals:$r(t.totals),...n===void 0?{}:{skippedBusySessionIds:n}}}function qr(e){let t=E(e);return{...Kr(t),archivedSessionIds:mn(t.archivedSessionIds,`archivedSessionIds`),deletedSessionIds:mn(t.deletedSessionIds,`deletedSessionIds`)}}function Jr(e){let t=E(e);if(t.archived!==!0)throw Error(`Expected bulk archived response`);return{archived:!0,archivedSessionIds:mn(t.archivedSessionIds,`archivedSessionIds`),failures:j(Xr)(t.failures),generatedAt:D(t,`generatedAt`)}}function Yr(e){let t=E(e);if(t.deleted!==!0)throw Error(`Expected bulk deleted response`);return{deleted:!0,deletedSessionIds:mn(t.deletedSessionIds,`deletedSessionIds`),failures:j(Xr)(t.failures),generatedAt:D(t,`generatedAt`)}}function Xr(e){let t=E(e);return{sessionId:D(t,`sessionId`),error:D(t,`error`)}}function Zr(e){let t=E(e);return{...N(`archiveIdleDays`,eo(t,`archiveIdleDays`)),...N(`deleteArchivedDays`,eo(t,`deleteArchivedDays`))}}function Qr(e){let t=E(e);return{cwd:D(t,`cwd`),archiveCount:k(t,`archiveCount`),deleteCount:k(t,`deleteCount`)}}function $r(e){let t=E(e);return{archiveCount:k(t,`archiveCount`),deleteCount:k(t,`deleteCount`)}}function ei(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 ti(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 ni(e){let t=E(e);return{...N(`provider`,O(t,`provider`)),...N(`id`,O(t,`id`)),...N(`name`,O(t,`name`)),...N(`contextWindow`,eo(t,`contextWindow`)),...N(`reasoning`,t.reasoning)}}function ri(e){return e===void 0?{}:{model:ni(e)}}function ii(e){let t=E(e);return{models:j(ni)(t.models)}}function ai(e){let t=E(e);return{provider:D(t,`provider`),id:D(t,`id`),...N(`name`,O(t,`name`)),...N(`contextWindow`,eo(t,`contextWindow`)),...N(`reasoning`,t.reasoning),enabled:A(t,`enabled`),...N(`editable`,$a(t,`editable`)),...N(`catalogIndex`,t.catalogIndex===void 0?void 0:Vr(t,`catalogIndex`))}}function oi(e){let t=E(e);return{models:j(ai)(t.models)}}function si(e){if(typeof e!=`string`)throw Error(`Invalid thinking level`);return e}function ci(e){let t=E(e);return{levels:j(si)(t.levels)}}function li(e){if(e!==`oauth`&&e!==`api_key`)throw Error(`Invalid auth type`);return e}function ui(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 di(e){let t=E(e),n=t.source===void 0?void 0:ui(t.source);return{configured:A(t,`configured`),...N(`source`,n),...N(`label`,O(t,`label`))}}function fi(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:li(t.authType),status:di(t.status),...n===void 0?{}:{loginFlow:n}}}function pi(e){let t=E(e);return{providers:j(fi)(t.providers)}}function mi(e){let t=E(e);return{flowId:D(t,`flowId`),providerId:D(t,`providerId`),providerName:D(t,`providerName`),status:hi(t.status),progress:j(e=>{if(typeof e!=`string`)throw Error(`Expected progress item string`);return e})(t.progress),...N(`error`,O(t,`error`)),...N(`auth`,gi(t.auth)),...N(`prompt`,vi(t.prompt)),...N(`select`,bi(t.select)),...N(`info`,xi(t.info))}}function hi(e){if(e!==`running`&&e!==`complete`&&e!==`error`&&e!==`cancelled`)throw Error(`Invalid OAuth flow status`);return e}function gi(e){if(e===void 0)return;let t=E(e);return{url:D(t,`url`),...N(`instructions`,O(t,`instructions`)),...N(`deviceCode`,_i(t.deviceCode))}}function _i(e){if(e===void 0)return;let t=E(e);return{userCode:D(t,`userCode`),...N(`intervalSeconds`,eo(t,`intervalSeconds`)),...N(`expiresInSeconds`,eo(t,`expiresInSeconds`))}}function vi(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`:yi(t.promptType);return{requestId:D(t,`requestId`),message:D(t,`message`),kind:n,promptType:r,...N(`placeholder`,O(t,`placeholder`)),...N(`allowEmpty`,$a(t,`allowEmpty`))}}function yi(e){if(e!==`text`&&e!==`secret`&&e!==`manual_code`)throw Error(`Invalid OAuth prompt type`);return e}function bi(e){if(e===void 0)return;let t=E(e);return{requestId:D(t,`requestId`),message:D(t,`message`),options:j(Ba)(t.options)}}function xi(e){if(e!==void 0)return j(e=>{let t=E(e);return{message:D(t,`message`),...N(`links`,t.links===void 0?void 0:j(Si)(t.links))}})(e)}function Si(e){let t=E(e);return{url:D(t,`url`),...N(`label`,O(t,`label`))}}function Ci(e){if(e===void 0)return{};let t=E(e);return{contextUsage:{tokens:to(t,`tokens`),contextWindow:k(t,`contextWindow`),percent:to(t,`percent`)}}}function wi(e){let t=E(e),n=D(t,`source`);if(n!==`extension`&&n!==`prompt`&&n!==`skill`&&n!==`builtin`)throw Error(`Invalid command source`);return{name:D(t,`name`),source:n,...N(`description`,O(t,`description`))}}function Ti(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 Ei(e){let t=E(e);return{path:D(t,`path`),entries:j(ki)(t.entries),scannedAt:D(t,`scannedAt`),truncated:A(t,`truncated`)}}function Di(e){let t=E(e);return{results:j(Oi)(t.results)}}function Oi(e){let t=E(e),n=D(t,`path`),r=t.tree,i=t.error;if(r===void 0==(i===void 0))throw Error(`File tree batch result must contain exactly one of tree or error`);return r===void 0?{path:n,error:D(t,`error`)}:{path:n,tree:Ei(r)}}function ki(e){let t=E(e),n=D(t,`type`);if(n!==`file`&&n!==`directory`&&n!==`symlink`)throw Error(`Invalid file tree entry type`);return{name:D(t,`name`),path:D(t,`path`),type:n,...N(`size`,eo(t,`size`)),...N(`modifiedAt`,O(t,`modifiedAt`))}}function Ai(e){let t=E(e),n=D(t,`encoding`);if(n!==`utf8`)throw Error(`Invalid file encoding`);return{path:D(t,`path`),...N(`language`,O(t,`language`)),...N(`mediaType`,Pi(t.mediaType)),...N(`mimeType`,O(t,`mimeType`)),encoding:n,size:k(t,`size`),modifiedAt:D(t,`modifiedAt`),content:D(t,`content`),truncated:A(t,`truncated`),binary:A(t,`binary`)}}function ji(e){let t=E(e);return{path:D(t,`path`),size:k(t,`size`),modifiedAt:D(t,`modifiedAt`),created:A(t,`created`)}}function Mi(e){let t=E(e);return{path:D(t,`path`),existed:A(t,`existed`)}}function Ni(e){let t=E(e);return{fromPath:D(t,`fromPath`),toPath:D(t,`toPath`),size:k(t,`size`),modifiedAt:D(t,`modifiedAt`)}}function Pi(e){if(e!==void 0){if(e!==`image`&&e!==`html`&&e!==`pdf`&&e!==`markdown`)throw Error(`Invalid file media type`);return e}}function Fi(e){let t=E(e);return{isGitRepo:A(t,`isGitRepo`),hash:D(t,`hash`),...N(`branch`,O(t,`branch`)),...N(`upstream`,O(t,`upstream`)),...N(`ahead`,eo(t,`ahead`)),...N(`behind`,eo(t,`behind`)),files:j(Ii)(t.files),submodules:t.submodules===void 0?[]:mn(t.submodules,`submodules`),...N(`truncated`,$a(t,`truncated`))}}function Ii(e){let t=E(e);return{path:D(t,`path`),...N(`oldPath`,O(t,`oldPath`)),index:Li(t.index),workingTree:Li(t.workingTree),...N(`submoduleFromCommit`,O(t,`submoduleFromCommit`)),...N(`submoduleToCommit`,O(t,`submoduleToCommit`))}}function Li(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 Ri(e){let t=E(e);return{...N(`path`,O(t,`path`)),staged:A(t,`staged`),hash:D(t,`hash`),diff:D(t,`diff`),truncated:A(t,`truncated`)}}function zi(e){let t=E(e);return{id:D(t,`id`),cwd:D(t,`cwd`),name:D(t,`name`),createdAt:D(t,`createdAt`),exited:A(t,`exited`),...N(`exitCode`,eo(t,`exitCode`)),...N(`commandRunId`,O(t,`commandRunId`))}}function Bi(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:Vi(t.status),...N(`exitCode`,eo(t,`exitCode`)),createdAt:D(t,`createdAt`),...N(`startedAt`,O(t,`startedAt`)),...N(`completedAt`,O(t,`completedAt`)),metadata:Hi(t.metadata,`metadata`)}}function Vi(e){if(e!==`queued`&&e!==`running`&&e!==`succeeded`&&e!==`failed`)throw Error(`Invalid terminal command run status`);return e}function Hi(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 Ui(e){let t=E(e);return{cwd:D(t,`cwd`),hasSessionActivity:A(t,`hasSessionActivity`),hasTerminalActivity:A(t,`hasTerminalActivity`),updatedAt:D(t,`updatedAt`)}}function Wi(e){let t=E(e);return{workspaces:j(Ui)(t.workspaces),generatedAt:D(t,`generatedAt`)}}function Gi(e){let t=cn(e);if(t===void 0)throw Error(`Expected machine status snapshot`);return t}function Ki(e){let t=E(e);return{path:D(t,`path`),exists:A(t,`exists`),config:qi(t.config),effectiveConfig:qi(t.effectiveConfig),envOverrides:ia(t.envOverrides)}}function qi(e){let t=E(e);return{...N(`host`,O(t,`host`)),...N(`port`,eo(t,`port`)),...N(`allowedHosts`,Yi(t.allowedHosts)),...N(`shortcuts`,na(t.shortcuts)),...N(`plugins`,ra(t.plugins)),...N(`pathAccess`,Xi(t.pathAccess)),...N(`uploads`,Qi(t.uploads)),...N(`attachments`,$i(t.attachments)),...N(`maxUploadBytes`,eo(t,`maxUploadBytes`)),...N(`agent`,Ji(t.agent)),...N(`spawnSessions`,$a(t,`spawnSessions`)),...N(`subsessions`,$a(t,`subsessions`)),...N(`askUser`,$a(t,`askUser`))}}function Ji(e){if(e!==void 0){if(!fn(e)||Array.isArray(e))throw Error(`Invalid PI WEB agent field`);return{...N(`command`,O(e,`command`)),...N(`dir`,O(e,`dir`))}}}function Yi(e){if(e!==void 0){if(e===!0)return!0;if(ea(e))return e;throw Error(`Invalid PI WEB allowedHosts field`)}}function Xi(e){if(e===void 0)return;if(!fn(e))throw Error(`Invalid PI WEB pathAccess field`);let t=e.allowedPaths;return{...N(`allowedPaths`,Zi(t,`pathAccess.allowedPaths`))}}function Zi(e,t){if(e!==void 0){if(ta(e))return e;throw Error(`Invalid PI WEB ${t} field`)}}function Qi(e){if(e!==void 0){if(!fn(e)||Array.isArray(e))throw Error(`Invalid PI WEB uploads field`);return{...N(`defaultFolder`,O(e,`defaultFolder`))}}}function $i(e){if(e!==void 0){if(!fn(e)||Array.isArray(e))throw Error(`Invalid PI WEB attachments field`);return{...N(`defaultFolder`,O(e,`defaultFolder`))}}}function ea(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`)}function ta(e){return Array.isArray(e)&&e.every(e=>typeof e==`string`&&e!==``)}function na(e){if(e!==void 0){if(!fn(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 ra(e){if(e!==void 0){if(!fn(e)||Array.isArray(e))throw Error(`Invalid PI WEB plugins field`);return Object.fromEntries(Object.entries(e).map(([e,t])=>{if(!fn(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&&(!fn(r)||Array.isArray(r)))throw Error(`Invalid PI WEB plugin settings field`);return[e,t]}))}}function ia(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:$a(t,`askUser`)??!1,agentCommand:$a(t,`agentCommand`)??!1,agentDir:$a(t,`agentDir`)??!1,...aa(t),agentSessionDir:$a(t,`agentSessionDir`)??!1}}function aa(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 oa(e){let t=E(e);return{packages:j(ca)(t.packages),...N(`installableKnownPackages`,la(t.installableKnownPackages))}}function sa(e){let t=E(e),n=O(t,`source`),r=t.scope===void 0?void 0:da(t.scope),i=ga(t.removed,`removed`);return{action:fa(t.action),...N(`source`,n),...N(`scope`,r),...N(`removed`,i),packages:j(ca)(t.packages),...N(`installableKnownPackages`,la(t.installableKnownPackages))}}function ca(e){let t=E(e);return{source:D(t,`source`),scope:da(t.scope),filtered:A(t,`filtered`),...N(`installedPath`,O(t,`installedPath`))}}function la(e){return e===void 0?void 0:j(ua)(e)}function ua(e){let t=E(e);return{id:D(t,`id`),label:D(t,`label`),description:D(t,`description`),source:D(t,`source`)}}function da(e){if(e!==`user`&&e!==`project`)throw Error(`Invalid Pi package scope`);return e}function fa(e){if(e!==`install`&&e!==`remove`&&e!==`update`)throw Error(`Invalid Pi package mutation action`);return e}function pa(e){let t=E(e);return{plugins:j(ma)(t.plugins)}}function ma(e){let t=E(e),n=O(t,`module`),r=O(t,`backendRevision`);return{id:D(t,`id`),...n===void 0?{}:{module:n},...r===void 0?{}:{backendRevision:r},source:D(t,`source`),scope:ha(t.scope),machineSpecific:ga(t.machineSpecific,`machineSpecific`)??!1,enabled:A(t,`enabled`)}}function ha(e){if(e!==`bundled`&&e!==`local`&&e!==`user`&&e!==`project`)throw Error(`Invalid PI WEB plugin scope`);return e}function ga(e,t){if(e!==void 0){if(typeof e!=`boolean`)throw Error(`Expected optional boolean field: ${t}`);return e}}function _a(e){let t=E(e);return{packageName:D(t,`packageName`),generatedAt:D(t,`generatedAt`),components:ya(t.components),release:wa(t.release),commands:Ta(t.commands),messages:j(Ea)(t.messages)}}function va(e){let t=E(e);return{packageName:D(t,`packageName`),generatedAt:D(t,`generatedAt`),components:ba(t.components),capabilities:Oa(t.capabilities)}}function ya(e){let t=E(e);return{web:Sa(t.web),sessiond:Sa(t.sessiond)}}function ba(e){let t=E(e);return{web:xa(t.web),sessiond:xa(t.sessiond)}}function xa(e){let t=E(e),n=Da(t.component),r=t.activeAgentProfile,i=r===void 0?void 0:Xt(r);if(r!==void 0&&(n!==`sessiond`||i===void 0))throw Error(`Invalid active agent profile descriptor`);return{component:n,label:D(t,`label`),...N(`runtimeVersion`,O(t,`runtimeVersion`)),...N(`piVersion`,O(t,`piVersion`)),available:A(t,`available`),capabilities:Oa(t.capabilities),...N(`activeAgentProfile`,i),...N(`error`,O(t,`error`))}}function Sa(e){let t=E(e);return{component:Da(t.component),label:D(t,`label`),...N(`runtimeVersion`,O(t,`runtimeVersion`)),...N(`installedVersion`,O(t,`installedVersion`)),...N(`piVersion`,O(t,`piVersion`)),stale:A(t,`stale`),available:A(t,`available`),...N(`installation`,Ca(t.installation)),...N(`error`,O(t,`error`))}}function Ca(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,...N(`path`,O(t,`path`)),...N(`source`,O(t,`source`)),...r===void 0?{}:{scope:r},...N(`npmRoot`,O(t,`npmRoot`)),...i===void 0?{}:{dockerMode:i}}}function wa(e){let t=E(e);return{packageName:D(t,`packageName`),...N(`latestVersion`,O(t,`latestVersion`)),updateAvailable:A(t,`updateAvailable`),...N(`checkedAt`,O(t,`checkedAt`)),...t.skipped===!0?{skipped:!0}:{},...N(`error`,O(t,`error`))}}function Ta(e){let t=E(e);return{...N(`update`,O(t,`update`)),...N(`restart`,O(t,`restart`)),...N(`restartWeb`,O(t,`restartWeb`)),...N(`restartSessiond`,O(t,`restartSessiond`)),...N(`status`,O(t,`status`))}}function Ea(e){let t=E(e);return{id:D(t,`id`),severity:ka(t.severity),title:D(t,`title`),body:D(t,`body`),...N(`command`,O(t,`command`))}}function Da(e){if(e!==`web`&&e!==`sessiond`)throw Error(`Invalid PI WEB service component`);return e}function Oa(e){let t=on(e);if(t===void 0)throw Error(`Invalid PI WEB capabilities`);return t}function ka(e){if(e!==`info`&&e!==`warning`&&e!==`error`)throw Error(`Invalid PI WEB status severity`);return e}function Aa(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(Ba)(t.options)};if(n===`tree`)return{type:n,tree:ja(t.tree)};if(n===`done`)return{type:n,...N(`message`,O(t,`message`)),...Va(t.session),...N(`promptDraft`,O(t,`promptDraft`))};throw Error(`Invalid command result type`)}function ja(e){let t=E(e),n=j(Ma)(t.nodes),r=new Set(n.map(e=>e.id));if(r.size!==n.length)throw Error(`Duplicate session tree node id`);let i=La(t,`activeLeafId`);if(i!==null&&!r.has(i))throw Error(`Invalid session tree activeLeafId`);return{nodes:n,activeLeafId:i,activePathIds:za(t.activePathIds,`activePathIds`)}}function Ma(e){let t=E(e);return{id:Ra(t,`id`),parentId:La(t,`parentId`),kind:Na(t.kind),summary:D(t,`summary`),...N(`timestamp`,O(t,`timestamp`)),...N(`label`,O(t,`label`))}}function Na(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 Pa(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){Ia(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 Ia(t,`aborted`,`session tree navigation result`),{cancelled:n,...N(`editorText`,O(t,`editorText`))}}function Fa(e){let t=E(e),n=A(t,`cancelled`);return n?(Ia(t,`session`,`session tree fork cancellation result`),Ia(t,`promptDraft`,`session tree fork cancellation result`),{cancelled:n}):{cancelled:n,session:kn(t.session),...N(`promptDraft`,O(t,`promptDraft`))}}function Ia(e,t,n){if(Object.hasOwn(e,t))throw Error(`Invalid ${n} field: ${t}`)}function La(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 Ra(e,t){let n=D(e,t);if(n.trim()===``)throw Error(`Expected non-blank string field: ${t}`);return n}function za(e,t){let n=mn(e,t);if(n.some(e=>e.trim()===``))throw Error(`Expected non-blank string array field: ${t}`);return n}function Ba(e){let t=E(e);return{value:D(t,`value`),label:D(t,`label`),...N(`description`,O(t,`description`))}}function Va(e){return e===void 0?{}:{session:kn(e)}}function Ha(e){if(E(e).accepted!==!0)throw Error(`Expected accepted response`);return{accepted:!0}}function Ua(e){let t=E(e);return j(Wa)(t.attachments)}function Wa(e){let t=E(e);return{path:D(t,`path`),mimeType:D(t,`mimeType`),size:k(t,`size`)}}function Ga(e){if(E(e).closed!==!0)throw Error(`Expected closed response`);return{closed:!0}}function Ka(e){if(E(e).aborted!==!0)throw Error(`Expected aborted response`);return{aborted:!0}}function qa(e){if(E(e).stopped!==!0)throw Error(`Expected stopped response`);return{stopped:!0}}function Ja(e){let t=E(e);if(t.archived!==!0)throw Error(`Expected archived response`);let n=t.sessionIds===void 0?void 0:mn(t.sessionIds,`sessionIds`),r=eo(t,`archivedCount`),i=eo(t,`skippedAlreadyArchivedCount`);return{archived:!0,...n===void 0?{}:{sessionIds:n},...r===void 0?{}:{archivedCount:r},...i===void 0?{}:{skippedAlreadyArchivedCount:i}}}function Ya(e){if(E(e).restored!==!0)throw Error(`Expected restored response`);return{restored:!0}}function Xa(e){if(E(e).deleted!==!0)throw Error(`Expected deleted response`);return{deleted:!0}}function Za(e){if(E(e).detached!==!0)throw Error(`Expected detached response`);return{detached:!0}}function Qa(e){if(E(e).reloaded!==!0)throw Error(`Expected reloaded response`);return{reloaded:!0}}function $a(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`boolean`)throw Error(`Invalid PI WEB ${t} field`);return n}}function eo(e,t){let n=e[t];if(n!==void 0){if(typeof n!=`number`)throw Error(`Expected optional number field: ${t}`);return n}}function to(e,t){let n=e[t];if(n===null)return null;if(typeof n!=`number`)throw Error(`Expected number|null field: ${t}`);return n}function N(e,t){return t===void 0?{}:{[e]:t}}function no(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 ro(e,t,n=`local`){let r=new URLSearchParams({cwd:e.cwd});t?.limit!==void 0&&r.set(`limit`,String(t.limit)),t?.before!==void 0&&r.set(`before`,String(t.before));let i=r.toString();return`api/machines/${encodeURIComponent(n)}/sessions/${encodeURIComponent(e.id)}/messages?${i}`}function io(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`),Dt(yt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`))}function ao(e,t,n,r){let i=new URLSearchParams;return i.set(`path`,n),r?.modifiedAt!==void 0&&i.set(`v`,r.modifiedAt),r?.download===!0&&i.set(`download`,`1`),yt(`${`api/machines/${encodeURIComponent(r?.machineId??`local`)}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${i.toString()}`)}function oo(e,t,n,r){return Dt(ao(e,t,n,r))}function so(e,t,n,r){return oo(e,t,n,{...r,download:!0})}var P=(e=`local`)=>`api/machines/${encodeURIComponent(e)}`;function co(e,t=`local`){return`${P(t)}/sessions/${encodeURIComponent(e.id)}`}function F(e,t,n=`local`){return`${co(e,n)}/${t}`}function lo(e,t,n=`local`){return`${F(e,t,n)}${fo(e)}`}function uo(e,t=`local`,n){return`${co(e,t)}${fo(e,n===void 0?{}:{scopeProjectId:n})}`}function fo(e,t={}){return`?${new URLSearchParams({cwd:e.cwd,...t}).toString()}`}function I(e,t={}){return JSON.stringify({cwd:e.cwd,...t})}function po(e,t){let n={sessions:[...e],...t===void 0?{}:{scopeProjectId:t}};return JSON.stringify(n)}function mo(e,t){let n=new URLSearchParams;t.projectId!==void 0&&n.set(`projectId`,t.projectId);let r=n.toString();return`${P(t.machineId)}/auth/${e}${r===``?``:`?${r}`}`}function ho(e){return e===`local`?`api/pi-web/status`:`${P(e)}/pi-web/status`}var go={piWebStatus:(e=`local`)=>w(ho(e),_a),checkForUpdates:(e=`local`)=>w(`${ho(e)}?refresh=1`,_a,{cache:`no-store`}),piWebRuntime:()=>w(`api/pi-web/runtime`,va)},_o={machines:()=>w(`api/machines`,gn),addMachine:e=>w(`api/machines`,_n,{method:`POST`,body:JSON.stringify(e)}),deleteMachine:e=>w(`api/machines/${encodeURIComponent(e)}`,e=>e,{method:`DELETE`}),health:e=>w(`api/machines/${encodeURIComponent(e)}/health`,vn),runtime:(e,t=!1)=>w(`api/machines/${encodeURIComponent(e)}/runtime${t?`?refresh=1`:``}`,yn,t?{cache:`no-store`}:{})};function vo(e){return e===void 0?`api/config`:`${P(e)}/config`}function yo(e){return e===void 0?`api/plugins`:`${P(e)}/plugins`}var bo={config:e=>w(vo(e),Ki),saveConfig:(e,t)=>w(vo(t),Ki,{method:`PUT`,body:JSON.stringify({config:e})})},xo={status:()=>w(`api/normal-auth/status`,An),setup:e=>w(`api/normal-auth/setup`,Ha,{method:`POST`,body:JSON.stringify({password:e})}),login:e=>w(`api/normal-auth/login`,Ha,{method:`POST`,body:JSON.stringify({password:e})}),changePassword:(e,t)=>w(`api/normal-auth/change-password`,Ha,{method:`POST`,body:JSON.stringify({currentPassword:e,newPassword:t})})},So={plugins:e=>w(yo(e),pa)};function Co(e=``,t){let n=t===void 0?`api/pi-packages`:`${P(t)}/pi-packages`;return e===``?n:`${n}/${e}`}var wo={packages:e=>w(Co(``,e),oa),install:(e,t)=>{let n={source:e};return w(Co(`install`,t),sa,{method:`POST`,body:JSON.stringify(n)})},remove:(e,t,n)=>{let r=t===void 0?{source:e}:{source:e,scope:t};return w(Co(`remove`,n),sa,{method:`POST`,body:JSON.stringify(r)})},update:(e,t)=>{let n=e===void 0?void 0:{source:e};return w(Co(`update`,t),sa,{method:`POST`,...n===void 0?{}:{body:JSON.stringify(n)}})}},To={workspaceActivity:(e=`local`)=>w(`${P(e)}/activity`,Wi)},Eo={machineStatus:(e=`local`)=>w(`${P(e)}/status`,Gi)},Do={snapshot:(e=`local`)=>w(`${P(e)}/notices`,Dr,{cache:`no-store`}),dismiss:(e,t,n)=>{let r={daemonInstanceId:t,noticeId:n};return w(`${P(e)}/notices/dismiss`,Dr,{method:`POST`,body:JSON.stringify(r)})}},Oo={projects:(e=`local`)=>w(`${P(e)}/projects`,j(Sn)),addProject:(e,t,n,r=`local`)=>w(`${P(r)}/projects`,Sn,{method:`POST`,body:JSON.stringify({path:e,name:t,create:n})}),closeProject:(e,t=`local`)=>w(`${P(t)}/projects/${encodeURIComponent(e)}`,Ga,{method:`DELETE`}),projectDirectories:(e,t=`local`)=>w(`${P(t)}/project-directories?q=${encodeURIComponent(e)}`,j(Ti))};function ko(e,t,n,r,i,a=`local`){let o=new URLSearchParams({path:n});i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!1&&o.set(`overwrite`,`false`);let s=r instanceof Uint8Array,c=s?new Uint8Array(r):new TextEncoder().encode(r);return w(`${P(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${o.toString()}`,ji,{method:`PUT`,body:c,headers:{"Content-Type":s?`application/octet-stream`:`text/plain`}})}var Ao={workspaces:(e,t=`local`)=>w(`${P(t)}/projects/${encodeURIComponent(e)}/workspaces`,j(Cn)),deleteWorkspace:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,Bi,{method:`DELETE`,body:JSON.stringify({precondition:n}),headers:{"Content-Type":`application/json`}}),workspaceTree:(e,t,n=``,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(n)}`,Ei),workspaceTreeBatch:(e,t,n,r=`local`)=>{let i={paths:[...n]};return w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree/batch`,Di,{method:`POST`,body:JSON.stringify(i)})},workspaceFile:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}`,Ai),optionalWorkspaceFile:(e,t,n,r=`local`)=>Ft(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(n)}&optional=true`,Ai),createWorkspaceFile:(e,t,n,r=`local`)=>ko(e,t,n,new Uint8Array,void 0,r),writeWorkspaceFile:ko,deleteWorkspaceFile:(e,t,n,r=`local`)=>{let i=new URLSearchParams({path:n});return w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?${i.toString()}`,Mi,{method:`DELETE`})},moveWorkspaceFile:(e,t,n,r,i,a=`local`)=>{let o=new URLSearchParams({fromPath:n,toPath:r});return i?.createDirs===!1&&o.set(`createDirs`,`false`),i?.overwrite===!0&&o.set(`overwrite`,`true`),w(`${P(a)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/move?${o.toString()}`,Ni,{method:`POST`})},createWorkspaceDirectory:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,jn,{method:`POST`,body:JSON.stringify({path:n})}),moveWorkspaceDirectory:(e,t,n,r,i=`local`)=>w(`${P(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,jn,{method:`PATCH`,body:JSON.stringify({fromPath:n,toPath:r})}),deleteWorkspaceDirectory:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(n)}`,Mn,{method:`DELETE`}),downloadWorkspaceFile:(e,t,n,r=`local`)=>Io(e,t,n,r)},jo={sessions:(e,t=`local`)=>w(`${P(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(kn)),search:(e,t,n=`local`)=>w(`${P(n)}/sessions/search?${new URLSearchParams({cwd:e,q:t}).toString()}`,j(kn)),searchContent:(e,t,n=`local`)=>w(`${P(n)}/sessions/search-content?${new URLSearchParams({cwd:e,q:t}).toString()}`,Fn),pinned:(e,t=`local`)=>w(`${P(t)}/sessions/pins?cwd=${encodeURIComponent(e)}`,Nn),pin:(e,t=`local`)=>w(`${co(e,t)}/pin`,Pn,{method:`PUT`,body:I(e)}),unpin:(e,t=`local`)=>w(`${co(e,t)}/pin${fo(e)}`,Pn,{method:`DELETE`}),unreadCatalog:(e=`local`)=>w(`${P(e)}/sessions/unread`,pr,{cache:`no-store`}),acknowledgeUnread:(e,t,n,r=`local`)=>{let i={cwd:e.cwd,catalogId:t,throughCompletionOrder:n};return w(F(e,`unread/acknowledge`,r),pr,{method:`POST`,body:JSON.stringify(i)})},notificationInbox:(e,t=`local`)=>w(lo(e,`notifications`,t),Tr),dismissNotification:(e,t,n,r=`local`)=>w(F(e,`notifications/dismiss`,r),Tr,{method:`POST`,body:I(e,{daemonInstanceId:t,notificationId:n})}),dismissAllNotifications:(e,t,n,r=`local`)=>w(F(e,`notifications/dismiss-all`,r),Tr,{method:`POST`,body:I(e,{daemonInstanceId:t,throughOrder:n.order,throughOverflowWatermark:n.overflowWatermark})}),startSession:(e,t=`local`,n)=>w(`${P(t)}/sessions`,kn,{method:`POST`,body:JSON.stringify(n===void 0?{cwd:e}:{cwd:e,startupToken:n})}),cleanupPreview:(e,t=`local`)=>w(`${P(t)}/sessions/cleanup/preview`,Kr,{method:`POST`,body:JSON.stringify(e)}),cleanup:(e,t=`local`)=>w(`${P(t)}/sessions/cleanup`,qr,{method:`POST`,body:JSON.stringify(e)}),archiveMany:(e,t=`local`,n)=>w(`${P(t)}/sessions/bulk/archive`,Jr,{method:`POST`,body:po(e,n)}),deleteArchivedMany:(e,t=`local`,n)=>w(`${P(t)}/sessions/bulk/delete-archived`,Yr,{method:`POST`,body:po(e,n)}),messages:(e,t,n=`local`)=>w(ro(e,t,n),hn),status:(e,t=`local`)=>w(lo(e,`status`,t),dr),streamSnapshot:(e,t=`local`)=>w(lo(e,`stream-snapshot`,t),fr),models:(e,t=`local`)=>w(lo(e,`models`,t),ii),modelCatalog:(e,t=`local`)=>w(lo(e,`models/catalog`,t),oi),setModelEnabled:(e,t,n,r,i=`local`)=>w(F(e,`models/enabled`,i),oi,{method:`POST`,body:I(e,{provider:t,modelId:n,enabled:r})}),setModelScope:(e,t,n=`local`)=>w(F(e,`models/scope`,n),oi,{method:`POST`,body:I(e,{mode:t})}),setModel:(e,t,n,r=`local`)=>w(F(e,`model`,r),dr,{method:`POST`,body:I(e,{provider:t,modelId:n})}),cycleModel:(e,t,n=`local`)=>w(F(e,`model/cycle`,n),dr,{method:`POST`,body:I(e,{direction:t})}),thinkingLevels:(e,t=`local`)=>w(lo(e,`thinking-levels`,t),ci),setThinkingLevel:(e,t,n=`local`)=>w(F(e,`thinking-level`,n),dr,{method:`POST`,body:I(e,{level:t})}),cycleThinkingLevel:(e,t=`local`)=>w(F(e,`thinking-level/cycle`,t),dr,{method:`POST`,body:I(e)}),commands:(e,t=`local`)=>w(lo(e,`commands`,t),j(wi)),prompt:(e,t,n,r=`local`,i)=>w(F(e,`prompt`,r),Ha,{method:`POST`,body:I(e,{text:t,...n===void 0?{}:{streamingBehavior:n},...i!==void 0&&i.length>0?{attachments:i}:{}})}),saveAttachments:(e,t,n=`local`,r)=>w(F(e,`attachments`,n),Ua,{method:`POST`,body:I(e,{attachments:t,...r===void 0?{}:{folder:r}})}),shell:(e,t,n=`local`)=>w(F(e,`shell`,n),Ha,{method:`POST`,body:I(e,{text:t})}),runCommand:(e,t,n=`local`)=>w(F(e,`commands/run`,n),Aa,{method:`POST`,body:I(e,{text:t})}),respondToCommand:(e,t,n,r=`local`)=>w(F(e,`commands/respond`,r),Aa,{method:`POST`,body:I(e,{requestId:t,value:n})}),navigateTree:(e,t,n=`local`)=>w(F(e,`tree/navigate`,n),Pa,{method:`POST`,body:I(e,{targetId:t.targetId,expectedLeafId:t.expectedLeafId,summary:t.summary})}),forkTree:(e,t,n=`local`)=>w(F(e,`tree/fork`,n),Fa,{method:`POST`,body:I(e,{entryId:t.entryId,expectedLeafId:t.expectedLeafId})}),abort:(e,t=`local`)=>w(F(e,`abort`,t),Ka,{method:`POST`,body:I(e)}),stop:(e,t=`local`)=>w(F(e,`stop`,t),qa,{method:`POST`,body:I(e)}),archive:(e,t=`local`,n)=>w(F(e,`archive`,t),Ja,{method:`POST`,body:I(e,n===void 0?{}:{scopeProjectId:n})}),archiveWithDescendants:(e,t=`local`,n)=>w(F(e,`archive-tree`,t),Ja,{method:`POST`,body:I(e,n===void 0?{}:{scopeProjectId:n})}),restore:(e,t=`local`,n)=>w(F(e,`restore`,t),Ya,{method:`POST`,body:I(e,n===void 0?{}:{scopeProjectId:n})}),deleteArchived:(e,t=`local`,n)=>w(uo(e,t,n),Xa,{method:`DELETE`}),detachParent:(e,t=`local`)=>w(F(e,`detach-parent`,t),Za,{method:`POST`,body:I(e)}),reloadSession:(e,t=`local`)=>w(F(e,`reload`,t),Qa,{method:`POST`,body:I(e)}),clearQueue:(e,t=`local`)=>w(F(e,`queue/clear`,t),dr,{method:`POST`,body:I(e)}),dismissWarning:(e,t,n=`local`)=>w(F(e,`warnings/dismiss`,n),dr,{method:`POST`,body:I(e,{dismissId:t})}),submitAsk:(e,t,n,r=`local`)=>w(F(e,`ask/submit`,r),Qn,{method:`POST`,body:I(e,{askId:t,answers:n.answers})}),cancelAsk:(e,t,n=`local`)=>w(F(e,`ask/cancel`,n),Qn,{method:`POST`,body:I(e,{askId:t})}),answerDialog:(e,t,n,r=`local`)=>w(F(e,`dialogs/answer`,r),$n,{method:`POST`,body:I(e,{dialogId:t,value:n})}),cancelDialog:(e,t,n=`local`)=>w(F(e,`dialogs/cancel`,n),$n,{method:`POST`,body:I(e,{dialogId: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 w(`${P(e.machineId)}/auth/providers${n===``?``:`?${n}`}`,pi)},saveApiKey:(e,t,n)=>w(mo(`api-key`,n),Ha,{method:`POST`,body:JSON.stringify({providerId:e,key:t})}),startInteractiveApiKeyLogin:(e,t)=>w(mo(`api-key/interactive`,t),mi,{method:`POST`,body:JSON.stringify({providerId:e})}),logoutProvider:(e,t)=>w(mo(`logout`,t),Ha,{method:`POST`,body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t)=>w(mo(`oauth`,t),mi,{method:`POST`,body:JSON.stringify({providerId:e})}),oauthFlow:(e,t)=>w(mo(`oauth/${encodeURIComponent(e)}`,t),mi),respondOAuthFlow:(e,t,n,r)=>w(mo(`oauth/${encodeURIComponent(e)}/respond`,r),mi,{method:`POST`,body:JSON.stringify({requestId:t,value:n})}),cancelOAuthFlow:(e,t)=>w(mo(`oauth/${encodeURIComponent(e)}/cancel`,t),mi,{method:`POST`})},Mo={terminals:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j(zi)),startTerminal:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,zi,{method:`POST`,body:JSON.stringify(n??{})}),closeWorkspaceTerminals:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Ga,{method:`DELETE`}),closeTerminal:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}`,Ga,{method:`DELETE`}),continueTerminal:(e,t,n,r=`local`)=>w(`${P(r)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/continue`,zi,{method:`POST`}),runTerminalCommand:(e,t,n=`local`)=>w(`${P(n)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,Bi,{method:`POST`,body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t=`local`)=>w(`${P(t)}/terminal-command-runs${Po(e)}`,j(Bi)),getCommandRun:(e,t=`local`)=>No(e,t),cancelCommandRun:(e,t=`local`)=>w(`${P(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,Bi,{method:`POST`})};async function No(e,t){return Ft(`${P(t)}/terminal-command-runs/${encodeURIComponent(e)}`,Bi)}function Po(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 Fo(e){if(!Lo(e))return;let t=e.error;return typeof t==`string`?t:void 0}async function Io(e,t,n,r){let i=await fetch(so(e,t,n,{machineId:r}));if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(Fo(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 Lo(e){return typeof e==`object`&&!!e}var Ro={files:(e,t,n={})=>{let r=new URLSearchParams({q:t});return n.kind!==void 0&&r.set(`kind`,n.kind),n.mode!==void 0&&r.set(`mode`,n.mode),n.scope!==void 0&&r.set(`scope`,n.scope),n.workspaceScoped===!0&&n.projectId!==void 0&&n.workspaceId!==void 0?w(`${P(n.machineId)}/projects/${encodeURIComponent(n.projectId)}/workspaces/${encodeURIComponent(n.workspaceId)}/files?${r.toString()}`,j(Ti),{signal:n.signal??null}):(r.set(`cwd`,e),w(`${P(n.machineId)}/files?${r.toString()}`,j(Ti),{signal:n.signal??null}))}},zo={gitStatus:(e,t,n=`local`,r=!1)=>w(`${P(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status${r?`?refresh=true`:``}`,Fi),gitDiff:(e,t,n,r=`local`)=>w(no(r,e,t,n),Ri)},L={...go,..._o,...bo,...xo,...So,...wo,...To,...Eo,...Do,...Oo,...Ao,...jo,...Mo,...Ro,...zo};function Bo(e,t=`local`,n=vt()){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=bt(`${Uo(t)}/sessions/${encodeURIComponent(a)}/events${i}`,void 0,n);return new WebSocket(Ot(o))}function Vo(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(Ot(`${Uo(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(n)}/socket${a}`))}function Ho(e=`local`,t=vt()){let n=bt(`${Uo(e)}/events`,void 0,t);return new WebSocket(Ot(n))}function Uo(e){return`api/machines/${encodeURIComponent(e)}`}var Wo=`.pi-web/uploads`,Go=class extends Error{constructor(e=`工作区上传已取消`){super(e),this.name=`WorkspaceUploadCancelledError`}},Ko=class extends Error{constructor(e,t){super(rs(e)),this.name=`WorkspaceUploadBatchError`,this.failures=e.map(e=>({...e})),this.responses=t.map(e=>({...e}))}};function qo(e){return e?.uploads?.defaultFolder??`.pi-web/uploads`}function Jo(e,t){return e?.uploads?.defaultFolder??t}function Yo(e,t){let n=os(e,`上传目标`,{allowEmpty:!0}),r=os(t,`上传文件名`,{allowEmpty:!1});return n===``?r:`${n}/${r}`}function Xo(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`,io(e,t,n.path,$o(r)),!0),i.responseType=`json`,i.setRequestHeader(`Content-Type`,(n.contentType??n.file.type)||`application/octet-stream`),i.upload.onprogress=e=>{r.onProgress?.(es(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(ji(cs(i)))}catch(e){l(e instanceof Error?e:Error(String(e)))}return}l(Error(ls(i)))},i.onerror=()=>{l(Error(`工作区上传失败`))},i.onabort=()=>{l(new Go(o?void 0:`工作区上传已中止`))},i.send(n.file)}),cancel:()=>{a||(o=!0,i.abort())}}}function Zo(e,t,n,r={}){let i=r.destinationFolder??`.pi-web/uploads`,a=n.map((e,t)=>({index:t,name:e.name,path:Yo(i,e.name),loaded:0,total:e.size,percent:ns(0,e.size),lengthComputable:!0,done:!1})),o,s=0,c={requested:!1},l=()=>{r.onProgress?.(ts(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 Go;s=d;let f=n[d],p=a[d];if(!(f===void 0||p===void 0)){o=Xo(e,t,{path:p.path,file:f},{...Qo(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(as(e,c))throw e;let t=is(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 Ko(u,i);return i})(),cancel:()=>{c.requested=!0,o?.cancel()}}}function Qo(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 $o(e){return{...e.createDirs===void 0?{}:{createDirs:e.createDirs},...e.overwrite===void 0?{}:{overwrite:e.overwrite},...e.machineId===void 0?{}:{machineId:e.machineId}}}function es(e,t){let n=e.lengthComputable?e.total:t;return{loaded:e.loaded,total:n,percent:ns(e.loaded,n),lengthComputable:e.lengthComputable}}function ts(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:ns(i,r),done:n}}function ns(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}function rs(e){return e.length===1?e[0]?.error??`工作区上传失败`:`${String(e.length)} 个文件上传失败`}function is(e){return e instanceof Error?e.message:String(e)}function as(e,t){return t.requested||e instanceof Go}function os(e,t,n){let r=e.trim();if(r===``){if(n.allowEmpty)return``;throw Error(`${t}不能为空`)}if(ss(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 ss(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function cs(e){return e.response!==void 0&&e.response!==null&&e.response!==``?e.response:e.responseText===``?{}:JSON.parse(e.responseText)}function ls(e){let t=us(e);return ds(t)&&typeof t.error==`string`?t.error:e.statusText||`HTTP ${String(e.status)}`}function us(e){try{return cs(e)}catch{return}}function ds(e){return typeof e==`object`&&!!e}var fs=`.pi-web/attachments`;function ps(e){return e?.attachments?.defaultFolder??`.pi-web/attachments`}function ms(e,t){return e?.attachments?.defaultFolder??t}function hs(){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,selectedFileLoadError:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,selectedTerminalId:void 0,error:``}}function gs(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},machineStatusSnapshots:{},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,pendingDialogs:[],closedDialogs:[],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,selectedFileLoadError: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,browserErrors:{},error:``}}function R(e){return{kind:`machine`,machineId:e}}function _s(e,t){return{kind:`project`,machineId:e,projectId:t}}function vs(e,t,n){return{kind:`workspace`,machineId:e,projectId:t,workspaceId:n}}function ys(e,t,n={}){return{kind:`session`,machineId:e,sessionId:t,...n.cwd===void 0?{}:{cwd:n.cwd},...n.projectId===void 0?{}:{projectId:n.projectId},...n.workspaceId===void 0?{}:{workspaceId:n.workspaceId}}}function bs(e){switch(e.kind){case`global`:return`global`;case`machine`:return JSON.stringify([e.kind,e.machineId]);case`project`:return JSON.stringify([e.kind,e.machineId,e.projectId]);case`workspace`:return JSON.stringify([e.kind,e.machineId,e.projectId,e.workspaceId]);case`session`:return JSON.stringify([e.kind,e.machineId,e.sessionId,e.cwd,e.projectId,e.workspaceId])}}function xs(e,t,n){return{...e,[bs(t)]:{scope:t,message:n}}}function Ss(e,t,n){let r=bs(t),i=e[r];return i===void 0||n!==void 0&&i.message!==n?e:Object.fromEntries(Object.entries(e).filter(([e])=>e!==r))}function Cs(e,t){let n=Object.fromEntries(Object.entries(e).filter(([,e])=>!ks(e.scope,t)));return Object.keys(n).length===Object.keys(e).length?e:n}function ws(e){let t=e.selectedSession;return{machineId:e.selectedMachine?.id??`local`,...e.selectedProject===void 0?{}:{projectId:e.selectedProject.id},...e.selectedWorkspace===void 0?{}:{workspaceId:e.selectedWorkspace.id},...t===void 0?{}:{sessionId:t.id,cwd:t.cwd}}}function Ts(e,t){return Object.values(e).filter(e=>Ds(e.scope,t)).sort((e,t)=>Os(e.scope)-Os(t.scope)||bs(e.scope).localeCompare(bs(t.scope)))}var Es=class{constructor(e,t){this.getState=e,this.setState=t}report(e,t){this.setState({browserErrors:xs(this.getState().browserErrors,e,t)})}clear(e,t){let n=this.getState().browserErrors,r=Ss(n,e,t);r!==n&&this.setState({browserErrors:r})}discard(e){let t=Cs(this.getState().browserErrors,e);t!==this.getState().browserErrors&&this.setState({browserErrors:t})}};function Ds(e,t){return e.kind===`global`?!0:e.machineId===t.machineId?e.kind===`machine`?!0:e.kind===`project`?e.projectId===t.projectId:e.kind===`workspace`?e.projectId===t.projectId&&e.workspaceId===t.workspaceId:e.sessionId===t.sessionId&&(e.cwd===void 0||e.cwd===t.cwd)&&(e.projectId===void 0||e.projectId===t.projectId)&&(e.workspaceId===void 0||e.workspaceId===t.workspaceId):!1}function Os(e){switch(e.kind){case`global`:return 0;case`machine`:return 1;case`project`:return 2;case`workspace`:return 3;case`session`:return 4}}function ks(e,t){return t.kind===`global`?!0:e.kind===`global`||e.machineId!==t.machineId?!1:t.kind===`machine`?!0:t.kind===`project`?e.kind!==`machine`&&e.projectId===t.projectId:t.kind===`workspace`?e.kind===`workspace`?e.projectId===t.projectId&&e.workspaceId===t.workspaceId:e.kind===`session`&&e.projectId===t.projectId&&e.workspaceId===t.workspaceId:e.kind===`session`&&e.sessionId===t.sessionId&&(t.cwd===void 0||e.cwd===t.cwd)}function As(e,t){return t?.phase===`active`&&t.startup!==!0||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function js(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}var Ms=`workspace.delete`,Ns=`pi.operation`,Ps=`target.workspaceId`,Fs=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function Is(e){return Fs.some(t=>t===e)}function Ls(e){return e===void 0||e===``?`off`:e}function Rs(e){let t=Ls(e);return Is(t)?{off:`关闭`,minimal:`最低`,low:`低`,medium:`中`,high:`高`,xhigh:`极高`,max:`最高`}[t]??t:t}function zs(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 Bs(e,t){let n=t.length>=2?t:Fs,r=n.length-1,i=Ls(e),a=n.indexOf(i);return{total:r,filled:a<=0?0:Math.min(a,r)}}function Vs(e,t){return`${e}:${t}`}function Hs(e,t){return`${e}:${t}`}function z(e){return e.selectedMachine?.id??`local`}var Us=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}},Ws=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new Us,this.api=n.api??To,this.onActivityApplied=n.onActivityApplied}refresh(e=z(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,Gs(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=z(this.getState())){let n=this.getState(),r=z(n)===t,i=Ks(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},...z(n)===e?{workspaceActivities:t}:{}}),this.onActivityApplied?.(e)}};function Gs(e){let t={};for(let n of e.workspaces)js(n)&&(t[n.cwd]=n);return t}function Ks(e,t){let n={...e};return js(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}var qs=class{constructor(e,t,n,r){this.getState=e,this.setState=t,this.applyStatus=n,this.oauthOperationGeneration=0,this.pollGeneration=0,this.api=r.api??L,this.pollIntervalMs=r.pollIntervalMs??1e3,this.scope=r.scope,this.browserErrors=new Es(e,t)}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=Zs(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,...Ys(t.target)});this.setState({authDialog:{step:`providers`,mode:`login`,authType:e,providers:n,target:t.target}})}catch(e){this.browserErrors.report(R(t.target.machineId),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`,...Ys(t)});if(e!==void 0&&e!==``){let r=n.find(t=>t.id===e);r===void 0?this.browserErrors.report(R(t.machineId),`没有 ${e} 的已保存凭据`):await this.logoutProviderForTarget(r.id,t);return}this.setState({authDialog:{step:`logout`,providers:n,target:t}})}catch(e){this.browserErrors.report(R(t.machineId),String(e))}}async logoutProvider(e){let t=this.getState().authDialog;t?.step===`logout`&&t.providers.find(t=>t.id===e)!==void 0&&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.browserErrors.report(R(t.machineId),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`||t.responding===!0)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||Xs(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`,...Ys(t)}),r=n.filter(t=>t.id===e);if(r.length===0){this.browserErrors.report(R(t.machineId),`找不到认证提供商:${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.browserErrors.report(R(t.machineId),String(e))}}async startOAuth(e,t){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.browserErrors.report(R(t.machineId),String(e))}}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`?Xs(n.flow):void 0,a=Xs(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||!Js(i.target,t)){this.stopPolling();return}let a=Xs(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||!Js(o.target,t)||Xs(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(z(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:z(e),...t?.kind===void 0?{}:{machineKind:t.kind}};if(this.scope===`management`)return n;let r=e.selectedProject;if(r===void 0){this.browserErrors.report(R(n.machineId),`请先选择项目,再配置提供商认证。`);return}return{...n,projectId:r.id,projectName:r.name}}targetStillSelected(e){return z(this.getState())===e.machineId?e.projectId===void 0||this.getState().selectedProject?.id===e.projectId:!1}};function Js(e,t){return e.machineId===t.machineId&&e.projectId===t.projectId}function Ys(e){return e.projectId===void 0?{machineId:e.machineId}:{machineId:e.machineId,projectId:e.projectId,...e.projectName===void 0?{}:{projectName:e.projectName}}}function Xs(e){return e.prompt?.requestId??e.select?.requestId}function Zs(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 Qs(e){return e.replaceAll(`:`,`.`)}function $s(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 ec(e,t){let n=$s(e)[t];return Array.isArray(n)?n[0]:n===``?void 0:n}function tc(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));nc(i,r)}function nc(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 rc(e){let t=e.files.map((t,n)=>{let r=t.size;return{index:n,name:t.name,path:Yo(e.destinationFolder,t.name),size:t.size,loaded:0,total:r,percent:lc(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:lc(0,n),status:`uploading`,startedAt:e.startedAt}}function ic(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 ac(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=cc(r);return{...e,files:r,currentFileIndex:r.length===0?-1:r.length-1,...i,status:`completed`,completedAt:n}}function oc(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,...cc(r),status:`error`,error:t,completedAt:n}}function sc(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,...cc(r),status:`cancelled`,error:n,completedAt:t}}function cc(e){let t=e.reduce((e,t)=>e+t.total,0);return{loaded:t,total:t,percent:e.length===0?0:1}}function lc(e,t){return t<=0?e<=0?0:1:Math.max(0,Math.min(1,e/t))}var uc=Qs(`core:workspace.files`),dc=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.updateUrl=n,this.uploadTasks=new Map,this.uploadBatchSequence=0,this.fileRequestGeneration=0,this.treeRequestGeneration=0,this.directoryRequestSequence=0,this.directoryRequestGeneration=new Map,this.treeRefreshes=new Map,this.api=r.api??L,this.uploadWorkspaceFiles=r.uploadWorkspaceFiles??Zo,this.createUploadBatchId=r.createUploadBatchId??(()=>(this.uploadBatchSequence+=1,`workspace-upload-${String(this.uploadBatchSequence)}`)),this.now=r.now??(()=>new Date().toISOString())}refreshFiles(){let e=this.getState();return e.selectedProject===void 0||e.selectedWorkspace===void 0?Promise.resolve():this.requestTreeRefresh({projectId:e.selectedProject.id,workspaceId:e.selectedWorkspace.id,machineId:z(e)})}requestTreeRefresh(e,t){let n=JSON.stringify([e.machineId,e.projectId,e.workspaceId]),r=this.treeRefreshes.get(n);if(r!==void 0){r.full||=t===void 0;for(let e of t??[])r.parents.add(e);return r.promise}let i={promise:Promise.resolve(),full:t===void 0,parents:new Set(t)};return this.treeRefreshes.set(n,i),i.promise=this.refreshLoop(e,i).finally(()=>{this.treeRefreshes.delete(n)}),i.promise}async refreshLoop(e,t){let n,r=!1;for(;t.full||t.parents.size>0;){if(!this.isCurrentWorkspace(e))return;let i=t.full,a=[...t.parents];t.full=!1,t.parents.clear();try{i?await this.refreshFileTree():await this.refreshParentTrees(e,a),r=!1}catch(e){n=e,r=!0}}if(r)throw n}async refreshFileTree(){let e=this.getState(),t=e.selectedProject,n=e.selectedWorkspace;if(t===void 0||n===void 0)return;let r={projectId:t.id,workspaceId:n.id,machineId:z(e)},i=++this.treeRequestGeneration,a=e.expandedDirs,o=()=>i===this.treeRequestGeneration&&this.isCurrentWorkspace(r);try{let e=r.machineId,i=[``,...Object.keys(a)],s=[];for(let r=0;r<i.length;r+=128){let a=await this.api.workspaceTreeBatch(t.id,n.id,i.slice(r,r+128),e);s.push(...a.results)}let c=s.find(e=>e.path===``);if(c===void 0||!(`tree`in c))throw Error(c?.error??`Unable to load file tree`);let l=s.filter(e=>e.path!==``).map(e=>[e.path,`tree`in e?e.tree.entries:void 0]);if(!o())return;let u={...this.getState().expandedDirs};for(let[e,t]of l)u[e]===a[e]&&(t===void 0?u=hc(u,e):u[e]=t);this.setState({fileTree:c.tree.entries,expandedDirs:u,fileTreeStale:!1,error:``})}catch(e){if(!o())return;this.setState({error:String(e)})}}async expandDir(e){let t=this.getState(),n=t.selectedProject,r=t.selectedWorkspace;if(n===void 0||r===void 0)return;let i={projectId:n.id,workspaceId:r.id,machineId:z(t)},a=++this.directoryRequestSequence;this.directoryRequestGeneration.set(e,a);let o=()=>this.directoryRequestGeneration.get(e)===a&&this.isCurrentWorkspace(i);if(this.getState().expandedDirs[e]!==void 0){this.directoryRequestGeneration.delete(e),this.setState({expandedDirs:hc(this.getState().expandedDirs,e)});return}try{let t=await this.api.workspaceTree(n.id,r.id,e,i.machineId);if(!o())return;this.setState({expandedDirs:{...this.getState().expandedDirs,[e]:t.entries},error:``})}catch(e){if(!o())return;this.setState({error:String(e)})}finally{this.directoryRequestGeneration.get(e)===a&&this.directoryRequestGeneration.delete(e)}}isCurrentWorkspace(e){let t=this.getState();return t.selectedProject?.id===e.projectId&&t.selectedWorkspace?.id===e.workspaceId&&z(t)===e.machineId}async refreshParents(e){let t=this.getState();if(t.selectedProject===void 0||t.selectedWorkspace===void 0)return;let n={projectId:t.selectedProject.id,workspaceId:t.selectedWorkspace.id,machineId:z(t)},r=[...new Set(e.map(mc))];r.length!==0&&await this.requestTreeRefresh(n,r)}async refreshParentTrees(e,t){let n=this.getState().expandedDirs;t=[...new Set(t.map(e=>{for(;e!==``&&n[e]===void 0;)e=mc(e);return e}))];let r=[];for(let n=0;n<t.length;n+=128){let i=await this.api.workspaceTreeBatch(e.projectId,e.workspaceId,t.slice(n,n+128),e.machineId);r.push(...i.results)}if(!this.isCurrentWorkspace(e))return;let i={...this.getState().expandedDirs},a=this.getState().fileTree;for(let e of r){if(!(`tree`in e))throw Error(e.error);e.path===``?a=e.tree.entries:i[e.path]!==void 0&&i[e.path]===n[e.path]&&(i[e.path]=e.tree.entries)}this.setState({fileTree:a,expandedDirs:i})}removeExpandedSubtree(e){for(let t of this.directoryRequestGeneration.keys())(t===e||t.startsWith(`${e}/`))&&this.directoryRequestGeneration.delete(t);let t=Object.fromEntries(Object.entries(this.getState().expandedDirs).filter(([t])=>t!==e&&!t.startsWith(`${e}/`)));this.setState({expandedDirs:t})}async selectFile(e){this.setState({selectedFilePath:e,selectedFileContent:void 0,selectedFileLoadError:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),tc(uc,`file`,e),this.updateUrl({replace:!0}),await this.restoreFile(e)}selectDirectory(e){this.fileRequestGeneration+=1,this.setState({selectedFilePath:e,selectedFileContent:void 0,selectedFileLoadError:void 0,workspaceTool:`core:workspace.files`,mainView:this.getState().mainView===`chat`?`chat`:`core:workspace.files`}),tc(uc,`file`,void 0,{replace:!0}),this.updateUrl({replace:!0})}async restoreFile(e){let t=++this.fileRequestGeneration,n=this.getState(),r=n.selectedProject,i=n.selectedWorkspace;if(r===void 0||i===void 0)return;let a={generation:t,machineId:z(n),projectId:r.id,workspaceId:i.id,path:e};this.setState({selectedFilePath:e,selectedFileContent:void 0,selectedFileLoadError:void 0});try{let e=await this.api.workspaceFile(a.projectId,a.workspaceId,a.path,a.machineId);if(!this.isCurrentFileRequest(a))return;this.setState({selectedFileContent:e,selectedFileLoadError:void 0,error:``})}catch(e){if(!this.isCurrentFileRequest(a))return;this.setState({selectedFileContent:void 0,selectedFileLoadError:pc(e)})}}isCurrentFileRequest(e){let t=this.getState();return e.generation===this.fileRequestGeneration&&t.selectedFilePath===e.path&&t.selectedProject?.id===e.projectId&&t.selectedWorkspace?.id===e.workspaceId&&z(t)===e.machineId}async createFile(e){let t=this.getState().selectedProject,n=this.getState().selectedWorkspace;if(t===void 0||n===void 0||e===``)return;let r={projectId:t.id,workspaceId:n.id,machineId:z(this.getState())};try{if(await this.api.createWorkspaceFile(t.id,n.id,e,r.machineId),!this.isCurrentWorkspace(r)||(await this.refreshParents([e]),!this.isCurrentWorkspace(r)))return;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===``)return;let r={projectId:t.id,workspaceId:n.id,machineId:z(this.getState())};try{if(await this.api.createWorkspaceDirectory(t.id,n.id,e,r.machineId),!this.isCurrentWorkspace(r)||(await this.refreshParents([e]),!this.isCurrentWorkspace(r)))return;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===``)return;let i={projectId:t.id,workspaceId:n.id,machineId:z(this.getState())};try{let a=z(this.getState());if(gc(this.getState())===`directory`){if(await this.api.moveWorkspaceDirectory(t.id,n.id,r,e,a),!this.isCurrentWorkspace(i)||(this.removeExpandedSubtree(r),await this.refreshParents([r,e]),!this.isCurrentWorkspace(i)))return;this.selectDirectory(e)}else{if(await this.api.moveWorkspaceFile(t.id,n.id,r,e,void 0,a),!this.isCurrentWorkspace(i)||(await this.refreshParents([r,e]),!this.isCurrentWorkspace(i)))return;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===``)return;let r={projectId:e.id,workspaceId:t.id,machineId:z(this.getState())};try{let i=z(this.getState());if(gc(this.getState())===`directory`?await this.api.deleteWorkspaceDirectory(e.id,t.id,n,i):await this.api.deleteWorkspaceFile(e.id,t.id,n,i),!this.isCurrentWorkspace(r)||(this.removeExpandedSubtree(n),await this.refreshParents([n]),!this.isCurrentWorkspace(r)))return;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===``||gc(this.getState())===`directory`))try{await this.api.downloadWorkspaceFile(e.id,t.id,n,z(this.getState())),this.setState({error:``})}catch(e){this.setState({error:String(e)})}}clearSelection(){this.fileRequestGeneration+=1,this.setState({selectedFilePath:void 0,selectedFileContent:void 0,selectedFileLoadError:void 0}),tc(uc,`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=z(this.getState()),a=t.overwrite??!1,o=t.createDirs??!0,s;try{s=rc({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(sc(t,this.now())),this.uploadTasks.get(e)?.cancel())}clearWorkspaceUpload(e){this.uploadTasks.get(e)?.cancel(),this.uploadTasks.delete(e),this.setState({workspaceUploadBatches:hc(this.getState().workspaceUploadBatches,e)})}updateUploadProgress(e,t){let n=this.getUploadBatch(e);n?.status===`uploading`&&this.setUploadBatch(ic(n,t))}async completeUploadBatch(e,t,n){let r=this.getUploadBatch(e);if(r?.status!==`uploading`||(this.setUploadBatch(ac(r,t,this.now()),{error:``}),!this.isCurrentWorkspaceBatch(r)))return;await this.refreshParents(t.map(e=>e.path));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 Ko)||t.responses.length===0||r===void 0||!this.isCurrentWorkspaceBatch(r))return;await this.refreshParents(t.responses.map(e=>e.path));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(fc(t)){let e=sc(n,this.now());return this.setUploadBatch(e),e}let r=pc(t),i=oc(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&&z(t)===e.machineId}};function fc(e){return e instanceof Go}function pc(e){return e instanceof Error?e.message:String(e)}function mc(e){let t=e.replace(/\\/g,`/`);return t.slice(0,Math.max(0,t.lastIndexOf(`/`)))}function hc(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function gc(e){let t=e.selectedFilePath;return t===void 0?`file`:_c(e.fileTree,e.expandedDirs,t)?.type===`directory`?`directory`:`file`}function _c(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 vc=Qs(`core:workspace.git`),yc=8e3,bc=3e4,xc=1e3;function Sc(e){return JSON.stringify([e.machineId,e.projectId,e.workspaceId])}var Cc=class{constructor(e,t,n){this.getState=e,this.setState=t,this.updateUrl=n,this.diffRequestGeneration=0,this.statusRefreshes=new Map,this.statusLifecycleGeneration=0,this.disposed=!1,this.onVisibilityChange=()=>{this.updatePolling(),this.isDocumentVisible()&&this.isGitSurfaceActive()&&this.refreshGit()}}connect(){this.disposed=!1,this.visibilityDocument=document,document.addEventListener(`visibilitychange`,this.onVisibilityChange)}dispose(){this.disposed=!0,this.statusLifecycleGeneration+=1,this.statusRefreshes.clear(),this.diffRequestGeneration+=1,this.stopPolling(),this.visibilityDocument?.removeEventListener(`visibilitychange`,this.onVisibilityChange),this.visibilityDocument=void 0}stopPolling(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0,this.pollDelay=void 0}refreshGit(e=!0){if(this.disposed)return Promise.resolve();let t=this.getGitStatusRefreshTarget();if(t===void 0)return Promise.resolve();let n=Sc(t),r=this.statusRefreshes.get(n);if(r!==void 0)return r.refreshPending=!0,r.forceRefreshPending||=e,r.promise;let i={promise:Promise.resolve(),refreshPending:!0,forceRefreshPending:e},a=this.statusLifecycleGeneration;this.statusRefreshes.set(n,i);let o=this.runStatusRefreshLoop(t,n,i,a).finally(()=>{this.statusRefreshes.get(n)===i&&this.statusRefreshes.delete(n)});return i.promise=o,o}async runStatusRefreshLoop(e,t,n,r){for(;this.isStatusRefreshActive(t,n,r)&&this.consumeRefresh(n);){let t=n.forceRefreshPending;n.forceRefreshPending=!1,await this.refreshGitOnce(e,t,r)}}consumeRefresh(e){let t=e.refreshPending;return e.refreshPending=!1,t}async refreshGitOnce(e,t,n){let r=()=>this.isStatusLifecycleCurrent(n)&&this.isCurrentWorkspace(e.projectId,e.workspaceId,e.machineId);try{let n=await L.gitStatus(e.projectId,e.workspaceId,e.machineId,t);if(!r())return;this.setState({gitStatus:n,gitStale:!1,error:``}),this.restartPollingWhenIntervalChanges();let i=this.getState().selectedDiffPath;i!==void 0&&(n.files.some(e=>e.path===i)?await this.refreshDiff(i):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),tc(vc,`diff`,void 0,{replace:!0})))}catch(e){if(!r())return;this.setState({error:String(e)})}}getGitStatusRefreshTarget(){let e=this.getState(),t=e.selectedProject,n=e.selectedWorkspace;if(!(t===void 0||n===void 0))return{projectId:t.id,workspaceId:n.id,machineId:z(e)}}isStatusRefreshActive(e,t,n){return this.isStatusLifecycleCurrent(n)&&this.statusRefreshes.get(e)===t}isStatusLifecycleCurrent(e){return!this.disposed&&e===this.statusLifecycleGeneration}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`}),tc(vc,`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)return;let r=z(this.getState()),i=++this.diffRequestGeneration,a=()=>i===this.diffRequestGeneration&&this.isCurrentWorkspace(t.id,n.id,r)&&this.getState().selectedDiffPath===e;try{let[i,o]=await Promise.all([L.gitDiff(t.id,n.id,{path:e},r),L.gitDiff(t.id,n.id,{path:e,staged:!0},r)]);if(!a())return;this.setState({selectedDiff:i,selectedStagedDiff:o,error:``})}catch(e){if(!a())return;this.setState({error:String(e)})}}isCurrentWorkspace(e,t,n){let r=this.getState();return r.selectedProject?.id===e&&r.selectedWorkspace?.id===t&&z(r)===n}updatePolling(){this.stopPolling();let e=this.getState();if(!this.isGitSurfaceActive(e)||!this.isDocumentVisible())return;let t=(e.gitStatus?.files.length??0)>xc?bc:yc;this.pollDelay=t,this.pollTimer=window.setInterval(()=>{this.isDocumentVisible()&&this.refreshGit(!1)},t)}restartPollingWhenIntervalChanges(){this.pollTimer!==void 0&&((this.getState().gitStatus?.files.length??0)>xc?bc:yc)!==this.pollDelay&&this.updatePolling()}isGitSurfaceActive(e=this.getState()){return e.workspaceTool===`core:workspace.git`||e.mainView===`core:workspace.git`}isDocumentVisible(){return typeof document>`u`||document.visibilityState===`visible`}},wc=class{constructor(e,t,n,r){this.getState=e,this.setState=t,this.updateUrl=n,this.projects=r,this.runtimeRefreshSeqByMachine=new Map,this.browserErrors=new Es(e,t)}async loadMachines(e){this.setState({error:``,isLoadingMachines:!0});try{let t=await L.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));for(let e of Object.values(this.getState().browserErrors))e.scope.kind!==`global`&&!r.has(e.scope.machineId)&&this.browserErrors.discard(R(e.scope.machineId));this.setState({machines:t,selectedMachine:n,machineActivities:Ec(this.getState().machineActivities,r),machineRuntimes:Ec(this.getState().machineRuntimes,r),machineStatusSnapshots:Ec(this.getState().machineStatusSnapshots,r)}),this.refreshMachineHealthFor(t),this.refreshMachineRuntimeFor(t)}catch(e){this.setState({error:String(e)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(e,t={}){this.getState().selectedMachine?.id!==e.id&&(this.setState({selectedMachine:e,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...hs()}),t.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(e.id),this.refreshMachineRuntime(e.id))}async addMachine(e){this.setState({error:``});try{let t=await L.addMachine(e);return this.setState({machines:[...this.getState().machines.filter(e=>e.id!==t.id),t]}),await this.selectMachine(t),t}catch(e){this.setState({error:String(e)});return}}async deleteMachine(e=this.getState().selectedMachine,t={}){if(e!==void 0){if(e.kind===`local`){this.browserErrors.report(R(e.id),`无法移除本地机器。`);return}try{let n=this.getState().selectedMachine?.id===e.id;await L.deleteMachine(e.id);let r=this.getState().machines.filter(t=>t.id!==e.id),i=r.find(e=>e.id===`local`)??r[0];return this.browserErrors.discard(R(e.id)),this.setState({machines:r,machineStatuses:Tc(this.getState().machineStatuses,e.id),machineRuntimes:Tc(this.getState().machineRuntimes,e.id),machineActivities:Tc(this.getState().machineActivities,e.id),machineStatusSnapshots:Tc(this.getState().machineStatusSnapshots,e.id)}),n&&i!==void 0?(t.selectFallback===!1||await this.selectMachine(i),i):void 0}catch(t){this.browserErrors.report(R(e.id),String(t));return}}}async refreshMachineHealth(e=this.getState().selectedMachine?.id??`local`){try{let t=await L.health(e);return this.setState({machineStatuses:{...this.getState().machineStatuses,[t.machineId]:t}}),t}catch(t){this.browserErrors.report(R(e),String(t));return}}async refreshMachineRuntime(e=this.getState().selectedMachine?.id??`local`){let t=(this.runtimeRefreshSeqByMachine.get(e)??0)+1;this.runtimeRefreshSeqByMachine.set(e,t);try{let n=await L.runtime(e,!0);return this.runtimeRefreshSeqByMachine.get(e)===t?(this.setState({machineRuntimes:{...this.getState().machineRuntimes,[n.machineId]:n}}),n):void 0}catch(n){this.runtimeRefreshSeqByMachine.get(e)===t&&this.browserErrors.report(R(e),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||this.browserErrors.report(R(n.id),`${n.name} 暂不可用,正在重新连接…`),n}async safeRemoteHealth(e){try{return await L.health(e.id)}catch(t){return{machineId:e.id,ok:!1,checkedAt:new Date().toISOString(),status:`offline`,error:t instanceof Error?t.message:String(t)}}}localMachine(e){return e.find(e=>e.id===`local`)??e[0]}async refreshMachineHealthFor(e){let t=await Promise.allSettled(e.map(e=>L.health(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...n}})}async refreshMachineRuntimeFor(e){let t=await Promise.allSettled(e.map(e=>L.runtime(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...n}})}};function Tc(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Ec(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}var Dc=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new Us,this.api=n.api??Eo}refresh(e){return this.refreshes.request(e,async()=>{this.apply(e,await this.api.machineStatus(e))})}apply(e,t){let n=this.getState().machineStatusSnapshots;Oc(n[e],t)&&this.setState({machineStatusSnapshots:{...n,[e]:t}})}};function Oc(e,t){return e===void 0||e.epochId!==t.epochId||t.revision>e.revision}var kc=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.api=r.api??L,this.onProjectsApplied=r.onProjectsApplied,this.browserErrors=new Es(e,t)}async loadProjects(){let e=z(this.getState());this.setState({isLoadingProjects:!0});try{let t=await this.api.projects(e);if(z(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){this.browserErrors.report(R(e),String(t))}finally{z(this.getState())===e&&this.setState({isLoadingProjects:!1})}}async addProject(e,t){if(e.trim()===``)return;let n=z(this.getState()),r;try{r=await this.api.addProject(e.trim(),void 0,t,n)}catch(e){this.browserErrors.report(R(n),String(e));return}if(z(this.getState())===n)try{let e=this.getState().projects;this.setState({projects:[...e.filter(e=>e.id!==r.id),r],projectDialogOpen:!1}),this.onProjectsApplied?.(n),await this.workspaces.selectProject(r)}catch(e){this.browserErrors.report(_s(n,r.id),String(e))}}async closeProject(e){let t=z(this.getState());try{if(await this.api.closeProject(e,t),z(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(n){this.browserErrors.report(_s(t,e),String(n))}}};function Ac(e,t){return t[e.path]}function jc(e){if(e?.hasSessionActivity===!0)return`session`;if(e?.hasTerminalActivity===!0)return`terminal`}function Mc(e,t,n){return Fc(Ic(e,t,n))}function Nc(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function Pc(e){return Fc(Object.values(e??{}))}function Fc(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function Ic(e,t,n){return Object.values(n).filter(n=>Nc(e,t,n.cwd))}var Lc=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??Ao,this.onError=n.onError}handleActivityApplied(e){return z(this.getState())===e?(this.activityMachineGeneration=this.machineGeneration,this.reconcile(e)):Promise.resolve()}handleProjectsApplied(e){return z(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(z(t)!==e)return Promise.resolve();let n=this.syncActiveCwds(t),r=new Map([...n].filter(([e,n])=>!Rc(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&&!Rc(t.projects,t.workspacesByProjectId,r)&&this.attemptedCwdActivations.set(r,i);let r=e.trailingRequested;this.activePass=void 0,r&&await this.reconcile(z(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&&z(this.getState())===e.machineId}syncActiveCwds(e){let t=new Set(Object.values(e.workspaceActivities).filter(js).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 Rc(e,t,n){return e.some(e=>Nc(e,t[e.id]??[],n))}var zc=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??go,this.onRefreshError=n.onRefreshError??(()=>void 0)}async refresh(){let e=z(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=z(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}),Bc(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 z(this.getState())===e&&t===this.requestSequence}};function Bc(e){if(e.release.error!==void 0)throw Error(`PI WEB 更新检查失败:${e.release.error}`);if(e.release.skipped===!0)throw Error(`由于离线或版本检查设置禁用了远程版本检查,已跳过 PI WEB 更新检查`)}function Vc(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}var Hc=`pi-web:cached-new-sessions:v1`,Uc=`browserCachedNew`,Wc=`local`;function Gc(e,t=Wc,n=Vc()){if(e.messageCount!==0||e.archived===!0)return;let r=Zc(n).filter(n=>n.id!==e.id||n.machineId!==t);Qc([Kc(e,t),...r],n)}function Kc(e,t=Wc){return{...e,browserCachedNew:!0,machineId:t}}function qc(e,t=Wc,n=Vc()){Qc(Zc(n).filter(n=>n.id!==e||n.machineId!==t),n)}function Jc(e,t,n=Wc,r=Vc()){let i=new Set(t.map(e=>e.id)),a=Zc(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&Qc(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function Yc(e){return e!==void 0&&el(e)&&e.browserCachedNew===!0}function Xc(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:Wc},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Zc(e=Vc()){try{let t=e?.getItem(Hc);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>$c(e)):[]}catch{return[]}}function Qc(e,t=Vc()){try{e.length===0?t?.removeItem(Hc):t?.setItem(Hc,JSON.stringify(e))}catch{}}function $c(e){if(!tl(e))return[];let t=nl(e,`id`),n=nl(e,`path`),r=nl(e,`cwd`),i=nl(e,`created`),a=nl(e,`modified`),o=nl(e,`firstMessage`),s=il(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=rl(e,`name`),l=rl(e,`parentSessionPath`),u=rl(e,`machineId`)??Wc;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 el(e){return Uc in e}function tl(e){return typeof e==`object`&&!!e}function nl(e,t){let n=e[t];return typeof n==`string`?n:void 0}function rl(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function il(e,t){let n=e[t];return typeof n==`number`?n:void 0}function al(e,t){return Dl(t===void 0?e.flatMap(ul):e.flatMap((e,n)=>ul(e).map(e=>({...e,transcriptIndex:t+n})))).filter(e=>e.parts.length>0)}function ol(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function sl(e,t){let n=gl(t);return n===void 0?e:{...e,meta:n}}function cl(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,ol(t,n)]}function ll(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 ul(e){if(fl(e))return[e];if(B(e,`role`)===`bashExecution`)return[sl(yl(e),e)];let t=B(e,`role`),n=bl(t),r=xl(Fl(e,`content`),e),i=t===`toolResult`?Cl(B(e,`toolName`)??``,Fl(e,`details`)):void 0,a=i===void 0?r:[...r,i],o=n===`user`?pl(a):void 0;if(o!==void 0)return o.map(t=>sl(t,e));let s=hl(e);if(n===`tool`)return[sl({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?[sl({role:l,parts:c,...s===void 0?{}:{source:s}},e)]:[],d=dl(e);return d===void 0?u:[...u,sl(d,e)]}function dl(e){if(B(e,`role`)!==`assistant`||B(e,`stopReason`)!==`error`)return;let t=B(e,`errorMessage`)?.trim();return ol(`system`,`模型响应失败:${t===void 0||t===``?`模型返回了错误。`:t}`)}function fl(e){let t=B(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(Fl(e,`parts`))}function pl(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=ml(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 ml(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 hl(e){let t=B(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function gl(e){let t=_l(Fl(e,`timestamp`)),n=vl(e),r=B(e,`thinkingLevel`);if(!(t===void 0&&n===void 0&&(r===void 0||r===``)))return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n},...r===void 0||r===``?{}:{thinkingLevel:r}}}function _l(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 vl(e){if(B(e,`role`)!==`assistant`)return;let t=B(e,`provider`),n=B(e,`model`),r=B(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 yl(e){let t=B(e,`command`)??``,n=Il(e,`excludeFromContext`)===!0?[`已从上下文中排除`,``,`$ ${t}`]:[`$ ${t}`],r=Fl(e,`output`);r!=null&&n.push(``,Rl(r));let i=Fl(e,`exitCode`);i!=null&&n.push(``,`退出码 ${Rl(i)}`),Il(e,`cancelled`)===!0&&n.push(``,`已取消`),Il(e,`truncated`)===!0&&n.push(``,`输出已截断`);let a=B(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`完整输出:${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
|
|
4
4
|
`)}]}}function bl(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function xl(e,t){let n=Sl(t);return n===void 0?typeof e==`string`?e===``?[]:[{type:`text`,text:e}]:Array.isArray(e)?e.flatMap(e=>{let t=B(e,`type`),n=B(e,`text`);if(t===`text`)return n!==void 0&&n!==``?[{type:`text`,text:n}]:[];if(t===`thinking`){let t=B(e,`thinking`)??n;return t!==void 0&&t!==``?[{type:`thinking`,text:t}]:[]}if(t===`toolCall`){let t=B(e,`name`)??`tool`,n=Fl(e,`arguments`),r=B(e,`id`),i=t===`read`?El(B(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:Ml(n),...n===void 0?{}:{args:n}}]:[{type:`skillRead`,...i,...r===void 0?{}:{toolCallId:r}}]}if(t===`image`){let t=B(e,`data`),n=B(e,`mimeType`);return t!==void 0&&t!==``&&n!==void 0&&n!==``?[{type:`image`,mimeType:n,data:t}]:[{type:`text`,text:`[image]`}]}return jl(e)}).map(e=>e.type===`text`&&B(t,`role`)===`toolResult`?Tl(e.text,t):e):jl(e):[n]}function Sl(e){if(!(B(e,`role`)!==`custom`||B(e,`customType`)!==`pi-web.ask.answers`))return wl(Fl(e,`details`))}function Cl(e,t){if(e===`ask_user`)return wl(Fl(t,`superseded`))}function wl(e){try{return{type:`askUserRecord`,outcome:Zn(e)}}catch{return}}function Tl(e,t){let n=B(t,`toolCallId`),r=Fl(t,`content`),i=Fl(t,`details`);return{type:`toolResult`,...n===void 0?{}:{toolCallId:n},toolName:B(t,`toolName`)??`tool`,text:e,...r===void 0?{}:{content:r},...i===void 0?{}:{details:i},isError:Il(t,`isError`)===!0}}function El(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 Dl(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=Ol(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&&kl(t,e,o)){n.delete(o.toolCallId??``);continue}}e.push(o)}a()}return t}function Ol(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 kl(e,t,n){let r=e[t.lineIndex],i=r?.parts[t.partIndex];if(r===void 0||i?.type!==`toolExecution`)return!1;let a=Al(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 Al(e){let t=Fl(e,`preview`);if(!Pl(t))return;let n=B(t,`diff`),r=B(t,`error`),i=Ll(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 jl(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:Ml(e)}]:[{type:`text`,text:Rl(e)}]}function Ml(e){if(!Pl(e))return Rl(e);let t=B(e,`command`);if(t!==void 0)return t;let n=B(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}: ${Nl(t)}`).join(` · `)}function Nl(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 Pl(e){return typeof e==`object`&&!!e}function Fl(e,t){return Pl(e)?e[t]:void 0}function B(e,t){let n=Fl(e,t);return typeof n==`string`?n:void 0}function Il(e,t){let n=Fl(e,t);return typeof n==`boolean`?n:void 0}function Ll(e,t){let n=Fl(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Rl(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var zl=`pi-web:prompt-draft:`;function Bl(e){return`${zl}${e}`}function Vl(e,t=Vc()){try{return t?.getItem(Bl(e))??``}catch{return``}}function Hl(e,t,n=Vc()){try{t?n?.setItem(Bl(e),t):n?.removeItem(Bl(e))}catch{}}function Ul(e,t=Vc()){try{t?.removeItem(Bl(e))}catch{}}function Wl(e,t,n=Vc()){let r=Vl(e,n);r!==``&&(Hl(t,r,n),Ul(e,n))}var Gl=new Map;function Kl(e,t=Gl){return t.get(e)??[]}function ql(e,t,n=Gl){t.length>0?n.set(e,t):n.delete(e)}function Jl(e,t=Gl){t.delete(e)}function Yl(e,t,n=Gl){let r=n.get(e);r!==void 0&&(n.set(t,r),n.delete(e))}var Xl=`pi-web:ask-draft:`;function Zl(e,t){return`${Xl}${e}:${t}`}function Ql(e,t,n=Vc()){try{let r=n?.getItem(Zl(e,t));return r==null?{}:tu(r)}catch{return{}}}function $l(e,t,n,r=Vc()){try{let i=Object.entries(n).filter(([,e])=>e.values.length>0||(e.otherText??``)!==``);i.length===0?r?.removeItem(Zl(e,t)):r?.setItem(Zl(e,t),JSON.stringify(Object.fromEntries(i)))}catch{}}function eu(e,t,n=Vc()){try{n?.removeItem(Zl(e,t))}catch{}}function tu(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=nu(r);t!==void 0&&(n[e]=t)}return n}function nu(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 ru(e,t){return e.filter(e=>ou(e,t[e.id])!==void 0).length}function iu(e,t){return e.filter(e=>ou(e,t[e.id])===void 0)}function au(e,t){let n=[];for(let r of e){let e=ou(r,t[r.id]);e!==void 0&&n.push(e)}return{answers:n}}function ou(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=su(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 su(e){if(e===void 0)return;let t=e.trim().slice(0,Ht);return t===``?void 0:t}function cu(e,t){return ol(`bash`,`${t===!0?`已从上下文中排除
|
|
@@ -16,7 +16,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
|
|
|
16
16
|
`)}function zu(e,t){let n=ul(t);return n.length===0?e:[...e,...n]}function Bu(e,t){let n=e.at(-1);return Vu(e,t)?e:n?.role===t.role&&t.role!==`skill`?[...e.slice(0,-1),{...n,parts:[...n.parts,...t.parts]}]:[...e,t]}function Vu(e,t){let n=Nu(t);if(t.role!==`skill`||n.length===0)return!1;let r=Uu(e)+1;return n.every(t=>Hu(e,t,r))}function Hu(e,t,n){for(let r=e.length-1;r>=n;r--)if(Nu(e[r]).some(e=>Fu(e,t)))return!0;return!1}function Uu(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role===`user`)return t;return-1}function Wu(e){return typeof e==`object`&&!!e}function Gu(e,t){return Wu(e)?e[t]:void 0}function Ku(e,t){let n=Gu(e,t);return typeof n==`string`?n:void 0}function qu(e,t){let n=Gu(e,t);return typeof n==`boolean`?n:void 0}var Ju=`pi-web:chat-history:v2:`,Yu=1800*1e3;function Xu(e){try{let t=sessionStorage.getItem(id(e));if(t===null||t===``)return;let n=JSON.parse(t);if(!ad(n))return;if(Date.now()-n.savedAt>Yu){sessionStorage.removeItem(id(e));return}return{messages:n.messages,start:n.start,total:n.total}}catch{return}}function Zu(e,t){try{sessionStorage.setItem(id(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function Qu(e){try{sessionStorage.removeItem(id(e))}catch{}}function $u(e,t){if(e===void 0||!od(e))return t;if(!od(t))return e;if(td(e,t))return t;let n=Math.min(e.start,t.start),r=Math.max(e.start+e.messages.length,t.start+t.messages.length),i=Array(r-n);return rd(i,n,e),rd(i,n,t),nd(i)?t:{start:n,total:Math.max(e.total,t.total),messages:i}}function ed(e,t){if(e===void 0||!od(t)||t.total!==e.total)return!1;let n=t.start-e.start;return n<0||n+t.messages.length!==e.messages.length?!1:JSON.stringify(t.messages)===JSON.stringify(e.messages.slice(n))}function td(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function nd(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function rd(e,t,n){n.messages.forEach((r,i)=>{e[n.start-t+i]=r})}function id(e){return`${Ju}${e}`}function ad(e){if(typeof e!=`object`||!e||!(`messages`in e)||!(`start`in e)||!(`total`in e)||!(`savedAt`in e))return!1;let{messages:t,start:n,total:r,savedAt:i}=e;return Array.isArray(t)&&typeof n==`number`&&typeof r==`number`&&typeof i==`number`&&od({messages:t,start:n,total:r})}function od(e){return Number.isInteger(e.start)&&Number.isInteger(e.total)&&e.start>=0&&e.total>=e.start&&e.messages.length<=e.total-e.start&&!e.messages.some(sd)}function sd(e){return typeof e==`object`&&!!e&&`role`in e&&`parts`in e&&!(`content`in e)&&typeof e.role==`string`&&Array.isArray(e.parts)}var cd={read:Xu,write:Zu,remove:Qu},ld=class{constructor(e=cd){this.cache=e,this.rawHistoryPages=new Map}cachedView(e){return ud(this.rawHistoryPage(e))}indexedView(e){return ud(this.rawHistoryPage(e),!0)}mergeHistory(e,t){let n=$u(this.rawHistoryPage(e),t);return this.rawHistoryPages.set(e,n),this.cache.write(e,n),ud(n)}applyLiveEvent(e,t){return pu(e,t)}seedStreamingPartial(e,t){return fu(e,t)}discard(e){this.rawHistoryPages.delete(e),this.cache.remove?.(e)}rawHistoryPage(e){let t=this.rawHistoryPages.get(e)??this.cache.read(e);return t!==void 0&&this.rawHistoryPages.set(e,t),t}};function ud(e,t=!1){let n=e?.start??0;return{messages:al(e?.messages??[],t||e!==void 0?n:void 0),messagePageStart:n,messagePageEnd:n+(e?.messages.length??0),messagePageTotal:e?.total??0}}function dd(e,t=e.length){let n=e.slice(0,t),r=_d(n,t);if(r!==void 0)return r;let i=vd(n,t);if(i!==void 0)return i;let a=Math.max(n.lastIndexOf(` `),n.lastIndexOf(`
|
|
17
17
|
`))+1,o=n.slice(a);if(n.slice(0,a).endsWith(`@ `))return{kind:`file`,query:o,from:a-2,to:t,fileScope:`all`,allPrefix:`@ `};if(o.startsWith(`/`)&&a===0)return{kind:`command`,query:o.slice(1),from:a,to:t};if(o.startsWith(`!@`))return{kind:`file`,query:o.slice(2),from:a,to:t,fileScope:`all`,allPrefix:`!@`};if(o.startsWith(`@`))return{kind:`file`,query:o.slice(1),from:a,to:t,fileScope:`tracked`};if(o.startsWith(`#`))return{kind:`model`,query:o.slice(1),from:a,to:t}}var fd=12;function pd(e,t){let n=t.toLowerCase(),r=[];for(let t of e)if(md(t)&&hd(t,n)&&(r.push({insertText:`#${t.provider}/${t.id}`,detail:t.provider,...t.name!==void 0&&t.name!==``&&t.name!==t.id?{description:t.name}:{}}),r.length>=fd))break;return r}function md(e){return typeof e.provider==`string`&&e.provider!==``&&typeof e.id==`string`&&e.id!==``}function hd(e,t){return`${e.provider}/${e.id}`.toLowerCase().includes(t)||e.id.toLowerCase().includes(t)||(e.name?.toLowerCase().includes(t)??!1)}function gd(e,t,n){let r=n??`@`;return!t&&!e.includes(` `)?`${r}${e}`:`${r}"${e}"`}function _d(e,t){let n=e.lastIndexOf(`"`);if(n===-1)return;let r=e.slice(0,n);if(r.endsWith(`!@`))return{kind:`file`,query:e.slice(n+1),from:r.length-2,to:t,fileScope:`all`,allPrefix:`!@`,quoted:!0};if(r.endsWith(`@`))return{kind:`file`,query:e.slice(n+1),from:r.length-1,to:t,fileScope:`tracked`,quoted:!0};if(r.endsWith(`@ `))return{kind:`file`,query:e.slice(n+1),from:r.length-2,to:t,fileScope:`all`,allPrefix:`@ `,quoted:!0}}function vd(e,t){let n=e.lastIndexOf(`
|
|
18
18
|
`)+1,r=e.slice(n),i=yd(r,`@ `),a=yd(r,`!@`),o=Math.max(i,a);if(o===-1)return;let s=o===a?`!@`:`@ `,c=n+o,l=c+s.length;return{kind:`file`,query:e.slice(l),from:c,to:t,fileScope:`all`,allPrefix:s}}function yd(e,t){for(let n=e.lastIndexOf(t);n>=0;n=e.lastIndexOf(t,n-1))if(n===0||bd(e[n-1]))return n;return-1}function bd(e){return e===` `||e===` `}function xd(e){let t=e.trimStart();if(t.startsWith(`!@`))return{kind:`file`};if(t.startsWith(`!`))return{kind:`shell`,excludeFromContext:t.startsWith(`!!`)};if(wd(e).startsWith(`/`))return{kind:`command`};let n=dd(e);return n?.kind===`file`?{kind:`file`}:n?.kind===`model`?{kind:`model`}:{kind:`normal`}}function Sd(e){return xd(e).kind===`shell`}function Cd(e,t){return e.kind===t.kind?e.kind===`shell`&&t.kind===`shell`?e.excludeFromContext===t.excludeFromContext:!0:!1}function wd(e){let t=Math.max(e.lastIndexOf(` `),e.lastIndexOf(`
|
|
19
|
-
`))+1;return e.slice(t)}var Td=class{constructor(e=`normal`){this.scope=e,this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId=`local`}connect(e,t,n,r=`local`,i){this.close(),this.machineId=r,this.session=e,this.onEvent=t,this.onReconnect=n,this.onInitialOpen=i,this.shouldReconnect=!0,this.open()}setHandler(e){this.onEvent=e}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Id(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.onInitialOpen=void 0,this.hasOpened=!1,this.machineId=`local`}open(){let e=this.session;if(e===void 0||e.id===``||e.cwd===``||!this.shouldReconnect)return;let t=Bo(e,this.machineId,this.scope);this.socket=t,t.onopen=()=>{if(this.socket!==t)return;this.reconnectDelay=500;let e=this.hasOpened;this.hasOpened=!0,e?this.onReconnect?.():this.onInitialOpen?.()},t.onmessage=n=>void this.handleMessage(n.data,t,e),t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t,n){let r=Dd(await Fd(e));this.socket!==t||r===void 0||r.type===`notifications.inbox`&&(n.id!==r.summary.sessionId||n.cwd!==r.summary.cwd)||this.onEvent?.(r)}},Ed=class{constructor(e=`normal`){this.scope=e,this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId=`local`}connect(e,t,n=`local`){this.close(),this.machineId=n,this.onEvent=e,this.onOpen=t,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Id(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId=`local`}open(){if(!this.shouldReconnect)return;let e=Ho(this.machineId,this.scope);this.socket=e,e.onopen=()=>{this.socket===e&&(this.reconnectDelay=500,this.onOpen?.())},e.onmessage=t=>void this.handleMessage(t.data,e),e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t){let n=Od(await Fd(e));this.socket===t&&n!==void 0&&this.onEvent?.(n)}};function Dd(e){let t=Pd(e);return t===`notifications.inbox`?Md(()=>Er(e)):t===`ask.opened`?Nd(()=>qn(e)):t===`ask.closed`?Nd(()=>Jn(e)):t===`dialog.opened`?Nd(()=>sr(e)):t===`dialog.closed`?Nd(()=>cr(e)):kd(e)?e:void 0}function Od(e){if(Pd(e)===`machine.status`){if(typeof e!=`object`||!e||!(`status`in e))return;let t=cn(e.status);return t===void 0?void 0:{type:`machine.status`,status:t}}if(Pd(e)===`sessions.unread`)return Nd(()=>mr(e));if(Pd(e)===`notices.updated`)return Nd(()=>Or(e));if(Pd(e)===`models.changed`)return Nd(()=>kr(e));if(Pd(e)===`session.startup`)return Nd(()=>hr(e));if(Ad(e)||jd(e))return e}function kd(e){return[`message.append`,`assistant.delta`,`assistant.thinking.delta`,`tool.start`,`tool.update`,`tool.end`,`shell.start`,`shell.chunk`,`shell.end`,`agent.start`,`agent.end`,`message.end`,`status.update`,`activity.update`,`command.output`,`session.error`,`session.name`,`session.created`,`pi.event`].includes(Pd(e))}function Ad(e){let t=Pd(e);return t===`status.update`||t===`activity.update`||t===`session.name`||t===`session.created`}function jd(e){let t=Pd(e);return t===`terminal.created`||t===`terminal.exited`||t===`terminal.closed`||t===`workspace.activity`}function Md(e){return Nd(e)}function Nd(e){try{return e()}catch{return}}function Pd(e){if(typeof e!=`object`||!e||!(`type`in e))return``;let t=e.type;return typeof t==`string`?t:``}async function Fd(e){try{return typeof e==`string`?JSON.parse(e):e instanceof Blob?JSON.parse(await e.text()):e instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(e)):void 0}catch{return}}function Id(e){if(e!==void 0){if(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING){e.onopen=()=>{e.close()};return}e.close()}}function Ld(e){return e?.ok===!0}function Rd(e){return{authoritative:Ld(e)}}function zd(e,t,n={}){if(e===void 0)return`unknown`;let r=(t?.sessionId===e.id?t.persisted:void 0)??e.persisted;return r===!0?`persisted`:r===!1||Yc(e)?`transient`:n.authoritative===!0?`unknown`:`persisted`}function Bd(e,t,n){return e!==void 0&&e.archived!==!0&&zd(e,t,n)===`persisted`}function Vd(e,t,n){return e!==void 0&&e.archived!==!0&&zd(e,t,n)===`transient`}function Hd(){try{return typeof sessionStorage>`u`?void 0:sessionStorage}catch{return}}var Ud=class{constructor(e,t,n=Hd()){this.storageKey=e,this.storage=n,this.values=new Map;for(let[r,i]of Gd(e,t,n))this.values.set(r,i)}get(e){return this.values.get(e)}set(e,t){this.values.set(e,t),this.save()}delete(e){this.values.delete(e),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}let e={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(e))}catch{}}};function Wd(e){return typeof e==`string`&&e!==``?e:void 0}function Gd(e,t,n){try{let r=n?.getItem(e);if(r==null||r===``)return[];let i=JSON.parse(r);if(!Kd(i))return[];let a=[];for(let e of i.entries){let n=e[0],r=t(e[1]);r!==void 0&&a.push([n,r])}return a}catch{return[]}}function Kd(e){return!qd(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`&&e[0]!==``)}function qd(e){return typeof e==`object`&&!!e}var Jd=class{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}},Yd=`pi-web:session-selection:v1`,Xd=class{constructor(e=Hd()){this.sessionIdsByCwd=new Ud(Yd,Wd,e)}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}};function Zd(e,t){let n=t?.targetSessionId;if(n!==void 0&&n!==``)return $d(e,n);let r=t?.latestSessionId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>e.archived!==!0):e.find(e=>e.archived!==!0)}function Qd(e,t){return t?.archived===!0&&!e.some(e=>e.archived!==!0)}function $d(e,t){return e.find(e=>e.id===t||e.id.startsWith(t))}function ef(e,t,n){return tf(e,[t],n)}function tf(e,t,n){let r=new Set(t);return e.map(e=>r.has(e.id)?{...e,archived:!0,archivedAt:n}:e)}function nf(e,t,n){return rf(e,t,[n])}function rf(e,t,n){if(t===void 0||!n.includes(t))return{type:`unchanged`};let r=new Set(n),i=e.find(e=>!r.has(e.id)&&e.archived!==!0);return i===void 0?{type:`clear`}:{type:`select`,session:i}}var af=100,of=500,sf=5e3,cf=class{constructor(e,t,n,r=new Jd,i={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessionSelection=r,this.selectionSeq=0,this.disposed=!1,this.pendingTranscriptEvents=[],this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.sessionRefreshInFlight=!1,this.searchSeq=0,this.searchTargetSeq=0,this.pendingSessionStartSeq=0,this.pendingQueuedSendSeq=0,this.pendingSessionStarts=new Map,this.suppressedCreatedSessions=new Map,this.selectedSessionRefreshes=new Us,this.socket=i.socket??new Td,this.api=i.api??L,this.transcripts=i.transcripts??new ld,this.streamSnapshot=i.streamSnapshot??i.api?.streamSnapshot??L.streamSnapshot,this.notifications=i.notifications,this.replacePromptEditorText=i.replacePromptEditorText,this.onSelectedSessionReady=i.onSelectedSessionReady,this.onModelScopeChanged=i.onModelScopeChanged,this.browserErrors=new Es(e,t)}applyGlobalEvent(e){e.type===`status.update`?this.queueStatusUpdate(e.status):e.type===`activity.update`?this.queueActivityUpdate(e.activity):e.type===`session.created`?this.applyCreatedSession(e.session):e.type===`session.name`?this.applySessionName(e.sessionId,e.name):e.type===`models.changed`?this.onModelScopeChanged?.(e.revision):e.type===`session.startup`&&this.queueStartupProgress(e)}dispose(){this.disposed=!0,this.selectionSeq+=1,this.searchSeq+=1,this.stopPolling(),this.searchTimer!==void 0&&clearTimeout(this.searchTimer),this.searchTimer=void 0,this.socket.close(),this.clearPendingUpdates()}updatePolling(){this.stopPolling(),this.getState().selectedWorkspace!==void 0&&(this.sessionPollTimer=setInterval(()=>{this.sessionRefreshInFlight||(this.sessionRefreshInFlight=!0,this.refreshCurrentWorkspaceSessions().finally(()=>{this.sessionRefreshInFlight=!1}))},sf))}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0})}deselectSession(e){let t=this.getState(),n=t.selectedSession?.cwd??t.selectedWorkspace?.path;e?.forgetRememberedSelection===!0&&n!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(n)),this.clearActiveSession(),e?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){let e=this.getState();Qd(e.sessions,e.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){let e=this.getState().selectedWorkspace;if(!e)return;let t=z(this.getState()),n=this.createPendingSessionStart(e,t);this.pendingSessionStarts.set(n.tempId,n),this.insertAndSelectPendingSession(n.session);try{let r=await this.api.startSession(e.path,t,n.tempId);await this.resolvePendingSessionStart(n.tempId,r)}catch(e){this.failPendingSessionStart(n.tempId,e)}}async refreshPinnedSessions(e,t=z(this.getState())){try{let n=await this.api.pinned(e,t);if(z(this.getState())!==t||this.getState().selectedWorkspace?.path!==e)return;this.setState({pinnedSessionIds:n.sessionIds})}catch{z(this.getState())===t&&this.getState().selectedWorkspace?.path===e&&this.setState({pinnedSessionIds:[]})}}togglePinned(e){if(e.persisted===!1)return;let t=this.getState(),n=t.pinnedSessionIds.includes(e.id),r=n?t.pinnedSessionIds.filter(t=>t!==e.id):[...t.pinnedSessionIds,e.id],i=z(t);this.setState({pinnedSessionIds:r}),(async()=>{try{let t=n?await this.api.unpin(e,i):await this.api.pin(e,i),r=this.getState();if(z(r)!==i||r.selectedWorkspace?.path!==e.cwd)return;let a=t.pinned;this.setState({pinnedSessionIds:a?[...new Set([...this.getState().pinnedSessionIds,e.id])]:this.getState().pinnedSessionIds.filter(t=>t!==e.id)})}catch(t){let r=this.getState();if(z(r)!==i||r.selectedWorkspace?.path!==e.cwd)return;this.setState({pinnedSessionIds:n?[...new Set([...r.pinnedSessionIds,e.id])]:r.pinnedSessionIds.filter(t=>t!==e.id)}),this.reportSessionError(e,i,t)}})()}searchSessions(e){let t=this.getState(),n=t.selectedWorkspace,r=z(t);this.searchSeq+=1;let i=this.searchSeq;this.searchTimer!==void 0&&clearTimeout(this.searchTimer),this.searchTimer=void 0,this.setState({sessionSearchQuery:e,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``});let a=e.trim();n===void 0||a===``||(this.setState({isSearchingSessions:!0}),this.searchTimer=setTimeout(()=>{this.searchTimer=void 0,this.performSessionSearch(i,a,n.id,n.path,r)},250))}async performSessionSearch(e,t,n,r,i){try{let a=await this.api.searchContent(r,t,i),o=this.getState();if(e!==this.searchSeq||z(o)!==i||o.selectedWorkspace?.id!==n||o.sessionSearchQuery.trim()!==t)return;this.setState({sessionSearchResults:a,isSearchingSessions:!1})}catch(t){let r=this.getState();if(e!==this.searchSeq||z(r)!==i||r.selectedWorkspace?.id!==n)return;this.setState({sessionSearchResults:{results:[],matchCount:0,truncated:!1},isSearchingSessions:!1,sessionSearchError:String(t)})}}preferredSession(e,t,n){return Zd(t,{targetSessionId:n,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(e))})}async selectSession(e,t){if(this.disposed)return;if(hf(e)){this.selectClientPendingStartSession(e,t);return}let n=z(this.getState()),r=this.captureSessionErrorOwner(e);this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)});let i=++this.selectionSeq;this.socket.close(),this.streamWatermark=void 0,this.clearPendingUpdates(),this.notifications?.prepareSelectedSession(e,n);let a=this.sessionCacheKey(e.id),o=this.transcripts.cachedView(a);this.setState({selectedSession:e,sessionSearchTarget:void 0,...o,isLoadingEarlierMessages:!1,status:e.archived===!0?void 0:this.getState().sessionStatuses[e.id],activity:e.archived===!0?void 0:this.getState().sessionActivities[e.id],pendingAsk:e.archived===!0?void 0:this.selectedPendingAsk(this.getState().sessionStatuses[e.id]),pendingDialogs:e.archived===!0?[]:this.getState().sessionStatuses[e.id]?.pendingDialogs??[],closedDialogs:[],availableThinkingLevels:[]});let s;try{if(e.archived===!0){let n=await this.api.messages(e,{limit:af},z(this.getState()));if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;let r=this.transcripts.mergeHistory(a,n);this.setState({...r,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[]}),t?.updateUrl!==!1&&this.updateUrl();return}let o=[];if(s=o,this.socket.connect(e,e=>o.push(e),()=>{this.refreshSelectedSession(e.id)},n,()=>{this.notifications?.refreshSelectedSession(e,n)}),await this.requestSelectedSessionRefresh({session:e,machineId:n,selectionSeq:i,errorOwner:r}),!this.isCurrentRefreshTarget({session:e,machineId:n,selectionSeq:i,errorOwner:r}))return;this.refreshAvailableThinkingLevels();for(let e of o)this.applyEvent(e);this.socket.setHandler(e=>{this.applyEvent(e)}),this.onSelectedSessionReady?.({machineId:n,session:e}),t?.updateUrl!==!1&&this.updateUrl()}catch(a){if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id){if(this.reportSessionError(e,n,a,r),t?.propagateRefreshError===!0&&this.isSelectedSessionIdentity(e.id,n))throw a;return}if(Yc(e)&&Df(a)){await this.recreateCachedNewSession(e,t);return}if(s!==void 0){for(let e of s)this.applyEvent(e);this.socket.setHandler(e=>{this.applyEvent(e)})}if(this.reportSessionError(e,n,a,r),t?.propagateRefreshError===!0)throw a}}async loadEarlierMessages(){let e=this.getState(),t=e.selectedSession;if(!t||e.isLoadingEarlierMessages||e.messagePageStart<=0)return;let n=z(e),r=this.selectionSeq,i=Hs(n,t.id),a=()=>{let e=this.getState();return!this.disposed&&r===this.selectionSeq&&z(e)===n&&e.selectedSession?.id===t.id&&e.selectedSession.cwd===t.cwd&&e.selectedSession.path===t.path&&e.selectedSession.archived===t.archived};this.setState({isLoadingEarlierMessages:!0});try{let r=await this.api.messages(t,{before:e.messagePageStart,limit:af},n);if(!a())return;let o=this.transcripts.mergeHistory(i,r);this.setState(o)}catch(e){if(!a())return;this.reportSessionError(t,n,e)}finally{a()&&this.setState({isLoadingEarlierMessages:!1})}}async send(e,t,n,r=`inline`,i){let a=this.getState().selectedSession;if(!a||a.archived===!0)return;let o=e.trim(),s=n!==void 0&&n.length>0;if(hf(a)){!s&&o.startsWith(`/`)?this.enqueuePendingSessionSend(a,{type:`command`,text:e}):!s&&Sd(e)?this.enqueuePendingSessionSend(a,{type:`shell`,text:e}):this.enqueuePendingSessionSend(a,{type:`prompt`,text:e,streamingBehavior:t,attachments:n,delivery:r,folder:i});return}if(!s&&o.startsWith(`/`))return this.runCommand(e);if(!s&&Sd(e))return this.runShell(e);await this.deliverPromptToSession(a,e,t,n,r,i,z(this.getState()),{markSending:s})}markSendingPrompt(e,t){let n=this.getState().sendingPrompts;t?n[e]!==!0&&this.setState({sendingPrompts:{...n,[e]:!0}}):e in n&&this.setState({sendingPrompts:df(n,e)})}async runShell(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0)){if(hf(t)){this.enqueuePendingSessionSend(t,{type:`shell`,text:e});return}await this.deliverShellToSession(t,e,z(this.getState()),{optimisticLine:!0})}}async runCommand(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0)){if(hf(t)){this.enqueuePendingSessionSend(t,{type:`command`,text:e});return}await this.deliverCommandToSession(t,e,z(this.getState()),{applyResult:!0})}}async renameSession(e,t){let n=t.trim();if(n===``||!Bd(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let r=z(this.getState());try{let t=await this.api.runCommand(e,`/name ${n}`,r);if(t.type===`done`){this.applySessionName(e.id,t.session?.name??n);return}this.reportSessionError(e,r,t.type===`unsupported`?t.message:`重命名会话失败`)}catch(t){this.reportSessionError(e,r,t)}}enqueuePendingSessionSend(e,t){let n=this.pendingSessionStarts.get(e.id);if(n===void 0||n.discarded){this.reportSessionError(e,e.machineId,`后端会话尚未准备好发送排队消息。丢弃此次启动失败前,请先复制你的消息。`);return}let r={...t,id:`pending-send-${String(++this.pendingQueuedSendSeq)}`};n.queuedSends.push(r);let i=this.getState(),a=i.clientQueuedSessionMessages[e.id]??[],o=_f(e.id,n.queuedSends.length);this.setState({clientQueuedSessionMessages:{...i.clientQueuedSessionMessages,[e.id]:[...a,yf(r)]},sessionActivities:{...i.sessionActivities,[e.id]:o},activity:i.selectedSession?.id===e.id?o:i.activity,error:``})}async flushQueuedPendingSends(e,t,n){for(let r of n){if(!await this.deliverQueuedPendingSend(e,t,r))return;this.dropNextQueuedSessionMessage(e.id)}}async deliverQueuedPendingSend(e,t,n){return n.type===`prompt`?this.deliverPromptToSession(e,n.text,n.streamingBehavior,n.attachments,n.delivery,n.folder,t,{markSending:!0}):n.type===`shell`?this.deliverShellToSession(e,n.text,t,{optimisticLine:!0}):this.deliverCommandToSession(e,n.text,t,{applyResult:!0})}async deliverPromptToSession(e,t,n,r,i,a,o,s){let c=r!==void 0&&r.length>0;s.markSending&&this.markSendingPrompt(e.id,!0);try{if(c&&i===`folder`){let i=(await this.api.saveAttachments(e,r,o,a)).map(e=>gd(e.path,!1)).join(` `),s=t===``?i:`${t}\n\n${i}`;await this.api.prompt(e,s,n,o)}else await this.api.prompt(e,t,n,o,r);return this.markCachedNewSessionPersisted(e),!0}catch(t){return this.reportSessionError(e,o,t),!1}finally{s.markSending&&this.markSendingPrompt(e.id,!1)}}async deliverShellToSession(e,t,n,r){r.optimisticLine&&this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ol(`user`,t)]});try{return await this.api.shell(e,t,n),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ol(`system`,String(t))]}),this.reportSessionError(e,n,t),!1}}async deliverCommandToSession(e,t,n,r){this.markSendingPrompt(e.id,!0);try{let i=await this.api.runCommand(e,t,n);return r.applyResult&&this.isSelectedSessionIdentity(e.id,n)?this.applyCommandResult(i):(i.type===`select`||i.type===`tree`)&&this.reportSessionError(e,n,`排队命令“${t}”需要输入;请打开会话并重新运行。`),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ol(`system`,String(t))]}),this.reportSessionError(e,n,t),!1}finally{this.markSendingPrompt(e.id,!1)}}dropNextQueuedSessionMessage(e){let t=this.getState(),n=t.clientQueuedSessionMessages[e]??[];if(n.length===0)return;let r=n.slice(1);this.setState({clientQueuedSessionMessages:r.length===0?df(t.clientQueuedSessionMessages,e):{...t.clientQueuedSessionMessages,[e]:r}})}async respondToCommand(e,t){let n=this.getState().selectedSession;if(!n)return;let r=z(this.getState());this.setState({commandDialog:void 0});try{let i=await this.api.respondToCommand(n,e,t,r);this.isSelectedSessionIdentity(n.id,r)&&this.applyCommandResult(i)}catch(e){this.reportSessionError(n,r,e)}}cancelCommand(){this.setState({commandDialog:void 0})}async navigateTree(e,t){let n=this.getState(),r=n.selectedSession,i=n.treeDialog;if(r===void 0||i===void 0||r.archived===!0||hf(r))throw Error(`会话树导航器已不可用`);let a=z(n),o=Hs(a,r.id),s;try{s=await this.api.navigateTree(r,{targetId:e,expectedLeafId:i.activeLeafId,summary:t},a)}catch(e){throw this.reportSessionError(r,a,e),e}if(s.cancelled)return s;let c=s.editorText??``;if(Hl(o,c),this.transcripts.discard(o),!this.isSelectedSessionIdentity(r.id,a))return s;this.clearPendingUpdates();let l;try{await this.selectSession(r,{updateUrl:!1,preserveTreeDialog:!0,propagateRefreshError:!0})}catch(e){l={error:e}}if(!this.isSelectedSessionIdentity(r.id,a))return s;try{await this.replacePromptEditorText?.({machineId:a,sessionId:r.id,text:c})}catch(e){throw this.reportSessionError(r,a,e),e}if(l!==void 0)throw this.reportSessionError(r,a,l.error),l.error;return this.isSelectedSessionIdentity(r.id,a)&&this.getState().treeDialog===i&&this.setState({treeDialog:void 0}),s}async forkFromTree(e){let t=this.getState(),n=t.selectedSession,r=t.treeDialog;if(n===void 0||r===void 0||n.archived===!0||hf(n))throw Error(`会话树导航器已不可用`);let i=z(t),a=Hs(i,n.id),o;try{o=await this.api.forkTree(n,{entryId:e,expectedLeafId:r.activeLeafId},i)}catch(e){throw this.reportSessionError(n,i,e),e}if(o.cancelled)return o;let s=o.session;if(o.promptDraft!==void 0&&Hl(Hs(i,s.id),o.promptDraft),this.transcripts.discard(a),!this.isSelectedSessionIdentity(n.id,i))return o;let c=[s,...this.getState().sessions.filter(e=>e.id!==s.id)];return this.setState({sessions:c,treeDialog:void 0}),this.selectSession(s),o}async abortTreeNavigation(){let e=this.getState(),t=e.selectedSession;if(t===void 0||e.treeDialog===void 0||hf(t))return;let n=z(e);try{await this.api.abort(t,n)}catch(e){throw this.reportSessionError(t,n,e),e}}closeTreeDialog(){this.setState({treeDialog:void 0})}applySessionStatus(e){this.applyStatus(e)}archiveScopeProjectId(){return _t()?this.getState().selectedProject?.id:void 0}async archiveSession(e=this.getState().selectedSession){if(!e)return;let t=this.statusForSession(e),n=this.sessionPersistenceOptions();if(Vd(e,t,n)){await this.deleteCachedNewSession(e);return}if(!Bd(e,t,n))return;let r=z(this.getState());try{await this.api.archive(e,r,this.archiveScopeProjectId());let t=this.getState(),n=ef(t.sessions,e.id,new Date().toISOString()),i=nf(n,t.selectedSession?.id,e.id);this.setState({sessions:n}),i.type===`select`?await this.selectSession(i.session):i.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}catch(t){this.reportSessionError(e,r,t)}}async archiveSessionWithDescendants(e=this.getState().selectedSession){if(e===void 0||!Bd(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=z(this.getState());try{let n=await this.api.archiveWithDescendants(e,t,this.archiveScopeProjectId()),r=n.sessionIds!==void 0&&n.sessionIds.length>0?n.sessionIds:[e.id],i=this.getState(),a=tf(i.sessions,r,new Date().toISOString()),o=rf(a,i.selectedSession?.id,r);this.setState({sessions:a}),o.type===`select`?await this.selectSession(o.session):o.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}catch(n){this.reportSessionError(e,t,n)}}async archiveSessions(e){let t=this.sessionPersistenceOptions(),n=Sf(e).filter(e=>Bd(e,this.statusForSession(e),t));if(n.length===0)return;let r=z(this.getState()),i=this.getState().selectedWorkspace;try{let{succeededIds:e,failures:t,generatedAt:a}=await this.archiveSessionBatch(n,r);if(e.length>0){let t=this.getState(),n=tf(t.sessions,e,a??new Date().toISOString()),r=rf(n,t.selectedSession?.id,e);this.setState({sessions:n}),r.type===`select`?await this.selectSession(r.session):r.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionFailures(`归档`,t,r,i,n[0])}catch(e){this.reportWorkspaceOrSessionError(i,n[0],r,`归档失败:${wf(e)}`)}}async deleteArchivedSessions(e){let t=Sf(e).filter(e=>e.archived===!0);if(t.length===0)return;let n=z(this.getState()),r=this.getState().selectedWorkspace;try{let{succeededIds:e,failures:i}=await this.deleteArchivedSessionBatch(t,n);if(e.length>0){let r=new Set(e),i=this.getState(),a=i.sessions.filter(e=>!r.has(e.id));if(this.setState({sessions:a}),i.selectedSession!==void 0&&r.has(i.selectedSession.id)){let e=a.find(e=>e.archived!==!0)??a[0];e===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(e)}await this.refreshPinnedSessions(t[0]?.cwd??``,n)}this.applyBulkSessionFailures(`删除`,i,n,r,t[0])}catch(e){this.reportWorkspaceOrSessionError(r,t[0],n,`删除失败:${wf(e)}`)}}async archiveSessionBatch(e,t){let n=await this.api.archiveMany(e,t,this.archiveScopeProjectId());return{succeededIds:n.archivedSessionIds,failures:Cf(n.failures),generatedAt:n.generatedAt}}async deleteArchivedSessionBatch(e,t){let n=await this.api.deleteArchivedMany(e,t,this.archiveScopeProjectId());return{succeededIds:n.deletedSessionIds,failures:Cf(n.failures)}}async applySessionCleanupResult(e,t=z(this.getState())){if(z(this.getState())!==t)return;let n=e.archivedSessionIds,r=e.deletedSessionIds;if(n.length>0||r.length>0){let t=this.getState(),i=new Set(r),a=[...n,...r],o=tf(t.sessions,n,e.generatedAt).filter(e=>!i.has(e.id)),s=t.selectedSession!==void 0&&a.includes(t.selectedSession.id);if(this.setState({sessions:o,sessionStatuses:ff(t.sessionStatuses,a),sessionActivities:ff(t.sessionActivities,a),...s?{status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[]}:{}}),t.selectedSession!==void 0&&i.has(t.selectedSession.id)){let e=o.find(e=>e.archived!==!0)??o[0];e===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(e)}else{let e=rf(o,t.selectedSession?.id,n);e.type===`select`?await this.selectSession(e.session):e.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}}await this.refreshCurrentWorkspaceSessions(t)}async refreshCurrentWorkspaceSessions(e=z(this.getState())){let t=this.getState().selectedWorkspace;if(t!==void 0)try{let n=Jc(t.path,await this.api.sessions(t.path,e),e).filter(t=>!this.isSuppressedCreatedSession(t,e));if(z(this.getState())!==e||this.getState().selectedWorkspace?.id!==t.id)return;let r=this.mergePendingStartSessions(t.path,n,e),i=this.getState().selectedSession;if(this.setState({sessions:r}),this.refreshPinnedSessions(t.path,e),i===void 0)return;let a=r.find(e=>e.id===i.id);if(a!==void 0){a!==i&&this.setState({selectedSession:a});return}let o=r.find(e=>e.archived!==!0)??r[0];o===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(o)}catch(n){this.reportWorkspaceError(t,e,n)}}stopPolling(){this.sessionPollTimer!==void 0&&clearInterval(this.sessionPollTimer),this.sessionPollTimer=void 0,this.sessionRefreshInFlight=!1}async deleteCachedNewSession(e=this.getState().selectedSession){if(e===void 0||!Vd(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=hf(e)?this.pendingSessionStarts.get(e.id):void 0;t===void 0?this.api.stop(e,z(this.getState())).catch(()=>{}):(t.discarded=!0,t.queuedSends=[]),qc(e.id,z(this.getState())),Ul(this.sessionCacheKey(e.id)),Jl(this.sessionCacheKey(e.id));let n=this.getState(),r=n.sessions.filter(t=>t.id!==e.id);if(this.setState({sessions:r,sessionStatuses:df(n.sessionStatuses,e.id),sessionActivities:uf(n.sessionActivities,e.id),sendingPrompts:df(n.sendingPrompts,e.id),clientQueuedSessionMessages:df(n.clientQueuedSessionMessages,e.id)}),this.getState().selectedSession?.id!==e.id)return;let i=r.find(e=>e.archived!==!0)??r[0];i===void 0?(this.clearActiveSession(),this.updateUrl()):await this.selectSession(i)}async restoreSession(e=this.getState().selectedSession){if(!e)return;let t=z(this.getState());try{await this.api.restore(e,t,this.archiveScopeProjectId());let n={...e};delete n.archived,delete n.archivedAt,this.replaceSession(n),this.getState().selectedSession?.id===n.id&&await this.selectSession(n)}catch(n){this.reportSessionError(e,t,n)}}async reloadSession(e=this.getState().selectedSession){if(e===void 0||!Bd(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=z(this.getState());try{await this.api.reloadSession(e,t),this.transcripts.discard(this.sessionCacheKey(e.id)),this.getState().selectedSession?.id===e.id&&await this.selectSession(e,{updateUrl:!1})}catch(n){this.reportSessionError(e,t,n)}}async detachParent(e=this.getState().selectedSession){if(e?.parentSessionPath===void 0)return;let t=z(this.getState());try{await this.api.detachParent(e,t);let n={...e};delete n.parentSessionPath,this.replaceSession(n)}catch(n){this.reportSessionError(e,t,n)}}async listModels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=z(this.getState());try{return(await this.api.models(e,t)).models}catch(n){return this.reportSessionError(e,t,n),[]}}async listModelCatalog(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=z(this.getState());try{return(await this.api.modelCatalog(e,t)).models}catch(n){return this.reportSessionError(e,t,n),[]}}async setModelEnabled(e,t,n){let r=this.getState().selectedSession;if(!r||r.archived===!0)return;let i=z(this.getState());try{return(await this.api.setModelEnabled(r,e,t,n,i)).models}catch(e){this.reportSessionError(r,i,e);return}}async setModelScope(e){let t=this.getState(),n=t.selectedSession;if(!n||n.archived===!0)return;let r=z(t);try{return(await this.api.setModelScope(n,e,r)).models}catch(e){this.reportSessionError(n,r,e);return}}async setModel(e,t){let n=this.getState().selectedSession;if(!n||n.archived===!0)return;let r=z(this.getState());try{this.applyStatus(await this.api.setModel(n,e,t,r)),await this.refreshAvailableThinkingLevels()}catch(e){this.reportSessionError(n,r,e)}}async cycleModel(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;let n=z(this.getState());try{this.applyStatus(await this.api.cycleModel(t,e,n)),await this.refreshAvailableThinkingLevels()}catch(e){this.reportSessionError(t,n,e)}}async listThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=z(this.getState());try{return(await this.api.thinkingLevels(e,t)).levels}catch(n){return this.reportSessionError(e,t,n),[]}}async refreshAvailableThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}let t=await this.listThinkingLevels();this.getState().selectedSession?.id===e.id&&this.setState({availableThinkingLevels:t})}async setThinkingLevel(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;let n=z(this.getState());try{this.applyStatus(await this.api.setThinkingLevel(t,e,n))}catch(e){this.reportSessionError(t,n,e)}}async cycleThinkingLevel(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return;let t=z(this.getState());try{this.applyStatus(await this.api.cycleThinkingLevel(e,t))}catch(n){this.reportSessionError(e,t,n)}}async clearServerQueue(){let e=this.getState(),t=e.selectedSession;if(t===void 0||t.archived===!0||hf(t))return;let n=z(e),r=this.selectionSeq;try{let e=await this.api.clearQueue(t,n);this.isCurrentSessionSelection(t.id,n,r)&&this.applyStatus(e)}catch(e){this.reportSessionError(t,n,e)}}async dismissWarning(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||hf(n))return;let r=z(t),i=this.selectionSeq;try{let t=await this.api.dismissWarning(n,e,r);this.isCurrentSessionSelection(n.id,r,i)&&this.applyStatus(t)}catch(e){this.reportSessionError(n,r,e)}}submitAsk(e,t){return this.closeOpenAsk(e,(n,r)=>this.api.submitAsk(n,e,t,r))}cancelAsk(e){return this.closeOpenAsk(e,(t,n)=>this.api.cancelAsk(t,e,n))}answerDialog(e,t){return this.closeOpenDialog(e,(n,r)=>this.api.answerDialog(n,e,t,r))}cancelDialog(e){return this.closeOpenDialog(e,(t,n)=>this.api.cancelDialog(t,e,n))}async closeOpenDialog(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0)return;if(hf(r)){await this.closePendingStartDialog(r,e,t);return}let i=z(n),a=this.selectionSeq;try{let e=await t(r,i);if(!this.isCurrentSessionSelection(r.id,i,a))return;this.recordDialogOutcome(e.outcome),this.applyStatus(e.sessionStatus)}catch(e){this.reportSessionError(r,i,e)}}async closePendingStartDialog(e,t,n){let r=this.pendingSessionStarts.get(e.id),i=r?.backendSessionId;if(r===void 0||i===void 0)return;let a=this.selectionSeq;try{let t=await n({...e,id:i},r.machineId);if(a!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;this.recordDialogOutcome(t.outcome),this.applyPendingStartStatus(r,t.sessionStatus)}catch(t){this.reportSessionError(e,r.machineId,t)}}recordDialogOutcome(e){if(e===void 0)return;let t=this.getState().pendingDialogs.find(t=>t.dialogId===e.dialogId);t!==void 0&&this.recordClosedDialog({dialog:t,reason:e.reason,...e.answer===void 0?{}:{answer:e.answer}})}async closeOpenAsk(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0||hf(r))return;let i=z(n),a=this.selectionSeq;try{let n=await t(r,i);eu(Hs(i,r.id),e),this.isCurrentSessionSelection(r.id,i,a)&&this.applyStatus(n.sessionStatus)}catch(e){this.reportSessionError(r,i,e)}}async stopActiveWork(){let e=this.getState().selectedSession;if(!e)return;let t=z(this.getState());try{await this.api.abort(e,t)}catch(n){this.reportSessionError(e,t,n)}}refreshSelectedSession(e=this.getState().selectedSession?.id,t){let n=this.getState().selectedSession;if(e===void 0||n?.id!==e||n.archived===!0||hf(n))return Promise.resolve();let r={session:n,machineId:z(this.getState()),selectionSeq:this.selectionSeq,errorOwner:this.captureSessionErrorOwner(n)};return this.requestSelectedSessionRefresh(r).catch(e=>{if(t?.silent===!0){console.warn(`Selected session background refresh failed`,e);return}this.reportSessionError(r.session,r.machineId,e,r.errorOwner)})}requestSelectedSessionRefresh(e){let t=Hs(e.machineId,e.session.id);return this.selectedSessionRefreshes.request(t,async()=>{if(!this.isCurrentRefreshTarget(e))return;this.flushPendingUpdates();let[n,r,i]=await Promise.all([this.api.messages(e.session,{limit:af},e.machineId),this.api.status(e.session,e.machineId),this.streamSnapshot(e.session,e.machineId).catch(()=>({seq:0,partial:null})),this.notifications?.refreshSelectedSession(e.session,e.machineId)??Promise.resolve()]);if(!this.isCurrentRefreshTarget(e)||this.isUnchangedSelectedRefresh(e,t,n,r,i))return;let a=this.transcripts.mergeHistory(t,n),o=this.transcripts.seedStreamingPartial(a.messages,i.partial);this.streamWatermark={sessionId:e.session.id,seq:i.seq},this.setState({...a,messages:o,status:r,activity:this.getState().sessionActivities[e.session.id]}),this.applyStatus(r),this.lastAppliedSelectedRefresh={selectionSeq:e.selectionSeq,partialJson:lf(i)}})}isUnchangedSelectedRefresh(e,t,n,r,i){let a=this.lastAppliedSelectedRefresh;return a?.selectionSeq!==e.selectionSeq||lf(i)!==a.partialJson||!ed(this.transcripts.rawHistoryPage(t),n)||JSON.stringify(r)!==JSON.stringify(this.getState().status)?!1:this.getState().sessionActivities[r.sessionId]?.phase!==`active`||As(r)}isCurrentRefreshTarget(e){return this.isCurrentSessionSelection(e.session.id,e.machineId,e.selectionSeq)}isCurrentSessionSelection(e,t,n){return n===this.selectionSeq&&this.isSelectedSessionIdentity(e,t)}isSelectedSessionIdentity(e,t){if(this.disposed)return!1;let n=this.getState(),r=n.selectedSession;return z(n)===t&&r?.id===e&&r.archived!==!0&&!hf(r)}reportSessionError(e,t,n,r={cwd:e.cwd}){this.browserErrors.report(ys(t,e.id,r),String(n))}captureSessionErrorOwner(e,t=this.workspaceForSessionError(e)){return{cwd:e.cwd,...t===void 0?{}:{projectId:t.projectId,workspaceId:t.id}}}workspaceForSessionError(e){let t=this.getState();return[t.selectedWorkspace,...t.workspaces,...Object.values(t.workspacesByProjectId).flat()].find(t=>t?.path===e.cwd)}reportWorkspaceError(e,t,n){this.browserErrors.report(vs(t,e.projectId,e.id),String(n))}applyBulkSessionFailures(e,t,n,r,i){t.length!==0&&this.reportWorkspaceOrSessionError(r,i,n,`${e}失败,${String(t.length)} 个会话处理失败:${t.join(`;`)}`)}reportWorkspaceOrSessionError(e,t,n,r){e===void 0?t!==void 0&&this.reportSessionError(t,n,r):this.reportWorkspaceError(e,n,r)}sessionCacheKey(e){return Hs(z(this.getState()),e)}statusForSession(e){if(e===void 0)return;let t=this.getState();return t.status?.sessionId===e.id&&t.selectedSession?.id===e.id?t.status:t.sessionStatuses[e.id]}sessionPersistenceOptions(){let e=this.getState();return Rd(e.machineRuntimes[z(e)])}workspaceSelectionKey(e){return`${z(this.getState())}:${e}`}replaceSession(e){let t=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(t=>t.id===e.id?e:t),selectedSession:t?.id===e.id?e:t})}createPendingSessionStart(e,t){let n=`pending-session-${String(++this.pendingSessionStartSeq)}-${Date.now().toString(36)}`,r=new Date().toISOString(),i={id:n,path:`pi-web://pending-session/${n}`,cwd:e.path,persisted:!1,name:`新会话`,created:r,modified:r,messageCount:0,firstMessage:``,clientPendingStart:!0,machineId:t};return{tempId:n,originWorkspace:e,workspaceId:e.id,cwd:e.path,machineId:t,session:i,queuedSends:[],discarded:!1}}insertAndSelectPendingSession(e){let t=this.getState();this.selectClientPendingStartSession(e,{activity:_f(e.id),sessions:[e,...t.sessions.filter(t=>t.id!==e.id)]})}selectClientPendingStartSession(e,t){this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)}),this.selectionSeq+=1,this.socket.close(),this.streamWatermark=void 0,this.clearPendingUpdates();let n=this.getState(),r=this.pendingSessionStarts.get(e.id),i=t?.activity??n.sessionActivities[e.id]??(r===void 0?void 0:_f(e.id,r.queuedSends.length));this.setState({...t?.sessions===void 0?{}:{sessions:t.sessions},selectedSession:e,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:i,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0,...i===void 0?{}:{sessionActivities:{...n.sessionActivities,[e.id]:i}},error:``}),r?.backendSessionId!==void 0&&this.connectPendingStartSocket(r),t?.updateUrl!==!1&&this.updateUrl()}async resolvePendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.queuedSends.splice(0),i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId,t.id);if(n.discarded){Ul(Hs(n.machineId,e)),Jl(Hs(n.machineId,e)),this.setState({clientQueuedSessionMessages:df(this.getState().clientQueuedSessionMessages,e)}),this.applyReleasedCreatedSessions(i,n.machineId),this.api.stop(t,n.machineId).catch(()=>{});return}Gc(t,n.machineId),Wl(Hs(n.machineId,e),Hs(n.machineId,t.id)),Yl(Hs(n.machineId,e),Hs(n.machineId,t.id));let a=Kc(t,n.machineId);if(!this.isCurrentPendingStart(n)){this.setState({clientQueuedSessionMessages:df(this.getState().clientQueuedSessionMessages,e)}),await this.flushQueuedPendingSends(a,n.machineId,r);return}let o=this.getState(),s=o.selectedSession?.id===e;this.setState({sessions:mf(o.sessions,e,a),sessionActivities:uf(o.sessionActivities,e),sendingPrompts:pf(o.sendingPrompts,e,a.id),clientQueuedSessionMessages:pf(o.clientQueuedSessionMessages,e,a.id),...s?{selectedSession:a,status:o.sessionStatuses[a.id],activity:o.sessionActivities[a.id],pendingAsk:this.selectedPendingAsk(o.sessionStatuses[a.id]),pendingDialogs:o.sessionStatuses[a.id]?.pendingDialogs??[],closedDialogs:[]}:{},error:``}),this.applyReleasedCreatedSessions(i,n.machineId),s&&(this.updateUrl({replace:!0}),await this.selectSession(a,{updateUrl:!1})),await this.flushQueuedPendingSends(a,n.machineId,r)}failPendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.discarded;n.discarded=!0,this.getState().selectedSession?.id===e&&this.socket.close();let i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId),a=this.isCurrentPendingStart(n);if(r){a&&this.applyReleasedCreatedSessions(i,n.machineId);return}let o=wf(t),s=`启动会话失败:${o}`;if(!a){this.browserErrors.report(vs(n.machineId,n.originWorkspace.projectId,n.originWorkspace.id),s);return}let c=this.getState(),l=vf(e,o,n.queuedSends.length),u=c.sessions.some(t=>t.id===e);this.setState({sessions:u?c.sessions:[n.session,...c.sessions],sessionActivities:{...c.sessionActivities,[e]:l},activity:c.selectedSession?.id===e?l:c.activity,...c.selectedSession?.id===e?{pendingDialogs:[]}:{}}),this.reportSessionError(n.session,n.machineId,s),this.applyReleasedCreatedSessions(i,n.machineId)}isCurrentPendingStart(e){let t=this.getState();return z(t)===e.machineId&&t.selectedWorkspace?.id===e.workspaceId&&t.selectedWorkspace.projectId===e.originWorkspace.projectId}hasPendingStartFor(e,t){return Array.from(this.pendingSessionStarts.values()).some(n=>n.cwd===e&&n.machineId===t)}isSuppressedCreatedSession(e,t){let n=this.suppressedCreatedSessions.get(e.id);return n?.session.cwd===e.cwd&&n.machineId===t}takeSuppressedCreatedSessionsFor(e,t,n){if(n!==void 0&&this.suppressedCreatedSessions.delete(n),this.hasPendingStartFor(e,t))return[];let r=[];for(let[n,i]of this.suppressedCreatedSessions)i.session.cwd!==e||i.machineId!==t||(this.suppressedCreatedSessions.delete(n),r.push(i.session));return r}applyReleasedCreatedSessions(e,t){if(e.length===0||z(this.getState())!==t)return;let n=this.getState();if(n.selectedWorkspace===void 0)return;let r=new Set(n.sessions.map(e=>e.id)),i=e.filter(e=>e.cwd===n.selectedWorkspace?.path&&!r.has(e.id));i.length!==0&&this.setState({sessions:[...i.reverse(),...n.sessions]})}mergePendingStartSessions(e,t,n){let r=this.getState().sessions.filter(t=>hf(t)&&t.cwd===e&&t.machineId===n);if(r.length===0)return t;let i=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!i.has(e.id))]}async recreateCachedNewSession(e,t){let n=z(this.getState());try{let r=await this.api.startSession(e.cwd,n);Gc(r,n),Wl(this.sessionCacheKey(e.id),this.sessionCacheKey(r.id)),Yl(this.sessionCacheKey(e.id),this.sessionCacheKey(r.id)),qc(e.id,n);let i=Kc(r,n);this.setState({sessions:[i,...this.getState().sessions.filter(t=>t.id!==e.id)],error:``}),await this.selectSession(i,{updateUrl:!1}),this.updateUrl(t?.updateUrl===!1?{replace:!0}:void 0)}catch(t){this.reportSessionError(e,n,t)}}markCachedNewSessionPersisted(e){if(!Yc(e))return;let t=this.getState().sessions.find(t=>t.id===e.id)??e;this.replaceSession(Xc(t))}applyCommandResult(e){if(e.type===`select`){this.setState({commandDialog:e});return}if(e.type===`tree`){this.setState({treeDialog:e.tree});return}let t=(e.type,e.message);if(t!==void 0&&t!==``&&this.setState({messages:[...this.getState().messages,ol(e.type===`unsupported`?`system`:`tool`,t)]}),e.type===`done`&&e.session){e.promptDraft!==void 0&&Hl(this.sessionCacheKey(e.session.id),e.promptDraft);let t=this.getState().selectedSession,n=[e.session,...this.getState().sessions.filter(t=>t.id!==e.session?.id)];this.setState({sessions:n,selectedSession:t?.id===e.session.id?e.session:t}),t?.id!==e.session.id&&this.selectSession(e.session)}}applyCreatedSession(e){let t=this.getState();if(t.selectedWorkspace?.path!==e.cwd||t.sessions.some(t=>t.id===e.id))return;let n=z(t);if(this.hasPendingStartFor(e.cwd,n)){this.suppressedCreatedSessions.set(e.id,{session:e,machineId:n});return}this.setState({sessions:[e,...t.sessions]})}applyActivity(e){this.setState({sessionActivities:{...this.getState().sessionActivities,[e.sessionId]:e},activity:this.getState().selectedSession?.id===e.sessionId?e:this.getState().activity})}applyStatus(e){let t=this.getState(),n=t.selectedSession?.id===e.sessionId,r=t.sessionActivities[e.sessionId]?.phase===`active`&&!As(e);this.setState({sessionStatuses:{...t.sessionStatuses,[e.sessionId]:e},...Tf(t,e.sessionId,e.messageCount),...r?{sessionActivities:uf(t.sessionActivities,e.sessionId)}:{},status:n?e:t.status,activity:n&&r?void 0:t.activity,...n?{pendingAsk:this.selectedPendingAsk(e)}:{},...n?{pendingDialogs:e.pendingDialogs??[]}:{}})}applyOpenedDialog(e){let t=this.getState();t.selectedSession===void 0||t.pendingDialogs.some(t=>t.dialogId===e.dialogId)||this.setState({pendingDialogs:[...t.pendingDialogs,e]})}applyClosedDialog(e,t,n){let r=this.getState().pendingDialogs.find(t=>t.dialogId===e);r!==void 0&&this.recordClosedDialog({dialog:r,reason:t,...n===void 0?{}:{answer:n}})}recordClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e.dialog.dialogId)||this.setState({pendingDialogs:t.pendingDialogs.filter(t=>t.dialogId!==e.dialog.dialogId),closedDialogs:[...t.closedDialogs,e]})}dismissClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e)&&this.setState({closedDialogs:t.closedDialogs.filter(t=>t.dialog.dialogId!==e)})}applyOpenedAsk(e){this.getState().selectedSession!==void 0&&this.setState({pendingAsk:this.selectedPendingAsk({pendingAsk:e})})}applyClosedAsk(e){this.getState().pendingAsk?.askId===e&&this.setState({pendingAsk:void 0})}selectedPendingAsk(e){if(e?.pendingAsk!==void 0)return e.pendingAsk}applySessionName(e,t){let n=n=>{if(n.id!==e)return n;let r={...n};return t===void 0||t===``?delete r.name:r.name=t,r},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(n),selectedSession:r===void 0?void 0:n(r)})}applyEvent(e){if(e.type===`notifications.inbox`){this.notifications?.applyInboxEvent(z(this.getState()),e);return}if(e.type===`command.output`&&this.notifications?.shouldFilterLegacyNotification(z(this.getState()),e.notificationId)===!0||this.isStreamEventBelowWatermark(e))return;if(e.type===`status.update`){this.queueStatusUpdate(e.status);return}if(e.type===`activity.update`){this.queueActivityUpdate(e.activity);return}if(Ef(e)){this.queueTranscriptEvent(e);return}if(this.flushPendingUpdates(),e.type===`ask.opened`){this.applyOpenedAsk(e.ask);return}if(e.type===`ask.closed`){this.applyClosedAsk(e.askId);return}if(e.type===`dialog.opened`){this.applyOpenedDialog(e.dialog);return}if(e.type===`dialog.closed`){this.applyClosedDialog(e.dialogId,e.reason,e.answer);return}let t=this.transcripts.applyLiveEvent(this.getState().messages,e);t?this.setState({messages:t}):e.type===`session.name`&&this.applySessionName(e.sessionId,e.name)}queueTranscriptEvent(e){this.pendingTranscriptEvents.push(e),this.schedulePendingFlush()}queueStatusUpdate(e){this.pendingStatusBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueActivityUpdate(e){this.pendingActivityBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueStartupProgress(e){if(this.getState().sessions.some(t=>t.id===e.activity.sessionId)){this.queueActivityUpdate(e.activity);return}let t=e.startupToken===void 0?void 0:this.pendingSessionStarts.get(e.startupToken);t===void 0||t.discarded||(this.learnPendingStartBackendSession(t,e.activity.sessionId),this.queueActivityUpdate(e.activity.phase===`idle`?_f(t.tempId,t.queuedSends.length):gf(e.activity,t.tempId)))}learnPendingStartBackendSession(e,t){t===``||e.backendSessionId!==void 0||(e.backendSessionId=t,this.getState().selectedSession?.id===e.tempId&&this.connectPendingStartSocket(e))}connectPendingStartSocket(e){let t=e.backendSessionId;if(t===void 0||e.discarded)return;let n={id:t,cwd:e.cwd};this.socket.connect(n,t=>{this.applyPendingStartEvent(e,t)},()=>{this.resyncPendingStartDialogs(e)},e.machineId),this.resyncPendingStartDialogs(e)}resyncPendingStartDialogs(e){let t=e.backendSessionId;t!==void 0&&this.api.status({id:t,cwd:e.cwd},e.machineId).then(t=>{if(e.discarded||this.getState().selectedSession?.id!==e.tempId)return;let n=this.getState(),r=new Set([...n.pendingDialogs.map(e=>e.dialogId),...n.closedDialogs.map(e=>e.dialog.dialogId)]),i=(t.pendingDialogs??[]).filter(e=>!r.has(e.dialogId));this.setState({sessionStatuses:{...n.sessionStatuses,[t.sessionId]:t},...i.length===0?{}:{pendingDialogs:[...n.pendingDialogs,...i]}})},()=>void 0)}applyPendingStartEvent(e,t){if(!(e.discarded||this.getState().selectedSession?.id!==e.tempId)){if(t.type===`dialog.opened`){this.applyOpenedDialog(t.dialog);return}if(t.type===`dialog.closed`){this.applyClosedDialog(t.dialogId,t.reason,t.answer);return}t.type===`status.update`&&this.applyPendingStartStatus(e,t.status)}}applyPendingStartStatus(e,t){if(e.discarded||this.getState().selectedSession?.id!==e.tempId)return;let n=this.getState();this.setState({sessionStatuses:{...n.sessionStatuses,[t.sessionId]:t},pendingDialogs:t.pendingDialogs??[]})}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){if(this.pendingTranscriptEvents.length>0){let e=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let t=this.getState().messages;for(let n of e)t=this.transcripts.applyLiveEvent(t,n)??t;t!==this.getState().messages&&this.setState({messages:t})}if(this.pendingActivityBySession.size>0){let e=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(let t of e)this.applyActivity(t)}if(this.pendingStatusBySession.size>0){let e=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(let t of e)this.applyStatus(t)}}clearPendingUpdates(){this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=void 0)}isStreamEventBelowWatermark(e){let t=this.streamWatermark;return t===void 0||t.sessionId!==this.getState().selectedSession?.id?!1:e.seq!==void 0&&e.seq<=t.seq}async selectSearchMatch(e,t,n){await this.selectSession(e);let r=z(this.getState()),i=this.selectionSeq;try{for(;this.isCurrentSearchJump(e.id,r,i)&&this.getState().messagePageStart>t.messageIndex;){let t=this.getState().messagePageStart,n=await this.api.messages(e,{before:t,limit:of},r);if(!this.isCurrentSearchJump(e.id,r,i))return;let a=this.transcripts.mergeHistory(this.sessionCacheKey(e.id),n);if(this.setState(a),a.messagePageStart>=t)break}}catch(t){this.reportSessionError(e,r,t);return}this.isCurrentSearchJump(e.id,r,i)&&this.setState({...this.transcripts.indexedView(this.sessionCacheKey(e.id)),sessionSearchTarget:{sessionId:e.id,messageIndex:t.messageIndex,query:n,requestId:++this.searchTargetSeq}})}isCurrentSearchJump(e,t,n){return this.selectionSeq===n&&z(this.getState())===t&&this.getState().selectedSession?.id===e}};function lf(e){return JSON.stringify(e.partial??null)}function uf(e,t){return df(e,t)}function df(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function ff(e,t){if(t.length===0)return e;let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function pf(e,t,n){if(t===n||!(t in e))return e;let r=e[t];return r===void 0?e:{...df(e,t),[n]:r}}function mf(e,t,n){let r=[],i=!1;for(let a of e){if(a.id===t){i||=(r.push(n),!0);continue}a.id!==n.id&&r.push(a)}return i?r:[n,...r]}function hf(e){return e!==void 0&&`clientPendingStart`in e&&e.clientPendingStart===!0}function gf(e,t){return{sessionId:t,phase:e.phase,label:e.label,...e.detail===void 0?{}:{detail:e.detail},at:e.at}}function _f(e,t=0){return{sessionId:e,phase:`active`,label:`正在创建会话`,detail:t>0?`后端会话准备好后将发送 ${String(t)} 条排队消息`:`正在等待后端会话准备就绪`,at:new Date().toISOString()}}function vf(e,t,n=0){return{sessionId:e,phase:`error`,label:`会话创建失败`,detail:`${t}${n>0?` · 下方保留了 ${String(n)} 条排队消息`:``}`,at:new Date().toISOString()}}function yf(e){return e.type===`prompt`?{kind:e.streamingBehavior===`steer`?`steer`:`followUp`,text:bf(e.text,e.attachments)}:{kind:`followUp`,text:e.text}}function bf(e,t){let n=xf(t);return n===void 0?e:e.trim()===``?n:`${e}\n\n${n}`}function xf(e){if(e===void 0||e.length===0)return;let t=e.map(e=>e.name?.trim()).filter(e=>e!==void 0&&e!==``),n=e.length,r=`${String(n)} 个附件`;return t.length===0?`[已排队 ${r}]`:`[已排队 ${r}:${t.slice(0,3).join(`、`)}${t.length>3?`,另有 ${String(t.length-3)} 个`:``}]`}function Sf(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function Cf(e){return e.map(e=>`${e.sessionId}: ${e.error}`)}function wf(e){return e instanceof Error?e.message:String(e)}function Tf(e,t,n){if(n===void 0)return{};let r=e.sessions.some(e=>e.id===t&&e.messageCount!==n)?e.sessions.map(e=>e.id===t?{...e,messageCount:n}:e):void 0,i=e.selectedSession?.id===t&&e.selectedSession.messageCount!==n?{...e.selectedSession,messageCount:n}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...i===e.selectedSession?{}:{selectedSession:i}}}function Ef(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`||e.type===`shell.chunk`}function Df(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`session not found`)||t.includes(`未找到会话`)}var Of={order:0,overflowWatermark:0};function kf(e){return{...e,status:`loading`,catalogRevision:0,notifications:[],dismissThrough:Of,optimisticDismissedIds:[],announcements:[]}}function Af(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)throw Error(`Notification inbox snapshot does not match the selected session`);let r=e!==void 0&&Wf(e,t)&&e.daemonInstanceId===n.daemonInstanceId;return{...t,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:n.notifications,dismissThrough:n.dismissThrough,optimisticDismissedIds:r?e.optimisticDismissedIds:[],...r&&e.optimisticDismissAllThrough!==void 0?{optimisticDismissAllThrough:e.optimisticDismissAllThrough}:{},announcements:r?e.announcements:[]}}function jf(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)return{value:e??kf(t),needsRefresh:!1,changed:!1};if(e===void 0||!Wf(e,t))return{value:Kf(t),needsRefresh:!0,changed:!0};if(e.daemonInstanceId!==n.daemonInstanceId)return{value:Kf(t),needsRefresh:!0,changed:e.status!==`stale`||e.daemonInstanceId!==void 0||e.notifications.length>0};let r=e.summary?.inboxRevision??0;if(n.summary.inboxRevision<=r)return{value:e,needsRefresh:!1,changed:!1};if(e.status!==`fresh`||n.summary.inboxRevision!==r+1||n.delta.kind===`resync`)return{value:{...e,status:`stale`},needsRefresh:!0,changed:e.status!==`stale`};let i,a;switch(n.delta.kind){case`added`:{let t=n.delta;if(e.notifications.some(e=>e.id===t.notification.id))return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};i=[t.notification,...e.notifications].filter(e=>e.id!==t.evictedNotificationId).sort((e,t)=>t.order-e.order).slice(0,100),a={id:`${n.daemonInstanceId}:${String(n.summary.inboxRevision)}:${t.notification.id}`,severity:t.notification.severity,message:t.notification.message};break}case`dismissed`:{let t=new Set(n.delta.notificationIds);i=e.notifications.filter(e=>!t.has(e.id));break}case`cleared`:i=[];break}let o=i[0]?.order??0;if(!qf(i,n.summary)||n.dismissThrough.order!==o||n.dismissThrough.overflowWatermark<n.summary.discardedCount)return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};let s=a===void 0?e.announcements:[...e.announcements,a].slice(-100);return{value:{...e,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:i,dismissThrough:n.dismissThrough,announcements:s},needsRefresh:!1,changed:!0}}function Mf(e){if(e?.status!==`fresh`||e.daemonInstanceId===void 0||e.summary===void 0)return;let t=new Set(e.optimisticDismissedIds),n=e.optimisticDismissAllThrough,r=e.notifications.filter(e=>!t.has(e.id)&&(n===void 0||e.order>n.order)),i=Yf(e.summary.discardedCount,e.dismissThrough.overflowWatermark,n?.overflowWatermark);return r.length===0&&t.size>0&&(i=0),{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd,daemonInstanceId:e.daemonInstanceId,notifications:r,retainedCount:r.length,discardedCount:i,...Xf(Jf(r)),dismissThrough:e.dismissThrough,pendingDismissedIds:t,dismissAllPending:n!==void 0,announcements:e.announcements}}function Nf(e){return e===`error`?`错误`:e===`warning`?`警告`:`信息`}function Pf(e){return`收到${Nf(e.severity)}通知。`}function Ff(e){return e.retainedCount+e.discardedCount}function If(e){return`通知(${String(Ff(e))})`}function Lf(e){let t=e.message.replace(/\s+/gu,` `).trim();if(t===``)return`关闭${Nf(e.severity)}通知`;let n=Array.from(t);return`关闭通知:${n.length<=80?t:`${n.slice(0,79).join(``).trimEnd()}…`}`}function Rf(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1)return{kind:`header`};let r=e[n+1];if(r!==void 0)return{kind:`notification`,notificationId:r.id};let i=e[n-1];return i===void 0?{kind:`header`}:{kind:`notification`,notificationId:i.id}}function zf(e){return JSON.stringify([e.machineId,e.cwd,e.sessionId])}function Bf(e,t){return e.has(zf(t))}function Vf(e,t,n){let r=new Set(e),i=zf(t);return n?r.add(i):r.delete(i),r}function Hf(e){return`还有 ${String(e)} 条较早通知未显示。`}function Uf(e){if(!e.truncated)return;let t=Bt/1024;return`消息已在 ${String(t)} KiB 处截断。`}function Wf(e,t){return e.machineId===t.machineId&&e.sessionId===t.sessionId&&e.cwd===t.cwd}function Gf(e,t){if(e===`error`||t===`error`)return`error`;if(e===`warning`||t===`warning`)return`warning`;if(e===`info`||t===`info`)return`info`}function Kf(e){return{...kf(e),status:`stale`}}function qf(e,t){return e.length===t.retainedCount&&Jf(e)===t.highestSeverity}function Jf(e){let t;for(let n of e)t=Gf(t,n.severity);return t}function Yf(e,t,n){if(e===0||n===void 0)return e;let r=t-e+1;return e-Math.max(0,Math.min(e,n-r+1))}function Xf(e){return e===void 0?{}:{highestSeverity:e}}var Zf=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.acceptedSupportByMachine=new Set,this.selectedGeneration=0,this.dismissingNotificationIds=new Set,this.dismissAllPending=!1,this.disposed=!1,this.api=n.api??L,this.onBackgroundError=n.onBackgroundError??((e,t)=>{console.warn(e,t)})}dispose(){this.disposed=!0,this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.acceptedSupportByMachine.clear(),this.dismissingNotificationIds.clear(),this.dismissAllPending=!1}prepareSelectedSession(e,t){if(this.selectedGeneration+=1,this.selectedTarget=e.archived===!0?void 0:{machineId:t,sessionId:e.id,cwd:e.cwd},this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.selectedTarget===void 0||!this.machineSupportsNotifications(t)){this.setState({selectedNotificationInbox:void 0});return}this.setState({selectedNotificationInbox:kf(this.selectedTarget)})}clearSelectedSession(){this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.setState({selectedNotificationInbox:void 0})}refreshSelectedSession(e,t){let n=this.selectedTarget;if(this.disposed||n?.machineId!==t||n.sessionId!==e.id||n.cwd!==e.cwd||!this.machineSupportsNotifications(t)||!this.machineIsReachable(t))return Promise.resolve();let r=this.selectedGeneration,i=this.selectedRefresh;if(i?.generation===r)return i.trailing=!0,i.promise;this.ensureSelectedProjection(n);let a={generation:r,promise:Promise.resolve(),trailing:!1};return a.promise=this.runSelectedRefresh(a,n).finally(()=>{this.selectedRefresh===a&&(this.selectedRefresh=void 0)}),this.selectedRefresh=a,a.promise}applyInboxEvent(e,t){let n=this.selectedTarget;if(n?.machineId!==e||n.sessionId!==t.summary.sessionId||n.cwd!==t.summary.cwd)return;this.acceptedSupportByMachine.add(e);let r=this.selectedJoin;if(r?.generation===this.selectedGeneration){r.events.push(t);return}let i=jf(this.getState().selectedNotificationInbox,n,t);i.changed&&this.setState({selectedNotificationInbox:i.value}),i.needsRefresh&&this.scheduleSelectedRefresh(n)}syncEnvironment(e,t){if(this.disposed)return;e.machines!==t.machines&&this.pruneRemovedMachines(t.machines);let n=e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||e.machineRuntimes!==t.machineRuntimes,r=this.selectedTarget;if(!n||r===void 0)return;let i=this.machineSupportsNotificationsInState(e,r.machineId)&&this.machineIsReachableInState(e,r.machineId);if(!this.machineSupportsNotifications(r.machineId)||!this.machineIsReachable(r.machineId)){this.markSelectedStale(r);return}this.ensureSelectedProjection(r),(!i||this.getState().selectedNotificationInbox?.status!==`fresh`)&&this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId)}shouldFilterLegacyNotification(e,t){return t!==void 0&&t!==``&&this.machineSupportsNotifications(e)}async dismissNotification(e){let t=this.getState().selectedNotificationInbox,n=Mf(t);if(t===void 0||n===void 0||this.dismissAllPending||this.dismissingNotificationIds.has(e)||!n.notifications.some(t=>t.id===e))return;let r=Qf(t),i=this.selectedGeneration;this.dismissingNotificationIds.add(e),this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:[...new Set([...t.optimisticDismissedIds,e])]}));try{let t=await this.api.dismissNotification({id:r.sessionId,cwd:r.cwd},n.daemonInstanceId,e,r.machineId);this.isCurrentTarget(r,i)&&this.applyMutationSnapshot(r,t,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)}))}catch(t){this.isCurrentTarget(r,i)&&(this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)})),this.setState({error:`关闭通知失败:${ep(t)}`}),await this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId))}finally{this.dismissingNotificationIds.delete(e)}}async dismissAll(){let e=this.getState().selectedNotificationInbox,t=Mf(e);if(e===void 0||t===void 0||this.dismissAllPending||t.retainedCount+t.discardedCount===0)return;let n=Qf(e),r=this.selectedGeneration,i={...e.dismissThrough};this.dismissAllPending=!0,this.patchSelectedOverlay(n,e=>({...e,optimisticDismissAllThrough:i}));try{let e=await this.api.dismissAllNotifications({id:n.sessionId,cwd:n.cwd},t.daemonInstanceId,i,n.machineId);this.isCurrentTarget(n,r)&&this.applyMutationSnapshot(n,e,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t})}catch(e){this.isCurrentTarget(n,r)&&(this.patchSelectedOverlay(n,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t}),this.setState({error:`关闭会话通知失败:${ep(e)}`}),await this.refreshSelectedSession({id:n.sessionId,cwd:n.cwd},n.machineId))}finally{r===this.selectedGeneration&&(this.dismissAllPending=!1)}}async runSelectedRefresh(e,t){do{e.trailing=!1;let n={generation:e.generation,events:[]};this.selectedJoin=n;try{let r=await this.api.notificationInbox({id:t.sessionId,cwd:t.cwd},t.machineId);if(!this.isCurrentTarget(t,e.generation))return;if(!this.machineSupportsNotifications(t.machineId)||!this.machineIsReachable(t.machineId)){this.markSelectedStale(t);return}this.acceptedSupportByMachine.add(t.machineId);let i=this.getState().selectedNotificationInbox,a=i===void 0||$f(i,t,r)?Af(i,t,r):i;for(let r of[...n.events].sort((e,t)=>e.summary.inboxRevision-t.summary.inboxRevision)){let n=jf(a,t,r);a=n.value,n.needsRefresh&&(e.trailing=!0)}this.setState({selectedNotificationInbox:a})}catch(n){if(this.isCurrentTarget(t,e.generation)){let e=this.getState().selectedNotificationInbox;e!==void 0&&Wf(e,t)&&e.status!==`stale`&&this.setState({selectedNotificationInbox:{...e,status:`stale`}}),this.onBackgroundError(`Failed to refresh notifications for session ${t.sessionId}`,n)}return}finally{this.selectedJoin===n&&(this.selectedJoin=void 0)}}while(e.trailing&&this.isCurrentTarget(t,e.generation)&&this.machineIsReachable(t.machineId))}applyMutationSnapshot(e,t,n){let r=this.getState().selectedNotificationInbox;if(r===void 0||!Wf(r,e))return;if(!this.machineSupportsNotifications(e.machineId)||!this.machineIsReachable(e.machineId)){this.setState({selectedNotificationInbox:{...n(r),status:`stale`}});return}let i=$f(r,e,t)?Af(r,e,t):r;this.setState({selectedNotificationInbox:n(i)})}patchSelectedOverlay(e,t){let n=this.getState().selectedNotificationInbox;n===void 0||!Wf(n,e)||this.setState({selectedNotificationInbox:t(n)})}ensureSelectedProjection(e){let t=this.getState().selectedNotificationInbox;(t===void 0||!Wf(t,e))&&this.setState({selectedNotificationInbox:kf(e)})}scheduleSelectedRefresh(e){queueMicrotask(()=>{!this.disposed&&this.selectedTarget!==void 0&&Wf(this.selectedTarget,e)&&this.refreshSelectedSession({id:e.sessionId,cwd:e.cwd},e.machineId)})}markSelectedStale(e){let t=this.getState().selectedNotificationInbox;t===void 0||!Wf(t,e)||t.status===`stale`||this.setState({selectedNotificationInbox:{...t,status:`stale`}})}pruneRemovedMachines(e){let t=new Set(e.map(e=>e.id));t.size===0&&t.add(`local`);for(let e of[...this.acceptedSupportByMachine])t.has(e)||this.acceptedSupportByMachine.delete(e)}isCurrentTarget(e,t){return!this.disposed&&t===this.selectedGeneration&&this.selectedTarget!==void 0&&Wf(this.selectedTarget,e)}machineSupportsNotifications(e){return this.machineSupportsNotificationsInState(this.getState(),e)}machineSupportsNotificationsInState(e,t){return this.acceptedSupportByMachine.has(t)||e.machineRuntimes[t]?.ok===!0}machineIsReachable(e){return this.machineIsReachableInState(this.getState(),e)}machineIsReachableInState(e,t){let n=e.machines.find(e=>e.id===t);if(t===`local`||n?.kind===`local`)return!0;let r=e.machineStatuses[t]?.status??n?.status;return r===void 0||r===`unknown`||r===`online`}};function Qf(e){return{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd}}function $f(e,t,n){return!Wf(e,t)||e.daemonInstanceId!==n.daemonInstanceId||e.summary===void 0||n.summary.inboxRevision>=e.summary.inboxRevision}function ep(e){return e instanceof Error?e.message:String(e)}var tp=class{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}},np=`pi-web:workspace-selection:v1`,rp=class{constructor(e=Hd()){this.workspaceIdsByProject=new Ud(np,Wd,e)}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}};function ip(e,t){let n=t?.targetWorkspaceId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestWorkspaceId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e[0]:e[0]}var ap=class{constructor(e,t,n,r,i=new tp,a={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessions=r,this.workspaceSelection=i,this.topologyRefreshes=new Us,this.api=a.api??L,this.onBackgroundError=a.onBackgroundError??((e,t)=>{console.warn(e,t)}),this.browserErrors=new Es(e,t)}clearSelection(e){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...hs()}),e?.updateUrl!==!1&&this.updateUrl()}forgetProject(e){let t=z(this.getState());this.browserErrors.discard(_s(t,e)),this.workspaceSelection.forgetProject(Vs(t,e));let n=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([t])=>t!==e));this.setState({workspacesByProjectId:n})}async selectProject(e,t){let n=z(this.getState()),r=_s(n,e.id);this.sessions.clearActiveSession(),this.setState({selectedProject:e,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...hs()});try{let r=await this.api.workspaces(e.id,n);if(z(this.getState())!==n||this.getState().selectedProject?.id!==e.id)return;this.setState({workspaces:r,workspacesByProjectId:{...this.getState().workspacesByProjectId,[e.id]:r},isLoadingWorkspaces:!1});let i=ip(r,{targetWorkspaceId:t?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Vs(n,e.id))});i?await this.selectWorkspace(i,{sessionId:t?.sessionId,updateUrl:t?.updateUrl}):t?.updateUrl!==!1&&this.updateUrl()}catch(t){z(this.getState())===n&&this.getState().selectedProject?.id===e.id&&this.setState({isLoadingWorkspaces:!1}),this.browserErrors.report(r,String(t))}}async selectWorkspace(e,t){let n=z(this.getState()),r=vs(n,e.projectId,e.id);this.workspaceSelection.rememberWorkspace({...e,projectId:Vs(n,e.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:e,isLoadingWorkspaces:!1,...hs()});try{let r=Jc(e.path,await this.api.sessions(e.path,n),n);if(z(this.getState())!==n||this.getState().selectedWorkspace?.id!==e.id||this.getState().selectedProject?.id!==e.projectId)return;this.setState({sessions:r});let i=this.sessions.preferredSession(e.path,r,t?.sessionId);i?await this.sessions.selectSession(i,{updateUrl:t?.updateUrl}):t?.updateUrl!==!1&&this.updateUrl()}catch(e){this.browserErrors.report(r,String(e))}}async refreshProjectWorkspaces(e){let t=this.getState().projects.find(t=>t.id===e);if(t===void 0)throw Error(`找不到项目`);let n=await this.api.workspaces(t.id,z(this.getState()));return this.applyProjectWorkspaces(t.id,n),n}async refreshSelectedProjectTopology(){let e=this.getState(),t=e.selectedProject;if(t===void 0)return;let n=z(e);await this.topologyRefreshes.request(Vs(n,t.id),async()=>{try{let e=await this.api.workspaces(t.id,n),r=this.getState();if(z(r)!==n||r.selectedProject?.id!==t.id)return;this.applyProjectWorkspaces(t.id,e)}catch(e){this.onBackgroundError(`Failed to refresh workspaces for project ${t.id} on ${n}`,e)}})}async refreshAfterWorkspaceDeleted(e,t){let n=await this.refreshProjectWorkspaces(e),r=this.getState();if(r.selectedProject?.id!==e||r.selectedWorkspace?.id!==t)return;let i=op(n);i===void 0?this.clearSelection():await this.selectWorkspace(i)}applyProjectWorkspaces(e,t){let n=this.getState(),r={...n.workspacesByProjectId,[e]:t};if(n.selectedProject?.id!==e){this.setState({workspacesByProjectId:r});return}this.setState({workspaces:t,workspacesByProjectId:r,...this.refreshedSelection(n.selectedWorkspace,t)})}refreshedSelection(e,t){if(e===void 0)return;let n=t.find(t=>t.id===e.id);if(!(n===void 0||sp(e,n)))return{selectedWorkspace:n}}};function op(e){return e.find(e=>e.isMain)??e[0]}function sp(e,t){return e.path===t.path&&e.label===t.label&&e.branch===t.branch&&e.isMain===t.isMain&&e.isGitRepo===t.isGitRepo&&e.isGitWorktree===t.isGitWorktree}var cp=`pi-web:machine-navigation:v1`,lp=class{constructor(e=Hd()){this.snapshotsByMachine=new Ud(cp,mp,e)}latest(e){let t=this.snapshotsByMachine.get(e);return t?.machineId===e?pp(t):void 0}remember(e){this.snapshotsByMachine.set(e.machineId,pp(e))}forget(e){this.snapshotsByMachine.delete(e)}};function up(e){return{machineId:e,surface:{}}}function dp(e){let t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??`local`,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id,tool:e.workspaceTool,view:e.mainView,surface:{selectedFilePath:t?e.selectedFilePath:void 0,selectedDiffPath:t?e.selectedDiffPath:void 0,selectedTerminalId:t?e.selectedTerminalId:void 0}}}function fp(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view===`navigation`?void 0:e.view}}function pp(e){return{...e,surface:{...e.surface}}}function mp(e){if(!bp(e))return;let t=yp(e,`machineId`);if(t===void 0)return;let n=_p(yp(e,`tool`)),r=gp(yp(e,`view`));return{machineId:t,projectId:yp(e,`projectId`),workspaceId:yp(e,`workspaceId`),sessionId:yp(e,`sessionId`),...n===void 0?{}:{tool:n},...r===void 0?{}:{view:r},surface:hp(e.surface)}}function hp(e){return bp(e)?{selectedFilePath:yp(e,`selectedFilePath`),selectedDiffPath:yp(e,`selectedDiffPath`),selectedTerminalId:yp(e,`selectedTerminalId`)}:{}}function gp(e){return e===`navigation`||e===`chat`?e:_p(e)}function _p(e){return vp(e)?e:void 0}function vp(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function yp(e,t){let n=e[t];return typeof n==`string`&&n!==``?n:void 0}function bp(e){return typeof e==`object`&&!!e}var xp=`pi-web:terminal-selection:v1`,Sp=class{constructor(e=Hd()){this.terminalIdsByCwd=new Ud(xp,Wd,e)}latestTerminalId(e){return this.terminalIdsByCwd.get(e)}rememberTerminal(e,t){this.terminalIdsByCwd.set(e,t)}forgetWorkspace(e){this.terminalIdsByCwd.delete(e)}forgetTerminal(e){for(let[t,n]of this.terminalIdsByCwd.entries())n===e&&this.terminalIdsByCwd.delete(t)}};function Cp(e,t){let n=t?.targetTerminalId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestTerminalId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>!e.exited)??e[0]:e.find(e=>!e.exited)??e[0]}function wp(e){return e.find(e=>!e.exited)??e[0]}var Tp=1200,Ep=[`mod`,`alt`,`shift`],Dp=class{constructor(){this.pendingTokens=[]}handle(e,t,n={}){let r=Mp(e);if(r===void 0)return!1;let i=Op(t,n.shortcuts,{enabledOnly:!0}).filter(e=>e.active).map(e=>({action:e.action,tokens:e.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,r],i))return!0;if(this.clearPending(),!Np(r))return!1}else if(!Np(r))return!1;return this.handleSequence([r],i)}reset(){this.clearPending()}handleSequence(e,t){let n=t.find(t=>Xp(t.tokens,e));return n===void 0?t.some(t=>Zp(t.tokens,e))?(this.setPending(e),!0):!1:(this.clearPending(),n.action.run(),!0)}setPending(e){this.clearPending(),this.pendingTokens=e,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},Tp)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}};function Op(e,t,n={}){let r=e.flatMap((e,r)=>{if(n.enabledOnly===!0&&e.enabled===!1)return[];let i=Pp(e,t,r);return i===void 0?[]:[i]}),i=new Map;for(let e of r)i.set(e.key,[...i.get(e.key)??[],e]);let a=new Map;for(let e of i.values()){let t=[...e].sort(Rp)[0];t!==void 0&&a.set(t.key,t)}let o=[...a.values()].sort(zp),s=new Map,c=new Map;for(let e of r){let t=a.get(e.key);if(t===void 0)continue;let n=Bp(t,o)??t;c.set(e,n),e!==n&&s.set(n,[...s.get(n)??[],e])}return r.map(e=>{let t=c.get(e),n=t===e,r=t===void 0||n?void 0:Lp(t),i=n?[...s.get(e)??[]].sort(Rp).map(Lp):[];return{...e,active:n,shadows:i,...r===void 0?{}:{shadowedBy:r}}}).sort((e,t)=>e.order-t.order)}function kp(e){return Up(e,{requireFirstChordActivator:!0})}function Ap(e){let t=Up(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function jp(e){return Ap(e).map(e=>e.split(`+`).map(Yp).join(`+`)).join(` `)}function Mp(e){if(e.isComposing)return;let t=qp(e.key);if(t===void 0)return;let n=[];return(e.metaKey||e.ctrlKey)&&n.push(`mod`),e.altKey&&n.push(`alt`),e.shiftKey&&n.push(`shift`),n.push(t),n.join(`+`)}function Np(e){return e.split(`+`).includes(`mod`)||e.split(`+`).includes(`alt`)}function Pp(e,t,n){let r=Fp(e.id,t);if(r===null)return;let i=r??e.shortcut;if(i===void 0||i===``)return;let a=Ap(i),o=a[0];if(!(o===void 0||!Np(o)))return{action:e,shortcut:a.join(` `),source:r===void 0?`default`:`custom`,tokens:a,key:Ip(a),order:n}}function Fp(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Ip(e){return e.join(`\0`)}function Lp(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function Rp(e,t){return Vp(e.source)-Vp(t.source)||Hp(e.action.id,t.action.id)||Hp(e.action.title,t.action.title)||e.order-t.order}function zp(e,t){return e.tokens.length-t.tokens.length||Rp(e,t)}function Bp(e,t){return t.find(t=>t!==e&&t.tokens.length<e.tokens.length&&Zp(e.tokens,t.tokens))}function Vp(e){switch(e){case`custom`:return 0;case`default`:return 1}}function Hp(e,t){return e<t?-1:+(e>t)}function Up(e,t){let n=e.trim().toLowerCase().replace(/\s*\+\s*/gu,`+`);if(n===``)return{ok:!1,message:`请输入快捷键,选择无,或重置为默认值。`};let r=[],i=n.split(/\s+/u).filter(e=>e!==``);for(let[e,n]of i.entries()){let i=Wp(n);if(!i.ok)return i;if(e===0&&t.requireFirstChordActivator&&!Np(i.token))return{ok:!1,message:`快捷键必须以 Ctrl/⌘ 或 Alt 开头,避免拦截普通输入。`};r.push(i.token)}return{ok:!0,shortcut:r.join(` `),tokens:r}}function Wp(e){let t=e.split(`+`).filter(e=>e!==``);if(t.length===0)return{ok:!1,message:`快捷键组合必须包含一个按键。`};let n=new Set,r;for(let e of t){let t=Gp(e);if(t!==void 0){if(n.has(t))return{ok:!1,message:`快捷键包含重复的 ${Yp(t)} 修饰键。`};n.add(t);continue}let i=Kp(e);if(i===void 0)return{ok:!1,message:`不支持的快捷键按键:${e}`};if(r!==void 0)return{ok:!1,message:`每个快捷键组合只能包含一个非修饰键。`};r=i}return r===void 0?{ok:!1,message:`快捷键组合必须包含一个按键。`}:{ok:!0,token:[...Ep.filter(e=>n.has(e)),r].join(`+`)}}function Gp(e){switch(e){case`mod`:case`meta`:case`cmd`:case`command`:case`ctrl`:case`control`:case`primary`:return`mod`;case`alt`:case`option`:case`opt`:return`alt`;case`shift`:return`shift`;default:return}}function Kp(e){let t=Jp(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function qp(e){return e===` `?`space`:Kp(e.toLowerCase())}function Jp(e){switch(e){case` `:case`spacebar`:case`space`:return`space`;case`esc`:case`escape`:return`escape`;case`return`:case`enter`:return`enter`;case`del`:case`delete`:return`delete`;case`backspace`:return`backspace`;case`tab`:return`tab`;case`up`:case`arrowup`:return`arrowup`;case`down`:case`arrowdown`:return`arrowdown`;case`left`:case`arrowleft`:return`arrowleft`;case`right`:case`arrowright`:return`arrowright`;case`pageup`:case`pagedown`:case`home`:case`end`:return e;case`+`:case`plus`:return`plus`;case`period`:case`dot`:return`.`;case`comma`:return`,`;case`slash`:return`/`;case`backslash`:return`\\`;case`minus`:return`-`;default:return}}function Yp(e){return e===`mod`?Qp()?`⌘`:`Ctrl`:e===`shift`?`Shift`:e===`alt`?Qp()?`⌥`:`Alt`:e===`enter`?`Enter`:e===`escape`?`Esc`:e===`space`?`Space`:e===`tab`?`Tab`:e===`backspace`?`Backspace`:e===`delete`?`Delete`:e===`arrowup`?`↑`:e===`arrowdown`?`↓`:e===`arrowleft`?`←`:e===`arrowright`?`→`:e===`pageup`?`PageUp`:e===`pagedown`?`PageDown`:e===`home`?`Home`:e===`end`?`End`:e===`plus`?`+`:/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1?e.toUpperCase():`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function Xp(e,t){return e.length===t.length&&Zp(e,t)}function Zp(e,t){return t.every((t,n)=>e[n]===t)}function Qp(){return typeof navigator<`u`&&navigator.userAgent.toLowerCase().includes(`mac`)}var $p={archiveIdleEnabled:!0,archiveIdleDays:`30`,deleteArchivedEnabled:!1,deleteArchivedDays:`90`};function em(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:`请至少启用一项清理操作。`};let t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){let n=um(e.archiveIdleDays,`归档空闲会话天数`);if(typeof n==`string`)return{ok:!1,error:n};t.archiveIdleDays=n}if(e.deleteArchivedEnabled){let n=um(e.deleteArchivedDays,`删除已归档会话天数`);if(typeof n==`string`)return{ok:!1,error:n};t.deleteArchivedDays=n}return{ok:!0,request:t}}function tm(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null,projectId:e?.projectId??null})}function nm(e){return!e.canCleanup||e.loading===!0||e.running===!0||e.preview===void 0||!rm(e.draft,e.preview)?!1:im(e.preview)}function rm(e,t){let n=em(e);return n.ok?dm(n.request)===dm(t.thresholds):!1}function im(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function am(e,t){let n=e.projects.map(e=>e.cwd);if(t===void 0)return n;let r=new Set(t);return n.filter(e=>r.has(e))}function om(e,t){let n=new Set(am(e,t)),r=e.projects.filter(e=>n.has(e.cwd));return{...e,projects:r,totals:r.reduce((e,t)=>({archiveCount:e.archiveCount+t.archiveCount,deleteCount:e.deleteCount+t.deleteCount}),{archiveCount:0,deleteCount:0})}}function sm(e,t){return t(cm(e))}function cm(e){let t=e.totals.archiveCount,n=e.totals.deleteCount,r=[];return t>0&&r.push(`归档 ${String(t)} 个空闲会话`),n>0&&r.push(`永久删除 ${String(n)} 个已归档会话`),`运行清理并${r.length===0?`执行清理`:r.join(`并`)}?\n\n永久删除只适用于已归档会话,且无法撤销。`}function lm(e){return`请更新并重启 ${e??`此机器`} 上的 Pi-Web 后再清理会话。`}function um(e,t){let n=e.trim();if(n===``)return`${t}必须设置。`;let r=Number(n);return!Number.isInteger(r)||r<0?`${t}必须是非负整数天数。`:r}function dm(e){return JSON.stringify({archiveIdleDays:e.archiveIdleDays??null,deleteArchivedDays:e.deleteArchivedDays??null})}var fm=new Set,pm=Rt+1,mm={unreadCatalog:e=>jo.unreadCatalog(e),acknowledgeUnread:(e,t,n,r)=>jo.acknowledgeUnread(e,t,n,r)},hm=class{constructor(e={}){this.machines=new Map,this.api=e.api??mm,this.onChange=e.onChange??(()=>void 0),this.onBackgroundError=e.onBackgroundError??(()=>void 0)}retainMachines(e){for(let[t,n]of this.machines){if(e.has(t))continue;let r=n.projection!==void 0;n.generation+=1,n.observers.clear(),n.acknowledgements.clear(),this.machines.delete(t),r&&this.onChange(t)}}setCapability(e,t){let n=this.machine(e),r=n.capability;if(r===t)return!1;if(n.capability=t,t===`unsupported`){let t=n.projection!==void 0;return n.generation+=1,n.projection=void 0,t&&(n.projectionVersion+=1),n.status=`stale`,n.refreshPromise=void 0,n.refreshQueued=!1,n.observers.clear(),n.acknowledgements.clear(),t&&this.onChange(e),!1}return t===`unknown`?(n.projection!==void 0&&n.status!==`stale`&&(n.status=`stale`,this.onChange(e)),!1):r!==`supported`}capability(e){return this.machines.get(e)?.capability??`unknown`}projection(e){let t=this.machines.get(e),n=t?.projection;if(!(t===void 0||n===void 0))return{status:t.status,catalogId:n.catalogId,catalogRevision:n.catalogRevision,sessions:[...n.summariesByIdentity.values()].sort((e,t)=>t.completionOrder-e.completionOrder).map(e=>({...e}))}}unreadSessionIds(e,t){let n=this.machines.get(e)?.projection;if(n===void 0||t.length===0)return fm;let r=new Set;for(let e of t)n.summariesByIdentity.has(xm(e))&&r.add(e.id);return r.size===0?fm:r}isUnread(e,t){return this.machines.get(e)?.projection?.summariesByIdentity.has(xm(t))===!0}applyEvent(e,t){let n=this.machine(e);if(n.capability!==`supported`)return;this.recordObservedEvent(n,t);let r=gm(n.projection,n.status,t);this.installProjection(n,r.projection,r.status)&&this.onChange(e),r.requiresRefresh&&(n.refreshPromise===void 0?this.refresh(e):n.refreshQueued=!0)}refresh(e){let t=this.machine(e);if(t.capability!==`supported`)return Promise.resolve();if(t.refreshPromise!==void 0)return t.refreshQueued=!0,t.refreshPromise;let n=t.generation,r=this.runRefreshLoop(t,n);return t.refreshPromise=r,r.finally(()=>{if(!this.isCurrent(t,n)||t.refreshPromise!==r)return;t.refreshPromise=void 0;let e=t.refreshQueued&&t.capability===`supported`;t.refreshQueued=!1,e&&this.refresh(t.machineId)}),r}async refreshAll(){await Promise.all([...this.machines.values()].filter(e=>e.capability===`supported`).map(async e=>{await this.refresh(e.machineId)}))}acknowledge(e,t){let n=this.machines.get(e),r=n?.projection;if(n?.capability!==`supported`||r===void 0)return Promise.resolve();let i=r.summariesByIdentity.get(xm(t));if(i===void 0)return Promise.resolve();let a=Sm(r.catalogId,i),o=n.acknowledgements.get(a);if(o!==void 0)return o;let s=n.generation,c=this.runAcknowledgement(n,s,t,r.catalogId,i.completionOrder);return n.acknowledgements.set(a,c),c.finally(()=>{n.acknowledgements.get(a)===c&&n.acknowledgements.delete(a)}),c}async runRefreshLoop(e,t){do{if(e.refreshQueued=!1,!this.isCurrentSupported(e,t))return;let n=e.status;this.markRefreshStarted(e)&&this.onChange(e.machineId);let r=this.beginNetworkObservation(e,t,n);try{let n=await this.api.unreadCatalog(e.machineId);if(!this.isCurrentSupported(e,t))return;this.applyNetworkSnapshot(e,n,r)&&(e.refreshQueued=!0)}catch(n){if(this.isCurrent(e,t)){let t=e.status!==`stale`;e.status=`stale`,t&&this.onChange(e.machineId),this.reportError(`snapshot`,e.machineId,n)}}finally{e.observers.delete(r)}}while(e.refreshQueued&&this.isCurrentSupported(e,t))}async runAcknowledgement(e,t,n,r,i){let a=this.beginNetworkObservation(e,t);try{let o=await this.api.acknowledgeUnread(n,r,i,e.machineId);if(!this.isCurrentSupported(e,t))return;this.applyNetworkSnapshot(e,o,a)&&this.refresh(e.machineId)}catch(n){this.isCurrent(e,t)&&this.reportError(`acknowledge`,e.machineId,n)}finally{e.observers.delete(a)}}applyNetworkSnapshot(e,t,n){let r=e.projection;if(e.projectionVersion!==n.projectionVersion&&r!==void 0&&r.catalogId!==t.catalogId||n.overflowed||n.events.some(e=>e.catalogId!==t.catalogId)){let t=e.status!==`stale`;return e.status=`stale`,t&&this.onChange(e.machineId),!0}let i=vm(t),a=`fresh`,o=!1;for(let e of n.events){let t=gm(i,a,e);i=t.projection,a=t.status,o||=t.requiresRefresh}if(r?.catalogId===i.catalogId&&r.catalogRevision>i.catalogRevision){if(e.projectionVersion===n.projectionVersion&&n.projectionStatus===`fresh`){let t=e.status!==`fresh`;e.status=`fresh`,t&&this.onChange(e.machineId)}o||=e.status===`stale`}else this.installProjection(e,i,a)&&this.onChange(e.machineId);return o}beginNetworkObservation(e,t,n=e.status){let r={generation:t,projectionVersion:e.projectionVersion,projectionStatus:n,events:[],overflowed:!1};return e.observers.add(r),r}recordObservedEvent(e,t){for(let n of e.observers)n.generation!==e.generation||n.overflowed||(n.events.length>=pm?(n.events.length=0,n.overflowed=!0):n.events.push(t))}markRefreshStarted(e){let t=e.projection===void 0?`loading`:`stale`;return e.status===t?!1:(e.status=t,!0)}installProjection(e,t,n){let r=!bm(e.projection,t);return e.status===n&&!r?!1:(r&&(e.projection=t,e.projectionVersion+=1),e.status=n,!0)}machine(e){let t=this.machines.get(e);if(t!==void 0)return t;let n={machineId:e,capability:`unknown`,status:`stale`,projection:void 0,projectionVersion:0,generation:0,observers:new Set,acknowledgements:new Map,refreshPromise:void 0,refreshQueued:!1};return this.machines.set(e,n),n}isCurrent(e,t){return this.machines.get(e.machineId)===e&&e.generation===t}isCurrentSupported(e,t){return this.isCurrent(e,t)&&e.capability===`supported`}reportError(e,t,n){this.onBackgroundError(e,t,n)}};function gm(e,t,n){if(e===void 0){let e=ym(n.catalogId);return n.catalogRevision===1?_m(e,`fresh`,n):{projection:e,status:`stale`,requiresRefresh:!0}}if(e.catalogId!==n.catalogId){let e=ym(n.catalogId);return n.catalogRevision===1?_m(e,`stale`,n):{projection:e,status:`stale`,requiresRefresh:!0}}return n.catalogRevision<=e.catalogRevision?{projection:e,status:t,requiresRefresh:t===`stale`}:n.catalogRevision===e.catalogRevision+1?_m(e,t,n):{projection:e,status:`stale`,requiresRefresh:!0}}function _m(e,t,n){let r=new Map(e.summariesByIdentity),i=xm(n);n.unread===null?r.delete(i):r.set(i,{...n.unread});let a=t===`stale`?`stale`:`fresh`;return{projection:{catalogId:n.catalogId,catalogRevision:n.catalogRevision,summariesByIdentity:r},status:a,requiresRefresh:a===`stale`}}function vm(e){return{catalogId:e.catalogId,catalogRevision:e.catalogRevision,summariesByIdentity:new Map(e.sessions.map(e=>[xm(e),{...e}]))}}function ym(e){return{catalogId:e,catalogRevision:0,summariesByIdentity:new Map}}function bm(e,t){if(e?.catalogId!==t.catalogId||e.catalogRevision!==t.catalogRevision||e.summariesByIdentity.size!==t.summariesByIdentity.size)return!1;for(let[n,r]of e.summariesByIdentity){let e=t.summariesByIdentity.get(n);if(e?.completionOrder!==r.completionOrder||e.completedAt!==r.completedAt)return!1}return!0}function xm(e){let t=`id`in e?e.id:e.sessionId;return JSON.stringify([t,e.cwd])}function Sm(e,t){return JSON.stringify([e,t.sessionId,t.cwd,t.completionOrder])}var Cm={machines:new Set,projects:new Set,workspaces:new Set};function wm(e){let t=Em(e.projectionFor(e.selectedMachineId));return{machines:Dm(e.machineIds,e.projectionFor),projects:km(e.projects,e.workspacesByProjectId,t),workspaces:Om(e.workspaces,t)}}function Tm(e){return e!==void 0&&e.sessions.length>0}function Em(e){return e===void 0||e.sessions.length===0?jm:new Set(e.sessions.map(e=>e.cwd))}function Dm(e,t){let n=new Set;for(let r of e)Tm(t(r))&&n.add(r);return n}function Om(e,t){let n=new Set;for(let r of e)t.has(r.path)&&n.add(r.id);return n}function km(e,t,n){let r=new Set;for(let i of e)(t[i.id]??[]).some(e=>n.has(e.path))&&r.add(i.id);return r}function Am(e,t){return Mm(e.machines,t.machines)&&Mm(e.projects,t.projects)&&Mm(e.workspaces,t.workspaces)}var jm=new Set;function Mm(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function Nm(){return{selectedSessionKey:void 0,warningSetSignature:Pm(void 0),warningCount:0,collapsed:!1,collapsedWarningSets:new Map}}function Pm(e){let t=(e??[]).map(e=>JSON.stringify([e.severity,e.message,e.source,e.path,e.dismiss?.id])).sort();return JSON.stringify(t)}function Fm(e,t,n){let r=Pm(n),i=n?.length??0,a=n!==void 0,o=t===void 0?void 0:e.collapsedWarningSets.get(t),s=e.collapsedWarningSets;if(a&&t!==void 0&&o!==void 0&&o!==r){let n=new Map(e.collapsedWarningSets);n.delete(t),s=n}let c=a&&i>0&&o===r;return e.selectedSessionKey===t&&e.warningSetSignature===r&&e.warningCount===i&&e.collapsed===c&&e.collapsedWarningSets===s?e:{selectedSessionKey:t,warningSetSignature:r,warningCount:i,collapsed:c,collapsedWarningSets:s}}function Im(e){if(e.collapsed||e.warningCount===0||e.selectedSessionKey===void 0)return e;let t=new Map(e.collapsedWarningSets);return t.set(e.selectedSessionKey,e.warningSetSignature),{...e,collapsed:!0,collapsedWarningSets:t}}function Lm(e){if(!e.collapsed)return e;let t=new Map(e.collapsedWarningSets);return e.selectedSessionKey!==void 0&&t.delete(e.selectedSessionKey),{...e,collapsed:!1,collapsedWarningSets:t}}function Rm(e){return e.collapsed?Lm(e):Im(e)}var zm=100;function Bm(e,t){return e.filter(e=>Um(e,t))}var Vm={snapshot:e=>Do.snapshot(e),dismiss:(e,t,n)=>Do.dismiss(e,t,n)},Hm=class{constructor(e={}){this.machines=new Map,this.api=e.api??Vm,this.onChange=e.onChange??(()=>void 0),this.onBackgroundError=e.onBackgroundError??(()=>void 0)}retainMachines(e){for(let[t,n]of this.machines){if(e.has(t))continue;let r=n.projection!==void 0;n.generation+=1,n.observers.clear(),n.pendingDismissedIds.clear(),n.dismissals.clear(),this.machines.delete(t),r&&this.onChange(t)}}projection(e){let t=this.machines.get(e),n=t?.projection;if(!(t===void 0||n===void 0))return{machineId:e,status:t.status,daemonInstanceId:n.daemonInstanceId,revision:n.revision,notices:n.notices.filter(e=>!t.pendingDismissedIds.has(e.id))}}hasNotice(e,t){let n=this.projection(e);return n?.status===`fresh`&&n.notices.some(t)}applyEvent(e,t){let n=this.machine(e);this.recordObservedEvent(n,t);let r=n.projection;if(r===void 0){this.installProjection(n,Gm(t.snapshot),`fresh`)&&this.onChange(e);return}if(r.daemonInstanceId!==t.snapshot.daemonInstanceId){let t=n.status!==`stale`;n.status=`stale`,t&&this.onChange(e),n.refreshPromise===void 0?this.refresh(e):n.refreshQueued=!0;return}if(t.snapshot.revision<=r.revision){n.status===`stale`&&(n.refreshPromise===void 0?this.refresh(e):n.refreshQueued=!0);return}this.installProjection(n,Gm(t.snapshot),`fresh`)&&this.onChange(e)}refresh(e){let t=this.machine(e);if(t.refreshPromise!==void 0)return t.refreshQueued=!0,t.refreshPromise;let n=t.generation,r=this.runRefreshLoop(t,n);return t.refreshPromise=r,r.finally(()=>{if(!this.isCurrent(t,n)||t.refreshPromise!==r)return;t.refreshPromise=void 0;let e=t.refreshQueued;t.refreshQueued=!1,e&&this.refresh(t.machineId)}),r}async refreshAll(){await Promise.all([...this.machines.values()].map(async e=>{await this.refresh(e.machineId)}))}dismiss(e,t){let n=this.machines.get(e),r=n?.projection;if(n===void 0||r===void 0||r.notices.find(e=>e.id===t)===void 0||n.pendingDismissedIds.has(t))return Promise.resolve();let i=`${r.daemonInstanceId}:${t}`,a=n.dismissals.get(i);if(a!==void 0)return a;let o=n.generation,s=this.beginNetworkObservation(n,o);n.pendingDismissedIds.add(t),this.onChange(e);let c=this.runDismissal(n,o,s,r.daemonInstanceId,t);return n.dismissals.set(i,c),c.finally(()=>{n.dismissals.get(i)===c&&n.dismissals.delete(i)}),c}async runRefreshLoop(e,t){do{if(e.refreshQueued=!1,!this.isCurrent(e,t))return;this.markRefreshStarted(e)&&this.onChange(e.machineId);let n=this.beginNetworkObservation(e,t);try{let r=await this.api.snapshot(e.machineId);if(!this.isCurrent(e,t))return;this.applyNetworkSnapshot(e,r,n)&&(e.refreshQueued=!0)}catch(n){if(this.isCurrent(e,t)){let t=e.status!==`stale`;e.status=`stale`,t&&this.onChange(e.machineId),this.onBackgroundError(`snapshot`,e.machineId,n)}}finally{e.observers.delete(n)}}while(e.refreshQueued&&this.isCurrent(e,t))}async runDismissal(e,t,n,r,i){try{let a=await this.api.dismiss(e.machineId,r,i);if(!this.isCurrent(e,t))return;let o=this.applyNetworkSnapshot(e,a,n);e.pendingDismissedIds.delete(i),o&&this.refresh(e.machineId)}catch(n){this.isCurrent(e,t)&&this.onBackgroundError(`dismiss`,e.machineId,n)}finally{e.observers.delete(n),this.isCurrent(e,t)&&(e.pendingDismissedIds.delete(i),this.onChange(e.machineId))}}applyNetworkSnapshot(e,t,n){if(n.overflowed)return this.markStale(e);let r=t;for(let t of n.events){if(t.snapshot.daemonInstanceId!==r.daemonInstanceId)return this.markStale(e);t.snapshot.revision>r.revision&&(r=t.snapshot)}let i=e.projection;if(i!==void 0&&e.projectionVersion!==n.projectionVersion){if(i.daemonInstanceId!==r.daemonInstanceId)return this.markStale(e);i.revision>r.revision&&(r={daemonInstanceId:i.daemonInstanceId,revision:i.revision,notices:i.notices})}return this.installProjection(e,Gm(r),`fresh`)&&this.onChange(e.machineId),!1}beginNetworkObservation(e,t){let n={generation:t,projectionVersion:e.projectionVersion,events:[],overflowed:!1};return e.observers.add(n),n}recordObservedEvent(e,t){for(let n of e.observers)n.generation!==e.generation||n.overflowed||(n.events.length>=zm?(n.events.length=0,n.overflowed=!0):n.events.push(t))}markRefreshStarted(e){let t=e.projection===void 0?`loading`:`stale`;return e.status===t?!1:(e.status=t,!0)}markStale(e){let t=e.status!==`stale`;return e.status=`stale`,t&&this.onChange(e.machineId),!0}installProjection(e,t,n){let r=!Km(e.projection,t);return e.status===n&&!r?!1:(r&&(e.projection=t,e.projectionVersion+=1),e.status=n,!0)}machine(e){let t=this.machines.get(e);if(t!==void 0)return t;let n={machineId:e,status:`stale`,projection:void 0,projectionVersion:0,generation:0,observers:new Set,pendingDismissedIds:new Set,dismissals:new Map,refreshPromise:void 0,refreshQueued:!1};return this.machines.set(e,n),n}isCurrent(e,t){return this.machines.get(e.machineId)===e&&e.generation===t}};function Um(e,t){let n=e.context;if(e.source===`workspace.delete`){let e=Wm(n,`projectId`);return e===void 0||e===t.projectId}let r=Wm(n,`projectId`),i=Wm(n,`workspaceId`),a=Wm(n,`sessionId`);return r===void 0&&i===void 0&&a===void 0||(r===void 0||r===t.projectId)&&(i===void 0||i===t.workspaceId)&&(a===void 0||a===t.sessionId)}function Wm(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function Gm(e){return{daemonInstanceId:e.daemonInstanceId,revision:e.revision,notices:e.notices.map(e=>({...e,...e.context===void 0?{}:{context:{...e.context}}}))}}function Km(e,t){return e?.daemonInstanceId!==t.daemonInstanceId||e.revision!==t.revision||e.notices.length!==t.notices.length?!1:e.notices.every((e,n)=>JSON.stringify(e)===JSON.stringify(t.notices[n]))}var qm=`themes:classic`,Jm={themeId:`themes:pi-web-dark`,auto:!0},Ym=`pi-web-app-theme`,Xm=`--pi-bg.--pi-surface.--pi-surface-hover.--pi-terminal-bg.--pi-terminal-text.--pi-border.--pi-border-muted.--pi-text.--pi-text-secondary.--pi-text-bright.--pi-muted.--pi-dim.--pi-accent.--pi-accent-border.--pi-selection-bg.--pi-success.--pi-success-border.--pi-success-bg.--pi-success-surface.--pi-success-ring.--pi-warning.--pi-warning-border.--pi-warning-surface.--pi-danger.--pi-purple.--pi-purple-border.--pi-purple-surface.--pi-overlay.--pi-shadow-soft.--pi-shadow.--pi-shadow-strong.--pi-bg-overlay-soft.--pi-bg-overlay.--pi-success-bg-overlay.--pi-terminal-selection`.split(`.`),Zm=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function Qm(){try{let e=window.localStorage.getItem(Ym);return e===null?void 0:ih(e)}catch{return}}function $m(e){try{window.localStorage.setItem(Ym,JSON.stringify(e))}catch{}}function eh(e){let t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(let n of Xm){let r=e.tokens[n];typeof r==`string`&&r!==``?t.style.setProperty(n,r):t.style.removeProperty(n)}}function th(e){let t=nh(e.themes,e.fallbackThemeId??`themes:classic`),n=e.themes.find(t=>t.id===e.preference.themeId)??t;if(n===void 0)return{selectedTheme:void 0,activeTheme:void 0,selectedThemePair:void 0,fallbackTheme:t};let r=rh(e.themePairs,n.id);if(!e.preference.auto||r===void 0)return{selectedTheme:n,activeTheme:n,selectedThemePair:r,fallbackTheme:t};let i=e.prefersLight?r.light:r.dark;return{selectedTheme:n,activeTheme:e.themes.find(e=>e.id===i)??n,selectedThemePair:r,fallbackTheme:t}}function nh(e,t=qm){return e.find(e=>e.id===t)??e[0]}function rh(e,t){return e.find(e=>e.light===t||e.dark===t)}function ih(e){let t=e.trim();if(t!==``)try{let e=JSON.parse(t);return ah(e)?e:void 0}catch{return}}function ah(e){if(!oh(e))return!1;let t=e.themeId,n=e.auto;return sh(t)&&typeof n==`boolean`}function oh(e){return typeof e==`object`&&!!e}function sh(e){return typeof e==`string`&&Zm.test(e)}function ch(e){return e?.removal!==void 0&&!e.isMain}function lh(e){return e.removal?.confirmation}function uh(e){return{...e===void 0?{}:{projectId:e},metadata:{[Ns]:Ms}}}function dh(e){let t={};for(let n of e){let e=mh(n);if(e===void 0)continue;let r=t[e];(r===void 0||n.createdAt.localeCompare(r.createdAt)>=0)&&(t[e]=n)}return t}function fh(e){return Object.entries(e).filter(([,e])=>hh(e)).map(([e])=>e)}function ph(e,t){if(t===void 0)return!1;let n=e.workspaceDeletionRuns[t.id];return n!==void 0&&hh(n)}function mh(e){return e.metadata[Ps]}function hh(e){return e.status===`queued`||e.status===`running`}function gh(){return[{id:`actions.show`,title:`显示操作`,description:`打开命令面板`,shortcut:`mod+k`,group:`通用`,run:e=>{e.openActionPalette()}},{id:`prompt.focus`,title:`聚焦提示词输入框`,description:`将键盘焦点移动到消息编辑器`,shortcut:`mod+g c`,group:`通用`,enabled:e=>e.state.selectedSession!==void 0,run:e=>{e.focusPrompt()}},{id:`machine.add`,title:`添加机器`,description:`注册另一个可从当前网关访问的 PI WEB 运行时`,group:`机器`,run:e=>e.addMachine()},{id:`machine.refresh`,title:`刷新所选机器`,description:`检查所选 PI WEB 运行时是否在线`,group:`机器`,run:e=>e.refreshSelectedMachine()},{id:`machine.open`,title:`打开所选机器的 PI WEB`,description:`在新标签页中直接打开所选远程 PI WEB`,group:`机器`,enabled:e=>e.state.selectedMachine?.kind===`remote`&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:`machine.remove`,title:`移除所选机器`,description:`从当前网关移除所选远程机器`,group:`机器`,enabled:e=>e.state.selectedMachine?.kind===`remote`,run:e=>e.removeSelectedMachine()},{id:`project.add`,title:`添加项目`,group:`项目`,run:e=>e.addProject()},{id:`auth.login`,title:`配置当前项目的提供商认证`,description:`为当前项目运行 /login`,group:`通用`,run:e=>e.configureAuth()},{id:`auth.logout`,title:`移除当前项目的提供商认证`,description:`移除当前项目已保存的凭据`,group:`通用`,run:e=>e.logoutAuth()},{id:`theme.select`,title:`选择主题`,description:`选择 PI WEB 颜色主题`,group:`偏好设置`,run:e=>{e.openThemePicker()}},{id:`settings.open`,title:`打开设置`,description:`管理 PI WEB 配置和键盘快捷键`,shortcut:`mod+,`,group:`偏好设置`,run:e=>{e.piWebUnstable?.openSettings?.()}},{id:`app.reload-page`,title:`完整重载页面`,description:`重新加载 PI WEB 浏览器页面`,group:`通用`,run:e=>{e.reloadPage()}},{id:`view.chat`,title:`转到聊天`,shortcut:`mod+1`,group:`导航`,run:e=>{e.focusPrompt()}},{id:`view.files`,title:`转到文件`,shortcut:`mod+2`,group:`导航`,enabled:_h,run:e=>{e.selectMainView(`core:workspace.files`)}},{id:`view.git`,title:`转到 Git`,shortcut:`mod+3`,group:`导航`,enabled:vh,run:e=>{e.selectMainView(`core:workspace.git`)}},{id:`view.terminal`,title:`转到终端`,shortcut:`mod+4`,group:`导航`,enabled:_h,run:e=>{e.selectMainView(`core:workspace.terminal`)}},{id:`workspace.refresh-files`,title:`刷新文件`,shortcut:`mod+shift+f`,group:`工作区`,enabled:_h,run:e=>e.refreshFiles()},{id:`workspace.refresh-git`,title:`刷新 Git`,shortcut:`mod+shift+g`,group:`工作区`,enabled:vh,run:e=>e.refreshGit()},{id:`workspace.refresh-current`,title:`刷新当前面板`,shortcut:`mod+shift+r`,group:`工作区`,enabled:_h,run:e=>e.state.workspaceTool===`core:workspace.git`&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:`workspace.delete`,title:`删除工作区`,description:`移除所选 Git worktree`,group:`工作区`,enabled:yh,run:e=>e.deleteWorkspace()},{id:`session.start`,title:`启动会话`,shortcut:`mod+enter`,group:`会话`,enabled:_h,run:e=>e.startSession()},{id:`model.select`,title:`选择模型`,description:`为所选会话选择模型`,group:`会话`,enabled:bh,run:e=>e.openModelPicker()},{id:`thinking.select`,title:`选择思考级别`,description:`为所选会话选择思考级别`,group:`会话`,enabled:bh,run:e=>e.openThinkingLevelPicker()},{id:`session.archive`,title:`归档会话`,description:`归档所选会话`,group:`会话`,enabled:xh,run:e=>e.archiveSession()},{id:`session.reload`,title:`重新加载会话`,description:`关闭并从会话文件重新打开所选会话;如需重载 Pi 运行时资源,请在提示词中使用 /reload`,group:`会话`,enabled:Ch,disabledReason:wh,run:e=>e.reloadSession()},{id:`session.delete`,title:`删除新会话`,description:`删除所选的临时新会话`,group:`会话`,enabled:Sh,run:e=>e.deleteCachedNewSession()},{id:`session.stop`,title:`停止活动工作`,shortcut:`mod+.`,group:`会话`,enabled:e=>e.state.selectedSession!==void 0&&As(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function _h(e){return e.state.selectedWorkspace!==void 0}function vh(e){return e.state.selectedWorkspace?.isGitRepo===!0}function yh(e){let t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!ph(e.state,t)}function bh(e){let t=e.state.selectedSession;return t!==void 0&&t.archived!==!0}function xh(e){return Bd(e.state.selectedSession,e.state.status,Th(e.state))}function Sh(e){return Vd(e.state.selectedSession,e.state.status,Th(e.state))}function Ch(e){return!Bd(e.state.selectedSession,e.state.status,Th(e.state))||wh(e)!==void 0?!1:!As(e.state.status,e.state.activity)}function wh(e){if(Bd(e.state.selectedSession,e.state.status,Th(e.state))&&!As(e.state.status,e.state.activity))return Eh(e.state,`从磁盘重新加载会话`)}function Th(e){return Rd(e.machineRuntimes[z(e)])}function Eh(e,t){if(e.machineRuntimes[z(e)]?.ok===!0)return;let n=e.selectedMachine?.name;return n!==void 0&&n!==``?`请更新并重启 ${n} 上的 Pi-Web,以便${t}。`:`请更新并重启此机器上的 Pi-Web,以便${t}。`}function Dh(e){return typeof e==`string`?Oh(e):g`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`}function Oh(e){switch(e){case`navigation`:return _`
|
|
19
|
+
`))+1;return e.slice(t)}var Td=class{constructor(e=`normal`){this.scope=e,this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId=`local`}connect(e,t,n,r=`local`,i){this.close(),this.machineId=r,this.session=e,this.onEvent=t,this.onReconnect=n,this.onInitialOpen=i,this.shouldReconnect=!0,this.open()}setHandler(e){this.onEvent=e}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Id(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.onInitialOpen=void 0,this.hasOpened=!1,this.machineId=`local`}open(){let e=this.session;if(e===void 0||e.id===``||e.cwd===``||!this.shouldReconnect)return;let t=Bo(e,this.machineId,this.scope);this.socket=t,t.onopen=()=>{if(this.socket!==t)return;this.reconnectDelay=500;let e=this.hasOpened;this.hasOpened=!0,e?this.onReconnect?.():this.onInitialOpen?.()},t.onmessage=n=>void this.handleMessage(n.data,t,e),t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t,n){let r=Dd(await Fd(e));this.socket!==t||r===void 0||r.type===`notifications.inbox`&&(n.id!==r.summary.sessionId||n.cwd!==r.summary.cwd)||this.onEvent?.(r)}},Ed=class{constructor(e=`normal`){this.scope=e,this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId=`local`}connect(e,t,n=`local`){this.close(),this.machineId=n,this.onEvent=e,this.onOpen=t,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Id(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId=`local`}open(){if(!this.shouldReconnect)return;let e=Ho(this.machineId,this.scope);this.socket=e,e.onopen=()=>{this.socket===e&&(this.reconnectDelay=500,this.onOpen?.())},e.onmessage=t=>void this.handleMessage(t.data,e),e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t){let n=Od(await Fd(e));this.socket===t&&n!==void 0&&this.onEvent?.(n)}};function Dd(e){let t=Pd(e);return t===`notifications.inbox`?Md(()=>Er(e)):t===`ask.opened`?Nd(()=>qn(e)):t===`ask.closed`?Nd(()=>Jn(e)):t===`dialog.opened`?Nd(()=>sr(e)):t===`dialog.closed`?Nd(()=>cr(e)):kd(e)?e:void 0}function Od(e){if(Pd(e)===`machine.status`){if(typeof e!=`object`||!e||!(`status`in e))return;let t=cn(e.status);return t===void 0?void 0:{type:`machine.status`,status:t}}if(Pd(e)===`sessions.unread`)return Nd(()=>mr(e));if(Pd(e)===`notices.updated`)return Nd(()=>Or(e));if(Pd(e)===`models.changed`)return Nd(()=>kr(e));if(Pd(e)===`session.startup`)return Nd(()=>hr(e));if(Ad(e)||jd(e))return e}function kd(e){return[`message.append`,`assistant.delta`,`assistant.thinking.delta`,`tool.start`,`tool.update`,`tool.end`,`shell.start`,`shell.chunk`,`shell.end`,`agent.start`,`agent.end`,`message.end`,`status.update`,`activity.update`,`command.output`,`session.error`,`session.name`,`session.created`,`pi.event`].includes(Pd(e))}function Ad(e){let t=Pd(e);return t===`status.update`||t===`activity.update`||t===`session.name`||t===`session.created`}function jd(e){let t=Pd(e);return t===`terminal.created`||t===`terminal.exited`||t===`terminal.closed`||t===`workspace.activity`}function Md(e){return Nd(e)}function Nd(e){try{return e()}catch{return}}function Pd(e){if(typeof e!=`object`||!e||!(`type`in e))return``;let t=e.type;return typeof t==`string`?t:``}async function Fd(e){try{return typeof e==`string`?JSON.parse(e):e instanceof Blob?JSON.parse(await e.text()):e instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(e)):void 0}catch{return}}function Id(e){if(e!==void 0){if(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING){e.onopen=()=>{e.close()};return}e.close()}}function Ld(e){return e?.ok===!0}function Rd(e){return{authoritative:Ld(e)}}function zd(e,t,n={}){if(e===void 0)return`unknown`;let r=(t?.sessionId===e.id?t.persisted:void 0)??e.persisted;return r===!0?`persisted`:r===!1||Yc(e)?`transient`:n.authoritative===!0?`unknown`:`persisted`}function Bd(e,t,n){return e!==void 0&&e.archived!==!0&&zd(e,t,n)===`persisted`}function Vd(e,t,n){return e!==void 0&&e.archived!==!0&&zd(e,t,n)===`transient`}function Hd(){try{return typeof sessionStorage>`u`?void 0:sessionStorage}catch{return}}var Ud=class{constructor(e,t,n=Hd()){this.storageKey=e,this.storage=n,this.values=new Map;for(let[r,i]of Gd(e,t,n))this.values.set(r,i)}get(e){return this.values.get(e)}set(e,t){this.values.set(e,t),this.save()}delete(e){this.values.delete(e),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}let e={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(e))}catch{}}};function Wd(e){return typeof e==`string`&&e!==``?e:void 0}function Gd(e,t,n){try{let r=n?.getItem(e);if(r==null||r===``)return[];let i=JSON.parse(r);if(!Kd(i))return[];let a=[];for(let e of i.entries){let n=e[0],r=t(e[1]);r!==void 0&&a.push([n,r])}return a}catch{return[]}}function Kd(e){return!qd(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`&&e[0]!==``)}function qd(e){return typeof e==`object`&&!!e}var Jd=class{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}},Yd=`pi-web:session-selection:v1`,Xd=class{constructor(e=Hd()){this.sessionIdsByCwd=new Ud(Yd,Wd,e)}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}};function Zd(e,t){let n=t?.targetSessionId;if(n!==void 0&&n!==``)return $d(e,n);let r=t?.latestSessionId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>e.archived!==!0):e.find(e=>e.archived!==!0)}function Qd(e,t){return t?.archived===!0&&!e.some(e=>e.archived!==!0)}function $d(e,t){return e.find(e=>e.id===t||e.id.startsWith(t))}function ef(e,t,n){return tf(e,[t],n)}function tf(e,t,n){let r=new Set(t);return e.map(e=>r.has(e.id)?{...e,archived:!0,archivedAt:n}:e)}function nf(e,t,n){return rf(e,t,[n])}function rf(e,t,n){if(t===void 0||!n.includes(t))return{type:`unchanged`};let r=new Set(n),i=e.find(e=>!r.has(e.id)&&e.archived!==!0);return i===void 0?{type:`clear`}:{type:`select`,session:i}}var af=/timed out|operation was aborted|request cancelled/i;function of(e){return e instanceof jt&&(e.status===504||e.status===499)||e instanceof Error&&af.test(e.message)}function sf(e){return of(e)?`会话守护进程请求超时。当前对话仍在继续。`:e instanceof Error?e.message:String(e)}var cf=100,lf=500,uf=5e3,df=class{constructor(e,t,n,r=new Jd,i={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessionSelection=r,this.selectionSeq=0,this.disposed=!1,this.pendingTranscriptEvents=[],this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.sessionRefreshInFlight=!1,this.searchSeq=0,this.searchTargetSeq=0,this.pendingSessionStartSeq=0,this.pendingQueuedSendSeq=0,this.pendingSessionStarts=new Map,this.suppressedCreatedSessions=new Map,this.selectedSessionRefreshes=new Us,this.socket=i.socket??new Td,this.api=i.api??L,this.transcripts=i.transcripts??new ld,this.streamSnapshot=i.streamSnapshot??i.api?.streamSnapshot??L.streamSnapshot,this.notifications=i.notifications,this.replacePromptEditorText=i.replacePromptEditorText,this.onSelectedSessionReady=i.onSelectedSessionReady,this.onModelScopeChanged=i.onModelScopeChanged,this.browserErrors=new Es(e,t)}applyGlobalEvent(e){e.type===`status.update`?this.queueStatusUpdate(e.status):e.type===`activity.update`?this.queueActivityUpdate(e.activity):e.type===`session.created`?this.applyCreatedSession(e.session):e.type===`session.name`?this.applySessionName(e.sessionId,e.name):e.type===`models.changed`?this.onModelScopeChanged?.(e.revision):e.type===`session.startup`&&this.queueStartupProgress(e)}dispose(){this.disposed=!0,this.selectionSeq+=1,this.searchSeq+=1,this.stopPolling(),this.searchTimer!==void 0&&clearTimeout(this.searchTimer),this.searchTimer=void 0,this.socket.close(),this.clearPendingUpdates()}updatePolling(){this.stopPolling(),this.getState().selectedWorkspace!==void 0&&(this.sessionPollTimer=setInterval(()=>{this.sessionRefreshInFlight||(this.sessionRefreshInFlight=!0,this.refreshCurrentWorkspaceSessions().finally(()=>{this.sessionRefreshInFlight=!1}))},uf))}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0})}deselectSession(e){let t=this.getState(),n=t.selectedSession?.cwd??t.selectedWorkspace?.path;e?.forgetRememberedSelection===!0&&n!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(n)),this.clearActiveSession(),e?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){let e=this.getState();Qd(e.sessions,e.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){let e=this.getState().selectedWorkspace;if(!e)return;let t=z(this.getState()),n=this.createPendingSessionStart(e,t);this.pendingSessionStarts.set(n.tempId,n),this.insertAndSelectPendingSession(n.session);try{let r=await this.api.startSession(e.path,t,n.tempId);await this.resolvePendingSessionStart(n.tempId,r)}catch(e){this.failPendingSessionStart(n.tempId,e)}}async refreshPinnedSessions(e,t=z(this.getState())){try{let n=await this.api.pinned(e,t);if(z(this.getState())!==t||this.getState().selectedWorkspace?.path!==e)return;this.setState({pinnedSessionIds:n.sessionIds})}catch{z(this.getState())===t&&this.getState().selectedWorkspace?.path===e&&this.setState({pinnedSessionIds:[]})}}togglePinned(e){if(e.persisted===!1)return;let t=this.getState(),n=t.pinnedSessionIds.includes(e.id),r=n?t.pinnedSessionIds.filter(t=>t!==e.id):[...t.pinnedSessionIds,e.id],i=z(t);this.setState({pinnedSessionIds:r}),(async()=>{try{let t=n?await this.api.unpin(e,i):await this.api.pin(e,i),r=this.getState();if(z(r)!==i||r.selectedWorkspace?.path!==e.cwd)return;let a=t.pinned;this.setState({pinnedSessionIds:a?[...new Set([...this.getState().pinnedSessionIds,e.id])]:this.getState().pinnedSessionIds.filter(t=>t!==e.id)})}catch(t){let r=this.getState();if(z(r)!==i||r.selectedWorkspace?.path!==e.cwd)return;this.setState({pinnedSessionIds:n?[...new Set([...r.pinnedSessionIds,e.id])]:r.pinnedSessionIds.filter(t=>t!==e.id)}),this.reportSessionError(e,i,t)}})()}searchSessions(e){let t=this.getState(),n=t.selectedWorkspace,r=z(t);this.searchSeq+=1;let i=this.searchSeq;this.searchTimer!==void 0&&clearTimeout(this.searchTimer),this.searchTimer=void 0,this.setState({sessionSearchQuery:e,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``});let a=e.trim();n===void 0||a===``||(this.setState({isSearchingSessions:!0}),this.searchTimer=setTimeout(()=>{this.searchTimer=void 0,this.performSessionSearch(i,a,n.id,n.path,r)},250))}async performSessionSearch(e,t,n,r,i){try{let a=await this.api.searchContent(r,t,i),o=this.getState();if(e!==this.searchSeq||z(o)!==i||o.selectedWorkspace?.id!==n||o.sessionSearchQuery.trim()!==t)return;this.setState({sessionSearchResults:a,isSearchingSessions:!1})}catch(t){let r=this.getState();if(e!==this.searchSeq||z(r)!==i||r.selectedWorkspace?.id!==n)return;this.setState({sessionSearchResults:{results:[],matchCount:0,truncated:!1},isSearchingSessions:!1,sessionSearchError:String(t)})}}preferredSession(e,t,n){return Zd(t,{targetSessionId:n,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(e))})}async selectSession(e,t){if(this.disposed)return;if(vf(e)){this.selectClientPendingStartSession(e,t);return}let n=z(this.getState()),r=this.captureSessionErrorOwner(e);this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)});let i=++this.selectionSeq;this.socket.close(),this.streamWatermark=void 0,this.clearPendingUpdates(),this.notifications?.prepareSelectedSession(e,n);let a=this.sessionCacheKey(e.id),o=this.transcripts.cachedView(a);this.setState({selectedSession:e,sessionSearchTarget:void 0,...o,isLoadingEarlierMessages:!1,status:e.archived===!0?void 0:this.getState().sessionStatuses[e.id],activity:e.archived===!0?void 0:this.getState().sessionActivities[e.id],pendingAsk:e.archived===!0?void 0:this.selectedPendingAsk(this.getState().sessionStatuses[e.id]),pendingDialogs:e.archived===!0?[]:this.getState().sessionStatuses[e.id]?.pendingDialogs??[],closedDialogs:[],availableThinkingLevels:[]});let s;try{if(e.archived===!0){let n=await this.api.messages(e,{limit:cf},z(this.getState()));if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;let r=this.transcripts.mergeHistory(a,n);this.setState({...r,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[]}),t?.updateUrl!==!1&&this.updateUrl();return}let o=[];if(s=o,this.socket.connect(e,e=>o.push(e),()=>{this.refreshSelectedSession(e.id,{silent:!0})},n,()=>{this.notifications?.refreshSelectedSession(e,n)}),await this.requestSelectedSessionRefresh({session:e,machineId:n,selectionSeq:i,errorOwner:r}),!this.isCurrentRefreshTarget({session:e,machineId:n,selectionSeq:i,errorOwner:r}))return;this.refreshAvailableThinkingLevels();for(let e of o)this.applyEvent(e);this.socket.setHandler(e=>{this.applyEvent(e)}),this.onSelectedSessionReady?.({machineId:n,session:e}),t?.updateUrl!==!1&&this.updateUrl()}catch(a){if(i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id){if(this.reportSessionError(e,n,a,r),t?.propagateRefreshError===!0&&this.isSelectedSessionIdentity(e.id,n))throw a;return}if(Yc(e)&&Af(a)){await this.recreateCachedNewSession(e,t);return}if(s!==void 0){for(let e of s)this.applyEvent(e);this.socket.setHandler(e=>{this.applyEvent(e)})}if(this.reportSessionError(e,n,a,r),t?.propagateRefreshError===!0)throw a}}async loadEarlierMessages(){let e=this.getState(),t=e.selectedSession;if(!t||e.isLoadingEarlierMessages||e.messagePageStart<=0)return;let n=z(e),r=this.selectionSeq,i=Hs(n,t.id),a=()=>{let e=this.getState();return!this.disposed&&r===this.selectionSeq&&z(e)===n&&e.selectedSession?.id===t.id&&e.selectedSession.cwd===t.cwd&&e.selectedSession.path===t.path&&e.selectedSession.archived===t.archived};this.setState({isLoadingEarlierMessages:!0});try{let r=await this.api.messages(t,{before:e.messagePageStart,limit:cf},n);if(!a())return;let o=this.transcripts.mergeHistory(i,r);this.setState(o)}catch(e){if(!a())return;this.reportSessionError(t,n,e)}finally{a()&&this.setState({isLoadingEarlierMessages:!1})}}async send(e,t,n,r=`inline`,i){let a=this.getState().selectedSession;if(!a||a.archived===!0)return;let o=e.trim(),s=n!==void 0&&n.length>0;if(vf(a)){!s&&o.startsWith(`/`)?this.enqueuePendingSessionSend(a,{type:`command`,text:e}):!s&&Sd(e)?this.enqueuePendingSessionSend(a,{type:`shell`,text:e}):this.enqueuePendingSessionSend(a,{type:`prompt`,text:e,streamingBehavior:t,attachments:n,delivery:r,folder:i});return}if(!s&&o.startsWith(`/`))return this.runCommand(e);if(!s&&Sd(e))return this.runShell(e);await this.deliverPromptToSession(a,e,t,n,r,i,z(this.getState()),{markSending:s})}markSendingPrompt(e,t){let n=this.getState().sendingPrompts;t?n[e]!==!0&&this.setState({sendingPrompts:{...n,[e]:!0}}):e in n&&this.setState({sendingPrompts:mf(n,e)})}async runShell(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0)){if(vf(t)){this.enqueuePendingSessionSend(t,{type:`shell`,text:e});return}await this.deliverShellToSession(t,e,z(this.getState()),{optimisticLine:!0})}}async runCommand(e){let t=this.getState().selectedSession;if(!(!t||t.archived===!0)){if(vf(t)){this.enqueuePendingSessionSend(t,{type:`command`,text:e});return}await this.deliverCommandToSession(t,e,z(this.getState()),{applyResult:!0})}}async renameSession(e,t){let n=t.trim();if(n===``||!Bd(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let r=z(this.getState());try{let t=await this.api.runCommand(e,`/name ${n}`,r);if(t.type===`done`){this.applySessionName(e.id,t.session?.name??n);return}this.reportSessionError(e,r,t.type===`unsupported`?t.message:`重命名会话失败`)}catch(t){this.reportSessionError(e,r,t)}}enqueuePendingSessionSend(e,t){let n=this.pendingSessionStarts.get(e.id);if(n===void 0||n.discarded){this.reportSessionError(e,e.machineId,`后端会话尚未准备好发送排队消息。丢弃此次启动失败前,请先复制你的消息。`);return}let r={...t,id:`pending-send-${String(++this.pendingQueuedSendSeq)}`};n.queuedSends.push(r);let i=this.getState(),a=i.clientQueuedSessionMessages[e.id]??[],o=bf(e.id,n.queuedSends.length);this.setState({clientQueuedSessionMessages:{...i.clientQueuedSessionMessages,[e.id]:[...a,Sf(r)]},sessionActivities:{...i.sessionActivities,[e.id]:o},activity:i.selectedSession?.id===e.id?o:i.activity,error:``})}async flushQueuedPendingSends(e,t,n){for(let r of n){if(!await this.deliverQueuedPendingSend(e,t,r))return;this.dropNextQueuedSessionMessage(e.id)}}async deliverQueuedPendingSend(e,t,n){return n.type===`prompt`?this.deliverPromptToSession(e,n.text,n.streamingBehavior,n.attachments,n.delivery,n.folder,t,{markSending:!0}):n.type===`shell`?this.deliverShellToSession(e,n.text,t,{optimisticLine:!0}):this.deliverCommandToSession(e,n.text,t,{applyResult:!0})}async deliverPromptToSession(e,t,n,r,i,a,o,s){let c=r!==void 0&&r.length>0;s.markSending&&this.markSendingPrompt(e.id,!0);try{if(c&&i===`folder`){let i=(await this.api.saveAttachments(e,r,o,a)).map(e=>gd(e.path,!1)).join(` `),s=t===``?i:`${t}\n\n${i}`;await this.api.prompt(e,s,n,o)}else await this.api.prompt(e,t,n,o,r);return this.markCachedNewSessionPersisted(e),!0}catch(t){return this.reportSessionError(e,o,t),!1}finally{s.markSending&&this.markSendingPrompt(e.id,!1)}}async deliverShellToSession(e,t,n,r){r.optimisticLine&&this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ol(`user`,t)]});try{return await this.api.shell(e,t,n),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ol(`system`,sf(t))]}),this.reportSessionError(e,n,t),!1}}async deliverCommandToSession(e,t,n,r){this.markSendingPrompt(e.id,!0);try{let i=await this.api.runCommand(e,t,n);return r.applyResult&&this.isSelectedSessionIdentity(e.id,n)?this.applyCommandResult(i):(i.type===`select`||i.type===`tree`)&&this.reportSessionError(e,n,`排队命令“${t}”需要输入;请打开会话并重新运行。`),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ol(`system`,sf(t))]}),this.reportSessionError(e,n,t),!1}finally{this.markSendingPrompt(e.id,!1)}}dropNextQueuedSessionMessage(e){let t=this.getState(),n=t.clientQueuedSessionMessages[e]??[];if(n.length===0)return;let r=n.slice(1);this.setState({clientQueuedSessionMessages:r.length===0?mf(t.clientQueuedSessionMessages,e):{...t.clientQueuedSessionMessages,[e]:r}})}async respondToCommand(e,t){let n=this.getState().selectedSession;if(!n)return;let r=z(this.getState());this.setState({commandDialog:void 0});try{let i=await this.api.respondToCommand(n,e,t,r);this.isSelectedSessionIdentity(n.id,r)&&this.applyCommandResult(i)}catch(e){this.reportSessionError(n,r,e)}}cancelCommand(){this.setState({commandDialog:void 0})}async navigateTree(e,t){let n=this.getState(),r=n.selectedSession,i=n.treeDialog;if(r===void 0||i===void 0||r.archived===!0||vf(r))throw Error(`会话树导航器已不可用`);let a=z(n),o=Hs(a,r.id),s;try{s=await this.api.navigateTree(r,{targetId:e,expectedLeafId:i.activeLeafId,summary:t},a)}catch(e){throw this.reportSessionError(r,a,e),e}if(s.cancelled)return s;let c=s.editorText??``;if(Hl(o,c),this.transcripts.discard(o),!this.isSelectedSessionIdentity(r.id,a))return s;this.clearPendingUpdates();let l;try{await this.selectSession(r,{updateUrl:!1,preserveTreeDialog:!0,propagateRefreshError:!0})}catch(e){l={error:e}}if(!this.isSelectedSessionIdentity(r.id,a))return s;try{await this.replacePromptEditorText?.({machineId:a,sessionId:r.id,text:c})}catch(e){throw this.reportSessionError(r,a,e),e}if(l!==void 0)throw this.reportSessionError(r,a,l.error),l.error;return this.isSelectedSessionIdentity(r.id,a)&&this.getState().treeDialog===i&&this.setState({treeDialog:void 0}),s}async forkFromTree(e){let t=this.getState(),n=t.selectedSession,r=t.treeDialog;if(n===void 0||r===void 0||n.archived===!0||vf(n))throw Error(`会话树导航器已不可用`);let i=z(t),a=Hs(i,n.id),o;try{o=await this.api.forkTree(n,{entryId:e,expectedLeafId:r.activeLeafId},i)}catch(e){throw this.reportSessionError(n,i,e),e}if(o.cancelled)return o;let s=o.session;if(o.promptDraft!==void 0&&Hl(Hs(i,s.id),o.promptDraft),this.transcripts.discard(a),!this.isSelectedSessionIdentity(n.id,i))return o;let c=[s,...this.getState().sessions.filter(e=>e.id!==s.id)];return this.setState({sessions:c,treeDialog:void 0}),this.selectSession(s),o}async abortTreeNavigation(){let e=this.getState(),t=e.selectedSession;if(t===void 0||e.treeDialog===void 0||vf(t))return;let n=z(e);try{await this.api.abort(t,n)}catch(e){throw this.reportSessionError(t,n,e),e}}closeTreeDialog(){this.setState({treeDialog:void 0})}applySessionStatus(e){this.applyStatus(e)}archiveScopeProjectId(){return _t()?this.getState().selectedProject?.id:void 0}async archiveSession(e=this.getState().selectedSession){if(!e)return;let t=this.statusForSession(e),n=this.sessionPersistenceOptions();if(Vd(e,t,n)){await this.deleteCachedNewSession(e);return}if(!Bd(e,t,n))return;let r=z(this.getState());try{await this.api.archive(e,r,this.archiveScopeProjectId());let t=this.getState(),n=ef(t.sessions,e.id,new Date().toISOString()),i=nf(n,t.selectedSession?.id,e.id);this.setState({sessions:n}),i.type===`select`?await this.selectSession(i.session):i.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}catch(t){this.reportSessionError(e,r,t)}}async archiveSessionWithDescendants(e=this.getState().selectedSession){if(e===void 0||!Bd(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=z(this.getState());try{let n=await this.api.archiveWithDescendants(e,t,this.archiveScopeProjectId()),r=n.sessionIds!==void 0&&n.sessionIds.length>0?n.sessionIds:[e.id],i=this.getState(),a=tf(i.sessions,r,new Date().toISOString()),o=rf(a,i.selectedSession?.id,r);this.setState({sessions:a}),o.type===`select`?await this.selectSession(o.session):o.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}catch(n){this.reportSessionError(e,t,n)}}async archiveSessions(e){let t=this.sessionPersistenceOptions(),n=Tf(e).filter(e=>Bd(e,this.statusForSession(e),t));if(n.length===0)return;let r=z(this.getState()),i=this.getState().selectedWorkspace;try{let{succeededIds:e,failures:t,generatedAt:a}=await this.archiveSessionBatch(n,r);if(e.length>0){let t=this.getState(),n=tf(t.sessions,e,a??new Date().toISOString()),r=rf(n,t.selectedSession?.id,e);this.setState({sessions:n}),r.type===`select`?await this.selectSession(r.session):r.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}this.applyBulkSessionFailures(`归档`,t,r,i,n[0])}catch(e){this.reportWorkspaceOrSessionError(i,n[0],r,`归档失败:${Df(e)}`)}}async deleteArchivedSessions(e){let t=Tf(e).filter(e=>e.archived===!0);if(t.length===0)return;let n=z(this.getState()),r=this.getState().selectedWorkspace;try{let{succeededIds:e,failures:i}=await this.deleteArchivedSessionBatch(t,n);if(e.length>0){let r=new Set(e),i=this.getState(),a=i.sessions.filter(e=>!r.has(e.id));if(this.setState({sessions:a}),i.selectedSession!==void 0&&r.has(i.selectedSession.id)){let e=a.find(e=>e.archived!==!0)??a[0];e===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(e)}await this.refreshPinnedSessions(t[0]?.cwd??``,n)}this.applyBulkSessionFailures(`删除`,i,n,r,t[0])}catch(e){this.reportWorkspaceOrSessionError(r,t[0],n,`删除失败:${Df(e)}`)}}async archiveSessionBatch(e,t){let n=await this.api.archiveMany(e,t,this.archiveScopeProjectId());return{succeededIds:n.archivedSessionIds,failures:Ef(n.failures),generatedAt:n.generatedAt}}async deleteArchivedSessionBatch(e,t){let n=await this.api.deleteArchivedMany(e,t,this.archiveScopeProjectId());return{succeededIds:n.deletedSessionIds,failures:Ef(n.failures)}}async applySessionCleanupResult(e,t=z(this.getState())){if(z(this.getState())!==t)return;let n=e.archivedSessionIds,r=e.deletedSessionIds;if(n.length>0||r.length>0){let t=this.getState(),i=new Set(r),a=[...n,...r],o=tf(t.sessions,n,e.generatedAt).filter(e=>!i.has(e.id)),s=t.selectedSession!==void 0&&a.includes(t.selectedSession.id);if(this.setState({sessions:o,sessionStatuses:hf(t.sessionStatuses,a),sessionActivities:hf(t.sessionActivities,a),...s?{status:void 0,activity:void 0,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[]}:{}}),t.selectedSession!==void 0&&i.has(t.selectedSession.id)){let e=o.find(e=>e.archived!==!0)??o[0];e===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(e)}else{let e=rf(o,t.selectedSession?.id,n);e.type===`select`?await this.selectSession(e.session):e.type===`clear`&&this.deselectSession({forgetRememberedSelection:!0})}}await this.refreshCurrentWorkspaceSessions(t)}async refreshCurrentWorkspaceSessions(e=z(this.getState())){let t=this.getState().selectedWorkspace;if(t!==void 0)try{let n=Jc(t.path,await this.api.sessions(t.path,e),e).filter(t=>!this.isSuppressedCreatedSession(t,e));if(z(this.getState())!==e||this.getState().selectedWorkspace?.id!==t.id)return;let r=this.mergePendingStartSessions(t.path,n,e),i=this.getState().selectedSession;if(this.setState({sessions:r}),this.refreshPinnedSessions(t.path,e),i===void 0)return;let a=r.find(e=>e.id===i.id);if(a!==void 0){a!==i&&this.setState({selectedSession:a});return}let o=r.find(e=>e.archived!==!0)??r[0];o===void 0?this.deselectSession({forgetRememberedSelection:!0}):await this.selectSession(o)}catch(n){if(of(n)){console.warn(`Workspace session list refresh timed out`,n);return}this.reportWorkspaceError(t,e,n)}}stopPolling(){this.sessionPollTimer!==void 0&&clearInterval(this.sessionPollTimer),this.sessionPollTimer=void 0,this.sessionRefreshInFlight=!1}async deleteCachedNewSession(e=this.getState().selectedSession){if(e===void 0||!Vd(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=vf(e)?this.pendingSessionStarts.get(e.id):void 0;t===void 0?this.api.stop(e,z(this.getState())).catch(()=>{}):(t.discarded=!0,t.queuedSends=[]),qc(e.id,z(this.getState())),Ul(this.sessionCacheKey(e.id)),Jl(this.sessionCacheKey(e.id));let n=this.getState(),r=n.sessions.filter(t=>t.id!==e.id);if(this.setState({sessions:r,sessionStatuses:mf(n.sessionStatuses,e.id),sessionActivities:pf(n.sessionActivities,e.id),sendingPrompts:mf(n.sendingPrompts,e.id),clientQueuedSessionMessages:mf(n.clientQueuedSessionMessages,e.id)}),this.getState().selectedSession?.id!==e.id)return;let i=r.find(e=>e.archived!==!0)??r[0];i===void 0?(this.clearActiveSession(),this.updateUrl()):await this.selectSession(i)}async restoreSession(e=this.getState().selectedSession){if(!e)return;let t=z(this.getState());try{await this.api.restore(e,t,this.archiveScopeProjectId());let n={...e};delete n.archived,delete n.archivedAt,this.replaceSession(n),this.getState().selectedSession?.id===n.id&&await this.selectSession(n)}catch(n){this.reportSessionError(e,t,n)}}async reloadSession(e=this.getState().selectedSession){if(e===void 0||!Bd(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=z(this.getState());try{await this.api.reloadSession(e,t),this.transcripts.discard(this.sessionCacheKey(e.id)),this.getState().selectedSession?.id===e.id&&await this.selectSession(e,{updateUrl:!1})}catch(n){this.reportSessionError(e,t,n)}}async detachParent(e=this.getState().selectedSession){if(e?.parentSessionPath===void 0)return;let t=z(this.getState());try{await this.api.detachParent(e,t);let n={...e};delete n.parentSessionPath,this.replaceSession(n)}catch(n){this.reportSessionError(e,t,n)}}async listModels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=z(this.getState());try{return(await this.api.models(e,t)).models}catch(n){return this.reportSessionError(e,t,n),[]}}async listModelCatalog(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=z(this.getState());try{return(await this.api.modelCatalog(e,t)).models}catch(n){return this.reportSessionError(e,t,n),[]}}async setModelEnabled(e,t,n){let r=this.getState().selectedSession;if(!r||r.archived===!0)return;let i=z(this.getState());try{return(await this.api.setModelEnabled(r,e,t,n,i)).models}catch(e){this.reportSessionError(r,i,e);return}}async setModelScope(e){let t=this.getState(),n=t.selectedSession;if(!n||n.archived===!0)return;let r=z(t);try{return(await this.api.setModelScope(n,e,r)).models}catch(e){this.reportSessionError(n,r,e);return}}async setModel(e,t){let n=this.getState().selectedSession;if(!n||n.archived===!0)return;let r=z(this.getState());try{this.applyStatus(await this.api.setModel(n,e,t,r)),await this.refreshAvailableThinkingLevels()}catch(e){this.reportSessionError(n,r,e)}}async cycleModel(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;let n=z(this.getState());try{this.applyStatus(await this.api.cycleModel(t,e,n)),await this.refreshAvailableThinkingLevels()}catch(e){this.reportSessionError(t,n,e)}}async listThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=z(this.getState());try{return(await this.api.thinkingLevels(e,t)).levels}catch(n){return this.reportSessionError(e,t,n),[]}}async refreshAvailableThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}let t=await this.listThinkingLevels();this.getState().selectedSession?.id===e.id&&this.setState({availableThinkingLevels:t})}async setThinkingLevel(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;let n=z(this.getState());try{this.applyStatus(await this.api.setThinkingLevel(t,e,n))}catch(e){this.reportSessionError(t,n,e)}}async cycleThinkingLevel(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return;let t=z(this.getState());try{this.applyStatus(await this.api.cycleThinkingLevel(e,t))}catch(n){this.reportSessionError(e,t,n)}}async clearServerQueue(){let e=this.getState(),t=e.selectedSession;if(t===void 0||t.archived===!0||vf(t))return;let n=z(e),r=this.selectionSeq;try{let e=await this.api.clearQueue(t,n);this.isCurrentSessionSelection(t.id,n,r)&&this.applyStatus(e)}catch(e){this.reportSessionError(t,n,e)}}async dismissWarning(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||vf(n))return;let r=z(t),i=this.selectionSeq;try{let t=await this.api.dismissWarning(n,e,r);this.isCurrentSessionSelection(n.id,r,i)&&this.applyStatus(t)}catch(e){this.reportSessionError(n,r,e)}}submitAsk(e,t){return this.closeOpenAsk(e,(n,r)=>this.api.submitAsk(n,e,t,r))}cancelAsk(e){return this.closeOpenAsk(e,(t,n)=>this.api.cancelAsk(t,e,n))}answerDialog(e,t){return this.closeOpenDialog(e,(n,r)=>this.api.answerDialog(n,e,t,r))}cancelDialog(e){return this.closeOpenDialog(e,(t,n)=>this.api.cancelDialog(t,e,n))}async closeOpenDialog(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0)return;if(vf(r)){await this.closePendingStartDialog(r,e,t);return}let i=z(n),a=this.selectionSeq;try{let e=await t(r,i);if(!this.isCurrentSessionSelection(r.id,i,a))return;this.recordDialogOutcome(e.outcome),this.applyStatus(e.sessionStatus)}catch(e){this.reportSessionError(r,i,e)}}async closePendingStartDialog(e,t,n){let r=this.pendingSessionStarts.get(e.id),i=r?.backendSessionId;if(r===void 0||i===void 0)return;let a=this.selectionSeq;try{let t=await n({...e,id:i},r.machineId);if(a!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;this.recordDialogOutcome(t.outcome),this.applyPendingStartStatus(r,t.sessionStatus)}catch(t){this.reportSessionError(e,r.machineId,t)}}recordDialogOutcome(e){if(e===void 0)return;let t=this.getState().pendingDialogs.find(t=>t.dialogId===e.dialogId);t!==void 0&&this.recordClosedDialog({dialog:t,reason:e.reason,...e.answer===void 0?{}:{answer:e.answer}})}async closeOpenAsk(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0||vf(r))return;let i=z(n),a=this.selectionSeq;try{let n=await t(r,i);eu(Hs(i,r.id),e),this.isCurrentSessionSelection(r.id,i,a)&&this.applyStatus(n.sessionStatus)}catch(e){this.reportSessionError(r,i,e)}}async stopActiveWork(){let e=this.getState().selectedSession;if(!e)return;let t=z(this.getState());try{await this.api.abort(e,t)}catch(n){this.reportSessionError(e,t,n)}}refreshSelectedSession(e=this.getState().selectedSession?.id,t){let n=this.getState().selectedSession;if(e===void 0||n?.id!==e||n.archived===!0||vf(n))return Promise.resolve();let r={session:n,machineId:z(this.getState()),selectionSeq:this.selectionSeq,errorOwner:this.captureSessionErrorOwner(n)};return this.requestSelectedSessionRefresh(r).catch(e=>{if(t?.silent===!0){console.warn(`Selected session background refresh failed`,e);return}this.reportSessionError(r.session,r.machineId,e,r.errorOwner)})}requestSelectedSessionRefresh(e){let t=Hs(e.machineId,e.session.id);return this.selectedSessionRefreshes.request(t,async()=>{if(!this.isCurrentRefreshTarget(e))return;this.flushPendingUpdates();let[n,r,i]=await Promise.all([this.api.messages(e.session,{limit:cf},e.machineId),this.api.status(e.session,e.machineId),this.streamSnapshot(e.session,e.machineId).catch(()=>({seq:0,partial:null})),this.notifications?.refreshSelectedSession(e.session,e.machineId)??Promise.resolve()]);if(!this.isCurrentRefreshTarget(e)||this.isUnchangedSelectedRefresh(e,t,n,r,i))return;let a=this.transcripts.mergeHistory(t,n),o=this.transcripts.seedStreamingPartial(a.messages,i.partial);this.streamWatermark={sessionId:e.session.id,seq:i.seq},this.setState({...a,messages:o,status:r,activity:this.getState().sessionActivities[e.session.id]}),this.applyStatus(r),this.lastAppliedSelectedRefresh={selectionSeq:e.selectionSeq,partialJson:ff(i)}})}isUnchangedSelectedRefresh(e,t,n,r,i){let a=this.lastAppliedSelectedRefresh;return a?.selectionSeq!==e.selectionSeq||ff(i)!==a.partialJson||!ed(this.transcripts.rawHistoryPage(t),n)||JSON.stringify(r)!==JSON.stringify(this.getState().status)?!1:this.getState().sessionActivities[r.sessionId]?.phase!==`active`||As(r)}isCurrentRefreshTarget(e){return this.isCurrentSessionSelection(e.session.id,e.machineId,e.selectionSeq)}isCurrentSessionSelection(e,t,n){return n===this.selectionSeq&&this.isSelectedSessionIdentity(e,t)}isSelectedSessionIdentity(e,t){if(this.disposed)return!1;let n=this.getState(),r=n.selectedSession;return z(n)===t&&r?.id===e&&r.archived!==!0&&!vf(r)}reportSessionError(e,t,n,r={cwd:e.cwd}){this.browserErrors.report(ys(t,e.id,r),sf(n))}captureSessionErrorOwner(e,t=this.workspaceForSessionError(e)){return{cwd:e.cwd,...t===void 0?{}:{projectId:t.projectId,workspaceId:t.id}}}workspaceForSessionError(e){let t=this.getState();return[t.selectedWorkspace,...t.workspaces,...Object.values(t.workspacesByProjectId).flat()].find(t=>t?.path===e.cwd)}reportWorkspaceError(e,t,n){this.browserErrors.report(vs(t,e.projectId,e.id),sf(n))}applyBulkSessionFailures(e,t,n,r,i){t.length!==0&&this.reportWorkspaceOrSessionError(r,i,n,`${e}失败,${String(t.length)} 个会话处理失败:${t.join(`;`)}`)}reportWorkspaceOrSessionError(e,t,n,r){e===void 0?t!==void 0&&this.reportSessionError(t,n,r):this.reportWorkspaceError(e,n,r)}sessionCacheKey(e){return Hs(z(this.getState()),e)}statusForSession(e){if(e===void 0)return;let t=this.getState();return t.status?.sessionId===e.id&&t.selectedSession?.id===e.id?t.status:t.sessionStatuses[e.id]}sessionPersistenceOptions(){let e=this.getState();return Rd(e.machineRuntimes[z(e)])}workspaceSelectionKey(e){return`${z(this.getState())}:${e}`}replaceSession(e){let t=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(t=>t.id===e.id?e:t),selectedSession:t?.id===e.id?e:t})}createPendingSessionStart(e,t){let n=`pending-session-${String(++this.pendingSessionStartSeq)}-${Date.now().toString(36)}`,r=new Date().toISOString(),i={id:n,path:`pi-web://pending-session/${n}`,cwd:e.path,persisted:!1,name:`新会话`,created:r,modified:r,messageCount:0,firstMessage:``,clientPendingStart:!0,machineId:t};return{tempId:n,originWorkspace:e,workspaceId:e.id,cwd:e.path,machineId:t,session:i,queuedSends:[],discarded:!1}}insertAndSelectPendingSession(e){let t=this.getState();this.selectClientPendingStartSession(e,{activity:bf(e.id),sessions:[e,...t.sessions.filter(t=>t.id!==e.id)]})}selectClientPendingStartSession(e,t){this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)}),this.selectionSeq+=1,this.socket.close(),this.streamWatermark=void 0,this.clearPendingUpdates();let n=this.getState(),r=this.pendingSessionStarts.get(e.id),i=t?.activity??n.sessionActivities[e.id]??(r===void 0?void 0:bf(e.id,r.queuedSends.length));this.setState({...t?.sessions===void 0?{}:{sessions:t.sessions},selectedSession:e,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:i,pendingAsk:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0,...i===void 0?{}:{sessionActivities:{...n.sessionActivities,[e.id]:i}},error:``}),r?.backendSessionId!==void 0&&this.connectPendingStartSocket(r),t?.updateUrl!==!1&&this.updateUrl()}async resolvePendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.queuedSends.splice(0),i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId,t.id);if(n.discarded){Ul(Hs(n.machineId,e)),Jl(Hs(n.machineId,e)),this.setState({clientQueuedSessionMessages:mf(this.getState().clientQueuedSessionMessages,e)}),this.applyReleasedCreatedSessions(i,n.machineId),this.api.stop(t,n.machineId).catch(()=>{});return}Gc(t,n.machineId),Wl(Hs(n.machineId,e),Hs(n.machineId,t.id)),Yl(Hs(n.machineId,e),Hs(n.machineId,t.id));let a=Kc(t,n.machineId);if(!this.isCurrentPendingStart(n)){this.setState({clientQueuedSessionMessages:mf(this.getState().clientQueuedSessionMessages,e)}),await this.flushQueuedPendingSends(a,n.machineId,r);return}let o=this.getState(),s=o.selectedSession?.id===e;this.setState({sessions:_f(o.sessions,e,a),sessionActivities:pf(o.sessionActivities,e),sendingPrompts:gf(o.sendingPrompts,e,a.id),clientQueuedSessionMessages:gf(o.clientQueuedSessionMessages,e,a.id),...s?{selectedSession:a,status:o.sessionStatuses[a.id],activity:o.sessionActivities[a.id],pendingAsk:this.selectedPendingAsk(o.sessionStatuses[a.id]),pendingDialogs:o.sessionStatuses[a.id]?.pendingDialogs??[],closedDialogs:[]}:{},error:``}),this.applyReleasedCreatedSessions(i,n.machineId),s&&(this.updateUrl({replace:!0}),await this.selectSession(a,{updateUrl:!1})),await this.flushQueuedPendingSends(a,n.machineId,r)}failPendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.discarded;n.discarded=!0,this.getState().selectedSession?.id===e&&this.socket.close();let i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId),a=this.isCurrentPendingStart(n);if(r){a&&this.applyReleasedCreatedSessions(i,n.machineId);return}let o=Df(t),s=`启动会话失败:${o}`;if(!a){this.browserErrors.report(vs(n.machineId,n.originWorkspace.projectId,n.originWorkspace.id),s);return}let c=this.getState(),l=xf(e,o,n.queuedSends.length),u=c.sessions.some(t=>t.id===e);this.setState({sessions:u?c.sessions:[n.session,...c.sessions],sessionActivities:{...c.sessionActivities,[e]:l},activity:c.selectedSession?.id===e?l:c.activity,...c.selectedSession?.id===e?{pendingDialogs:[]}:{}}),this.reportSessionError(n.session,n.machineId,s),this.applyReleasedCreatedSessions(i,n.machineId)}isCurrentPendingStart(e){let t=this.getState();return z(t)===e.machineId&&t.selectedWorkspace?.id===e.workspaceId&&t.selectedWorkspace.projectId===e.originWorkspace.projectId}hasPendingStartFor(e,t){return Array.from(this.pendingSessionStarts.values()).some(n=>n.cwd===e&&n.machineId===t)}isSuppressedCreatedSession(e,t){let n=this.suppressedCreatedSessions.get(e.id);return n?.session.cwd===e.cwd&&n.machineId===t}takeSuppressedCreatedSessionsFor(e,t,n){if(n!==void 0&&this.suppressedCreatedSessions.delete(n),this.hasPendingStartFor(e,t))return[];let r=[];for(let[n,i]of this.suppressedCreatedSessions)i.session.cwd!==e||i.machineId!==t||(this.suppressedCreatedSessions.delete(n),r.push(i.session));return r}applyReleasedCreatedSessions(e,t){if(e.length===0||z(this.getState())!==t)return;let n=this.getState();if(n.selectedWorkspace===void 0)return;let r=new Set(n.sessions.map(e=>e.id)),i=e.filter(e=>e.cwd===n.selectedWorkspace?.path&&!r.has(e.id));i.length!==0&&this.setState({sessions:[...i.reverse(),...n.sessions]})}mergePendingStartSessions(e,t,n){let r=this.getState().sessions.filter(t=>vf(t)&&t.cwd===e&&t.machineId===n);if(r.length===0)return t;let i=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!i.has(e.id))]}async recreateCachedNewSession(e,t){let n=z(this.getState());try{let r=await this.api.startSession(e.cwd,n);Gc(r,n),Wl(this.sessionCacheKey(e.id),this.sessionCacheKey(r.id)),Yl(this.sessionCacheKey(e.id),this.sessionCacheKey(r.id)),qc(e.id,n);let i=Kc(r,n);this.setState({sessions:[i,...this.getState().sessions.filter(t=>t.id!==e.id)],error:``}),await this.selectSession(i,{updateUrl:!1}),this.updateUrl(t?.updateUrl===!1?{replace:!0}:void 0)}catch(t){this.reportSessionError(e,n,t)}}markCachedNewSessionPersisted(e){if(!Yc(e))return;let t=this.getState().sessions.find(t=>t.id===e.id)??e;this.replaceSession(Xc(t))}applyCommandResult(e){if(e.type===`select`){this.setState({commandDialog:e});return}if(e.type===`tree`){this.setState({treeDialog:e.tree});return}let t=(e.type,e.message);if(t!==void 0&&t!==``&&this.setState({messages:[...this.getState().messages,ol(e.type===`unsupported`?`system`:`tool`,t)]}),e.type===`done`&&e.session){e.promptDraft!==void 0&&Hl(this.sessionCacheKey(e.session.id),e.promptDraft);let t=this.getState().selectedSession,n=[e.session,...this.getState().sessions.filter(t=>t.id!==e.session?.id)];this.setState({sessions:n,selectedSession:t?.id===e.session.id?e.session:t}),t?.id!==e.session.id&&this.selectSession(e.session)}}applyCreatedSession(e){let t=this.getState();if(t.selectedWorkspace?.path!==e.cwd||t.sessions.some(t=>t.id===e.id))return;let n=z(t);if(this.hasPendingStartFor(e.cwd,n)){this.suppressedCreatedSessions.set(e.id,{session:e,machineId:n});return}this.setState({sessions:[e,...t.sessions]})}applyActivity(e){this.setState({sessionActivities:{...this.getState().sessionActivities,[e.sessionId]:e},activity:this.getState().selectedSession?.id===e.sessionId?e:this.getState().activity})}applyStatus(e){let t=this.getState(),n=t.selectedSession?.id===e.sessionId,r=t.sessionActivities[e.sessionId]?.phase===`active`&&!As(e);this.setState({sessionStatuses:{...t.sessionStatuses,[e.sessionId]:e},...Of(t,e.sessionId,e.messageCount),...r?{sessionActivities:pf(t.sessionActivities,e.sessionId)}:{},status:n?e:t.status,activity:n&&r?void 0:t.activity,...n?{pendingAsk:this.selectedPendingAsk(e)}:{},...n?{pendingDialogs:e.pendingDialogs??[]}:{}})}applyOpenedDialog(e){let t=this.getState();t.selectedSession===void 0||t.pendingDialogs.some(t=>t.dialogId===e.dialogId)||this.setState({pendingDialogs:[...t.pendingDialogs,e]})}applyClosedDialog(e,t,n){let r=this.getState().pendingDialogs.find(t=>t.dialogId===e);r!==void 0&&this.recordClosedDialog({dialog:r,reason:t,...n===void 0?{}:{answer:n}})}recordClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e.dialog.dialogId)||this.setState({pendingDialogs:t.pendingDialogs.filter(t=>t.dialogId!==e.dialog.dialogId),closedDialogs:[...t.closedDialogs,e]})}dismissClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e)&&this.setState({closedDialogs:t.closedDialogs.filter(t=>t.dialog.dialogId!==e)})}applyOpenedAsk(e){this.getState().selectedSession!==void 0&&this.setState({pendingAsk:this.selectedPendingAsk({pendingAsk:e})})}applyClosedAsk(e){this.getState().pendingAsk?.askId===e&&this.setState({pendingAsk:void 0})}selectedPendingAsk(e){if(e?.pendingAsk!==void 0)return e.pendingAsk}applySessionName(e,t){let n=n=>{if(n.id!==e)return n;let r={...n};return t===void 0||t===``?delete r.name:r.name=t,r},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(n),selectedSession:r===void 0?void 0:n(r)})}applyEvent(e){if(e.type===`notifications.inbox`){this.notifications?.applyInboxEvent(z(this.getState()),e);return}if(e.type===`command.output`&&this.notifications?.shouldFilterLegacyNotification(z(this.getState()),e.notificationId)===!0||this.isStreamEventBelowWatermark(e))return;if(e.type===`status.update`){this.queueStatusUpdate(e.status);return}if(e.type===`activity.update`){this.queueActivityUpdate(e.activity);return}if(kf(e)){this.queueTranscriptEvent(e);return}if(this.flushPendingUpdates(),e.type===`ask.opened`){this.applyOpenedAsk(e.ask);return}if(e.type===`ask.closed`){this.applyClosedAsk(e.askId);return}if(e.type===`dialog.opened`){this.applyOpenedDialog(e.dialog);return}if(e.type===`dialog.closed`){this.applyClosedDialog(e.dialogId,e.reason,e.answer);return}let t=this.transcripts.applyLiveEvent(this.getState().messages,e);t?this.setState({messages:t}):e.type===`session.name`&&this.applySessionName(e.sessionId,e.name)}queueTranscriptEvent(e){this.pendingTranscriptEvents.push(e),this.schedulePendingFlush()}queueStatusUpdate(e){this.pendingStatusBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueActivityUpdate(e){this.pendingActivityBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueStartupProgress(e){if(this.getState().sessions.some(t=>t.id===e.activity.sessionId)){this.queueActivityUpdate(e.activity);return}let t=e.startupToken===void 0?void 0:this.pendingSessionStarts.get(e.startupToken);t===void 0||t.discarded||(this.learnPendingStartBackendSession(t,e.activity.sessionId),this.queueActivityUpdate(e.activity.phase===`idle`?bf(t.tempId,t.queuedSends.length):yf(e.activity,t.tempId)))}learnPendingStartBackendSession(e,t){t===``||e.backendSessionId!==void 0||(e.backendSessionId=t,this.getState().selectedSession?.id===e.tempId&&this.connectPendingStartSocket(e))}connectPendingStartSocket(e){let t=e.backendSessionId;if(t===void 0||e.discarded)return;let n={id:t,cwd:e.cwd};this.socket.connect(n,t=>{this.applyPendingStartEvent(e,t)},()=>{this.resyncPendingStartDialogs(e)},e.machineId),this.resyncPendingStartDialogs(e)}resyncPendingStartDialogs(e){let t=e.backendSessionId;t!==void 0&&this.api.status({id:t,cwd:e.cwd},e.machineId).then(t=>{if(e.discarded||this.getState().selectedSession?.id!==e.tempId)return;let n=this.getState(),r=new Set([...n.pendingDialogs.map(e=>e.dialogId),...n.closedDialogs.map(e=>e.dialog.dialogId)]),i=(t.pendingDialogs??[]).filter(e=>!r.has(e.dialogId));this.setState({sessionStatuses:{...n.sessionStatuses,[t.sessionId]:t},...i.length===0?{}:{pendingDialogs:[...n.pendingDialogs,...i]}})},()=>void 0)}applyPendingStartEvent(e,t){if(!(e.discarded||this.getState().selectedSession?.id!==e.tempId)){if(t.type===`dialog.opened`){this.applyOpenedDialog(t.dialog);return}if(t.type===`dialog.closed`){this.applyClosedDialog(t.dialogId,t.reason,t.answer);return}t.type===`status.update`&&this.applyPendingStartStatus(e,t.status)}}applyPendingStartStatus(e,t){if(e.discarded||this.getState().selectedSession?.id!==e.tempId)return;let n=this.getState();this.setState({sessionStatuses:{...n.sessionStatuses,[t.sessionId]:t},pendingDialogs:t.pendingDialogs??[]})}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){if(this.pendingTranscriptEvents.length>0){let e=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let t=this.getState().messages;for(let n of e)t=this.transcripts.applyLiveEvent(t,n)??t;t!==this.getState().messages&&this.setState({messages:t})}if(this.pendingActivityBySession.size>0){let e=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(let t of e)this.applyActivity(t)}if(this.pendingStatusBySession.size>0){let e=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(let t of e)this.applyStatus(t)}}clearPendingUpdates(){this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=void 0)}isStreamEventBelowWatermark(e){let t=this.streamWatermark;return t===void 0||t.sessionId!==this.getState().selectedSession?.id?!1:e.seq!==void 0&&e.seq<=t.seq}async selectSearchMatch(e,t,n){await this.selectSession(e);let r=z(this.getState()),i=this.selectionSeq;try{for(;this.isCurrentSearchJump(e.id,r,i)&&this.getState().messagePageStart>t.messageIndex;){let t=this.getState().messagePageStart,n=await this.api.messages(e,{before:t,limit:lf},r);if(!this.isCurrentSearchJump(e.id,r,i))return;let a=this.transcripts.mergeHistory(this.sessionCacheKey(e.id),n);if(this.setState(a),a.messagePageStart>=t)break}}catch(t){this.reportSessionError(e,r,t);return}this.isCurrentSearchJump(e.id,r,i)&&this.setState({...this.transcripts.indexedView(this.sessionCacheKey(e.id)),sessionSearchTarget:{sessionId:e.id,messageIndex:t.messageIndex,query:n,requestId:++this.searchTargetSeq}})}isCurrentSearchJump(e,t,n){return this.selectionSeq===n&&z(this.getState())===t&&this.getState().selectedSession?.id===e}};function ff(e){return JSON.stringify(e.partial??null)}function pf(e,t){return mf(e,t)}function mf(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function hf(e,t){if(t.length===0)return e;let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function gf(e,t,n){if(t===n||!(t in e))return e;let r=e[t];return r===void 0?e:{...mf(e,t),[n]:r}}function _f(e,t,n){let r=[],i=!1;for(let a of e){if(a.id===t){i||=(r.push(n),!0);continue}a.id!==n.id&&r.push(a)}return i?r:[n,...r]}function vf(e){return e!==void 0&&`clientPendingStart`in e&&e.clientPendingStart===!0}function yf(e,t){return{sessionId:t,phase:e.phase,label:e.label,...e.detail===void 0?{}:{detail:e.detail},at:e.at}}function bf(e,t=0){return{sessionId:e,phase:`active`,label:`正在创建会话`,detail:t>0?`后端会话准备好后将发送 ${String(t)} 条排队消息`:`正在等待后端会话准备就绪`,at:new Date().toISOString()}}function xf(e,t,n=0){return{sessionId:e,phase:`error`,label:`会话创建失败`,detail:`${t}${n>0?` · 下方保留了 ${String(n)} 条排队消息`:``}`,at:new Date().toISOString()}}function Sf(e){return e.type===`prompt`?{kind:e.streamingBehavior===`steer`?`steer`:`followUp`,text:Cf(e.text,e.attachments)}:{kind:`followUp`,text:e.text}}function Cf(e,t){let n=wf(t);return n===void 0?e:e.trim()===``?n:`${e}\n\n${n}`}function wf(e){if(e===void 0||e.length===0)return;let t=e.map(e=>e.name?.trim()).filter(e=>e!==void 0&&e!==``),n=e.length,r=`${String(n)} 个附件`;return t.length===0?`[已排队 ${r}]`:`[已排队 ${r}:${t.slice(0,3).join(`、`)}${t.length>3?`,另有 ${String(t.length-3)} 个`:``}]`}function Tf(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function Ef(e){return e.map(e=>`${e.sessionId}: ${e.error}`)}function Df(e){return e instanceof Error?e.message:String(e)}function Of(e,t,n){if(n===void 0)return{};let r=e.sessions.some(e=>e.id===t&&e.messageCount!==n)?e.sessions.map(e=>e.id===t?{...e,messageCount:n}:e):void 0,i=e.selectedSession?.id===t&&e.selectedSession.messageCount!==n?{...e.selectedSession,messageCount:n}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...i===e.selectedSession?{}:{selectedSession:i}}}function kf(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`||e.type===`shell.chunk`}function Af(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`session not found`)||t.includes(`未找到会话`)}var jf={order:0,overflowWatermark:0};function Mf(e){return{...e,status:`loading`,catalogRevision:0,notifications:[],dismissThrough:jf,optimisticDismissedIds:[],announcements:[]}}function Nf(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)throw Error(`Notification inbox snapshot does not match the selected session`);let r=e!==void 0&&qf(e,t)&&e.daemonInstanceId===n.daemonInstanceId;return{...t,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:n.notifications,dismissThrough:n.dismissThrough,optimisticDismissedIds:r?e.optimisticDismissedIds:[],...r&&e.optimisticDismissAllThrough!==void 0?{optimisticDismissAllThrough:e.optimisticDismissAllThrough}:{},announcements:r?e.announcements:[]}}function Pf(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)return{value:e??Mf(t),needsRefresh:!1,changed:!1};if(e===void 0||!qf(e,t))return{value:Yf(t),needsRefresh:!0,changed:!0};if(e.daemonInstanceId!==n.daemonInstanceId)return{value:Yf(t),needsRefresh:!0,changed:e.status!==`stale`||e.daemonInstanceId!==void 0||e.notifications.length>0};let r=e.summary?.inboxRevision??0;if(n.summary.inboxRevision<=r)return{value:e,needsRefresh:!1,changed:!1};if(e.status!==`fresh`||n.summary.inboxRevision!==r+1||n.delta.kind===`resync`)return{value:{...e,status:`stale`},needsRefresh:!0,changed:e.status!==`stale`};let i,a;switch(n.delta.kind){case`added`:{let t=n.delta;if(e.notifications.some(e=>e.id===t.notification.id))return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};i=[t.notification,...e.notifications].filter(e=>e.id!==t.evictedNotificationId).sort((e,t)=>t.order-e.order).slice(0,100),a={id:`${n.daemonInstanceId}:${String(n.summary.inboxRevision)}:${t.notification.id}`,severity:t.notification.severity,message:t.notification.message};break}case`dismissed`:{let t=new Set(n.delta.notificationIds);i=e.notifications.filter(e=>!t.has(e.id));break}case`cleared`:i=[];break}let o=i[0]?.order??0;if(!Xf(i,n.summary)||n.dismissThrough.order!==o||n.dismissThrough.overflowWatermark<n.summary.discardedCount)return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};let s=a===void 0?e.announcements:[...e.announcements,a].slice(-100);return{value:{...e,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:i,dismissThrough:n.dismissThrough,announcements:s},needsRefresh:!1,changed:!0}}function Ff(e){if(e?.status!==`fresh`||e.daemonInstanceId===void 0||e.summary===void 0)return;let t=new Set(e.optimisticDismissedIds),n=e.optimisticDismissAllThrough,r=e.notifications.filter(e=>!t.has(e.id)&&(n===void 0||e.order>n.order)),i=Qf(e.summary.discardedCount,e.dismissThrough.overflowWatermark,n?.overflowWatermark);return r.length===0&&t.size>0&&(i=0),{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd,daemonInstanceId:e.daemonInstanceId,notifications:r,retainedCount:r.length,discardedCount:i,...$f(Zf(r)),dismissThrough:e.dismissThrough,pendingDismissedIds:t,dismissAllPending:n!==void 0,announcements:e.announcements}}function If(e){return e===`error`?`错误`:e===`warning`?`警告`:`信息`}function Lf(e){return`收到${If(e.severity)}通知。`}function Rf(e){return e.retainedCount+e.discardedCount}function zf(e){return`通知(${String(Rf(e))})`}function Bf(e){let t=e.message.replace(/\s+/gu,` `).trim();if(t===``)return`关闭${If(e.severity)}通知`;let n=Array.from(t);return`关闭通知:${n.length<=80?t:`${n.slice(0,79).join(``).trimEnd()}…`}`}function Vf(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1)return{kind:`header`};let r=e[n+1];if(r!==void 0)return{kind:`notification`,notificationId:r.id};let i=e[n-1];return i===void 0?{kind:`header`}:{kind:`notification`,notificationId:i.id}}function Hf(e){return JSON.stringify([e.machineId,e.cwd,e.sessionId])}function Uf(e,t){return e.has(Hf(t))}function Wf(e,t,n){let r=new Set(e),i=Hf(t);return n?r.add(i):r.delete(i),r}function Gf(e){return`还有 ${String(e)} 条较早通知未显示。`}function Kf(e){if(!e.truncated)return;let t=Bt/1024;return`消息已在 ${String(t)} KiB 处截断。`}function qf(e,t){return e.machineId===t.machineId&&e.sessionId===t.sessionId&&e.cwd===t.cwd}function Jf(e,t){if(e===`error`||t===`error`)return`error`;if(e===`warning`||t===`warning`)return`warning`;if(e===`info`||t===`info`)return`info`}function Yf(e){return{...Mf(e),status:`stale`}}function Xf(e,t){return e.length===t.retainedCount&&Zf(e)===t.highestSeverity}function Zf(e){let t;for(let n of e)t=Jf(t,n.severity);return t}function Qf(e,t,n){if(e===0||n===void 0)return e;let r=t-e+1;return e-Math.max(0,Math.min(e,n-r+1))}function $f(e){return e===void 0?{}:{highestSeverity:e}}var ep=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.acceptedSupportByMachine=new Set,this.selectedGeneration=0,this.dismissingNotificationIds=new Set,this.dismissAllPending=!1,this.disposed=!1,this.api=n.api??L,this.onBackgroundError=n.onBackgroundError??((e,t)=>{console.warn(e,t)})}dispose(){this.disposed=!0,this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.acceptedSupportByMachine.clear(),this.dismissingNotificationIds.clear(),this.dismissAllPending=!1}prepareSelectedSession(e,t){if(this.selectedGeneration+=1,this.selectedTarget=e.archived===!0?void 0:{machineId:t,sessionId:e.id,cwd:e.cwd},this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.selectedTarget===void 0||!this.machineSupportsNotifications(t)){this.setState({selectedNotificationInbox:void 0});return}this.setState({selectedNotificationInbox:Mf(this.selectedTarget)})}clearSelectedSession(){this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.setState({selectedNotificationInbox:void 0})}refreshSelectedSession(e,t){let n=this.selectedTarget;if(this.disposed||n?.machineId!==t||n.sessionId!==e.id||n.cwd!==e.cwd||!this.machineSupportsNotifications(t)||!this.machineIsReachable(t))return Promise.resolve();let r=this.selectedGeneration,i=this.selectedRefresh;if(i?.generation===r)return i.trailing=!0,i.promise;this.ensureSelectedProjection(n);let a={generation:r,promise:Promise.resolve(),trailing:!1};return a.promise=this.runSelectedRefresh(a,n).finally(()=>{this.selectedRefresh===a&&(this.selectedRefresh=void 0)}),this.selectedRefresh=a,a.promise}applyInboxEvent(e,t){let n=this.selectedTarget;if(n?.machineId!==e||n.sessionId!==t.summary.sessionId||n.cwd!==t.summary.cwd)return;this.acceptedSupportByMachine.add(e);let r=this.selectedJoin;if(r?.generation===this.selectedGeneration){r.events.push(t);return}let i=Pf(this.getState().selectedNotificationInbox,n,t);i.changed&&this.setState({selectedNotificationInbox:i.value}),i.needsRefresh&&this.scheduleSelectedRefresh(n)}syncEnvironment(e,t){if(this.disposed)return;e.machines!==t.machines&&this.pruneRemovedMachines(t.machines);let n=e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||e.machineRuntimes!==t.machineRuntimes,r=this.selectedTarget;if(!n||r===void 0)return;let i=this.machineSupportsNotificationsInState(e,r.machineId)&&this.machineIsReachableInState(e,r.machineId);if(!this.machineSupportsNotifications(r.machineId)||!this.machineIsReachable(r.machineId)){this.markSelectedStale(r);return}this.ensureSelectedProjection(r),(!i||this.getState().selectedNotificationInbox?.status!==`fresh`)&&this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId)}shouldFilterLegacyNotification(e,t){return t!==void 0&&t!==``&&this.machineSupportsNotifications(e)}async dismissNotification(e){let t=this.getState().selectedNotificationInbox,n=Ff(t);if(t===void 0||n===void 0||this.dismissAllPending||this.dismissingNotificationIds.has(e)||!n.notifications.some(t=>t.id===e))return;let r=tp(t),i=this.selectedGeneration;this.dismissingNotificationIds.add(e),this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:[...new Set([...t.optimisticDismissedIds,e])]}));try{let t=await this.api.dismissNotification({id:r.sessionId,cwd:r.cwd},n.daemonInstanceId,e,r.machineId);this.isCurrentTarget(r,i)&&this.applyMutationSnapshot(r,t,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)}))}catch(t){this.isCurrentTarget(r,i)&&(this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)})),this.setState({error:`关闭通知失败:${rp(t)}`}),await this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId))}finally{this.dismissingNotificationIds.delete(e)}}async dismissAll(){let e=this.getState().selectedNotificationInbox,t=Ff(e);if(e===void 0||t===void 0||this.dismissAllPending||t.retainedCount+t.discardedCount===0)return;let n=tp(e),r=this.selectedGeneration,i={...e.dismissThrough};this.dismissAllPending=!0,this.patchSelectedOverlay(n,e=>({...e,optimisticDismissAllThrough:i}));try{let e=await this.api.dismissAllNotifications({id:n.sessionId,cwd:n.cwd},t.daemonInstanceId,i,n.machineId);this.isCurrentTarget(n,r)&&this.applyMutationSnapshot(n,e,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t})}catch(e){this.isCurrentTarget(n,r)&&(this.patchSelectedOverlay(n,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t}),this.setState({error:`关闭会话通知失败:${rp(e)}`}),await this.refreshSelectedSession({id:n.sessionId,cwd:n.cwd},n.machineId))}finally{r===this.selectedGeneration&&(this.dismissAllPending=!1)}}async runSelectedRefresh(e,t){do{e.trailing=!1;let n={generation:e.generation,events:[]};this.selectedJoin=n;try{let r=await this.api.notificationInbox({id:t.sessionId,cwd:t.cwd},t.machineId);if(!this.isCurrentTarget(t,e.generation))return;if(!this.machineSupportsNotifications(t.machineId)||!this.machineIsReachable(t.machineId)){this.markSelectedStale(t);return}this.acceptedSupportByMachine.add(t.machineId);let i=this.getState().selectedNotificationInbox,a=i===void 0||np(i,t,r)?Nf(i,t,r):i;for(let r of[...n.events].sort((e,t)=>e.summary.inboxRevision-t.summary.inboxRevision)){let n=Pf(a,t,r);a=n.value,n.needsRefresh&&(e.trailing=!0)}this.setState({selectedNotificationInbox:a})}catch(n){if(this.isCurrentTarget(t,e.generation)){let e=this.getState().selectedNotificationInbox;e!==void 0&&qf(e,t)&&e.status!==`stale`&&this.setState({selectedNotificationInbox:{...e,status:`stale`}}),this.onBackgroundError(`Failed to refresh notifications for session ${t.sessionId}`,n)}return}finally{this.selectedJoin===n&&(this.selectedJoin=void 0)}}while(e.trailing&&this.isCurrentTarget(t,e.generation)&&this.machineIsReachable(t.machineId))}applyMutationSnapshot(e,t,n){let r=this.getState().selectedNotificationInbox;if(r===void 0||!qf(r,e))return;if(!this.machineSupportsNotifications(e.machineId)||!this.machineIsReachable(e.machineId)){this.setState({selectedNotificationInbox:{...n(r),status:`stale`}});return}let i=np(r,e,t)?Nf(r,e,t):r;this.setState({selectedNotificationInbox:n(i)})}patchSelectedOverlay(e,t){let n=this.getState().selectedNotificationInbox;n===void 0||!qf(n,e)||this.setState({selectedNotificationInbox:t(n)})}ensureSelectedProjection(e){let t=this.getState().selectedNotificationInbox;(t===void 0||!qf(t,e))&&this.setState({selectedNotificationInbox:Mf(e)})}scheduleSelectedRefresh(e){queueMicrotask(()=>{!this.disposed&&this.selectedTarget!==void 0&&qf(this.selectedTarget,e)&&this.refreshSelectedSession({id:e.sessionId,cwd:e.cwd},e.machineId)})}markSelectedStale(e){let t=this.getState().selectedNotificationInbox;t===void 0||!qf(t,e)||t.status===`stale`||this.setState({selectedNotificationInbox:{...t,status:`stale`}})}pruneRemovedMachines(e){let t=new Set(e.map(e=>e.id));t.size===0&&t.add(`local`);for(let e of[...this.acceptedSupportByMachine])t.has(e)||this.acceptedSupportByMachine.delete(e)}isCurrentTarget(e,t){return!this.disposed&&t===this.selectedGeneration&&this.selectedTarget!==void 0&&qf(this.selectedTarget,e)}machineSupportsNotifications(e){return this.machineSupportsNotificationsInState(this.getState(),e)}machineSupportsNotificationsInState(e,t){return this.acceptedSupportByMachine.has(t)||e.machineRuntimes[t]?.ok===!0}machineIsReachable(e){return this.machineIsReachableInState(this.getState(),e)}machineIsReachableInState(e,t){let n=e.machines.find(e=>e.id===t);if(t===`local`||n?.kind===`local`)return!0;let r=e.machineStatuses[t]?.status??n?.status;return r===void 0||r===`unknown`||r===`online`}};function tp(e){return{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd}}function np(e,t,n){return!qf(e,t)||e.daemonInstanceId!==n.daemonInstanceId||e.summary===void 0||n.summary.inboxRevision>=e.summary.inboxRevision}function rp(e){return e instanceof Error?e.message:String(e)}var ip=class{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}},ap=`pi-web:workspace-selection:v1`,op=class{constructor(e=Hd()){this.workspaceIdsByProject=new Ud(ap,Wd,e)}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}};function sp(e,t){let n=t?.targetWorkspaceId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestWorkspaceId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e[0]:e[0]}var cp=class{constructor(e,t,n,r,i=new ip,a={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessions=r,this.workspaceSelection=i,this.topologyRefreshes=new Us,this.api=a.api??L,this.onBackgroundError=a.onBackgroundError??((e,t)=>{console.warn(e,t)}),this.browserErrors=new Es(e,t)}clearSelection(e){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...hs()}),e?.updateUrl!==!1&&this.updateUrl()}forgetProject(e){let t=z(this.getState());this.browserErrors.discard(_s(t,e)),this.workspaceSelection.forgetProject(Vs(t,e));let n=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([t])=>t!==e));this.setState({workspacesByProjectId:n})}async selectProject(e,t){let n=z(this.getState()),r=_s(n,e.id);this.sessions.clearActiveSession(),this.setState({selectedProject:e,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...hs()});try{let r=await this.api.workspaces(e.id,n);if(z(this.getState())!==n||this.getState().selectedProject?.id!==e.id)return;this.setState({workspaces:r,workspacesByProjectId:{...this.getState().workspacesByProjectId,[e.id]:r},isLoadingWorkspaces:!1});let i=sp(r,{targetWorkspaceId:t?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(Vs(n,e.id))});i?await this.selectWorkspace(i,{sessionId:t?.sessionId,updateUrl:t?.updateUrl}):t?.updateUrl!==!1&&this.updateUrl()}catch(t){z(this.getState())===n&&this.getState().selectedProject?.id===e.id&&this.setState({isLoadingWorkspaces:!1}),this.browserErrors.report(r,String(t))}}async selectWorkspace(e,t){let n=z(this.getState()),r=vs(n,e.projectId,e.id);this.workspaceSelection.rememberWorkspace({...e,projectId:Vs(n,e.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:e,isLoadingWorkspaces:!1,...hs()});try{let r=Jc(e.path,await this.api.sessions(e.path,n),n);if(z(this.getState())!==n||this.getState().selectedWorkspace?.id!==e.id||this.getState().selectedProject?.id!==e.projectId)return;this.setState({sessions:r});let i=this.sessions.preferredSession(e.path,r,t?.sessionId);i?await this.sessions.selectSession(i,{updateUrl:t?.updateUrl}):t?.updateUrl!==!1&&this.updateUrl()}catch(e){this.browserErrors.report(r,String(e))}}async refreshProjectWorkspaces(e){let t=this.getState().projects.find(t=>t.id===e);if(t===void 0)throw Error(`找不到项目`);let n=await this.api.workspaces(t.id,z(this.getState()));return this.applyProjectWorkspaces(t.id,n),n}async refreshSelectedProjectTopology(){let e=this.getState(),t=e.selectedProject;if(t===void 0)return;let n=z(e);await this.topologyRefreshes.request(Vs(n,t.id),async()=>{try{let e=await this.api.workspaces(t.id,n),r=this.getState();if(z(r)!==n||r.selectedProject?.id!==t.id)return;this.applyProjectWorkspaces(t.id,e)}catch(e){this.onBackgroundError(`Failed to refresh workspaces for project ${t.id} on ${n}`,e)}})}async refreshAfterWorkspaceDeleted(e,t){let n=await this.refreshProjectWorkspaces(e),r=this.getState();if(r.selectedProject?.id!==e||r.selectedWorkspace?.id!==t)return;let i=lp(n);i===void 0?this.clearSelection():await this.selectWorkspace(i)}applyProjectWorkspaces(e,t){let n=this.getState(),r={...n.workspacesByProjectId,[e]:t};if(n.selectedProject?.id!==e){this.setState({workspacesByProjectId:r});return}this.setState({workspaces:t,workspacesByProjectId:r,...this.refreshedSelection(n.selectedWorkspace,t)})}refreshedSelection(e,t){if(e===void 0)return;let n=t.find(t=>t.id===e.id);if(!(n===void 0||up(e,n)))return{selectedWorkspace:n}}};function lp(e){return e.find(e=>e.isMain)??e[0]}function up(e,t){return e.path===t.path&&e.label===t.label&&e.branch===t.branch&&e.isMain===t.isMain&&e.isGitRepo===t.isGitRepo&&e.isGitWorktree===t.isGitWorktree}var dp=`pi-web:machine-navigation:v1`,fp=class{constructor(e=Hd()){this.snapshotsByMachine=new Ud(dp,_p,e)}latest(e){let t=this.snapshotsByMachine.get(e);return t?.machineId===e?gp(t):void 0}remember(e){this.snapshotsByMachine.set(e.machineId,gp(e))}forget(e){this.snapshotsByMachine.delete(e)}};function pp(e){return{machineId:e,surface:{}}}function mp(e){let t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??`local`,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id,tool:e.workspaceTool,view:e.mainView,surface:{selectedFilePath:t?e.selectedFilePath:void 0,selectedDiffPath:t?e.selectedDiffPath:void 0,selectedTerminalId:t?e.selectedTerminalId:void 0}}}function hp(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view===`navigation`?void 0:e.view}}function gp(e){return{...e,surface:{...e.surface}}}function _p(e){if(!Cp(e))return;let t=Sp(e,`machineId`);if(t===void 0)return;let n=bp(Sp(e,`tool`)),r=yp(Sp(e,`view`));return{machineId:t,projectId:Sp(e,`projectId`),workspaceId:Sp(e,`workspaceId`),sessionId:Sp(e,`sessionId`),...n===void 0?{}:{tool:n},...r===void 0?{}:{view:r},surface:vp(e.surface)}}function vp(e){return Cp(e)?{selectedFilePath:Sp(e,`selectedFilePath`),selectedDiffPath:Sp(e,`selectedDiffPath`),selectedTerminalId:Sp(e,`selectedTerminalId`)}:{}}function yp(e){return e===`navigation`||e===`chat`?e:bp(e)}function bp(e){return xp(e)?e:void 0}function xp(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Sp(e,t){let n=e[t];return typeof n==`string`&&n!==``?n:void 0}function Cp(e){return typeof e==`object`&&!!e}var wp=`pi-web:terminal-selection:v1`,Tp=class{constructor(e=Hd()){this.terminalIdsByCwd=new Ud(wp,Wd,e)}latestTerminalId(e){return this.terminalIdsByCwd.get(e)}rememberTerminal(e,t){this.terminalIdsByCwd.set(e,t)}forgetWorkspace(e){this.terminalIdsByCwd.delete(e)}forgetTerminal(e){for(let[t,n]of this.terminalIdsByCwd.entries())n===e&&this.terminalIdsByCwd.delete(t)}};function Ep(e,t){let n=t?.targetTerminalId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestTerminalId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>!e.exited)??e[0]:e.find(e=>!e.exited)??e[0]}function Dp(e){return e.find(e=>!e.exited)??e[0]}var Op=1200,kp=[`mod`,`alt`,`shift`],Ap=class{constructor(){this.pendingTokens=[]}handle(e,t,n={}){let r=Fp(e);if(r===void 0)return!1;let i=jp(t,n.shortcuts,{enabledOnly:!0}).filter(e=>e.active).map(e=>({action:e.action,tokens:e.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,r],i))return!0;if(this.clearPending(),!Ip(r))return!1}else if(!Ip(r))return!1;return this.handleSequence([r],i)}reset(){this.clearPending()}handleSequence(e,t){let n=t.find(t=>$p(t.tokens,e));return n===void 0?t.some(t=>em(t.tokens,e))?(this.setPending(e),!0):!1:(this.clearPending(),n.action.run(),!0)}setPending(e){this.clearPending(),this.pendingTokens=e,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},Op)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}};function jp(e,t,n={}){let r=e.flatMap((e,r)=>{if(n.enabledOnly===!0&&e.enabled===!1)return[];let i=Lp(e,t,r);return i===void 0?[]:[i]}),i=new Map;for(let e of r)i.set(e.key,[...i.get(e.key)??[],e]);let a=new Map;for(let e of i.values()){let t=[...e].sort(Vp)[0];t!==void 0&&a.set(t.key,t)}let o=[...a.values()].sort(Hp),s=new Map,c=new Map;for(let e of r){let t=a.get(e.key);if(t===void 0)continue;let n=Up(t,o)??t;c.set(e,n),e!==n&&s.set(n,[...s.get(n)??[],e])}return r.map(e=>{let t=c.get(e),n=t===e,r=t===void 0||n?void 0:Bp(t),i=n?[...s.get(e)??[]].sort(Vp).map(Bp):[];return{...e,active:n,shadows:i,...r===void 0?{}:{shadowedBy:r}}}).sort((e,t)=>e.order-t.order)}function Mp(e){return Kp(e,{requireFirstChordActivator:!0})}function Np(e){let t=Kp(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function Pp(e){return Np(e).map(e=>e.split(`+`).map(Qp).join(`+`)).join(` `)}function Fp(e){if(e.isComposing)return;let t=Xp(e.key);if(t===void 0)return;let n=[];return(e.metaKey||e.ctrlKey)&&n.push(`mod`),e.altKey&&n.push(`alt`),e.shiftKey&&n.push(`shift`),n.push(t),n.join(`+`)}function Ip(e){return e.split(`+`).includes(`mod`)||e.split(`+`).includes(`alt`)}function Lp(e,t,n){let r=Rp(e.id,t);if(r===null)return;let i=r??e.shortcut;if(i===void 0||i===``)return;let a=Np(i),o=a[0];if(!(o===void 0||!Ip(o)))return{action:e,shortcut:a.join(` `),source:r===void 0?`default`:`custom`,tokens:a,key:zp(a),order:n}}function Rp(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function zp(e){return e.join(`\0`)}function Bp(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function Vp(e,t){return Wp(e.source)-Wp(t.source)||Gp(e.action.id,t.action.id)||Gp(e.action.title,t.action.title)||e.order-t.order}function Hp(e,t){return e.tokens.length-t.tokens.length||Vp(e,t)}function Up(e,t){return t.find(t=>t!==e&&t.tokens.length<e.tokens.length&&em(e.tokens,t.tokens))}function Wp(e){switch(e){case`custom`:return 0;case`default`:return 1}}function Gp(e,t){return e<t?-1:+(e>t)}function Kp(e,t){let n=e.trim().toLowerCase().replace(/\s*\+\s*/gu,`+`);if(n===``)return{ok:!1,message:`请输入快捷键,选择无,或重置为默认值。`};let r=[],i=n.split(/\s+/u).filter(e=>e!==``);for(let[e,n]of i.entries()){let i=qp(n);if(!i.ok)return i;if(e===0&&t.requireFirstChordActivator&&!Ip(i.token))return{ok:!1,message:`快捷键必须以 Ctrl/⌘ 或 Alt 开头,避免拦截普通输入。`};r.push(i.token)}return{ok:!0,shortcut:r.join(` `),tokens:r}}function qp(e){let t=e.split(`+`).filter(e=>e!==``);if(t.length===0)return{ok:!1,message:`快捷键组合必须包含一个按键。`};let n=new Set,r;for(let e of t){let t=Jp(e);if(t!==void 0){if(n.has(t))return{ok:!1,message:`快捷键包含重复的 ${Qp(t)} 修饰键。`};n.add(t);continue}let i=Yp(e);if(i===void 0)return{ok:!1,message:`不支持的快捷键按键:${e}`};if(r!==void 0)return{ok:!1,message:`每个快捷键组合只能包含一个非修饰键。`};r=i}return r===void 0?{ok:!1,message:`快捷键组合必须包含一个按键。`}:{ok:!0,token:[...kp.filter(e=>n.has(e)),r].join(`+`)}}function Jp(e){switch(e){case`mod`:case`meta`:case`cmd`:case`command`:case`ctrl`:case`control`:case`primary`:return`mod`;case`alt`:case`option`:case`opt`:return`alt`;case`shift`:return`shift`;default:return}}function Yp(e){let t=Zp(e);if(t!==void 0)return t;if(/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1)return e}function Xp(e){return e===` `?`space`:Yp(e.toLowerCase())}function Zp(e){switch(e){case` `:case`spacebar`:case`space`:return`space`;case`esc`:case`escape`:return`escape`;case`return`:case`enter`:return`enter`;case`del`:case`delete`:return`delete`;case`backspace`:return`backspace`;case`tab`:return`tab`;case`up`:case`arrowup`:return`arrowup`;case`down`:case`arrowdown`:return`arrowdown`;case`left`:case`arrowleft`:return`arrowleft`;case`right`:case`arrowright`:return`arrowright`;case`pageup`:case`pagedown`:case`home`:case`end`:return e;case`+`:case`plus`:return`plus`;case`period`:case`dot`:return`.`;case`comma`:return`,`;case`slash`:return`/`;case`backslash`:return`\\`;case`minus`:return`-`;default:return}}function Qp(e){return e===`mod`?tm()?`⌘`:`Ctrl`:e===`shift`?`Shift`:e===`alt`?tm()?`⌥`:`Alt`:e===`enter`?`Enter`:e===`escape`?`Esc`:e===`space`?`Space`:e===`tab`?`Tab`:e===`backspace`?`Backspace`:e===`delete`?`Delete`:e===`arrowup`?`↑`:e===`arrowdown`?`↓`:e===`arrowleft`?`←`:e===`arrowright`?`→`:e===`pageup`?`PageUp`:e===`pagedown`?`PageDown`:e===`home`?`Home`:e===`end`?`End`:e===`plus`?`+`:/^f(?:[1-9]|1[0-9]|2[0-4])$/u.test(e)||e.length===1?e.toUpperCase():`${e.charAt(0).toUpperCase()}${e.slice(1)}`}function $p(e,t){return e.length===t.length&&em(e,t)}function em(e,t){return t.every((t,n)=>e[n]===t)}function tm(){return typeof navigator<`u`&&navigator.userAgent.toLowerCase().includes(`mac`)}var nm={archiveIdleEnabled:!0,archiveIdleDays:`30`,deleteArchivedEnabled:!1,deleteArchivedDays:`90`};function rm(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:`请至少启用一项清理操作。`};let t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){let n=pm(e.archiveIdleDays,`归档空闲会话天数`);if(typeof n==`string`)return{ok:!1,error:n};t.archiveIdleDays=n}if(e.deleteArchivedEnabled){let n=pm(e.deleteArchivedDays,`删除已归档会话天数`);if(typeof n==`string`)return{ok:!1,error:n};t.deleteArchivedDays=n}return{ok:!0,request:t}}function im(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null,projectId:e?.projectId??null})}function am(e){return!e.canCleanup||e.loading===!0||e.running===!0||e.preview===void 0||!om(e.draft,e.preview)?!1:sm(e.preview)}function om(e,t){let n=rm(e);return n.ok?mm(n.request)===mm(t.thresholds):!1}function sm(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function cm(e,t){let n=e.projects.map(e=>e.cwd);if(t===void 0)return n;let r=new Set(t);return n.filter(e=>r.has(e))}function lm(e,t){let n=new Set(cm(e,t)),r=e.projects.filter(e=>n.has(e.cwd));return{...e,projects:r,totals:r.reduce((e,t)=>({archiveCount:e.archiveCount+t.archiveCount,deleteCount:e.deleteCount+t.deleteCount}),{archiveCount:0,deleteCount:0})}}function um(e,t){return t(dm(e))}function dm(e){let t=e.totals.archiveCount,n=e.totals.deleteCount,r=[];return t>0&&r.push(`归档 ${String(t)} 个空闲会话`),n>0&&r.push(`永久删除 ${String(n)} 个已归档会话`),`运行清理并${r.length===0?`执行清理`:r.join(`并`)}?\n\n永久删除只适用于已归档会话,且无法撤销。`}function fm(e){return`请更新并重启 ${e??`此机器`} 上的 Pi-Web 后再清理会话。`}function pm(e,t){let n=e.trim();if(n===``)return`${t}必须设置。`;let r=Number(n);return!Number.isInteger(r)||r<0?`${t}必须是非负整数天数。`:r}function mm(e){return JSON.stringify({archiveIdleDays:e.archiveIdleDays??null,deleteArchivedDays:e.deleteArchivedDays??null})}var hm=new Set,gm=Rt+1,_m={unreadCatalog:e=>jo.unreadCatalog(e),acknowledgeUnread:(e,t,n,r)=>jo.acknowledgeUnread(e,t,n,r)},vm=class{constructor(e={}){this.machines=new Map,this.api=e.api??_m,this.onChange=e.onChange??(()=>void 0),this.onBackgroundError=e.onBackgroundError??(()=>void 0)}retainMachines(e){for(let[t,n]of this.machines){if(e.has(t))continue;let r=n.projection!==void 0;n.generation+=1,n.observers.clear(),n.acknowledgements.clear(),this.machines.delete(t),r&&this.onChange(t)}}setCapability(e,t){let n=this.machine(e),r=n.capability;if(r===t)return!1;if(n.capability=t,t===`unsupported`){let t=n.projection!==void 0;return n.generation+=1,n.projection=void 0,t&&(n.projectionVersion+=1),n.status=`stale`,n.refreshPromise=void 0,n.refreshQueued=!1,n.observers.clear(),n.acknowledgements.clear(),t&&this.onChange(e),!1}return t===`unknown`?(n.projection!==void 0&&n.status!==`stale`&&(n.status=`stale`,this.onChange(e)),!1):r!==`supported`}capability(e){return this.machines.get(e)?.capability??`unknown`}projection(e){let t=this.machines.get(e),n=t?.projection;if(!(t===void 0||n===void 0))return{status:t.status,catalogId:n.catalogId,catalogRevision:n.catalogRevision,sessions:[...n.summariesByIdentity.values()].sort((e,t)=>t.completionOrder-e.completionOrder).map(e=>({...e}))}}unreadSessionIds(e,t){let n=this.machines.get(e)?.projection;if(n===void 0||t.length===0)return hm;let r=new Set;for(let e of t)n.summariesByIdentity.has(wm(e))&&r.add(e.id);return r.size===0?hm:r}isUnread(e,t){return this.machines.get(e)?.projection?.summariesByIdentity.has(wm(t))===!0}applyEvent(e,t){let n=this.machine(e);if(n.capability!==`supported`)return;this.recordObservedEvent(n,t);let r=ym(n.projection,n.status,t);this.installProjection(n,r.projection,r.status)&&this.onChange(e),r.requiresRefresh&&(n.refreshPromise===void 0?this.refresh(e):n.refreshQueued=!0)}refresh(e){let t=this.machine(e);if(t.capability!==`supported`)return Promise.resolve();if(t.refreshPromise!==void 0)return t.refreshQueued=!0,t.refreshPromise;let n=t.generation,r=this.runRefreshLoop(t,n);return t.refreshPromise=r,r.finally(()=>{if(!this.isCurrent(t,n)||t.refreshPromise!==r)return;t.refreshPromise=void 0;let e=t.refreshQueued&&t.capability===`supported`;t.refreshQueued=!1,e&&this.refresh(t.machineId)}),r}async refreshAll(){await Promise.all([...this.machines.values()].filter(e=>e.capability===`supported`).map(async e=>{await this.refresh(e.machineId)}))}acknowledge(e,t){let n=this.machines.get(e),r=n?.projection;if(n?.capability!==`supported`||r===void 0)return Promise.resolve();let i=r.summariesByIdentity.get(wm(t));if(i===void 0)return Promise.resolve();let a=Tm(r.catalogId,i),o=n.acknowledgements.get(a);if(o!==void 0)return o;let s=n.generation,c=this.runAcknowledgement(n,s,t,r.catalogId,i.completionOrder);return n.acknowledgements.set(a,c),c.finally(()=>{n.acknowledgements.get(a)===c&&n.acknowledgements.delete(a)}),c}async runRefreshLoop(e,t){do{if(e.refreshQueued=!1,!this.isCurrentSupported(e,t))return;let n=e.status;this.markRefreshStarted(e)&&this.onChange(e.machineId);let r=this.beginNetworkObservation(e,t,n);try{let n=await this.api.unreadCatalog(e.machineId);if(!this.isCurrentSupported(e,t))return;this.applyNetworkSnapshot(e,n,r)&&(e.refreshQueued=!0)}catch(n){if(this.isCurrent(e,t)){let t=e.status!==`stale`;e.status=`stale`,t&&this.onChange(e.machineId),this.reportError(`snapshot`,e.machineId,n)}}finally{e.observers.delete(r)}}while(e.refreshQueued&&this.isCurrentSupported(e,t))}async runAcknowledgement(e,t,n,r,i){let a=this.beginNetworkObservation(e,t);try{let o=await this.api.acknowledgeUnread(n,r,i,e.machineId);if(!this.isCurrentSupported(e,t))return;this.applyNetworkSnapshot(e,o,a)&&this.refresh(e.machineId)}catch(n){this.isCurrent(e,t)&&this.reportError(`acknowledge`,e.machineId,n)}finally{e.observers.delete(a)}}applyNetworkSnapshot(e,t,n){let r=e.projection;if(e.projectionVersion!==n.projectionVersion&&r!==void 0&&r.catalogId!==t.catalogId||n.overflowed||n.events.some(e=>e.catalogId!==t.catalogId)){let t=e.status!==`stale`;return e.status=`stale`,t&&this.onChange(e.machineId),!0}let i=xm(t),a=`fresh`,o=!1;for(let e of n.events){let t=ym(i,a,e);i=t.projection,a=t.status,o||=t.requiresRefresh}if(r?.catalogId===i.catalogId&&r.catalogRevision>i.catalogRevision){if(e.projectionVersion===n.projectionVersion&&n.projectionStatus===`fresh`){let t=e.status!==`fresh`;e.status=`fresh`,t&&this.onChange(e.machineId)}o||=e.status===`stale`}else this.installProjection(e,i,a)&&this.onChange(e.machineId);return o}beginNetworkObservation(e,t,n=e.status){let r={generation:t,projectionVersion:e.projectionVersion,projectionStatus:n,events:[],overflowed:!1};return e.observers.add(r),r}recordObservedEvent(e,t){for(let n of e.observers)n.generation!==e.generation||n.overflowed||(n.events.length>=gm?(n.events.length=0,n.overflowed=!0):n.events.push(t))}markRefreshStarted(e){let t=e.projection===void 0?`loading`:`stale`;return e.status===t?!1:(e.status=t,!0)}installProjection(e,t,n){let r=!Cm(e.projection,t);return e.status===n&&!r?!1:(r&&(e.projection=t,e.projectionVersion+=1),e.status=n,!0)}machine(e){let t=this.machines.get(e);if(t!==void 0)return t;let n={machineId:e,capability:`unknown`,status:`stale`,projection:void 0,projectionVersion:0,generation:0,observers:new Set,acknowledgements:new Map,refreshPromise:void 0,refreshQueued:!1};return this.machines.set(e,n),n}isCurrent(e,t){return this.machines.get(e.machineId)===e&&e.generation===t}isCurrentSupported(e,t){return this.isCurrent(e,t)&&e.capability===`supported`}reportError(e,t,n){this.onBackgroundError(e,t,n)}};function ym(e,t,n){if(e===void 0){let e=Sm(n.catalogId);return n.catalogRevision===1?bm(e,`fresh`,n):{projection:e,status:`stale`,requiresRefresh:!0}}if(e.catalogId!==n.catalogId){let e=Sm(n.catalogId);return n.catalogRevision===1?bm(e,`stale`,n):{projection:e,status:`stale`,requiresRefresh:!0}}return n.catalogRevision<=e.catalogRevision?{projection:e,status:t,requiresRefresh:t===`stale`}:n.catalogRevision===e.catalogRevision+1?bm(e,t,n):{projection:e,status:`stale`,requiresRefresh:!0}}function bm(e,t,n){let r=new Map(e.summariesByIdentity),i=wm(n);n.unread===null?r.delete(i):r.set(i,{...n.unread});let a=t===`stale`?`stale`:`fresh`;return{projection:{catalogId:n.catalogId,catalogRevision:n.catalogRevision,summariesByIdentity:r},status:a,requiresRefresh:a===`stale`}}function xm(e){return{catalogId:e.catalogId,catalogRevision:e.catalogRevision,summariesByIdentity:new Map(e.sessions.map(e=>[wm(e),{...e}]))}}function Sm(e){return{catalogId:e,catalogRevision:0,summariesByIdentity:new Map}}function Cm(e,t){if(e?.catalogId!==t.catalogId||e.catalogRevision!==t.catalogRevision||e.summariesByIdentity.size!==t.summariesByIdentity.size)return!1;for(let[n,r]of e.summariesByIdentity){let e=t.summariesByIdentity.get(n);if(e?.completionOrder!==r.completionOrder||e.completedAt!==r.completedAt)return!1}return!0}function wm(e){let t=`id`in e?e.id:e.sessionId;return JSON.stringify([t,e.cwd])}function Tm(e,t){return JSON.stringify([e,t.sessionId,t.cwd,t.completionOrder])}var Em={machines:new Set,projects:new Set,workspaces:new Set};function Dm(e){let t=km(e.projectionFor(e.selectedMachineId));return{machines:Am(e.machineIds,e.projectionFor),projects:Mm(e.projects,e.workspacesByProjectId,t),workspaces:jm(e.workspaces,t)}}function Om(e){return e!==void 0&&e.sessions.length>0}function km(e){return e===void 0||e.sessions.length===0?Pm:new Set(e.sessions.map(e=>e.cwd))}function Am(e,t){let n=new Set;for(let r of e)Om(t(r))&&n.add(r);return n}function jm(e,t){let n=new Set;for(let r of e)t.has(r.path)&&n.add(r.id);return n}function Mm(e,t,n){let r=new Set;for(let i of e)(t[i.id]??[]).some(e=>n.has(e.path))&&r.add(i.id);return r}function Nm(e,t){return Fm(e.machines,t.machines)&&Fm(e.projects,t.projects)&&Fm(e.workspaces,t.workspaces)}var Pm=new Set;function Fm(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function Im(){return{selectedSessionKey:void 0,warningSetSignature:Lm(void 0),warningCount:0,collapsed:!1,collapsedWarningSets:new Map}}function Lm(e){let t=(e??[]).map(e=>JSON.stringify([e.severity,e.message,e.source,e.path,e.dismiss?.id])).sort();return JSON.stringify(t)}function Rm(e,t,n){let r=Lm(n),i=n?.length??0,a=n!==void 0,o=t===void 0?void 0:e.collapsedWarningSets.get(t),s=e.collapsedWarningSets;if(a&&t!==void 0&&o!==void 0&&o!==r){let n=new Map(e.collapsedWarningSets);n.delete(t),s=n}let c=a&&i>0&&o===r;return e.selectedSessionKey===t&&e.warningSetSignature===r&&e.warningCount===i&&e.collapsed===c&&e.collapsedWarningSets===s?e:{selectedSessionKey:t,warningSetSignature:r,warningCount:i,collapsed:c,collapsedWarningSets:s}}function zm(e){if(e.collapsed||e.warningCount===0||e.selectedSessionKey===void 0)return e;let t=new Map(e.collapsedWarningSets);return t.set(e.selectedSessionKey,e.warningSetSignature),{...e,collapsed:!0,collapsedWarningSets:t}}function Bm(e){if(!e.collapsed)return e;let t=new Map(e.collapsedWarningSets);return e.selectedSessionKey!==void 0&&t.delete(e.selectedSessionKey),{...e,collapsed:!1,collapsedWarningSets:t}}function Vm(e){return e.collapsed?Bm(e):zm(e)}var Hm=100;function Um(e,t){return e.filter(e=>Km(e,t))}var Wm={snapshot:e=>Do.snapshot(e),dismiss:(e,t,n)=>Do.dismiss(e,t,n)},Gm=class{constructor(e={}){this.machines=new Map,this.api=e.api??Wm,this.onChange=e.onChange??(()=>void 0),this.onBackgroundError=e.onBackgroundError??(()=>void 0)}retainMachines(e){for(let[t,n]of this.machines){if(e.has(t))continue;let r=n.projection!==void 0;n.generation+=1,n.observers.clear(),n.pendingDismissedIds.clear(),n.dismissals.clear(),this.machines.delete(t),r&&this.onChange(t)}}projection(e){let t=this.machines.get(e),n=t?.projection;if(!(t===void 0||n===void 0))return{machineId:e,status:t.status,daemonInstanceId:n.daemonInstanceId,revision:n.revision,notices:n.notices.filter(e=>!t.pendingDismissedIds.has(e.id))}}hasNotice(e,t){let n=this.projection(e);return n?.status===`fresh`&&n.notices.some(t)}applyEvent(e,t){let n=this.machine(e);this.recordObservedEvent(n,t);let r=n.projection;if(r===void 0){this.installProjection(n,Jm(t.snapshot),`fresh`)&&this.onChange(e);return}if(r.daemonInstanceId!==t.snapshot.daemonInstanceId){let t=n.status!==`stale`;n.status=`stale`,t&&this.onChange(e),n.refreshPromise===void 0?this.refresh(e):n.refreshQueued=!0;return}if(t.snapshot.revision<=r.revision){n.status===`stale`&&(n.refreshPromise===void 0?this.refresh(e):n.refreshQueued=!0);return}this.installProjection(n,Jm(t.snapshot),`fresh`)&&this.onChange(e)}refresh(e){let t=this.machine(e);if(t.refreshPromise!==void 0)return t.refreshQueued=!0,t.refreshPromise;let n=t.generation,r=this.runRefreshLoop(t,n);return t.refreshPromise=r,r.finally(()=>{if(!this.isCurrent(t,n)||t.refreshPromise!==r)return;t.refreshPromise=void 0;let e=t.refreshQueued;t.refreshQueued=!1,e&&this.refresh(t.machineId)}),r}async refreshAll(){await Promise.all([...this.machines.values()].map(async e=>{await this.refresh(e.machineId)}))}dismiss(e,t){let n=this.machines.get(e),r=n?.projection;if(n===void 0||r===void 0||r.notices.find(e=>e.id===t)===void 0||n.pendingDismissedIds.has(t))return Promise.resolve();let i=`${r.daemonInstanceId}:${t}`,a=n.dismissals.get(i);if(a!==void 0)return a;let o=n.generation,s=this.beginNetworkObservation(n,o);n.pendingDismissedIds.add(t),this.onChange(e);let c=this.runDismissal(n,o,s,r.daemonInstanceId,t);return n.dismissals.set(i,c),c.finally(()=>{n.dismissals.get(i)===c&&n.dismissals.delete(i)}),c}async runRefreshLoop(e,t){do{if(e.refreshQueued=!1,!this.isCurrent(e,t))return;this.markRefreshStarted(e)&&this.onChange(e.machineId);let n=this.beginNetworkObservation(e,t);try{let r=await this.api.snapshot(e.machineId);if(!this.isCurrent(e,t))return;this.applyNetworkSnapshot(e,r,n)&&(e.refreshQueued=!0)}catch(n){if(this.isCurrent(e,t)){let t=e.status!==`stale`;e.status=`stale`,t&&this.onChange(e.machineId),this.onBackgroundError(`snapshot`,e.machineId,n)}}finally{e.observers.delete(n)}}while(e.refreshQueued&&this.isCurrent(e,t))}async runDismissal(e,t,n,r,i){try{let a=await this.api.dismiss(e.machineId,r,i);if(!this.isCurrent(e,t))return;let o=this.applyNetworkSnapshot(e,a,n);e.pendingDismissedIds.delete(i),o&&this.refresh(e.machineId)}catch(n){this.isCurrent(e,t)&&this.onBackgroundError(`dismiss`,e.machineId,n)}finally{e.observers.delete(n),this.isCurrent(e,t)&&(e.pendingDismissedIds.delete(i),this.onChange(e.machineId))}}applyNetworkSnapshot(e,t,n){if(n.overflowed)return this.markStale(e);let r=t;for(let t of n.events){if(t.snapshot.daemonInstanceId!==r.daemonInstanceId)return this.markStale(e);t.snapshot.revision>r.revision&&(r=t.snapshot)}let i=e.projection;if(i!==void 0&&e.projectionVersion!==n.projectionVersion){if(i.daemonInstanceId!==r.daemonInstanceId)return this.markStale(e);i.revision>r.revision&&(r={daemonInstanceId:i.daemonInstanceId,revision:i.revision,notices:i.notices})}return this.installProjection(e,Jm(r),`fresh`)&&this.onChange(e.machineId),!1}beginNetworkObservation(e,t){let n={generation:t,projectionVersion:e.projectionVersion,events:[],overflowed:!1};return e.observers.add(n),n}recordObservedEvent(e,t){for(let n of e.observers)n.generation!==e.generation||n.overflowed||(n.events.length>=Hm?(n.events.length=0,n.overflowed=!0):n.events.push(t))}markRefreshStarted(e){let t=e.projection===void 0?`loading`:`stale`;return e.status===t?!1:(e.status=t,!0)}markStale(e){let t=e.status!==`stale`;return e.status=`stale`,t&&this.onChange(e.machineId),!0}installProjection(e,t,n){let r=!Ym(e.projection,t);return e.status===n&&!r?!1:(r&&(e.projection=t,e.projectionVersion+=1),e.status=n,!0)}machine(e){let t=this.machines.get(e);if(t!==void 0)return t;let n={machineId:e,status:`stale`,projection:void 0,projectionVersion:0,generation:0,observers:new Set,pendingDismissedIds:new Set,dismissals:new Map,refreshPromise:void 0,refreshQueued:!1};return this.machines.set(e,n),n}isCurrent(e,t){return this.machines.get(e.machineId)===e&&e.generation===t}};function Km(e,t){let n=e.context;if(e.source===`workspace.delete`){let e=qm(n,`projectId`);return e===void 0||e===t.projectId}let r=qm(n,`projectId`),i=qm(n,`workspaceId`),a=qm(n,`sessionId`);return r===void 0&&i===void 0&&a===void 0||(r===void 0||r===t.projectId)&&(i===void 0||i===t.workspaceId)&&(a===void 0||a===t.sessionId)}function qm(e,t){let n=e?.[t];return typeof n==`string`?n:void 0}function Jm(e){return{daemonInstanceId:e.daemonInstanceId,revision:e.revision,notices:e.notices.map(e=>({...e,...e.context===void 0?{}:{context:{...e.context}}}))}}function Ym(e,t){return e?.daemonInstanceId!==t.daemonInstanceId||e.revision!==t.revision||e.notices.length!==t.notices.length?!1:e.notices.every((e,n)=>JSON.stringify(e)===JSON.stringify(t.notices[n]))}var Xm=`themes:classic`,Zm={themeId:`themes:pi-web-dark`,auto:!0},Qm=`pi-web-app-theme`,$m=`--pi-bg.--pi-surface.--pi-surface-hover.--pi-terminal-bg.--pi-terminal-text.--pi-border.--pi-border-muted.--pi-text.--pi-text-secondary.--pi-text-bright.--pi-muted.--pi-dim.--pi-accent.--pi-accent-border.--pi-selection-bg.--pi-success.--pi-success-border.--pi-success-bg.--pi-success-surface.--pi-success-ring.--pi-warning.--pi-warning-border.--pi-warning-surface.--pi-danger.--pi-purple.--pi-purple-border.--pi-purple-surface.--pi-overlay.--pi-shadow-soft.--pi-shadow.--pi-shadow-strong.--pi-bg-overlay-soft.--pi-bg-overlay.--pi-success-bg-overlay.--pi-terminal-selection`.split(`.`),eh=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function th(){try{let e=window.localStorage.getItem(Qm);return e===null?void 0:sh(e)}catch{return}}function nh(e){try{window.localStorage.setItem(Qm,JSON.stringify(e))}catch{}}function rh(e){let t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(let n of $m){let r=e.tokens[n];typeof r==`string`&&r!==``?t.style.setProperty(n,r):t.style.removeProperty(n)}}function ih(e){let t=ah(e.themes,e.fallbackThemeId??`themes:classic`),n=e.themes.find(t=>t.id===e.preference.themeId)??t;if(n===void 0)return{selectedTheme:void 0,activeTheme:void 0,selectedThemePair:void 0,fallbackTheme:t};let r=oh(e.themePairs,n.id);if(!e.preference.auto||r===void 0)return{selectedTheme:n,activeTheme:n,selectedThemePair:r,fallbackTheme:t};let i=e.prefersLight?r.light:r.dark;return{selectedTheme:n,activeTheme:e.themes.find(e=>e.id===i)??n,selectedThemePair:r,fallbackTheme:t}}function ah(e,t=Xm){return e.find(e=>e.id===t)??e[0]}function oh(e,t){return e.find(e=>e.light===t||e.dark===t)}function sh(e){let t=e.trim();if(t!==``)try{let e=JSON.parse(t);return ch(e)?e:void 0}catch{return}}function ch(e){if(!lh(e))return!1;let t=e.themeId,n=e.auto;return uh(t)&&typeof n==`boolean`}function lh(e){return typeof e==`object`&&!!e}function uh(e){return typeof e==`string`&&eh.test(e)}function dh(e){return e?.removal!==void 0&&!e.isMain}function fh(e){return e.removal?.confirmation}function ph(e){return{...e===void 0?{}:{projectId:e},metadata:{[Ns]:Ms}}}function mh(e){let t={};for(let n of e){let e=_h(n);if(e===void 0)continue;let r=t[e];(r===void 0||n.createdAt.localeCompare(r.createdAt)>=0)&&(t[e]=n)}return t}function hh(e){return Object.entries(e).filter(([,e])=>vh(e)).map(([e])=>e)}function gh(e,t){if(t===void 0)return!1;let n=e.workspaceDeletionRuns[t.id];return n!==void 0&&vh(n)}function _h(e){return e.metadata[Ps]}function vh(e){return e.status===`queued`||e.status===`running`}function yh(){return[{id:`actions.show`,title:`显示操作`,description:`打开命令面板`,shortcut:`mod+k`,group:`通用`,run:e=>{e.openActionPalette()}},{id:`prompt.focus`,title:`聚焦提示词输入框`,description:`将键盘焦点移动到消息编辑器`,shortcut:`mod+g c`,group:`通用`,enabled:e=>e.state.selectedSession!==void 0,run:e=>{e.focusPrompt()}},{id:`machine.add`,title:`添加机器`,description:`注册另一个可从当前网关访问的 PI WEB 运行时`,group:`机器`,run:e=>e.addMachine()},{id:`machine.refresh`,title:`刷新所选机器`,description:`检查所选 PI WEB 运行时是否在线`,group:`机器`,run:e=>e.refreshSelectedMachine()},{id:`machine.open`,title:`打开所选机器的 PI WEB`,description:`在新标签页中直接打开所选远程 PI WEB`,group:`机器`,enabled:e=>e.state.selectedMachine?.kind===`remote`&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:`machine.remove`,title:`移除所选机器`,description:`从当前网关移除所选远程机器`,group:`机器`,enabled:e=>e.state.selectedMachine?.kind===`remote`,run:e=>e.removeSelectedMachine()},{id:`project.add`,title:`添加项目`,group:`项目`,run:e=>e.addProject()},{id:`auth.login`,title:`配置当前项目的提供商认证`,description:`为当前项目运行 /login`,group:`通用`,run:e=>e.configureAuth()},{id:`auth.logout`,title:`移除当前项目的提供商认证`,description:`移除当前项目已保存的凭据`,group:`通用`,run:e=>e.logoutAuth()},{id:`theme.select`,title:`选择主题`,description:`选择 PI WEB 颜色主题`,group:`偏好设置`,run:e=>{e.openThemePicker()}},{id:`settings.open`,title:`打开设置`,description:`管理 PI WEB 配置和键盘快捷键`,shortcut:`mod+,`,group:`偏好设置`,run:e=>{e.piWebUnstable?.openSettings?.()}},{id:`app.reload-page`,title:`完整重载页面`,description:`重新加载 PI WEB 浏览器页面`,group:`通用`,run:e=>{e.reloadPage()}},{id:`view.chat`,title:`转到聊天`,shortcut:`mod+1`,group:`导航`,run:e=>{e.focusPrompt()}},{id:`view.files`,title:`转到文件`,shortcut:`mod+2`,group:`导航`,enabled:bh,run:e=>{e.selectMainView(`core:workspace.files`)}},{id:`view.git`,title:`转到 Git`,shortcut:`mod+3`,group:`导航`,enabled:xh,run:e=>{e.selectMainView(`core:workspace.git`)}},{id:`view.terminal`,title:`转到终端`,shortcut:`mod+4`,group:`导航`,enabled:bh,run:e=>{e.selectMainView(`core:workspace.terminal`)}},{id:`workspace.refresh-files`,title:`刷新文件`,shortcut:`mod+shift+f`,group:`工作区`,enabled:bh,run:e=>e.refreshFiles()},{id:`workspace.refresh-git`,title:`刷新 Git`,shortcut:`mod+shift+g`,group:`工作区`,enabled:xh,run:e=>e.refreshGit()},{id:`workspace.refresh-current`,title:`刷新当前面板`,shortcut:`mod+shift+r`,group:`工作区`,enabled:bh,run:e=>e.state.workspaceTool===`core:workspace.git`&&e.state.selectedWorkspace?.isGitRepo===!0?e.refreshGit():e.refreshFiles()},{id:`workspace.delete`,title:`删除工作区`,description:`移除所选 Git worktree`,group:`工作区`,enabled:Sh,run:e=>e.deleteWorkspace()},{id:`session.start`,title:`启动会话`,shortcut:`mod+enter`,group:`会话`,enabled:bh,run:e=>e.startSession()},{id:`model.select`,title:`选择模型`,description:`为所选会话选择模型`,group:`会话`,enabled:Ch,run:e=>e.openModelPicker()},{id:`thinking.select`,title:`选择思考级别`,description:`为所选会话选择思考级别`,group:`会话`,enabled:Ch,run:e=>e.openThinkingLevelPicker()},{id:`session.archive`,title:`归档会话`,description:`归档所选会话`,group:`会话`,enabled:wh,run:e=>e.archiveSession()},{id:`session.reload`,title:`重新加载会话`,description:`关闭并从会话文件重新打开所选会话;如需重载 Pi 运行时资源,请在提示词中使用 /reload`,group:`会话`,enabled:Eh,disabledReason:Dh,run:e=>e.reloadSession()},{id:`session.delete`,title:`删除新会话`,description:`删除所选的临时新会话`,group:`会话`,enabled:Th,run:e=>e.deleteCachedNewSession()},{id:`session.stop`,title:`停止活动工作`,shortcut:`mod+.`,group:`会话`,enabled:e=>e.state.selectedSession!==void 0&&As(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function bh(e){return e.state.selectedWorkspace!==void 0}function xh(e){return e.state.selectedWorkspace?.isGitRepo===!0}function Sh(e){let t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!gh(e.state,t)}function Ch(e){let t=e.state.selectedSession;return t!==void 0&&t.archived!==!0}function wh(e){return Bd(e.state.selectedSession,e.state.status,Oh(e.state))}function Th(e){return Vd(e.state.selectedSession,e.state.status,Oh(e.state))}function Eh(e){return!Bd(e.state.selectedSession,e.state.status,Oh(e.state))||Dh(e)!==void 0?!1:!As(e.state.status,e.state.activity)}function Dh(e){if(Bd(e.state.selectedSession,e.state.status,Oh(e.state))&&!As(e.state.status,e.state.activity))return kh(e.state,`从磁盘重新加载会话`)}function Oh(e){return Rd(e.machineRuntimes[z(e)])}function kh(e,t){if(e.machineRuntimes[z(e)]?.ok===!0)return;let n=e.selectedMachine?.name;return n!==void 0&&n!==``?`请更新并重启 ${n} 上的 Pi-Web,以便${t}。`:`请更新并重启此机器上的 Pi-Web,以便${t}。`}function Ah(e){return typeof e==`string`?jh(e):g`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`}function jh(e){switch(e){case`navigation`:return _`
|
|
20
20
|
<svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
21
21
|
<circle cx="6" cy="7" r="1.5"></circle>
|
|
22
22
|
<path d="M10 7h8"></path>
|
|
@@ -50,7 +50,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
|
|
|
50
50
|
<path d="m7 10 3 3-3 3"></path>
|
|
51
51
|
<path d="M12 16h5"></path>
|
|
52
52
|
</svg>
|
|
53
|
-
`}}function
|
|
53
|
+
`}}function Mh(e){return Number.isFinite(e)?e<1e3?Math.round(e).toString():e<1e4?`${(e/1e3).toFixed(1)}k`:e<1e6?`${String(Math.round(e/1e3))}k`:e<1e7?`${(e/1e6).toFixed(1)}M`:`${String(Math.round(e/1e6))}M`:`0`}function Nh(e){if(!Number.isFinite(e)||e<0)return`0 B`;if(e<1024)return`${String(e)} B`;let t=e/1024;if(t<1024)return`${Ph(t)} KB`;let n=t/1024;return n<1024?`${Ph(n)} MB`:`${Ph(n/1024)} GB`}function Ph(e){return e>=10?String(Math.round(e)):e.toFixed(1)}function Fh(e){return!Number.isFinite(e)||e===0?`$0`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var Ih=new Set,Lh=0;function Rh(e){let t=e.element.ownerDocument,n=Xh(t),r=n instanceof HTMLElement?Wh(t,n):void 0,i={layer:e,order:++Lh,restorationPath:n instanceof HTMLElement?[n,...r?.restorationPath??[]]:[]},a=!0;return Ih.add(i),Vh(t),{get isTop(){return a&&Hh(t)===i},focus:()=>a&&qh(i),unregister:()=>{a&&(a=!1,Ih.delete(i),Vh(t),Bh(i))}}}function zh(e){return e!==void 0&&Hh(e)!==void 0}function Bh(e){let{element:t}=e.layer,n=t.ownerDocument,r=Xh(n);if(!(r===null||r===n.body||r===n.documentElement)&&!$h(t,r))return;let i=Hh(n);if(i!==void 0){if(Jh(e.restorationPath.filter(e=>$h(i.layer.element,e))))return;qh(i);return}Jh(e.restorationPath)}function Vh(e){let t=Hh(e);for(let n of[...Ih])n.layer.element.ownerDocument===e&&n.layer.onTopChange?.(n===t)}function Hh(e){let t;for(let n of Ih)Uh(e,n)&&(t===void 0||Gh(n,t)>0)&&(t=n);return t}function Uh(e,t){let{element:n,nativeTopLayer:r}=t.layer;return!n.isConnected||n.ownerDocument!==e?!1:r===!0||!Zh(n)}function Wh(e,t){let n;for(let r of Ih)!Uh(e,r)||!$h(r.layer.element,t)||(n===void 0||Gh(r,n)>0)&&(n=r);return n}function Gh(e,t){let n=Number(e.layer.nativeTopLayer===!0)-Number(t.layer.nativeTopLayer===!0);if(n!==0)return n;let r=e.layer.paintElement??e.layer.element,i=t.layer.paintElement??t.layer.element,a=Kh(r)-Kh(i);if(a!==0)return a;if(r!==i){let e=r.compareDocumentPosition(i);if((e&Node.DOCUMENT_POSITION_DISCONNECTED)===0){if((e&Node.DOCUMENT_POSITION_FOLLOWING)!==0)return-1;if((e&Node.DOCUMENT_POSITION_PRECEDING)!==0)return 1}}return e.order-t.order}function Kh(e){let t=e.ownerDocument.defaultView?.getComputedStyle(e).zIndex??``,n=Number.parseFloat(t);return Number.isFinite(n)?n:0}function qh(e){if(Hh(e.layer.element.ownerDocument)!==e)return!1;e.layer.focus();let t=Xh(e.layer.element.ownerDocument);return t!==null&&$h(e.layer.element,t)}function Jh(e){for(let t of e)if(Yh(t))return!0;return!1}function Yh(e){if(!e.isConnected||e.matches(`:disabled`)||Zh(e))return!1;e.focus();let t=Xh(e.ownerDocument);return t===e||t!==null&&$h(e,t)}function Xh(e){let t=e.activeElement;for(;t instanceof HTMLElement;){let e=t.shadowRoot?.activeElement??null;if(e===null)return t;t=e}return t??null}function Zh(e){let t=e.ownerDocument.defaultView,n=t?.getComputedStyle(e);if(n?.visibility===`hidden`||n?.visibility===`collapse`)return!0;let r=e;for(;r!==null;){if(r.hasAttribute(`hidden`)||r.hasAttribute(`inert`))return!0;let e=t?.getComputedStyle(r);if(e?.display===`none`||e?.getPropertyValue(`content-visibility`)===`hidden`)return!0;r=Qh(r)}return!1}function Qh(e){let t=e.assignedSlot;if(t instanceof HTMLSlotElement)return t;let n=e.parentElement;if(n instanceof Element)return n;let r=e.getRootNode();return r instanceof ShadowRoot&&r.host instanceof Element?r.host:null}function $h(e,t){let n=t;for(;;){if(n===e)return!0;let t=n.parentNode;if(t!=null&&t!==n){n=t;continue}let r=n instanceof ShadowRoot?n:n.getRootNode();if(!(r instanceof ShadowRoot))return!1;n=r.host}}function eg(e,t){return e===`error`?_`
|
|
54
54
|
<svg class=${t} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
55
55
|
<circle cx="12" cy="12" r="10"></circle>
|
|
56
56
|
<path d="m15 9-6 6"></path>
|
|
@@ -170,7 +170,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
|
|
|
170
170
|
.error.info { border-bottom-color: var(--pi-accent-border); color: var(--pi-text); background: var(--pi-selection-bg); }
|
|
171
171
|
.error .error-text { flex: 1 1 auto; min-width: 0; overflow-wrap: anywhere; }
|
|
172
172
|
.error .error-dismiss { flex: 0 0 auto; padding: 0 6px; border: 0; background: none; color: inherit; line-height: 1.4; }
|
|
173
|
-
`;var
|
|
173
|
+
`;var tg=h`
|
|
174
174
|
: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; }
|
|
175
175
|
header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
|
|
176
176
|
.workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
|
|
@@ -225,7 +225,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
|
|
|
225
225
|
.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); }
|
|
226
226
|
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; }
|
|
227
227
|
p { margin: 10px; }
|
|
228
|
-
|
|
228
|
+
`,ng=h`
|
|
229
229
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
230
230
|
:host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
231
231
|
section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
|
|
@@ -294,7 +294,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
|
|
|
294
294
|
.workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
|
|
295
295
|
.workspace-detail-row .workspace-label-base, .workspace-detail-row .workspace-label-item, .workspace-detail-row .workspace-label-render { overflow: visible; text-overflow: clip; overflow-wrap: anywhere; white-space: normal; }
|
|
296
296
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
297
|
-
`,
|
|
297
|
+
`,rg=h`
|
|
298
298
|
:host { position: relative; z-index: 0; display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
299
299
|
.chat-wrap { position: relative; flex: 1 1 0; min-height: 0; max-height: 100%; overflow: hidden; }
|
|
300
300
|
.top-notices { box-sizing: border-box; flex: 0 0 auto; max-height: 40%; min-height: 0; display: flex; flex-direction: column; overflow: hidden; border-bottom: 1px solid var(--pi-border); background: var(--pi-bg-overlay); }
|
|
@@ -455,7 +455,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
|
|
|
455
455
|
pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; direction: ltr; text-align: left; unicode-bidi: isolate; }
|
|
456
456
|
.shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; direction: ltr; text-align: left; unicode-bidi: isolate; }
|
|
457
457
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
458
|
-
`,
|
|
458
|
+
`,ig=h`
|
|
459
459
|
:host { display: block; }
|
|
460
460
|
.formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; text-align: start; unicode-bidi: plaintext; }
|
|
461
461
|
p, ul, ol, pre, blockquote, .table-scroll, .code-block-wrapper { margin: 0 0 10px; }
|
|
@@ -482,7 +482,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
|
|
|
482
482
|
table { border-collapse: collapse; width: max-content; min-width: 100%; max-width: none; }
|
|
483
483
|
th, td { border: 1px solid var(--pi-border); padding: 4px 8px; max-width: 48ch; overflow-wrap: anywhere; }
|
|
484
484
|
th { background: var(--pi-surface); }
|
|
485
|
-
`,
|
|
485
|
+
`,ag=h`
|
|
486
486
|
:host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
|
|
487
487
|
.bar { display: flex; justify-content: flex-end; gap: 12px; align-items: center; min-width: 0; padding: 7px 12px; border-top: 1px solid var(--pi-border); background: var(--pi-bg); white-space: nowrap; overflow: hidden; }
|
|
488
488
|
span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
@@ -538,7 +538,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
|
|
|
538
538
|
.group { grid-column: 1 / -1; font-size: 12px; }
|
|
539
539
|
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; }
|
|
540
540
|
.empty { padding: 24px; color: var(--pi-muted); text-align: center; }
|
|
541
|
-
`;var
|
|
541
|
+
`;var og=h`
|
|
542
542
|
:host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
543
543
|
footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
|
|
544
544
|
footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
|
|
@@ -593,18 +593,18 @@ 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
|
|
|
593
593
|
button { padding: 5px 7px; }
|
|
594
594
|
.icon-button { width: 34px; height: 34px; }
|
|
595
595
|
}
|
|
596
|
-
`;function
|
|
596
|
+
`;function sg(e){return _`
|
|
597
597
|
<svg class="file-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
598
598
|
${e}
|
|
599
599
|
</svg>
|
|
600
|
-
`}function
|
|
601
|
-
]`).replace(`lheading`,
|
|
602
|
-
`),n=t.length-1;for(;n>=0&&
|
|
603
|
-
`)}function
|
|
600
|
+
`}function cg(){return sg(_`<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z"></path><path d="M14 2v6h6"></path><path d="M12 12v6"></path><path d="M9 15h6"></path>`)}function lg(){return sg(_`<path d="M3 6a2 2 0 0 1 2-2h5l2 2h7a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"></path><path d="M12 10v6"></path><path d="M9 13h6"></path>`)}function ug(){return sg(_`<path d="M12 16V4"></path><path d="m7 9 5-5 5 5"></path><path d="M5 20h14"></path>`)}function dg(){return sg(_`<path d="M12 4v12"></path><path d="m7 11 5 5 5-5"></path><path d="M5 20h14"></path>`)}function fg(){return sg(_`<path d="M12 20h9"></path><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L8 18l-4 1 1-4Z"></path>`)}function pg(){return sg(_`<path d="M3 6h18"></path><path d="M8 6V4h8v2"></path><path d="m19 6-1 14H6L5 6"></path><path d="M10 11v5"></path><path d="M14 11v5"></path>`)}function mg(){return sg(_`<path d="M20 6v5h-5"></path><path d="M20 11a8 8 0 1 0-2.34 5.66"></path>`)}var hg=e=>e??v,gg={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},_g=e=>(...t)=>({_$litDirective$:e,values:t}),vg=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)}},yg=class extends vg{constructor(e){if(super(e),this.it=v,e.type!==gg.CHILD)throw Error(this.constructor.directiveName+`() can only be used in child bindings`)}render(e){if(e===v||e==null)return this._t=void 0,this.it=e;if(e===Je)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:[]}}};yg.directiveName=`unsafeHTML`,yg.resultType=1;var bg=_g(yg);function xg(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Sg=xg();function Cg(e){Sg=e}var wg={exec:()=>null};function Tg(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 V(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(Dg.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var Eg=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),Dg={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:Tg(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:Tg(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:Tg(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:Tg(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:Tg(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:Tg(e=>RegExp(`^ {0,${e}}>`))},Og=/^(?:[ \t]*(?:\n|$))+/,kg=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Ag=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,jg=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Mg=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Ng=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Pg=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Fg=V(Pg).replace(/bull/g,Ng).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(),Ig=V(Pg).replace(/bull/g,Ng).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(),Lg=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,Rg=/^[^\n]+/,zg=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Bg=V(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,zg).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Vg=V(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,Ng).getRegex(),Hg=`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`,Ug=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Wg=V(`^ {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`,Ug).replace(`tag`,Hg).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Gg=e=>V(Lg).replace(`hr`,jg).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`,Hg).getRegex(),Kg=Gg(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),qg=Gg(/ {0,3}(?:[*+-]|\d{1,9}[.)])[ \t]+[^ \t\n]/),Jg={blockquote:V(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,qg).getRegex(),code:kg,def:Bg,fences:Ag,heading:Mg,hr:jg,html:Wg,lheading:Fg,list:Vg,newline:Og,paragraph:Kg,table:wg,text:Rg},Yg=V(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,jg).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`,Hg).getRegex(),Xg={...Jg,lheading:Ig,table:Yg,paragraph:V(Lg).replace(`hr`,jg).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,Yg).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`,Hg).getRegex()},Zg={...Jg,html:V(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,Ug).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:wg,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:V(Lg).replace(`hr`,jg).replace(`heading`,` *#{1,6} *[^
|
|
601
|
+
]`).replace(`lheading`,Fg).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},Qg=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,$g=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,e_=/^( {2,}|\\)\n(?!\s*$)/,t_=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,n_=/[\p{P}\p{S}]/u,r_=/[\s\p{P}\p{S}]/u,i_=/[^\s\p{P}\p{S}]/u,a_=V(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,r_).getRegex(),o_=/(?!~)[\p{P}\p{S}]/u,s_=/(?!~)[\s\p{P}\p{S}]/u,c_=/(?:[^\s\p{P}\p{S}]|~)/u,l_=V(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,Eg?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),u_=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,d_=V(u_,`u`).replace(/punct/g,n_).getRegex(),f_=V(u_,`u`).replace(/punct/g,o_).getRegex(),p_=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,m_=V(p_,`gu`).replace(/notPunctSpace/g,i_).replace(/punctSpace/g,r_).replace(/punct/g,n_).getRegex(),h_=V(p_,`gu`).replace(/notPunctSpace/g,c_).replace(/punctSpace/g,s_).replace(/punct/g,o_).getRegex(),g_=V(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,i_).replace(/punctSpace/g,r_).replace(/punct/g,n_).getRegex(),__=V(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,n_).getRegex(),v_=V(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,i_).replace(/punctSpace/g,r_).replace(/punct/g,n_).getRegex(),y_=V(/\\(punct)/,`gu`).replace(/punct/g,n_).getRegex(),b_=V(/^<(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(),x_=V(Ug).replace(`(?:-->|$)`,`-->`).getRegex(),S_=V(`^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`,x_).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),C_=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,w_=V(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,C_).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),T_=V(/^!?\[(label)\]\[(ref)\]/).replace(`label`,C_).replace(`ref`,zg).getRegex(),E_=V(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,zg).getRegex(),D_=V(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,T_).replace(`nolink`,E_).getRegex(),O_=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,k_={_backpedal:wg,anyPunctuation:y_,autolink:b_,blockSkip:l_,br:e_,code:$g,del:wg,delLDelim:wg,delRDelim:wg,emStrongLDelim:d_,emStrongRDelimAst:m_,emStrongRDelimUnd:g_,escape:Qg,link:w_,nolink:E_,punctuation:a_,reflink:T_,reflinkSearch:D_,tag:S_,text:t_,url:wg},A_={...k_,link:V(/^!?\[(label)\]\((.*?)\)/).replace(`label`,C_).getRegex(),reflink:V(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,C_).getRegex()},j_={...k_,emStrongRDelimAst:h_,emStrongLDelim:f_,delLDelim:__,delRDelim:v_,url:V(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,O_).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:V(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,O_).getRegex()},M_={...j_,br:V(e_).replace(`{2,}`,`*`).getRegex(),text:V(j_.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},N_={normal:Jg,gfm:Xg,pedantic:Zg},P_={normal:k_,gfm:j_,breaks:M_,pedantic:A_},F_={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},I_=e=>F_[e];function L_(e,t){if(t){if(Dg.escapeTest.test(e))return e.replace(Dg.escapeReplace,I_)}else if(Dg.escapeTestNoEncode.test(e))return e.replace(Dg.escapeReplaceNoEncode,I_);return e}function R_(e){try{e=encodeURI(e).replace(Dg.percentDecode,`%`)}catch{return null}return e}function z_(e,t){let n=e.replace(Dg.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(Dg.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(Dg.slashPipe,`|`);return n}function B_(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 V_(e){let t=e.split(`
|
|
602
|
+
`),n=t.length-1;for(;n>=0&&Dg.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
|
|
603
|
+
`)}function H_(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 U_(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 W_(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 G_(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
604
604
|
`).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(`
|
|
605
|
-
`)}var
|
|
606
|
-
`),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:
|
|
607
|
-
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=
|
|
605
|
+
`)}var K_=class{options;rules;lexer;constructor(e){this.options=e||Sg}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]:V_(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=G_(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=B_(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:B_(t[0],`
|
|
606
|
+
`),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:B_(t[0],`
|
|
607
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=B_(t[0],`
|
|
608
608
|
`).split(`
|
|
609
609
|
`),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(`
|
|
610
610
|
`),c=s.replace(this.rules.other.blockquoteSetextReplace,`
|
|
@@ -615,20 +615,20 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
615
615
|
`),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+`
|
|
616
616
|
`+e.join(`
|
|
617
617
|
`),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(`
|
|
618
|
-
`);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=
|
|
618
|
+
`);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=U_(t[2].split(`
|
|
619
619
|
`,1)[0],t[1].length),l=e.split(`
|
|
620
620
|
`,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+`
|
|
621
621
|
`,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(`
|
|
622
622
|
`,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+=`
|
|
623
623
|
`+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+=`
|
|
624
624
|
`+l}u=!l.trim(),r+=p+`
|
|
625
|
-
`,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=
|
|
626
|
-
`),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=
|
|
627
|
-
`):[],a={type:`table`,raw:
|
|
628
|
-
`),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(
|
|
625
|
+
`,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=V_(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:B_(t[0],`
|
|
626
|
+
`),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=z_(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
|
|
627
|
+
`):[],a={type:`table`,raw:B_(t[0],`
|
|
628
|
+
`),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(z_(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:B_(t[0],`
|
|
629
629
|
`),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)===`
|
|
630
|
-
`?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=
|
|
631
|
-
`),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(
|
|
630
|
+
`?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=B_(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=H_(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)),W_(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 W_(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}}}},q_=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Sg,this.options.tokenizer=this.options.tokenizer||new K_,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:Dg,block:N_.normal,inline:P_.normal};this.options.pedantic?(t.block=N_.pedantic,t.inline=P_.pedantic):this.options.gfm&&(t.block=N_.gfm,this.options.breaks?t.inline=P_.breaks:t.inline=P_.gfm),this.tokenizer.rules=t}static get rules(){return{block:N_,inline:P_}}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(Dg.carriageReturn,`
|
|
631
|
+
`),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(Dg.tabCharGlobal,` `).replace(Dg.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+=`
|
|
632
632
|
`: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(`
|
|
633
633
|
`)?``:`
|
|
634
634
|
`)+i.raw,n.text+=`
|
|
@@ -641,9 +641,9 @@ ${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTo
|
|
|
641
641
|
`+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(`
|
|
642
642
|
`)?``:`
|
|
643
643
|
`)+i.raw,n.text+=`
|
|
644
|
-
`+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)}},
|
|
645
|
-
`;return r?`<pre><code class="language-`+
|
|
646
|
-
`:`<pre><code>`+(n?i:
|
|
644
|
+
`+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)}},J_=class{options;parser;constructor(e){this.options=e||Sg}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(Dg.notSpaceStart)?.[0],i=e.replace(Dg.endingNewline,``)+`
|
|
645
|
+
`;return r?`<pre><code class="language-`+L_(r)+`">`+(n?i:L_(i,!0))+`</code></pre>
|
|
646
|
+
`:`<pre><code>`+(n?i:L_(i,!0))+`</code></pre>
|
|
647
647
|
`}blockquote({tokens:e}){return`<blockquote>
|
|
648
648
|
${this.parser.parse(e)}</blockquote>
|
|
649
649
|
`}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
@@ -659,12 +659,12 @@ ${this.parser.parse(e)}</blockquote>
|
|
|
659
659
|
`}tablerow({text:e}){return`<tr>
|
|
660
660
|
${e}</tr>
|
|
661
661
|
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
662
|
-
`}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>${
|
|
663
|
-
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+
|
|
664
|
-
${this.renderViewerHeader(t,
|
|
665
|
-
${
|
|
662
|
+
`}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>${L_(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=R_(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+L_(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=R_(e);if(i===null)return L_(n);e=i;let a=`<img src="${e}" alt="${L_(n)}"`;return t&&(a+=` title="${L_(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:L_(e.text)}},Y_=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}},X_=class e{options;renderer;textRenderer;constructor(e){this.options=e||Sg,this.options.renderer=this.options.renderer||new J_,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Y_}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}},Z_=class{options;block;constructor(e){this.options=e||Sg}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?q_.lex:q_.lexInline}provideParser(e=this.block){return e?X_.parse:X_.parseInline}},Q_=new class{defaults=xg();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=X_;Renderer=J_;TextRenderer=Y_;Lexer=q_;Tokenizer=K_;Hooks=Z_;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 J_(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 K_(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 Z_;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];Z_.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&Z_.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 q_.lex(e,t??this.defaults)}parser(e,t){return X_.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?q_.lex:q_.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?X_.parse:X_.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?q_.lex:q_.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?X_.parse:X_.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+=`
|
|
663
|
+
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+L_(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}};function H(e,t){return Q_.parse(e,t)}H.options=H.setOptions=function(e){return Q_.setOptions(e),H.defaults=Q_.defaults,Cg(H.defaults),H},H.getDefaults=xg,H.defaults=Sg,H.use=function(...e){return Q_.use(...e),H.defaults=Q_.defaults,Cg(H.defaults),H},H.walkTokens=function(e,t){return Q_.walkTokens(e,t)},H.parseInline=Q_.parseInline,H.Parser=X_,H.parser=X_.parse,H.Renderer=J_,H.TextRenderer=Y_,H.Lexer=q_,H.lexer=q_.lex,H.Tokenizer=K_,H.Hooks=Z_,H.parse=H,H.options,H.setOptions,H.use,H.walkTokens,H.parseInline,X_.parse,q_.lex;var $_=new H.Renderer;$_.html=({text:e})=>dv(e),$_.image=({text:e})=>dv(e===``?`[已省略图片]`:`[已省略图片:${e}]`),$_.checkbox=({checked:e})=>e?`[x] `:`[ ] `;var U=new Set,ev={a:new Set([`href`,`title`]),blockquote:U,br:U,code:U,del:U,em:U,h1:U,h2:U,h3:U,h4:U,h5:U,h6:U,hr:U,li:U,ol:new Set([`start`]),p:U,pre:U,strong:U,table:U,tbody:U,td:new Set([`align`]),th:new Set([`align`]),thead:U,tr:U,ul:U},tv=new Set([`http:`,`https:`,`mailto:`]),nv=new Set([`left`,`center`,`right`]),rv=`table-scroll`;function iv(e){return av(H.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:$_}))}function av(e){let t=document.createElement(`template`);t.innerHTML=e;for(let e of[...t.content.querySelectorAll(`*`)]){let t=e.tagName.toLowerCase(),n=ev[t];if(n===void 0){e.remove();continue}for(let r of[...e.attributes]){let i=r.name.toLowerCase();(!n.has(i)||!sv(t,i,r.value))&&e.removeAttribute(r.name)}t===`a`&&ov(e)}return uv(t.content),t.innerHTML}function ov(e){if(!e.hasAttribute(`href`)){e.removeAttribute(`target`),e.removeAttribute(`rel`),e.removeAttribute(`referrerpolicy`);return}e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noopener noreferrer`),e.setAttribute(`referrerpolicy`,`no-referrer`)}function sv(e,t,n){return e===`a`&&t===`href`?cv(n):e===`ol`&&t===`start`?/^-?\d+$/.test(n):(e===`td`||e===`th`)&&t===`align`?nv.has(n.toLowerCase()):!0}function cv(e){if(e===``||lv(e))return!1;try{return tv.has(new URL(e).protocol)}catch{return!1}}function lv(e){for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n<=31||n===127)return!0}return!1}function uv(e){e.querySelectorAll(`table`).forEach(e=>{let t=document.createElement(`div`);t.className=rv,t.setAttribute(`role`,`region`),t.setAttribute(`aria-label`,`表格`),t.setAttribute(`tabindex`,`0`),e.before(t),t.append(e)})}function dv(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}var fv=`10 MB`;function pv(e){let t=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`));return e.slice(t+1)}var mv=`pi-web.workspace.files.viewMode`,hv=`mode`,gv=Qs(`core:workspace.files`);function _v(e){return e===`preview`||e===`raw`?e:void 0}function vv(e,t){let n=_v(e.read());return n===void 0?bv(t)??`raw`:(xv(n,t),n)}function yv(e,t,n){xv(e,n),t.write(e)}function bv(e){if(e!==void 0)try{return _v(e.getItem(mv))}catch{return}}function xv(e,t){if(t!==void 0)try{t.setItem(mv,e)}catch{}}var Sv={adopt:()=>vv(Cv(),wv()),publish:e=>{yv(e,Cv(),wv())}};function Cv(){return{read:()=>typeof window>`u`?void 0:ec(gv,hv),write:e=>{typeof window>`u`||tc(gv,hv,e,{replace:!0})}}}function wv(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function W(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}var Tv=`modulepreload`,Ev=function(e,t){return new URL(e,t).href},Dv={},Ov=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=Ev(t,n),t=s(t),t in Dv)return;Dv[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:Tv,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},kv=class extends y{constructor(...e){super(...e),this.machineId=``,this.projectId=``,this.workspaceId=``,this.previewUrlBuilder=oo,this.modeStore=Sv,this.selectionToken=0}willUpdate(){this.mode??=this.modeStore.adopt();let e=this.currentFileKey();e!==this.activeFileKey&&(this.activeFileKey=e,this.selectionToken+=1,this.failedPreviewToken=void 0)}updated(){let e=this.mode;e===void 0||e===this.publishedMode||this.selectionHasRawAndPreviewModes()&&(this.publishedMode=e,this.modeStore.publish(e))}render(){let e=this.selectedPath;if(e===void 0||e===``)return this.renderStatus(`请选择文件。`);if(this.loadError!==void 0)return this.renderStatus(`无法加载 ${e}:${this.loadError}`,!0);let t=this.file;if(t===void 0)return this.renderStatus(`正在加载 ${e}…`);if(t.path!==e)return this.renderStatus(`无法预览 ${e}:已加载内容属于 ${t.path}。`,!0);let n=this.selectionToken,r=jv(t),i=Pv(r)&&t.size>0&&t.size<=10485760;return g`
|
|
664
|
+
${this.renderViewerHeader(t,Fv(t,r),i)}
|
|
665
|
+
${Mv(t,r)?this.renderModeControls(t,n):null}
|
|
666
666
|
${this.renderLoadedFile(t,r,n)}
|
|
667
|
-
`}renderLoadedFile(e,t,n){if(
|
|
667
|
+
`}renderLoadedFile(e,t,n){if(Mv(e,t)&&this.mode===`raw`)return this.renderRawSource(e);if(e.size===0)return this.renderStatus(`此文件为空。`);switch(t){case`image`:return this.renderImagePreview(e,n);case`html`:return this.renderFramePreview(e,`html`,n);case`pdf`:return this.renderFramePreview(e,`pdf`,n);case`markdown`:return this.renderMarkdownPreview(e);case`download`:return this.renderUnsupportedFile(e);case`code`:return this.renderRawSource(e)}}renderViewerHeader(e,t,n){let r=pv(e.path),i={modifiedAt:e.modifiedAt,machineId:this.machineId},a=this.previewUrlBuilder(this.projectId,this.workspaceId,e.path,i),o=this.previewUrlBuilder(this.projectId,this.workspaceId,e.path,{...i,download:!0});return g`
|
|
668
668
|
<div class="viewer-header">
|
|
669
669
|
<strong title=${e.path}>${e.path}</strong>
|
|
670
670
|
<div class="viewer-actions">
|
|
@@ -695,12 +695,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
695
695
|
@click=${()=>{this.setMode(`raw`,t)}}
|
|
696
696
|
>源码</button>
|
|
697
697
|
</div>
|
|
698
|
-
`}renderRawSource(e){return e.size===0?this.renderStatus(`此文件为空。`):(
|
|
698
|
+
`}renderRawSource(e){return e.size===0?this.renderStatus(`此文件为空。`):(Iv(),g`
|
|
699
699
|
${e.truncated?g`<p class="preview-note" role="status">源码已截断,请下载完整文件。</p>`:null}
|
|
700
700
|
<code-viewer .content=${e.content} .language=${e.language}></code-viewer>
|
|
701
|
-
`)}renderMarkdownPreview(e){if(e.size>10485760)return this.renderPreviewTooLarge(e);try{let t=
|
|
701
|
+
`)}renderMarkdownPreview(e){if(e.size>10485760)return this.renderPreviewTooLarge(e);try{let t=iv(e.content);return g`
|
|
702
702
|
${e.truncated?g`<p class="preview-note" role="status">预览基于已截断的源码,请下载完整文件。</p>`:null}
|
|
703
|
-
<div class="formatted markdown-preview" dir="auto">${
|
|
703
|
+
<div class="formatted markdown-preview" dir="auto">${bg(t)}</div>
|
|
704
704
|
`}catch{return this.renderStatus(`Markdown 预览失败,请改用源码或下载。`,!0)}}renderImagePreview(e,t){return e.size>10485760?this.renderPreviewTooLarge(e):this.failedPreviewToken===t?this.renderPreviewFailure(e,t):g`
|
|
705
705
|
<div class="image-preview">
|
|
706
706
|
<img
|
|
@@ -716,7 +716,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
716
716
|
<iframe
|
|
717
717
|
class="file-frame-preview"
|
|
718
718
|
src=${r}
|
|
719
|
-
sandbox=${
|
|
719
|
+
sandbox=${hg(Nv(t))}
|
|
720
720
|
allow=""
|
|
721
721
|
referrerpolicy="no-referrer"
|
|
722
722
|
title=${`${e.path} 的预览`}
|
|
@@ -728,12 +728,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
728
728
|
<span>请在新标签页中打开,或使用上方的下载。</span>
|
|
729
729
|
<button type="button" @click=${()=>{this.retryPreview(t)}}>重试预览</button>
|
|
730
730
|
</div>
|
|
731
|
-
`}renderUnsupportedFile(e){let t=
|
|
731
|
+
`}renderUnsupportedFile(e){let t=pv(e.path);return g`
|
|
732
732
|
<div class="preview-state">
|
|
733
733
|
<p>此文件类型不支持预览。</p>
|
|
734
|
-
<a class="download-link" href=${this.previewUrlBuilder(this.projectId,this.workspaceId,e.path,{modifiedAt:e.modifiedAt,machineId:this.machineId,download:!0})} download=${t}>下载 ${t} · ${
|
|
734
|
+
<a class="download-link" href=${this.previewUrlBuilder(this.projectId,this.workspaceId,e.path,{modifiedAt:e.modifiedAt,machineId:this.machineId,download:!0})} download=${t}>下载 ${t} · ${Nh(e.size)}</a>
|
|
735
735
|
</div>
|
|
736
|
-
`}renderPreviewTooLarge(e){return this.renderStatus(`文件过大,无法预览:${
|
|
736
|
+
`}renderPreviewTooLarge(e){return this.renderStatus(`文件过大,无法预览:${Nh(e.size)} · 上限 ${fv}。请使用上方的下载。`)}renderStatus(e,t=!1){return t?g`<p class="viewer-status" role="alert">${e}</p>`:g`<p class="viewer-status" role="status" aria-live="polite">${e}</p>`}previewUrl(e){return this.previewUrlBuilder(this.projectId,this.workspaceId,e.path,{modifiedAt:e.modifiedAt,machineId:this.machineId})}setMode(e,t){t===this.selectionToken&&(this.mode=e,this.failedPreviewToken=void 0,this.requestUpdate())}recordPreviewFailure(e){e!==this.selectionToken||this.showsRawSource()||(this.failedPreviewToken=e,this.requestUpdate())}retryPreview(e){e===this.selectionToken&&(this.failedPreviewToken=void 0,this.requestUpdate())}currentFileKey(){return Av(this)}showsRawSource(){return this.mode===`raw`&&this.selectionHasRawAndPreviewModes()}selectionHasRawAndPreviewModes(){let e=this.file;return e===void 0||this.loadError!==void 0||this.selectedPath===void 0||e.path!==this.selectedPath?!1:Mv(e,jv(e))}static{this.styles=[ig,h`
|
|
737
737
|
:host { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: auto; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
738
738
|
.viewer-header { position: sticky; top: 0; z-index: 1; display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
|
|
739
739
|
.viewer-header strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
@@ -762,7 +762,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
762
762
|
.viewer-header { align-items: flex-start; flex-direction: column; }
|
|
763
763
|
.viewer-actions { width: 100%; flex-wrap: wrap; }
|
|
764
764
|
}
|
|
765
|
-
`]}};W([x({attribute:!1})],
|
|
765
|
+
`]}};W([x({attribute:!1})],kv.prototype,`machineId`,void 0),W([x({attribute:!1})],kv.prototype,`projectId`,void 0),W([x({attribute:!1})],kv.prototype,`workspaceId`,void 0),W([x({attribute:!1})],kv.prototype,`selectedPath`,void 0),W([x({attribute:!1})],kv.prototype,`file`,void 0),W([x({attribute:!1})],kv.prototype,`loadError`,void 0),W([x({attribute:!1})],kv.prototype,`previewUrlBuilder`,void 0),W([x({attribute:!1})],kv.prototype,`modeStore`,void 0),kv=W([b(`workspace-file-viewer`)],kv);function Av(e){return JSON.stringify([e.machineId,e.projectId,e.workspaceId,e.selectedPath??null,e.file?.path??null,e.file?.modifiedAt??null,e.file?.mediaType??null])}function jv(e){return e.mediaType===`image`?`image`:e.mediaType===`html`?`html`:e.mediaType===`pdf`?`pdf`:e.mediaType===`markdown`?`markdown`:e.binary?`download`:`code`}function Mv(e,t){return t!==`code`&&t!==`download`&&!e.binary}function Nv(e){return e===`html`?``:void 0}function Pv(e){return e===`image`||e===`html`||e===`pdf`}function Fv(e,t){return`${t===`code`?e.language??`文本`:t===`download`?e.mimeType??`二进制`:t===`markdown`?`markdown`:e.mimeType??t} · ${Nh(e.size)}${e.truncated?` · 已截断`:``}`}function Iv(){Ov(()=>import(`./CodeViewer-CZHnKRwQ.js`),__vite__mapDeps([0,1,2,3]),import.meta.url)}var Lv=class extends y{constructor(...e){super(...e),this.destinationFolder=``,this.overwrite=!1,this.createDirs=!0,this.formError=``,this.dragActive=!1,this.dragDepth=0,this.visibleRows=200,this.openFilePicker=()=>{this.uploadInput?.click()},this.handleFileInputChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0,n=Xv(t?.files);t!==void 0&&(t.value=``),n.length>0&&this.openUploadReview(n)},this.handleDragEnter=e=>{Zv(e)&&(e.preventDefault(),this.dragDepth+=1,this.dragActive=!0)},this.handleDragOver=e=>{Zv(e)&&(e.preventDefault(),e.dataTransfer!==null&&(e.dataTransfer.dropEffect=`copy`),this.dragActive=!0)},this.handleDragLeave=e=>{Zv(e)&&(e.preventDefault(),this.dragDepth=Math.max(0,this.dragDepth-1),this.dragDepth===0&&(this.dragActive=!1))},this.handleDrop=e=>{if(!Zv(e))return;e.preventDefault(),this.dragDepth=0,this.dragActive=!1;let t=Xv(e.dataTransfer?.files),n=this.context;t.length>0&&n!==void 0&&Wv(n,t)},this.handleDestinationInput=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.destinationFolder=t?.value??``,this.formError=``},this.handleCreateDirsChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.createDirs=t?.checked??!0},this.handleOverwriteChange=e=>{let t=e.currentTarget instanceof HTMLInputElement?e.currentTarget:void 0;this.overwrite=t?.checked??!1},this.handleDialogKeyDown=e=>{e.key===`Escape`&&(e.preventDefault(),this.closeUploadDialog())}}willUpdate(e){if(!e.has(`context`))return;let t=e.get(`context`);if(t!==void 0&&this.context!==void 0&&Gv(t)!==Gv(this.context)&&(this.visibleRows=200),this.context!==void 0){let e=Hv(this.context.fileTree,this.context.expandedDirs).findIndex(({entry:e})=>e.path===this.context?.selectedFilePath);this.visibleRows=Math.max(this.visibleRows,Math.ceil((e+1)/200)*200)}t!==void 0&&this.context!==void 0&&Gv(t)!==Gv(this.context)&&this.resetPendingUpload()}render(){let e=this.context;if(e===void 0)return g`<p class="muted">文件不可用。</p>`;let t=e.selectedFilePath,n=Vv(e.fileTree,e.expandedDirs,t),r=t!==void 0&&t!==``,i=r&&n===`file`,a=Hv(e.fileTree,e.expandedDirs);return g`
|
|
766
766
|
<section
|
|
767
767
|
class=${this.dragActive?`files-panel dragging`:`files-panel`}
|
|
768
768
|
@dragenter=${this.handleDragEnter}
|
|
@@ -774,13 +774,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
774
774
|
<strong>文件</strong>
|
|
775
775
|
${e.fileTreeStale?g`<span class="stale">已过期</span>`:null}
|
|
776
776
|
<div class="toolbar-actions">
|
|
777
|
-
<button class="icon-button" title="新建文件" aria-label="新建文件" @click=${()=>{this.promptCreateFile(e,n)}}>${
|
|
778
|
-
<button class="icon-button" title="新建文件夹" aria-label="新建文件夹" @click=${()=>{this.promptCreateDirectory(e,n)}}>${
|
|
779
|
-
<button class="icon-button" title="上传文件" aria-label="上传文件" @click=${this.openFilePicker}>${
|
|
780
|
-
<button class="icon-button" aria-label="下载文件" title=${i?`下载 ${t}`:`请选择要下载的文件`} ?disabled=${!i} @click=${e.onDownloadSelectedFile}>${
|
|
781
|
-
<button class="icon-button" aria-label="移动或重命名" title=${r?`移动或重命名 ${t}`:`请选择要移动或重命名的文件或文件夹`} ?disabled=${!r} @click=${()=>{this.promptMoveSelectedPath(e,n)}}>${
|
|
782
|
-
<button class="icon-button danger" aria-label="删除文件或文件夹" title=${r?`删除 ${t}`:`请选择要删除的文件或文件夹`} ?disabled=${!r} @click=${()=>{this.confirmDeleteSelectedPath(e,n)}}>${
|
|
783
|
-
<button class="icon-button" title="刷新" aria-label="刷新" @click=${e.onRefreshFiles}>${
|
|
777
|
+
<button class="icon-button" title="新建文件" aria-label="新建文件" @click=${()=>{this.promptCreateFile(e,n)}}>${cg()}</button>
|
|
778
|
+
<button class="icon-button" title="新建文件夹" aria-label="新建文件夹" @click=${()=>{this.promptCreateDirectory(e,n)}}>${lg()}</button>
|
|
779
|
+
<button class="icon-button" title="上传文件" aria-label="上传文件" @click=${this.openFilePicker}>${ug()}</button>
|
|
780
|
+
<button class="icon-button" aria-label="下载文件" title=${i?`下载 ${t}`:`请选择要下载的文件`} ?disabled=${!i} @click=${e.onDownloadSelectedFile}>${dg()}</button>
|
|
781
|
+
<button class="icon-button" aria-label="移动或重命名" title=${r?`移动或重命名 ${t}`:`请选择要移动或重命名的文件或文件夹`} ?disabled=${!r} @click=${()=>{this.promptMoveSelectedPath(e,n)}}>${fg()}</button>
|
|
782
|
+
<button class="icon-button danger" aria-label="删除文件或文件夹" title=${r?`删除 ${t}`:`请选择要删除的文件或文件夹`} ?disabled=${!r} @click=${()=>{this.confirmDeleteSelectedPath(e,n)}}>${pg()}</button>
|
|
783
|
+
<button class="icon-button" title="刷新" aria-label="刷新" @click=${e.onRefreshFiles}>${mg()}</button>
|
|
784
784
|
</div>
|
|
785
785
|
<input id="workspace-upload-input" class="visually-hidden" type="file" multiple hidden @change=${this.handleFileInputChange} />
|
|
786
786
|
</section>
|
|
@@ -807,7 +807,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
807
807
|
<span>${t.type===`directory`?r?`▾`:`▸`:`·`}</span>
|
|
808
808
|
<span>${t.name}</span>
|
|
809
809
|
</button>
|
|
810
|
-
`}selectTreeEntry(e,t){if(t.type===`directory`){e.onSelectDirectory(t.path),e.onExpandDir(t.path);return}e.onSelectFile(t.path)}updated(){this.syncUploadModal(),this.treeObserver?.disconnect();let e=this.renderRoot.querySelector(`.tree-more`);e!==null&&typeof IntersectionObserver<`u`&&(this.treeObserver=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&(this.visibleRows+=200)},{root:this.renderRoot.querySelector(`.tree`),rootMargin:`200px`}),this.treeObserver.observe(e))}disconnectedCallback(){this.treeObserver?.disconnect(),this.releaseUploadModal(),super.disconnectedCallback()}renderFileViewer(e){return
|
|
810
|
+
`}selectTreeEntry(e,t){if(t.type===`directory`){e.onSelectDirectory(t.path),e.onExpandDir(t.path);return}e.onSelectFile(t.path)}updated(){this.syncUploadModal(),this.treeObserver?.disconnect();let e=this.renderRoot.querySelector(`.tree-more`);e!==null&&typeof IntersectionObserver<`u`&&(this.treeObserver=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&(this.visibleRows+=200)},{root:this.renderRoot.querySelector(`.tree`),rootMargin:`200px`}),this.treeObserver.observe(e))}disconnectedCallback(){this.treeObserver?.disconnect(),this.releaseUploadModal(),super.disconnectedCallback()}renderFileViewer(e){return Vv(e.fileTree,e.expandedDirs,e.selectedFilePath)===`directory`?g`<p class="muted">已选择文件夹:${e.selectedFilePath}</p>`:g`
|
|
811
811
|
<workspace-file-viewer
|
|
812
812
|
.machineId=${e.machine.id}
|
|
813
813
|
.projectId=${e.workspace.projectId}
|
|
@@ -816,11 +816,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
816
816
|
.file=${e.selectedFileContent}
|
|
817
817
|
.loadError=${e.selectedFileLoadError}
|
|
818
818
|
></workspace-file-viewer>
|
|
819
|
-
`}renderUploadProgress(e){let t=
|
|
819
|
+
`}renderUploadProgress(e){let t=Rv(e.state.workspaceUploadBatches,{projectId:e.workspace.projectId,workspaceId:e.workspace.id,machineId:e.machine.id});return t.length===0?null:g`
|
|
820
820
|
<section class="upload-progress" aria-label="工作区上传">
|
|
821
821
|
<div class="upload-progress-header">
|
|
822
822
|
<strong>上传</strong>
|
|
823
|
-
<small>${
|
|
823
|
+
<small>${Qv(t)}</small>
|
|
824
824
|
</div>
|
|
825
825
|
${t.map(t=>this.renderUploadBatch(e,t))}
|
|
826
826
|
</section>
|
|
@@ -828,12 +828,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
828
828
|
<article class=${`upload-batch ${t.status}`}>
|
|
829
829
|
<div class="upload-batch-heading">
|
|
830
830
|
<div>
|
|
831
|
-
<strong>${
|
|
831
|
+
<strong>${$v(t)}</strong>
|
|
832
832
|
<small>${t.destinationFolder===``?`工作区根目录`:t.destinationFolder}</small>
|
|
833
833
|
</div>
|
|
834
|
-
<span>${
|
|
834
|
+
<span>${ey(t)}</span>
|
|
835
835
|
</div>
|
|
836
|
-
<progress max="1" .value=${
|
|
836
|
+
<progress max="1" .value=${ty(t)}></progress>
|
|
837
837
|
<div class="upload-file-list">
|
|
838
838
|
${t.files.map(e=>this.renderUploadFile(e))}
|
|
839
839
|
</div>
|
|
@@ -841,13 +841,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
841
841
|
${t.status===`uploading`?g`<button @click=${()=>{e.onCancelWorkspaceUpload(t.id)}}>取消</button>`:g`<button @click=${()=>{e.onClearWorkspaceUpload(t.id)}}>关闭</button>`}
|
|
842
842
|
</div>
|
|
843
843
|
</article>
|
|
844
|
-
`}renderUploadFile(e){let t=
|
|
844
|
+
`}renderUploadFile(e){let t=ry(e);return g`
|
|
845
845
|
<div class=${`upload-file ${e.status}`}>
|
|
846
846
|
<div class="upload-file-main">
|
|
847
847
|
<span>${e.name}</span>
|
|
848
848
|
<small>${t}</small>
|
|
849
849
|
</div>
|
|
850
|
-
<span class="upload-file-status">${
|
|
850
|
+
<span class="upload-file-status">${ny(e)}</span>
|
|
851
851
|
</div>
|
|
852
852
|
`}renderUploadDialog(e,t){let n=t.files.length;return g`
|
|
853
853
|
<div class="dialog-backdrop" @mousedown=${()=>{this.closeUploadDialog()}}>
|
|
@@ -880,7 +880,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
880
880
|
${t.files.map(e=>g`
|
|
881
881
|
<div class="review-file">
|
|
882
882
|
<span>${e.name}</span>
|
|
883
|
-
<small>${
|
|
883
|
+
<small>${Nh(e.size)}</small>
|
|
884
884
|
</div>
|
|
885
885
|
`)}
|
|
886
886
|
</section>
|
|
@@ -892,7 +892,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
892
892
|
</form>
|
|
893
893
|
</section>
|
|
894
894
|
</div>
|
|
895
|
-
`}promptCreateFile(e,t){let n=
|
|
895
|
+
`}promptCreateFile(e,t){let n=Kv(`新建文件路径`,Uv(e.selectedFilePath,t,`new-file.txt`));n!==void 0&&e.onCreateFile(n)}promptCreateDirectory(e,t){let n=Kv(`新建文件夹路径`,Uv(e.selectedFilePath,t,`new-folder`));n!==void 0&&e.onCreateDirectory(n)}promptMoveSelectedPath(e,t){let n=e.selectedFilePath;if(n===void 0||n===``)return;let r=Kv(t===`directory`?`移动或重命名文件夹到`:`移动或重命名文件到`,n);r!==void 0&&r!==n&&e.onMoveSelectedPath(r)}confirmDeleteSelectedPath(e,t){let n=e.selectedFilePath;if(n===void 0||n===``)return;let r=t===`directory`?`空文件夹`:`文件`;window.confirm(`删除${r} ${n}?此操作无法撤销。`)&&e.onDeleteSelectedPath()}openUploadReview(e){let t=this.context,n=Bv(t?.workspaceUploadDefaultFolder??``);this.pendingUpload={files:e},this.destinationFolder=n.destinationFolder,this.overwrite=n.overwrite,this.createDirs=n.createDirs,this.formError=``}submitUploadReview(e,t,n){e.preventDefault();let r=zv(n.files,this.destinationFolder);if(r!==void 0){this.formError=r;return}t.onStartWorkspaceUpload(n.files,{destinationFolder:this.destinationFolder,createDirs:this.createDirs,overwrite:this.overwrite,selectUploadedFile:!0})!==void 0&&this.closeUploadDialog()}closeUploadDialog(){this.pendingUpload=void 0,this.formError=``}syncUploadModal(){let e=this.uploadDialogBackdrop,t=this.uploadDialog;if(!(e instanceof HTMLElement)||!(t instanceof HTMLElement)){this.releaseUploadModal();return}if(this.uploadModalRegistration!==void 0){this.applyUploadModalAccessibility(t,this.uploadModalRegistration.isTop);return}let n=Rh({element:e,paintElement:ay(this),focus:()=>{(this.renderRoot.querySelector(`#workspace-upload-destination`)??t).focus()},onTopChange:e=>{this.applyUploadModalAccessibility(t,e)}});this.uploadModalRegistration=n,n.focus()}applyUploadModalAccessibility(e,t){e.setAttribute(`aria-modal`,t?`true`:`false`),t?e.removeAttribute(`aria-hidden`):e.setAttribute(`aria-hidden`,`true`)}releaseUploadModal(){let e=this.uploadModalRegistration;this.uploadModalRegistration=void 0,e?.unregister()}resetPendingUpload(){this.closeUploadDialog(),this.dragDepth=0,this.dragActive=!1}static{this.styles=[tg,h`
|
|
896
896
|
:host { flex: 1 1 auto; }
|
|
897
897
|
workspace-file-viewer { flex: 1 1 auto; min-height: 0; }
|
|
898
898
|
.files-panel { position: relative; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; }
|
|
@@ -945,7 +945,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
945
945
|
.review-file span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
946
946
|
.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; }
|
|
947
947
|
footer { display: flex; justify-content: flex-end; gap: 8px; padding-top: 4px; }
|
|
948
|
-
`]}};W([x({attribute:!1})],Pv.prototype,`context`,void 0),W([C(`#workspace-upload-input`)],Pv.prototype,`uploadInput`,void 0),W([C(`.dialog-backdrop`)],Pv.prototype,`uploadDialogBackdrop`,void 0),W([C(`.upload-dialog`)],Pv.prototype,`uploadDialog`,void 0),W([S()],Pv.prototype,`pendingUpload`,void 0),W([S()],Pv.prototype,`destinationFolder`,void 0),W([S()],Pv.prototype,`overwrite`,void 0),W([S()],Pv.prototype,`createDirs`,void 0),W([S()],Pv.prototype,`formError`,void 0),W([S()],Pv.prototype,`dragActive`,void 0),W([S()],Pv.prototype,`visibleRows`,void 0),Pv=W([b(`workspace-files-panel`)],Pv);function Fv(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 Iv(e,t){if(e.length===0)return`请至少选择一个要上传的文件。`;for(let n of e)try{Yo(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function Lv(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function Rv(e,t,n){if(n!==void 0)return Wv(e,t,n)?.type}function zv(e,t){let n=[],r=(e,i)=>{for(let a of e){n.push({entry:a,depth:i});let e=t[a.path];e!==void 0&&r(e,i+1)}};return r(e,0),n}function Bv(e,t,n){if(e===void 0||e===``)return n;if(t===`directory`)return Kv(e,n);let r=Gv(e);return r===``?n:Kv(r,n)}function Vv(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function Hv(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Uv(e,t){let n=window.prompt(e,t);if(n===null)return;let r=n.trim();return r===``?void 0:r}function Wv(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}}function Gv(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function Kv(e,t){return e===``?t:`${e.replace(/\/+$/u,``)}/${t.replace(/^\/+/u,``)}`}function qv(e){return e==null?[]:Array.from(e)}function Jv(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function Yv(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`最近 ${String(e.length)} 项`:`${String(t)} 项正在上传`}function Xv(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 Zv(e){switch(e.status){case`completed`:return`完成`;case`error`:return`失败`;case`cancelled`:return`已取消`;case`uploading`:return ty(e.percent)}}function Qv(e){return e.status===`uploading`?e.percent:1}function $v(e){switch(e.status){case`pending`:return`等待中`;case`uploading`:return ty(e.percent);case`completed`:return`完成`;case`error`:return`错误`;case`cancelled`:return`已取消`}}function ey(e){return e.error===void 0?e.response===void 0?`${e.path} · ${Ah(e.loaded)} / ${Ah(e.total)}`:`已写入 ${e.response.path}`:e.error}function ty(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function ny(e){let t=e.getRootNode();return t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host:e}function ry(){return[{id:`workspace.files`,title:`文件`,icon:Oh(`files`),order:10,render:iy},{id:`workspace.terminal`,title:`终端`,icon:Oh(`terminal`),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:ay}]}function iy(e){return g`<workspace-files-panel .context=${e}></workspace-files-panel>`}function ay(e){return oy(),g`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function oy(){Tv(()=>import(`./TerminalPanel-Bb2lTnwP.js`),__vite__mapDeps([4,5,6]),import.meta.url)}var sy={apiVersion:2,name:`PI WEB 核心`,activate:()=>{let e=!_t();return{contributions:{actions:e?gh():gh().filter(e=>e.id!==`view.terminal`),workspacePanels:e?ry():ry().filter(e=>e.id!==`workspace.terminal`)}}}},cy={"--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`},ly={"--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`},uy={"--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`},dy={apiVersion:2,name:`PI WEB 主题`,activate:()=>({contributions:{themes:[{id:`pi-web-dark`,name:`PI WEB 深色`,description:`PI WEB 深色配色。`,order:10,colorScheme:`dark`,tokens:ly},{id:`pi-web-light`,name:`PI WEB 浅色`,description:`PI WEB 浅色配色。`,order:20,colorScheme:`light`,tokens:uy},{id:`classic`,name:`PI WEB 经典`,description:`原始 PI WEB 深色配色。`,order:30,colorScheme:`dark`,tokens:cy}],themePairs:[{id:`pi-web`,name:`PI WEB`,description:`跟随系统浅色/深色偏好使用 PI WEB 主题。`,order:10,light:`pi-web-light`,dark:`pi-web-dark`}]}})},fy=256*1024,py=8*1024*1024,my=266240,hy=8392704,gy=/^[a-z][a-z0-9.-]*$/u,_y=64;function vy(e){return e.length<=128&&gy.test(e)}function yy(e){if(!vy(e))throw Error(`Plugin backend operation must match ${String(gy)} and be at most 128 characters`);return e}function by(e){if(typeof e!=`string`||e===``||e.length>512)throw Error(`Plugin backend revision must be a non-empty string of at most 512 characters`);return e}function xy(e,t,n=fy){let r=wy(e,new Set,t,0);if(Cy(JSON.stringify(r))>n)throw Error(`${t} exceeds the ${String(n)} byte limit`);return r}function Sy(e,t,n=fy){if(Cy(e)>n)throw Error(`${t} exceeds the ${String(n)} byte limit`);let r;try{r=JSON.parse(e)}catch(e){throw Error(`${t} must be valid JSON`,{cause:e})}return xy(r,t,n)}function Cy(e){return new TextEncoder().encode(e).byteLength}function wy(e,t,n,r){if(r>_y)throw Error(`${n} exceeds the maximum JSON depth of ${String(_y)}`);if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`){if(!Number.isFinite(e))throw Error(`${n} must contain only finite JSON numbers`);return e}if(Array.isArray(e)){if(t.has(e))throw Error(`${n} must not contain cycles`);t.add(e);let i=e.map(e=>wy(e,t,n,r+1));return t.delete(e),Object.freeze(i),i}if(!Ey(e))throw Error(`${n} must contain only JSON values`);if(t.has(e))throw Error(`${n} must not contain cycles`);t.add(e);let i={};for(let[a,o]of Object.entries(e))Ty(i,a,wy(o,t,n,r+1));return t.delete(e),Object.freeze(i)}function Ty(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})}function Ey(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var Dy=/^[a-z][a-z0-9.-]*$/u,Oy=/^[a-z][a-z0-9.-]*$/u,ky=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u,Ay=/^[a-z][a-z0-9.-]*(?::[a-z][a-z0-9.-]*)?$/u,jy=new WeakMap,My=new WeakMap,Ny=new WeakMap,Py=class{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.registeringPluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{plugin:t}=e,n=e.id,r=e.sourcePluginId??n;this.validatePluginId(n),this.validatePluginId(r);let i=this.parseMachineSpecific(n,e.machineSpecific),a=this.parseBackendRevision(n,e.backendRevision);if(this.pluginIds.has(n)||this.registeringPluginIds.has(n))throw Error(`Duplicate plugin id: ${n}`);if(!this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,i)){this.registeringPluginIds.add(n);try{let o=t.apiVersion;if(o!==2)throw Error(`Unsupported browser plugin API version for ${r}: ${String(o)} (expected 2)`);let s=t.activate(Object.freeze({apiVersion:2,pluginId:r,runtimePluginId:n,html:g,svg:_})).contributions,c=new Set,l=(s.actions??[]).map(t=>this.qualifyAction(n,t,e.machineId,e.sourcePluginId,c)),u=(s.workspacePanels??[]).map(t=>this.qualifyWorkspacePanel(n,t,e.machineId,e.sourcePluginId,a,c)),d=(s.workspaceLabels??[]).map(t=>this.qualifyWorkspaceLabelContribution(n,t,e.machineId,e.sourcePluginId,a,c)),f=e.machineId===void 0?(s.themes??[]).map(e=>this.qualifyTheme(n,e,c)):[],p=e.machineId===void 0?(s.themePairs??[]).map(e=>this.qualifyThemePair(n,e,c)):[];this.pluginIds.add(n);for(let e of c)this.contributionIds.add(e);this.actions.push(...l),this.workspacePanels.push(...u),this.workspaceLabels.push(...d),this.themes.push(...f),this.themePairs.push(...p),e.machineId===void 0?(this.gatewayPluginIds.add(n),i&&this.gatewayMachineSpecificPluginIds.add(n)):e.sourcePluginId!==void 0&&i&&Hy(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}finally{this.registeringPluginIds.delete(n)}}}hasPlugin(e){return this.pluginIds.has(e)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=Gy(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=Fy(e,t.pluginId),r=t.enabled?.(n),i=r===!1?t.disabledReason?.(n):void 0,a={id:t.id,pluginId:t.pluginId,localId:t.localId,...t.machineId===void 0?{}:{machineId:t.machineId},title:t.title,run:()=>t.run(n)};return t.description!==void 0&&(a.description=t.description),t.shortcut!==void 0&&(a.shortcut=t.shortcut),t.shortcutAliases!==void 0&&(a.shortcutAliases=[...t.shortcutAliases]),t.group!==void 0&&(a.group=t.group),r!==void 0&&(a.enabled=r),i!==void 0&&i!==``&&(a.disabledReason=i),a})}getWorkspacePanels(){return[...this.workspacePanels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}resolveWorkspacePanelRouteId(e,t){let n=this.workspacePanels.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)),r=n.find(t=>t.id===e);if(r!==void 0)return r.id;let i=n.filter(t=>t.routeAliases?.includes(e)===!0);if(i.length===1)return i[0]?.id;i.length>1&&console.warn(`Ambiguous PI WEB workspace panel route: ${e}`)}async invalidateWorkspacePanels(e,t){await Promise.all(this.workspacePanels.map(async n=>{if(!(n.onInvalidate===void 0||t!==void 0&&n.id!==t))try{await n.onInvalidate(e)}catch(e){console.warn(`Failed to invalidate PI WEB plugin panel ${n.id}`,e)}}))}getThemes(){return[...this.themes].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getThemePairs(){return[...this.themePairs].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getWorkspaceLabelItems(e){return[...this.workspaceLabels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.id.localeCompare(t.id)).flatMap(t=>t.visible?.(e)===!1?[]:t.items(e))}qualifyAction(e,t,n,r,i){let a=this.qualify(e,t.id,i),o=`${r??e}:${t.id}`,s=this.parseShortcutAliases(a,t.shortcutAliases,o);return{...t,id:a,pluginId:e,localId:t.id,...s.length===0?{}:{shortcutAliases:s},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.badge,c=t.visible,l=t.onInvalidate,u=Vy(e,r,i),d=`${r??e}:${t.id}`,f=this.parseRouteAliases(o,t.routeAliases,d);return{...t,id:o,pluginId:e,localId:t.id,...f.length===0?{}:{routeAliases:f},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(c?.(Iy(t,u))??!0),...s===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?s(Iy(t,u)):void 0},...l===void 0?{}:{onInvalidate:t=>this.isContributionActive(e,n,t.machine.id,r)?l(Iy(t,u)):void 0},render:e=>t.render(Iy(e,u))}}qualifyWorkspaceLabelContribution(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.visible,c=t.items,l=Vy(e,r,i);return{...t,id:o,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(s?.(Ly(t,l))??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?c(Ly(t,l)):[]}}qualifyTheme(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id}}qualifyThemePair(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t,n){this.validateLocalId(t);let r=`${e}:${t}`;if(this.contributionIds.has(r)||n.has(r))throw Error(`Duplicate contribution id: ${r}`);return n.add(r),r}qualifyReference(e,t){return this.validateLocalId(t),`${e}:${t}`}isContributionActive(e,t,n,r){return t===void 0?!this.isGatewayPluginHiddenForMachine(e,n):t===n&&!this.isRemotePluginHiddenByGateway(r,t)}isRemoteDuplicateHiddenByGateway(e,t,n){return e!==void 0&&t!==void 0&&this.gatewayPluginIds.has(e)&&!this.gatewayMachineSpecificPluginIds.has(e)&&!n}isRemotePluginHiddenByGateway(e,t){return e===void 0||this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0?!1:this.gatewayPluginIds.has(e)}isGatewayPluginHiddenForMachine(e,t){return t!==`local`&&(this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0)}parseShortcutAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e),i=r.find(e=>!Uy(e));if(i!==void 0)throw Error(`Invalid shortcut alias for ${e}: ${i}`);return r.filter(Uy)}parseRouteAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e);for(let t of r)if(!Ay.test(t))throw Error(`Invalid workspace panel route alias for ${e}: ${t}`);return r}validatePluginId(e){if(!Dy.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!Oy.test(e))throw Error(`Invalid contribution id: ${e}`)}parseBackendRevision(e,t){if(t!==void 0)try{return by(t)}catch{throw Error(`Invalid plugin backend revision for ${e}`)}}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${Wy(t)}`);return t}};function Fy(e,t){return jy.get(e)?.(t)??e}function Iy(e,t){return My.get(e)?.(t)??e}function Ly(e,t){return Ny.get(e)?.(t)??e}function Ry(e,t){return jy.set(e,t),e}function zy(e,t){return My.set(e,t),e}function By(e,t){return Ny.set(e,t),e}function Vy(e,t,n){return Object.freeze({registrationPluginId:e,sourcePluginId:t??e,...n===void 0?{}:{backendRevision:n}})}function Hy(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function Uy(e){return ky.test(e)}function Wy(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 Gy(e){return e.state.selectedMachine?.id??`local`}var Ky=/^[a-z][a-z0-9.-]*$/u;function qy(e){return Ky.test(e)}function Jy(e){return e===`core`}function Yy(e,t){if(!qy(e.pluginId))throw Error(`Invalid PI WEB plugin id: ${e.pluginId}`);if(e.machineId===``)throw Error(`Machine id is required`);if(e.projectId===``)throw Error(`Project id is required`);if(e.workspaceId===``)throw Error(`Workspace id is required`);let n=yy(t);return`${e.machineId===`local`?`api`:`api/machines/${encodeURIComponent(e.machineId)}`}/plugin-backends/${encodeURIComponent(e.pluginId)}/projects/${encodeURIComponent(e.projectId)}/workspaces/${encodeURIComponent(e.workspaceId)}/${encodeURIComponent(n)}`}async function Xy(e,t,n){let r=by(e.backendRevision),i=xy(n,`Plugin backend request input`),a=JSON.stringify({revision:r,input:i});if(Cy(a)>266240)throw Error(`Plugin backend request exceeds the ${String(my)} byte wire limit`);let o;try{o=await fetch(Pt(Yy(e,t)),{method:`POST`,headers:{"content-type":`application/json`},body:a})}catch(e){throw Error(`Plugin backend request unavailable: ${eb(e)}`,{cause:e})}let s=await Zy(o);if(!o.ok)throw Error($y(s)??`Plugin backend request returned HTTP ${String(o.status)}`);return Sy(s,`Plugin backend response`,py)}async function Zy(e){let t=e.headers.get(`content-length`);if(t!==null&&/^\d+$/u.test(t)&&Number(t)>8392704)throw await e.body?.cancel(),Error(`Plugin backend response exceeds the ${String(hy)} byte wire limit`);if(e.body===null){let t=await e.text();if(Cy(t)>8392704)throw Qy();return t}let n=e.body.getReader(),r=new TextDecoder,i=0,a=``;try{let e=await n.read();for(;!e.done;){if(i+=e.value.byteLength,i>8392704)throw await n.cancel(),Qy();a+=r.decode(e.value,{stream:!0}),e=await n.read()}return a+r.decode()}finally{n.releaseLock()}}function Qy(){return Error(`Plugin backend response exceeds the ${String(hy)} byte wire limit`)}function $y(e){try{let t=JSON.parse(e);return tb(t)&&typeof t.error==`string`?t.error:void 0}catch{return}}function eb(e){return e instanceof Error?e.message:String(e)}function tb(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function nb(e,t,n,r=Xy){let i=e.backendRevision;if(i!==void 0)return{request:(a,o)=>r({pluginId:e.sourcePluginId,backendRevision:i,machineId:n,projectId:t.projectId,workspaceId:t.id},a,o)}}var rb=`machine.`;function ib(e,t){if(e===``)throw Error(`Machine id is required`);if(!qy(t))throw Error(`Invalid PI WEB plugin id: ${t}`);return`${rb}${ab(e)}.${t}`}function ab(e){return[...new TextEncoder().encode(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function ob(e=`pi-web-plugins/manifest.json`,t={}){let n=Dt(e),r=await lb(n);if(r===void 0)return{registrations:[],failures:[]};let i=[],a=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=sb(e.module,n),a=mb(await(t.moduleLoader??cb)(r),r);i.push({id:t.machineId===void 0?e.id:ib(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...e.backendRevision===void 0?{}:{backendRevision:e.backendRevision},...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){a.push({entry:e,error:t})}return{registrations:i,failures:a}}function sb(e,t,n){return e.startsWith(`/`)?n===void 0?Dt(e):Dt(e,n):new URL(e,t).toString()}async function cb(e){return Tv(()=>import(e),[],import.meta.url)}async function lb(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(await db(t));return ub(await t.json())}}function ub(e){if(!gb(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);let t=e.plugins.map(e=>{if(!gb(e)||typeof e.id!=`string`||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);let t=e.id;if(!qy(t))throw Error(`Invalid plugin manifest id: ${t}`);if(Jy(t))throw Error(`Reserved plugin manifest id: ${t}`);return{id:t,module:e.module,...fb(e.backendRevision),machineSpecific:pb(e.machineSpecific)}}),n=new Set;for(let e of t){if(n.has(e.id))throw Error(`Duplicate plugin manifest id: ${e.id}`);n.add(e.id)}return{plugins:t}}async function db(e){let t;try{let n=await e.json();if(gb(n)){let e=n.error,r=n.detail;t=typeof r==`string`?`${typeof e==`string`?`${e}: `:``}${r}`:typeof e==`string`?e:void 0}}catch{}return`Failed to load plugin manifest (${`${String(e.status)}${e.statusText===``?``:` ${e.statusText}`}`})${t===void 0?``:`: ${t}`}`}function fb(e){if(e===void 0)return{};try{return{backendRevision:by(e)}}catch{throw Error(`Invalid plugin manifest entry`)}}function pb(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function mb(e,t){if(!gb(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(gb(n)&&n.apiVersion!==2)throw Error(`Unsupported browser plugin API version for ${t}: ${String(n.apiVersion)} (expected 2)`);if(!hb(n))throw Error(`Plugin module ${t} default export is not a PiWebPlugin`);return n}function hb(e){return gb(e)&&e.apiVersion===2&&typeof e.name==`string`&&typeof e.activate==`function`}function gb(e){return typeof e==`object`&&!!e}var _b=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 插件`,async()=>(await ob()).registrations),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 插件`,async()=>(await ob(`api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.shouldLoadRemotePlugin(e.id,e.machineSpecific)})).registrations).then(t=>{t&&this.loadedMachineIds.add(e.id)}).finally(()=>{this.machineLoads.delete(e.id)});this.machineLoads.set(e.id,n),await n}},vb=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function yb(){return typeof window>`u`||!(`matchMedia`in window)?[]:vb.map(e=>window.matchMedia(e))}function bb(e,t=xb()){return e.some(e=>e.matches)||Sb(t)}function xb(){return typeof navigator>`u`?void 0:navigator}function Sb(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var Cb=class{constructor(e=wb()){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 wb(){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 Tb=`(max-width: 760px)`,Eb=`(max-width: 1180px)`,Db=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=bb(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??Ob(),this.stackedWorkspaceMedia=t.stackedWorkspaceMedia??kb(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??yb(),this.viewportPositionRepairer=t.viewportPositionRepairer??new Cb,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=bb(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 Ab(e,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:t})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function Ob(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(Tb)}function kb(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(Eb)}function Ab(e,t){let n=e??(t.isMobileNavigationLayout?`navigation`:`chat`);return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||n===`navigation`||n===`chat`?n:`chat`}var jb=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new Us,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??Mb(),this.documentTarget=t.documentTarget??Nb(),this.isDocumentVisible=t.isDocumentVisible??Pb,this.scheduleFrame=t.scheduleFrame??Fb}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 Mb(){return typeof window>`u`?void 0:window}function Nb(){return typeof document>`u`?void 0:document}function Pb(){return typeof document>`u`||document.visibilityState===`visible`}function Fb(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 Ib=[`machines`,`projects`,`workspaces`,`sessions`];function Lb(e){return e.selectedProject===void 0?`projects`:e.selectedWorkspace===void 0?`workspaces`:`sessions`}function Rb(e,t){if(e!==`none`)return e??Lb(t)}function zb(e,t){return t.isMobileLayout?Rb(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Bb(e,t,n){return n.isMobileLayout?Rb(e,n.state)===t?`none`:t:e}function Vb(e,t,n){return n?t:e}function Hb(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Gb(n)}function Ub(e){return Ib[Ib.indexOf(e)+1]}var Wb=class{hostConnected(){}constructor(e,t,n){this.host=e,this.getState=t,this.isMobileLayout=n,this.collapsedSections=[],e.addController(this)}expandedSection(){return Rb(this.expanded,this.getState())}isCollapsed(e){return zb(e,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(e){if(this.isMobileLayout()){this.setExpanded(Bb(this.expanded,e,{isMobileLayout:!0,state:this.getState()}));return}this.setCollapsedSections(Hb(this.collapsedSections,e))}expand(e){if(this.isMobileLayout()){this.setExpanded(Vb(this.expanded,e,!0));return}this.setCollapsedSections(this.collapsedSections.filter(t=>t!==e))}advanceAfterSelection(e){if(!this.isMobileLayout())return;let t=Ub(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){Kb(this.collapsedSections,e)||(this.collapsedSections=e,this.host.requestUpdate())}};function Gb(e){let t=new Set(e);return Ib.filter(e=>t.has(e))}function Kb(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var qb=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`,Jb(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...this.workspacePanelCollapsed?[`workspace-panel-collapsed`]:[]].join(` `)}};function Jb(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var Yb=`pi-web:panel-sizes:v1`,Xb={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},Zb=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??dx(),this.panelSizes=rx(this.storage)}hostConnected(){}constraints(e){return Qb(e)}panelWidth(e,t){return nx(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=nx(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=sx(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=cx(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(){ix(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${ux(nx(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${ux(nx(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function Qb(e){return Xb[e]}function $b(e,t,n){return e===`navigation`?n-t:t-n}function ex(e,t,n,r,i=Qb(e)){return nx(e,t+$b(e,n,r),i)}function tx(e,t,n,r={}){let i=r.constraints??Qb(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=lx(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return nx(e,t+a,i)}function nx(e,t,n=Qb(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function rx(e=dx()){try{let t=e?.getItem(Yb);return t==null||t===``?{}:ax(JSON.parse(t))}catch{return{}}}function ix(e,t=dx()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Yb);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=nx(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=nx(`workspace`,e.workspacePanelWidth)),t.setItem(Yb,JSON.stringify(n))}catch{}}function ax(e){if(!fx(e)||e.version!==1)return{};let t={},n=ox(e.navigationPanelWidth),r=ox(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=nx(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=nx(`workspace`,r)),t}function ox(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function sx(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function cx(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function lx(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 ux(e){return`${String(Math.round(e))}px`}function dx(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function fx(e){return typeof e==`object`&&!!e}function px(){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:hx(e.get(`tool`)),view:gx(e.get(`view`))}}function mx(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 hx(e){return e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:_x(e)?e:void 0}function gx(e){return e===`chat`?`chat`:e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:_x(e)?e:void 0}function _x(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function vx(){return bx(new URLSearchParams(window.location.search).get(`settings`))}function yx(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 bx(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 xx(e,t){return t===void 0?e:e.map(e=>Cx(e,t))}function Sx(e,t){let n=new Set(Op(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return xx(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?wx(e):e)}function Cx(e,t){if(!Object.hasOwn(t,e.id))return e;let n=t[e.id];return n===void 0?e:n===null?wx(e):{...e,shortcut:n}}function wx(e){let t={...e};return delete t.shortcut,t}function Tx(e,t){let n=t.api??Mo,r=t.pollIntervalMs??1e3,i=t.setTimeout??Ox(),a=t.clearTimeout??kx();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:Ex(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function Ex(e,t,n,r,i){return Dx(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&&Dx(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function Dx(e){return e.status===`succeeded`||e.status===`failed`}function Ox(){return(e,t)=>globalThis.setTimeout(e,t)}function kx(){return e=>{globalThis.clearTimeout(e)}}function Ax(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 jx(e,t=`活动中`,n){let r=Ax(e,t,n);if(r!==void 0)return g`<span class="action-activity">${r}</span>`}function Mx(e){if(e!==void 0)return e[sn.working]===!0?`session`:e[sn.terminal]===!0?`terminal`:Object.entries(e).some(([e,t])=>t&&e!==sn.unread)?`session`:void 0}function Nx(e){return e?.[sn.unread]===!0}var Px=0,Fx=120;function Ix(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?Rx():Lx(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-Px,f=n.top-c-Px;return[...d<Fx&&f>d?[`bottom: ${zx(a-n.top+Px)};`,`max-height: ${zx(Math.max(0,f))};`]:[`top: ${zx(n.bottom+Px)};`,`max-height: ${zx(Math.max(0,d))};`],`right: ${zx(Math.max(0,i-u))};`,`max-width: ${zx(Math.max(0,u-o))};`].join(` `)}function Lx(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Rx()}function Rx(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function zx(e){return`${String(Math.round(e))}px`}var Bx=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=Ix(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)}},Vx=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function Hx(e){return e.composedPath().some(e=>Ux(e,Vx))}function Ux(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 Wx(e,t){Hx(e)||t()}function Gx(e,t){return Hx(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?qx(e,()=>{Jx(e.currentTarget,-1)}):e.key===`ArrowDown`?qx(e,()=>{Jx(e.currentTarget,1)}):e.key===`Home`?qx(e,()=>{Yx(e.currentTarget,0)}):e.key===`End`?qx(e,()=>{Yx(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?qx(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?qx(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&qx(e,t.cancel)}function Kx(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 qx(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function Jx(e,t){let n=Zx(e),r=$x(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||Xx(n,i+t)}function Yx(e,t){let n=Zx(e);n.length!==0&&Xx(n,t<0?n.length-1:t)}function Xx(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function Zx(e){let t=$x(e)?.getRootNode();return t===void 0||!Qx(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function Qx(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function $x(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var eS=h`
|
|
948
|
+
`]}};W([x({attribute:!1})],Lv.prototype,`context`,void 0),W([C(`#workspace-upload-input`)],Lv.prototype,`uploadInput`,void 0),W([C(`.dialog-backdrop`)],Lv.prototype,`uploadDialogBackdrop`,void 0),W([C(`.upload-dialog`)],Lv.prototype,`uploadDialog`,void 0),W([S()],Lv.prototype,`pendingUpload`,void 0),W([S()],Lv.prototype,`destinationFolder`,void 0),W([S()],Lv.prototype,`overwrite`,void 0),W([S()],Lv.prototype,`createDirs`,void 0),W([S()],Lv.prototype,`formError`,void 0),W([S()],Lv.prototype,`dragActive`,void 0),W([S()],Lv.prototype,`visibleRows`,void 0),Lv=W([b(`workspace-files-panel`)],Lv);function Rv(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 zv(e,t){if(e.length===0)return`请至少选择一个要上传的文件。`;for(let n of e)try{Yo(t,n.name)}catch(e){return e instanceof Error?e.message:String(e)}}function Bv(e){return{destinationFolder:e,createDirs:!0,overwrite:!1}}function Vv(e,t,n){if(n!==void 0)return qv(e,t,n)?.type}function Hv(e,t){let n=[],r=(e,i)=>{for(let a of e){n.push({entry:a,depth:i});let e=t[a.path];e!==void 0&&r(e,i+1)}};return r(e,0),n}function Uv(e,t,n){if(e===void 0||e===``)return n;if(t===`directory`)return Yv(e,n);let r=Jv(e);return r===``?n:Yv(r,n)}function Wv(e,t){if(t.length!==0)return e.onStartWorkspaceUpload(t,{destinationFolder:e.workspaceUploadDefaultFolder,createDirs:!0,overwrite:!1,selectUploadedFile:!0})}function Gv(e){return`${e.machine.id}:${e.workspace.projectId}:${e.workspace.id}`}function Kv(e,t){let n=window.prompt(e,t);if(n===null)return;let r=n.trim();return r===``?void 0:r}function qv(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}}function Jv(e){let t=e.lastIndexOf(`/`);return t<0?``:e.slice(0,t)}function Yv(e,t){return e===``?t:`${e.replace(/\/+$/u,``)}/${t.replace(/^\/+/u,``)}`}function Xv(e){return e==null?[]:Array.from(e)}function Zv(e){return Array.from(e.dataTransfer?.types??[]).includes(`Files`)}function Qv(e){let t=e.filter(e=>e.status===`uploading`).length;return t===0?`最近 ${String(e.length)} 项`:`${String(t)} 项正在上传`}function $v(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 ey(e){switch(e.status){case`completed`:return`完成`;case`error`:return`失败`;case`cancelled`:return`已取消`;case`uploading`:return iy(e.percent)}}function ty(e){return e.status===`uploading`?e.percent:1}function ny(e){switch(e.status){case`pending`:return`等待中`;case`uploading`:return iy(e.percent);case`completed`:return`完成`;case`error`:return`错误`;case`cancelled`:return`已取消`}}function ry(e){return e.error===void 0?e.response===void 0?`${e.path} · ${Nh(e.loaded)} / ${Nh(e.total)}`:`已写入 ${e.response.path}`:e.error}function iy(e){return`${String(Math.round(Math.max(0,Math.min(1,e))*100))}%`}function ay(e){let t=e.getRootNode();return t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host:e}function oy(){return[{id:`workspace.files`,title:`文件`,icon:jh(`files`),order:10,render:sy},{id:`workspace.terminal`,title:`终端`,icon:jh(`terminal`),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:cy}]}function sy(e){return g`<workspace-files-panel .context=${e}></workspace-files-panel>`}function cy(e){return ly(),g`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function ly(){Ov(()=>import(`./TerminalPanel-B_EaRPHY.js`),__vite__mapDeps([4,5,6]),import.meta.url)}var uy={apiVersion:2,name:`PI WEB 核心`,activate:()=>{let e=!_t();return{contributions:{actions:e?yh():yh().filter(e=>e.id!==`view.terminal`),workspacePanels:e?oy():oy().filter(e=>e.id!==`workspace.terminal`)}}}},dy={"--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`},fy={"--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`},py={"--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`},my={apiVersion:2,name:`PI WEB 主题`,activate:()=>({contributions:{themes:[{id:`pi-web-dark`,name:`PI WEB 深色`,description:`PI WEB 深色配色。`,order:10,colorScheme:`dark`,tokens:fy},{id:`pi-web-light`,name:`PI WEB 浅色`,description:`PI WEB 浅色配色。`,order:20,colorScheme:`light`,tokens:py},{id:`classic`,name:`PI WEB 经典`,description:`原始 PI WEB 深色配色。`,order:30,colorScheme:`dark`,tokens:dy}],themePairs:[{id:`pi-web`,name:`PI WEB`,description:`跟随系统浅色/深色偏好使用 PI WEB 主题。`,order:10,light:`pi-web-light`,dark:`pi-web-dark`}]}})},hy=256*1024,gy=8*1024*1024,_y=266240,vy=8392704,yy=/^[a-z][a-z0-9.-]*$/u,by=64;function xy(e){return e.length<=128&&yy.test(e)}function Sy(e){if(!xy(e))throw Error(`Plugin backend operation must match ${String(yy)} and be at most 128 characters`);return e}function Cy(e){if(typeof e!=`string`||e===``||e.length>512)throw Error(`Plugin backend revision must be a non-empty string of at most 512 characters`);return e}function wy(e,t,n=hy){let r=Dy(e,new Set,t,0);if(Ey(JSON.stringify(r))>n)throw Error(`${t} exceeds the ${String(n)} byte limit`);return r}function Ty(e,t,n=hy){if(Ey(e)>n)throw Error(`${t} exceeds the ${String(n)} byte limit`);let r;try{r=JSON.parse(e)}catch(e){throw Error(`${t} must be valid JSON`,{cause:e})}return wy(r,t,n)}function Ey(e){return new TextEncoder().encode(e).byteLength}function Dy(e,t,n,r){if(r>by)throw Error(`${n} exceeds the maximum JSON depth of ${String(by)}`);if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`){if(!Number.isFinite(e))throw Error(`${n} must contain only finite JSON numbers`);return e}if(Array.isArray(e)){if(t.has(e))throw Error(`${n} must not contain cycles`);t.add(e);let i=e.map(e=>Dy(e,t,n,r+1));return t.delete(e),Object.freeze(i),i}if(!ky(e))throw Error(`${n} must contain only JSON values`);if(t.has(e))throw Error(`${n} must not contain cycles`);t.add(e);let i={};for(let[a,o]of Object.entries(e))Oy(i,a,Dy(o,t,n,r+1));return t.delete(e),Object.freeze(i)}function Oy(e,t,n){Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0})}function ky(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}var Ay=/^[a-z][a-z0-9.-]*$/u,jy=/^[a-z][a-z0-9.-]*$/u,My=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u,Ny=/^[a-z][a-z0-9.-]*(?::[a-z][a-z0-9.-]*)?$/u,Py=new WeakMap,Fy=new WeakMap,Iy=new WeakMap,Ly=class{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.registeringPluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set}register(e){let{plugin:t}=e,n=e.id,r=e.sourcePluginId??n;this.validatePluginId(n),this.validatePluginId(r);let i=this.parseMachineSpecific(n,e.machineSpecific),a=this.parseBackendRevision(n,e.backendRevision);if(this.pluginIds.has(n)||this.registeringPluginIds.has(n))throw Error(`Duplicate plugin id: ${n}`);if(!this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId,e.machineId,i)){this.registeringPluginIds.add(n);try{let o=t.apiVersion;if(o!==2)throw Error(`Unsupported browser plugin API version for ${r}: ${String(o)} (expected 2)`);let s=t.activate(Object.freeze({apiVersion:2,pluginId:r,runtimePluginId:n,html:g,svg:_})).contributions,c=new Set,l=(s.actions??[]).map(t=>this.qualifyAction(n,t,e.machineId,e.sourcePluginId,c)),u=(s.workspacePanels??[]).map(t=>this.qualifyWorkspacePanel(n,t,e.machineId,e.sourcePluginId,a,c)),d=(s.workspaceLabels??[]).map(t=>this.qualifyWorkspaceLabelContribution(n,t,e.machineId,e.sourcePluginId,a,c)),f=e.machineId===void 0?(s.themes??[]).map(e=>this.qualifyTheme(n,e,c)):[],p=e.machineId===void 0?(s.themePairs??[]).map(e=>this.qualifyThemePair(n,e,c)):[];this.pluginIds.add(n);for(let e of c)this.contributionIds.add(e);this.actions.push(...l),this.workspacePanels.push(...u),this.workspaceLabels.push(...d),this.themes.push(...f),this.themePairs.push(...p),e.machineId===void 0?(this.gatewayPluginIds.add(n),i&&this.gatewayMachineSpecificPluginIds.add(n)):e.sourcePluginId!==void 0&&i&&Gy(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId)}finally{this.registeringPluginIds.delete(n)}}}hasPlugin(e){return this.pluginIds.has(e)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=Jy(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=Ry(e,t.pluginId),r=t.enabled?.(n),i=r===!1?t.disabledReason?.(n):void 0,a={id:t.id,pluginId:t.pluginId,localId:t.localId,...t.machineId===void 0?{}:{machineId:t.machineId},title:t.title,run:()=>t.run(n)};return t.description!==void 0&&(a.description=t.description),t.shortcut!==void 0&&(a.shortcut=t.shortcut),t.shortcutAliases!==void 0&&(a.shortcutAliases=[...t.shortcutAliases]),t.group!==void 0&&(a.group=t.group),r!==void 0&&(a.enabled=r),i!==void 0&&i!==``&&(a.disabledReason=i),a})}getWorkspacePanels(){return[...this.workspacePanels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}resolveWorkspacePanelRouteId(e,t){let n=this.workspacePanels.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)),r=n.find(t=>t.id===e);if(r!==void 0)return r.id;let i=n.filter(t=>t.routeAliases?.includes(e)===!0);if(i.length===1)return i[0]?.id;i.length>1&&console.warn(`Ambiguous PI WEB workspace panel route: ${e}`)}async invalidateWorkspacePanels(e,t){await Promise.all(this.workspacePanels.map(async n=>{if(!(n.onInvalidate===void 0||t!==void 0&&n.id!==t))try{await n.onInvalidate(e)}catch(e){console.warn(`Failed to invalidate PI WEB plugin panel ${n.id}`,e)}}))}getThemes(){return[...this.themes].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getThemePairs(){return[...this.themePairs].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getWorkspaceLabelItems(e){return[...this.workspaceLabels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.id.localeCompare(t.id)).flatMap(t=>t.visible?.(e)===!1?[]:t.items(e))}qualifyAction(e,t,n,r,i){let a=this.qualify(e,t.id,i),o=`${r??e}:${t.id}`,s=this.parseShortcutAliases(a,t.shortcutAliases,o);return{...t,id:a,pluginId:e,localId:t.id,...s.length===0?{}:{shortcutAliases:s},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyWorkspacePanel(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.badge,c=t.visible,l=t.onInvalidate,u=Wy(e,r,i),d=`${r??e}:${t.id}`,f=this.parseRouteAliases(o,t.routeAliases,d);return{...t,id:o,pluginId:e,localId:t.id,...f.length===0?{}:{routeAliases:f},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(c?.(zy(t,u))??!0),...s===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?s(zy(t,u)):void 0},...l===void 0?{}:{onInvalidate:t=>this.isContributionActive(e,n,t.machine.id,r)?l(zy(t,u)):void 0},render:e=>t.render(zy(e,u))}}qualifyWorkspaceLabelContribution(e,t,n,r,i,a){let o=this.qualify(e,t.id,a),s=t.visible,c=t.items,l=Wy(e,r,i);return{...t,id:o,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(s?.(By(t,l))??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?c(By(t,l)):[]}}qualifyTheme(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id}}qualifyThemePair(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t,n){this.validateLocalId(t);let r=`${e}:${t}`;if(this.contributionIds.has(r)||n.has(r))throw Error(`Duplicate contribution id: ${r}`);return n.add(r),r}qualifyReference(e,t){return this.validateLocalId(t),`${e}:${t}`}isContributionActive(e,t,n,r){return t===void 0?!this.isGatewayPluginHiddenForMachine(e,n):t===n&&!this.isRemotePluginHiddenByGateway(r,t)}isRemoteDuplicateHiddenByGateway(e,t,n){return e!==void 0&&t!==void 0&&this.gatewayPluginIds.has(e)&&!this.gatewayMachineSpecificPluginIds.has(e)&&!n}isRemotePluginHiddenByGateway(e,t){return e===void 0||this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0?!1:this.gatewayPluginIds.has(e)}isGatewayPluginHiddenForMachine(e,t){return t!==`local`&&(this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0)}parseShortcutAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e),i=r.find(e=>!Ky(e));if(i!==void 0)throw Error(`Invalid shortcut alias for ${e}: ${i}`);return r.filter(Ky)}parseRouteAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e);for(let t of r)if(!Ny.test(t))throw Error(`Invalid workspace panel route alias for ${e}: ${t}`);return r}validatePluginId(e){if(!Ay.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!jy.test(e))throw Error(`Invalid contribution id: ${e}`)}parseBackendRevision(e,t){if(t!==void 0)try{return Cy(t)}catch{throw Error(`Invalid plugin backend revision for ${e}`)}}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${qy(t)}`);return t}};function Ry(e,t){return Py.get(e)?.(t)??e}function zy(e,t){return Fy.get(e)?.(t)??e}function By(e,t){return Iy.get(e)?.(t)??e}function Vy(e,t){return Py.set(e,t),e}function Hy(e,t){return Fy.set(e,t),e}function Uy(e,t){return Iy.set(e,t),e}function Wy(e,t,n){return Object.freeze({registrationPluginId:e,sourcePluginId:t??e,...n===void 0?{}:{backendRevision:n}})}function Gy(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function Ky(e){return My.test(e)}function qy(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 Jy(e){return e.state.selectedMachine?.id??`local`}var Yy=/^[a-z][a-z0-9.-]*$/u;function Xy(e){return Yy.test(e)}function Zy(e){return e===`core`}function Qy(e,t){if(!Xy(e.pluginId))throw Error(`Invalid PI WEB plugin id: ${e.pluginId}`);if(e.machineId===``)throw Error(`Machine id is required`);if(e.projectId===``)throw Error(`Project id is required`);if(e.workspaceId===``)throw Error(`Workspace id is required`);let n=Sy(t);return`${e.machineId===`local`?`api`:`api/machines/${encodeURIComponent(e.machineId)}`}/plugin-backends/${encodeURIComponent(e.pluginId)}/projects/${encodeURIComponent(e.projectId)}/workspaces/${encodeURIComponent(e.workspaceId)}/${encodeURIComponent(n)}`}async function $y(e,t,n){let r=Cy(e.backendRevision),i=wy(n,`Plugin backend request input`),a=JSON.stringify({revision:r,input:i});if(Ey(a)>266240)throw Error(`Plugin backend request exceeds the ${String(_y)} byte wire limit`);let o;try{o=await fetch(Pt(Qy(e,t)),{method:`POST`,headers:{"content-type":`application/json`},body:a})}catch(e){throw Error(`Plugin backend request unavailable: ${rb(e)}`,{cause:e})}let s=await eb(o);if(!o.ok)throw Error(nb(s)??`Plugin backend request returned HTTP ${String(o.status)}`);return Ty(s,`Plugin backend response`,gy)}async function eb(e){let t=e.headers.get(`content-length`);if(t!==null&&/^\d+$/u.test(t)&&Number(t)>8392704)throw await e.body?.cancel(),Error(`Plugin backend response exceeds the ${String(vy)} byte wire limit`);if(e.body===null){let t=await e.text();if(Ey(t)>8392704)throw tb();return t}let n=e.body.getReader(),r=new TextDecoder,i=0,a=``;try{let e=await n.read();for(;!e.done;){if(i+=e.value.byteLength,i>8392704)throw await n.cancel(),tb();a+=r.decode(e.value,{stream:!0}),e=await n.read()}return a+r.decode()}finally{n.releaseLock()}}function tb(){return Error(`Plugin backend response exceeds the ${String(vy)} byte wire limit`)}function nb(e){try{let t=JSON.parse(e);return ib(t)&&typeof t.error==`string`?t.error:void 0}catch{return}}function rb(e){return e instanceof Error?e.message:String(e)}function ib(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ab(e,t,n,r=$y){let i=e.backendRevision;if(i!==void 0)return{request:(a,o)=>r({pluginId:e.sourcePluginId,backendRevision:i,machineId:n,projectId:t.projectId,workspaceId:t.id},a,o)}}var ob=`machine.`;function sb(e,t){if(e===``)throw Error(`Machine id is required`);if(!Xy(t))throw Error(`Invalid PI WEB plugin id: ${t}`);return`${ob}${cb(e)}.${t}`}function cb(e){return[...new TextEncoder().encode(e)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function lb(e=`pi-web-plugins/manifest.json`,t={}){let n=Dt(e),r=await fb(n);if(r===void 0)return{registrations:[],failures:[]};let i=[],a=[];for(let e of r.plugins)if(t.shouldLoadPlugin?.(e)!==!1)try{let r=ub(e.module,n),a=_b(await(t.moduleLoader??db)(r),r);i.push({id:t.machineId===void 0?e.id:sb(t.machineId,e.id),plugin:a,machineSpecific:e.machineSpecific,...e.backendRevision===void 0?{}:{backendRevision:e.backendRevision},...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:e.id}})}catch(t){a.push({entry:e,error:t})}return{registrations:i,failures:a}}function ub(e,t,n){return e.startsWith(`/`)?n===void 0?Dt(e):Dt(e,n):new URL(e,t).toString()}async function db(e){return Ov(()=>import(e),[],import.meta.url)}async function fb(e){let t=await fetch(e,{cache:`no-store`});if(t.status!==404){if(!t.ok)throw Error(await mb(t));return pb(await t.json())}}function pb(e){if(!yb(e)||!Array.isArray(e.plugins))throw Error(`Invalid plugin manifest`);let t=e.plugins.map(e=>{if(!yb(e)||typeof e.id!=`string`||typeof e.module!=`string`||e.module===``)throw Error(`Invalid plugin manifest entry`);let t=e.id;if(!Xy(t))throw Error(`Invalid plugin manifest id: ${t}`);if(Zy(t))throw Error(`Reserved plugin manifest id: ${t}`);return{id:t,module:e.module,...hb(e.backendRevision),machineSpecific:gb(e.machineSpecific)}}),n=new Set;for(let e of t){if(n.has(e.id))throw Error(`Duplicate plugin manifest id: ${e.id}`);n.add(e.id)}return{plugins:t}}async function mb(e){let t;try{let n=await e.json();if(yb(n)){let e=n.error,r=n.detail;t=typeof r==`string`?`${typeof e==`string`?`${e}: `:``}${r}`:typeof e==`string`?e:void 0}}catch{}return`Failed to load plugin manifest (${`${String(e.status)}${e.statusText===``?``:` ${e.statusText}`}`})${t===void 0?``:`: ${t}`}`}function hb(e){if(e===void 0)return{};try{return{backendRevision:Cy(e)}}catch{throw Error(`Invalid plugin manifest entry`)}}function gb(e){if(e===void 0)return!1;if(typeof e!=`boolean`)throw Error(`Invalid plugin manifest entry`);return e}function _b(e,t){if(!yb(e))throw Error(`Plugin module ${t} did not export an object`);let n=e.default;if(yb(n)&&n.apiVersion!==2)throw Error(`Unsupported browser plugin API version for ${t}: ${String(n.apiVersion)} (expected 2)`);if(!vb(n))throw Error(`Plugin module ${t} default export is not a PiWebPlugin`);return n}function vb(e){return yb(e)&&e.apiVersion===2&&typeof e.name==`string`&&typeof e.activate==`function`}function yb(e){return typeof e==`object`&&!!e}var bb=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 插件`,async()=>(await lb()).registrations),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 插件`,async()=>(await lb(`api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.shouldLoadRemotePlugin(e.id,e.machineSpecific)})).registrations).then(t=>{t&&this.loadedMachineIds.add(e.id)}).finally(()=>{this.machineLoads.delete(e.id)});this.machineLoads.set(e.id,n),await n}},xb=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function Sb(){return typeof window>`u`||!(`matchMedia`in window)?[]:xb.map(e=>window.matchMedia(e))}function Cb(e,t=wb()){return e.some(e=>e.matches)||Tb(t)}function wb(){return typeof navigator>`u`?void 0:navigator}function Tb(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var Eb=class{constructor(e=Db()){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 Db(){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 Ob=`(max-width: 760px)`,kb=`(max-width: 1180px)`,Ab=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=Cb(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.mobileNavigationMedia=t.mobileNavigationMedia??jb(),this.stackedWorkspaceMedia=t.stackedWorkspaceMedia??Mb(),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??Sb(),this.viewportPositionRepairer=t.viewportPositionRepairer??new Eb,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isStackedWorkspaceLayout=this.stackedWorkspaceMedia?.matches??!1,this.isPwaDisplayMode=Cb(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 Nb(e,{isMobileNavigationLayout:this.isMobileNavigationLayout,isStackedWorkspaceLayout:this.isStackedWorkspaceLayout,hasSelectedSession:t})}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function jb(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(Ob)}function Mb(){if(!(typeof window>`u`||!(`matchMedia`in window)))return window.matchMedia(kb)}function Nb(e,t){let n=e??(t.isMobileNavigationLayout?`navigation`:`chat`);return t.isMobileNavigationLayout||!t.isStackedWorkspaceLayout||!t.hasSelectedSession||n===`navigation`||n===`chat`?n:`chat`}var Pb=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new Us,this.connected=!1,this.onFocus=()=>{this.handleResumeSignal()},this.onVisibilityChange=()=>{this.isDocumentVisible()&&this.handleResumeSignal()},this.windowTarget=t.windowTarget??Fb(),this.documentTarget=t.documentTarget??Ib(),this.isDocumentVisible=t.isDocumentVisible??Lb,this.scheduleFrame=t.scheduleFrame??Rb}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 Fb(){return typeof window>`u`?void 0:window}function Ib(){return typeof document>`u`?void 0:document}function Lb(){return typeof document>`u`||document.visibilityState===`visible`}function Rb(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 zb=[`machines`,`projects`,`workspaces`,`sessions`];function Bb(e){return e.selectedProject===void 0?`projects`:e.selectedWorkspace===void 0?`workspaces`:`sessions`}function Vb(e,t){if(e!==`none`)return e??Bb(t)}function Hb(e,t){return t.isMobileLayout?Vb(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Ub(e,t,n){return n.isMobileLayout?Vb(e,n.state)===t?`none`:t:e}function Wb(e,t,n){return n?t:e}function Gb(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Jb(n)}function Kb(e){return zb[zb.indexOf(e)+1]}var qb=class{hostConnected(){}constructor(e,t,n){this.host=e,this.getState=t,this.isMobileLayout=n,this.collapsedSections=[],e.addController(this)}expandedSection(){return Vb(this.expanded,this.getState())}isCollapsed(e){return Hb(e,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(e){if(this.isMobileLayout()){this.setExpanded(Ub(this.expanded,e,{isMobileLayout:!0,state:this.getState()}));return}this.setCollapsedSections(Gb(this.collapsedSections,e))}expand(e){if(this.isMobileLayout()){this.setExpanded(Wb(this.expanded,e,!0));return}this.setCollapsedSections(this.collapsedSections.filter(t=>t!==e))}advanceAfterSelection(e){if(!this.isMobileLayout())return;let t=Kb(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){Yb(this.collapsedSections,e)||(this.collapsedSections=e,this.host.requestUpdate())}};function Jb(e){let t=new Set(e);return zb.filter(e=>t.has(e))}function Yb(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var Xb=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`,Zb(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...this.workspacePanelCollapsed?[`workspace-panel-collapsed`]:[]].join(` `)}};function Zb(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}var Qb=`pi-web:panel-sizes:v1`,$b={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},ex=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??mx(),this.panelSizes=ox(this.storage)}hostConnected(){}constraints(e){return tx(e)}panelWidth(e,t){return ax(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=ax(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=ux(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=dx(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(){sx(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${px(ax(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${px(ax(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function tx(e){return $b[e]}function nx(e,t,n){return e===`navigation`?n-t:t-n}function rx(e,t,n,r,i=tx(e)){return ax(e,t+nx(e,n,r),i)}function ix(e,t,n,r={}){let i=r.constraints??tx(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=fx(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return ax(e,t+a,i)}function ax(e,t,n=tx(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function ox(e=mx()){try{let t=e?.getItem(Qb);return t==null||t===``?{}:cx(JSON.parse(t))}catch{return{}}}function sx(e,t=mx()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Qb);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=ax(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=ax(`workspace`,e.workspacePanelWidth)),t.setItem(Qb,JSON.stringify(n))}catch{}}function cx(e){if(!hx(e)||e.version!==1)return{};let t={},n=lx(e.navigationPanelWidth),r=lx(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=ax(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=ax(`workspace`,r)),t}function lx(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function ux(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function dx(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function fx(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 px(e){return`${String(Math.round(e))}px`}function mx(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function hx(e){return typeof e==`object`&&!!e}function gx(){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:vx(e.get(`tool`)),view:yx(e.get(`view`))}}function _x(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 vx(e){return e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:bx(e)?e:void 0}function yx(e){return e===`chat`?`chat`:e===`files`?`core:workspace.files`:e===`git`?`core:workspace.git`:bx(e)?e:void 0}function bx(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function xx(){return Cx(new URLSearchParams(window.location.search).get(`settings`))}function Sx(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 Cx(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 wx(e,t){return t===void 0?e:e.map(e=>Ex(e,t))}function Tx(e,t){let n=new Set(jp(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return wx(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?Dx(e):e)}function Ex(e,t){if(!Object.hasOwn(t,e.id))return e;let n=t[e.id];return n===void 0?e:n===null?Dx(e):{...e,shortcut:n}}function Dx(e){let t={...e};return delete t.shortcut,t}function Ox(e,t){let n=t.api??Mo,r=t.pollIntervalMs??1e3,i=t.setTimeout??jx(),a=t.clearTimeout??Mx();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:kx(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function kx(e,t,n,r,i){return Ax(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&&Ax(e)){l(e);return}s=r(d,n)}).catch(u)};s=r(d,n)})}function Ax(e){return e.status===`succeeded`||e.status===`failed`}function jx(){return(e,t)=>globalThis.setTimeout(e,t)}function Mx(){return e=>{globalThis.clearTimeout(e)}}function Nx(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 Px(e,t=`活动中`,n){let r=Nx(e,t,n);if(r!==void 0)return g`<span class="action-activity">${r}</span>`}function Fx(e){if(e!==void 0)return e[sn.working]===!0?`session`:e[sn.terminal]===!0?`terminal`:Object.entries(e).some(([e,t])=>t&&e!==sn.unread)?`session`:void 0}function Ix(e){return e?.[sn.unread]===!0}var Lx=0,Rx=120;function zx(e,t={}){if(typeof HTMLElement>`u`||typeof window>`u`||!(e instanceof HTMLElement))return``;let n=e.getBoundingClientRect(),r=t.constrainTo===`viewport`?Vx():Bx(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-Lx,f=n.top-c-Lx;return[...d<Rx&&f>d?[`bottom: ${Hx(a-n.top+Lx)};`,`max-height: ${Hx(Math.max(0,f))};`]:[`top: ${Hx(n.bottom+Lx)};`,`max-height: ${Hx(Math.max(0,d))};`],`right: ${Hx(Math.max(0,i-u))};`,`max-width: ${Hx(Math.max(0,u-o))};`].join(` `)}function Bx(e){let t=e.getRootNode();return typeof ShadowRoot<`u`&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Vx()}function Vx(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function Hx(e){return`${String(Math.round(e))}px`}var Ux=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=zx(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)}},Wx=[`a[href]`,`button`,`input`,`select`,`textarea`,`summary`,`[role='button']`,`[role='link']`,`[contenteditable='true']`].join(`,`);function Gx(e){return e.composedPath().some(e=>Kx(e,Wx))}function Kx(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 qx(e,t){Gx(e)||t()}function Jx(e,t){return Gx(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?Xx(e,()=>{Zx(e.currentTarget,-1)}):e.key===`ArrowDown`?Xx(e,()=>{Zx(e.currentTarget,1)}):e.key===`Home`?Xx(e,()=>{Qx(e.currentTarget,0)}):e.key===`End`?Xx(e,()=>{Qx(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?Xx(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?Xx(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&Xx(e,t.cancel)}function Yx(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 Xx(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function Zx(e,t){let n=eS(e),r=nS(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||$x(n,i+t)}function Qx(e,t){let n=eS(e);n.length!==0&&$x(n,t<0?n.length-1:t)}function $x(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function eS(e){let t=nS(e)?.getRootNode();return t===void 0||!tS(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function tS(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function nS(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))return e.closest(`.action-row`)??void 0}var rS=h`
|
|
949
949
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
950
950
|
:host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
951
951
|
section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
|
|
@@ -1012,7 +1012,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1012
1012
|
.workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
|
|
1013
1013
|
.workspace-detail-row .workspace-label-base, .workspace-detail-row .workspace-label-item, .workspace-detail-row .workspace-label-render { overflow: visible; text-overflow: clip; overflow-wrap: anywhere; white-space: normal; }
|
|
1014
1014
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
1015
|
-
`,
|
|
1015
|
+
`,iS=class extends y{constructor(...e){super(...e),this.machines=[],this.statuses={},this.activities={},this.unreadMachineIds=new Set,this.statusSnapshots={},this.collapsible=!1,this.collapsed=!1,this.menu=new Ux(this)}updated(e){e.has(`machines`)&&this.menu.closeIfOpenIdMissing(e=>this.machines.some(t=>t.id===e)),e.has(`collapsed`)&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,Yx(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
|
|
1016
1016
|
<section>
|
|
1017
1017
|
<h2>${this.renderHeading()}</h2>
|
|
1018
1018
|
${this.collapsed?null:g`
|
|
@@ -1021,12 +1021,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1021
1021
|
</div>
|
|
1022
1022
|
`}
|
|
1023
1023
|
</section>
|
|
1024
|
-
`}renderMachine(e){let t=this.statuses[e.id]?.status??e.status??`unknown`,n=t===`online`?`在线`:t===`offline`?`离线`:t===`error`?`错误`:`未知`,r=
|
|
1024
|
+
`}renderMachine(e){let t=this.statuses[e.id]?.status??e.status??`unknown`,n=t===`online`?`在线`:t===`offline`?`离线`:t===`error`?`错误`:`未知`,r=aS(e)&&this.onRemove!==void 0;return g`
|
|
1025
1025
|
<div
|
|
1026
1026
|
class=${`action-row machine-row ${this.selected?.id===e.id?`selected`:``} ${r?``:`no-actions`}`}
|
|
1027
1027
|
tabindex="0"
|
|
1028
1028
|
title=${e.baseUrl??e.name}
|
|
1029
|
-
@click=${t=>{
|
|
1029
|
+
@click=${t=>{qx(t,()=>this.onSelect?.(e))}}
|
|
1030
1030
|
@keydown=${t=>{this.handleMachineKeydown(t,e)}}
|
|
1031
1031
|
>
|
|
1032
1032
|
<div class="action-main">
|
|
@@ -1034,7 +1034,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1034
1034
|
</div>
|
|
1035
1035
|
${r?this.renderMachineMenu(e):null}
|
|
1036
1036
|
</div>
|
|
1037
|
-
`}renderActivity(e){let t=this.statuses[e.id]?.status??e.status,n=this.statusSnapshots[e.id],r=n?.machine,i=t===`offline`||t===`error`?void 0:n===void 0?Pc(this.activities[e.id]):
|
|
1037
|
+
`}renderActivity(e){let t=this.statuses[e.id]?.status??e.status,n=this.statusSnapshots[e.id],r=n?.machine,i=t===`offline`||t===`error`?void 0:n===void 0?Pc(this.activities[e.id]):Fx(r),a=n===void 0?this.unreadMachineIds.has(e.id)?`此机器上有未读会话`:void 0:Ix(r)?`此机器上有未读会话`:void 0;return Px(i,i===`terminal`?`机器终端活动中`:`机器活动中`,a)}renderMachineMenu(e){let t=this.menu.isOpen(e.id),n=oS(e.id);return g`
|
|
1038
1038
|
<div class="action-menu">
|
|
1039
1039
|
<button
|
|
1040
1040
|
class="action-menu-toggle"
|
|
@@ -1050,13 +1050,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1050
1050
|
</div>
|
|
1051
1051
|
`:null}
|
|
1052
1052
|
</div>
|
|
1053
|
-
`}renderHeading(){if(!this.collapsible)return`机器`;let e=this.selected?.name??`未选择机器`,t=this.selected?.baseUrl??e;return g`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} 机器</span>${this.collapsed?g`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}removeMachine(e){this.menu.close(),this.onRemove?.(e)}handleMachineKeydown(e,t){this.menu.closeForEscape(e,t.id)||
|
|
1053
|
+
`}renderHeading(){if(!this.collapsible)return`机器`;let e=this.selected?.name??`未选择机器`,t=this.selected?.baseUrl??e;return g`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} 机器</span>${this.collapsed?g`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}removeMachine(e){this.menu.close(),this.onRemove?.(e)}handleMachineKeydown(e,t){this.menu.closeForEscape(e,t.id)||Jx(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}static{this.styles=[rS,h`
|
|
1054
1054
|
.machine-row.no-actions .action-main { border-radius: 8px; }
|
|
1055
1055
|
.machine-primary { display: flex; align-items: baseline; gap: 6px; }
|
|
1056
1056
|
.machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
1057
1057
|
.machine-menu-panel button.danger { color: var(--pi-danger); }
|
|
1058
1058
|
.machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
|
|
1059
|
-
`]}};W([x({attribute:!1})],
|
|
1059
|
+
`]}};W([x({attribute:!1})],iS.prototype,`machines`,void 0),W([x({attribute:!1})],iS.prototype,`selected`,void 0),W([x({attribute:!1})],iS.prototype,`statuses`,void 0),W([x({attribute:!1})],iS.prototype,`activities`,void 0),W([x({attribute:!1})],iS.prototype,`unreadMachineIds`,void 0),W([x({attribute:!1})],iS.prototype,`statusSnapshots`,void 0),W([x({type:Boolean,reflect:!0})],iS.prototype,`collapsible`,void 0),W([x({type:Boolean,reflect:!0})],iS.prototype,`collapsed`,void 0),W([x({attribute:!1})],iS.prototype,`onSelect`,void 0),W([x({attribute:!1})],iS.prototype,`onRemove`,void 0),W([x({attribute:!1})],iS.prototype,`onToggleCollapsed`,void 0),W([x({attribute:!1})],iS.prototype,`onFocusNextSection`,void 0),W([x({attribute:!1})],iS.prototype,`onCancelKeyboardNavigation`,void 0),iS=W([b(`machine-list`)],iS);function aS(e){return e.kind===`remote`}function oS(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}var sS=class extends y{constructor(...e){super(...e),this.projects=[],this.activities={},this.workspacesByProjectId={},this.unreadProjectIds=new Set,this.collapsible=!1,this.collapsed=!1,this.managementMode=!1,this.menu=new Ux(this)}updated(e){e.has(`projects`)&&this.menu.closeIfOpenIdMissing(e=>this.projects.some(t=>t.id===e)),e.has(`collapsed`)&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,Yx(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
|
|
1060
1060
|
<section>
|
|
1061
1061
|
<h2>${this.renderHeading()}</h2>
|
|
1062
1062
|
${this.collapsed?null:g`
|
|
@@ -1071,7 +1071,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1071
1071
|
class=${`action-row ${this.selected?.id===e.id?`selected`:``}`}
|
|
1072
1072
|
tabindex="0"
|
|
1073
1073
|
title=${e.path}
|
|
1074
|
-
@click=${t=>{
|
|
1074
|
+
@click=${t=>{qx(t,()=>this.onSelect?.(e))}}
|
|
1075
1075
|
@keydown=${t=>{this.handleProjectKeydown(t,e)}}
|
|
1076
1076
|
>
|
|
1077
1077
|
<div class="action-main">
|
|
@@ -1091,17 +1091,17 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1091
1091
|
</div>
|
|
1092
1092
|
`}
|
|
1093
1093
|
</section>
|
|
1094
|
-
`}handleProjectKeydown(e,t){
|
|
1094
|
+
`}handleProjectKeydown(e,t){Jx(e,{activate:()=>this.onSelect?.(t),previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}renderHeading(){if(!this.collapsible)return`项目`;let e=this.selected?.name??`未选择项目`,t=this.selected?.path??e;return g`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} 项目</span>${this.collapsed?g`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){let t=this.statusSnapshot?.projects[e.id],n=this.statusSnapshot===void 0?Mc(e,this.workspacesByProjectId[e.id]??[],this.activities):Fx(t),r=this.statusSnapshot===void 0?this.unreadProjectIds.has(e.id)?`此项目中有未读会话`:void 0:Ix(t)?`此项目中有未读会话`:void 0;return Px(n,n===`terminal`?`项目终端活动中`:`项目活动中`,r)}close(e){this.menu.close(),confirm(`关闭 ${e.name}?\n\n这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}static{this.styles=rS}};W([x({attribute:!1})],sS.prototype,`projects`,void 0),W([x({attribute:!1})],sS.prototype,`selected`,void 0),W([x({attribute:!1})],sS.prototype,`activities`,void 0),W([x({attribute:!1})],sS.prototype,`workspacesByProjectId`,void 0),W([x({attribute:!1})],sS.prototype,`unreadProjectIds`,void 0),W([x({attribute:!1})],sS.prototype,`statusSnapshot`,void 0),W([x({type:Boolean,reflect:!0})],sS.prototype,`collapsible`,void 0),W([x({type:Boolean,reflect:!0})],sS.prototype,`collapsed`,void 0),W([x({type:Boolean})],sS.prototype,`managementMode`,void 0),W([x({attribute:!1})],sS.prototype,`onSelect`,void 0),W([x({attribute:!1})],sS.prototype,`onClose`,void 0),W([x({attribute:!1})],sS.prototype,`onToggleCollapsed`,void 0),W([x({attribute:!1})],sS.prototype,`onFocusPreviousSection`,void 0),W([x({attribute:!1})],sS.prototype,`onFocusNextSection`,void 0),W([x({attribute:!1})],sS.prototype,`onCancelKeyboardNavigation`,void 0),sS=W([b(`project-list`)],sS);async function cS(e,t=lS()){if(!t.isSecureContext)return t.fallbackWriteText(e);if(t.writeText!==void 0)try{return await t.writeText(e),!0}catch{return t.fallbackWriteText(e)}return t.fallbackWriteText(e)}function lS(){let e=e=>fS(e),t=dS();return t===void 0?{isSecureContext:uS(),fallbackWriteText:e}:{isSecureContext:uS(),writeText:t,fallbackWriteText:e}}function uS(){return typeof window<`u`&&window.isSecureContext}function dS(){if(!(typeof navigator>`u`||!(`clipboard`in navigator)))return navigator.clipboard.writeText.bind(navigator.clipboard)}function fS(e){if(typeof document>`u`)return!1;let t=document.activeElement,n=document.getSelection(),r=n===null?[]:pS(n),i=document.createElement(`textarea`);i.value=e,i.readOnly=!0,i.setAttribute(`aria-hidden`,`true`),i.style.position=`fixed`,i.style.top=`0`,i.style.left=`-9999px`,i.style.width=`1px`,i.style.height=`1px`,i.style.padding=`0`,i.style.border=`0`,i.style.opacity=`0`,i.style.pointerEvents=`none`,document.body.append(i),i.focus(),i.select(),i.setSelectionRange(0,i.value.length);try{return document.execCommand(`copy`)}catch{return!1}finally{i.remove(),mS(n,r),hS(t)}}function pS(e){let t=[];for(let n=0;n<e.rangeCount;n+=1)t.push(e.getRangeAt(n));return t}function mS(e,t){if(e!==null)try{e.removeAllRanges();for(let n of t)e.addRange(n)}catch{}}function hS(e){if(!(typeof HTMLElement>`u`||!(e instanceof HTMLElement)))try{e.focus({preventScroll:!0})}catch{e.focus()}}function gS(e=[]){return e.map((e,t)=>g`${t===0?null:g`<span class="workspace-label-separator">·</span>`}${_S(e)}`)}function _S(e){if(e.type===`render`)return g`<span class="workspace-label-render">${e.render()}</span>`;if(e.type===`link`&&vS(e.href)){let t=e.target??`_blank`,n=t===`_blank`?`noopener noreferrer`:void 0;return g`<a class="workspace-label-item workspace-label-link" href=${e.href} title=${e.title??e.text} target=${t} rel=${n??void 0}>${e.text}</a>`}return g`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function vS(e){let t=e.trim().toLowerCase();return t!==``&&!t.startsWith(`javascript:`)&&!t.startsWith(`data:`)}var G=class extends y{constructor(...e){super(...e),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.unreadWorkspaceIds=new Set,this.menuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuWorkspaceId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.onDocumentClick)}disconnectedCallback(){document.removeEventListener(`click`,this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has(`workspaces`)&&this.openMenuWorkspaceId!==void 0&&!this.workspaces.some(e=>e.id===this.openMenuWorkspaceId)&&(this.openMenuWorkspaceId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuWorkspaceId=void 0),this.shouldRevealSelectedRow(e)&&this.scrollSelectedIntoView()}shouldRevealSelectedRow(e){return this.collapsed?!1:e.has(`collapsed`)?!0:e.has(`selected`)&&e.get(`selected`)?.id!==this.selected?.id}async focusSelectedOrFirst(){return await this.updateComplete,Yx(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return g`
|
|
1095
1095
|
<section>
|
|
1096
1096
|
<h2>${this.renderHeading()}</h2>
|
|
1097
1097
|
${this.collapsed?null:g`
|
|
1098
1098
|
<div class="list-body">
|
|
1099
|
-
${this.workspaces.map(e=>{let t=
|
|
1099
|
+
${this.workspaces.map(e=>{let t=yS(e),n=this.workspaceLabelItems(e);return g`
|
|
1100
1100
|
<div
|
|
1101
1101
|
class=${`action-row workspace-row ${this.selected?.id===e.id?`selected`:``}`}
|
|
1102
1102
|
tabindex="0"
|
|
1103
1103
|
title=${t}
|
|
1104
|
-
@click=${t=>{
|
|
1104
|
+
@click=${t=>{qx(t,()=>this.onSelect?.(e))}}
|
|
1105
1105
|
@keydown=${t=>{this.handleWorkspaceKeydown(t,e)}}
|
|
1106
1106
|
>
|
|
1107
1107
|
<div class="action-main">
|
|
@@ -1113,18 +1113,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1113
1113
|
</div>
|
|
1114
1114
|
`}
|
|
1115
1115
|
</section>
|
|
1116
|
-
`}renderHeading(){if(!this.collapsible)return g`<span>工作区</span>`;let e=this.selected===void 0?`未选择工作区`:`${this.selected.label}${this.selected.isMain?` · main`:``} · ${this.selected.path}`,t=this.selected?.path??e;return g`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} 工作区</span>${this.collapsed?g`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){let t=this.statusSnapshot?.workspaces[e.id],n=this.statusSnapshot===void 0?jc(Ac(e,this.activities)):
|
|
1116
|
+
`}renderHeading(){if(!this.collapsible)return g`<span>工作区</span>`;let e=this.selected===void 0?`未选择工作区`:`${this.selected.label}${this.selected.isMain?` · main`:``} · ${this.selected.path}`,t=this.selected?.path??e;return g`<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} 工作区</span>${this.collapsed?g`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){let t=this.statusSnapshot?.workspaces[e.id],n=this.statusSnapshot===void 0?jc(Ac(e,this.activities)):Fx(t),r=this.statusSnapshot===void 0?this.unreadWorkspaceIds.has(e.id)?`此工作区中有未读会话`:void 0:Ix(t)?`此工作区中有未读会话`:void 0;return Px(n,n===`terminal`?`工作区终端活动中`:`工作区活动中`,r)}renderWorkspaceMain(e,t,n){return g`
|
|
1117
1117
|
<span class="workspace-primary">
|
|
1118
1118
|
<span class="workspace-primary-label">${e}</span>
|
|
1119
1119
|
${this.isDeleting(n)?g`<span class="workspace-status">正在删除…</span>`:null}
|
|
1120
1120
|
</span>
|
|
1121
1121
|
${t.length===0?null:g`
|
|
1122
1122
|
<small class="workspace-secondary">
|
|
1123
|
-
<span class="workspace-label">${
|
|
1123
|
+
<span class="workspace-label">${gS(t)}</span>
|
|
1124
1124
|
</small>
|
|
1125
1125
|
`}
|
|
1126
1126
|
${this.renderActivity(n)}
|
|
1127
|
-
`}renderWorkspaceMenu(e,t,n){let r=this.openMenuWorkspaceId===n.id,i=
|
|
1127
|
+
`}renderWorkspaceMenu(e,t,n){let r=this.openMenuWorkspaceId===n.id,i=bS(n.id);return g`
|
|
1128
1128
|
<div class="action-menu">
|
|
1129
1129
|
<button
|
|
1130
1130
|
class="action-menu-toggle"
|
|
@@ -1141,7 +1141,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1141
1141
|
</div>
|
|
1142
1142
|
`:null}
|
|
1143
1143
|
</div>
|
|
1144
|
-
`}renderWorkspaceActions(e){if(!
|
|
1144
|
+
`}renderWorkspaceActions(e){if(!dh(e))return;let t=this.isDeleting(e),n=e.removal?.actionLabel??`删除工作区`;return g`
|
|
1145
1145
|
<div class="workspace-menu-actions">
|
|
1146
1146
|
<button class="danger" title=${t?`正在处理工作区`:n} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?`正在处理…`:n}</button>
|
|
1147
1147
|
</div>
|
|
@@ -1158,7 +1158,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1158
1158
|
${t.length===0?null:g`
|
|
1159
1159
|
<div class="workspace-detail-row">
|
|
1160
1160
|
<dt>详情</dt>
|
|
1161
|
-
<dd><span class="workspace-label">${
|
|
1161
|
+
<dd><span class="workspace-label">${gS(t)}</span></dd>
|
|
1162
1162
|
</div>
|
|
1163
1163
|
`}
|
|
1164
1164
|
</dl>
|
|
@@ -1166,7 +1166,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1166
1166
|
<button type="button" class="detail-copy" title=${i} aria-label=${i} @click=${()=>{this.copyDetail(e,t)}}>
|
|
1167
1167
|
<span aria-hidden="true">${r?`✓`:`⧉`}</span>
|
|
1168
1168
|
</button>
|
|
1169
|
-
`}async copyDetail(e,t){await
|
|
1169
|
+
`}async copyDetail(e,t){await cS(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=zx(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}Jx(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=ng}};W([x({attribute:!1})],G.prototype,`workspaces`,void 0),W([x({attribute:!1})],G.prototype,`selected`,void 0),W([x({type:Boolean,reflect:!0})],G.prototype,`collapsible`,void 0),W([x({type:Boolean,reflect:!0})],G.prototype,`collapsed`,void 0),W([x({attribute:!1})],G.prototype,`workspaceLabelItems`,void 0),W([x({attribute:!1})],G.prototype,`activities`,void 0),W([x({attribute:!1})],G.prototype,`deletingWorkspaceIds`,void 0),W([x({attribute:!1})],G.prototype,`unreadWorkspaceIds`,void 0),W([x({attribute:!1})],G.prototype,`statusSnapshot`,void 0),W([x({attribute:!1})],G.prototype,`onSelect`,void 0),W([x({attribute:!1})],G.prototype,`onDelete`,void 0),W([x({attribute:!1})],G.prototype,`onToggleCollapsed`,void 0),W([x({attribute:!1})],G.prototype,`onFocusPreviousSection`,void 0),W([x({attribute:!1})],G.prototype,`onFocusNextSection`,void 0),W([x({attribute:!1})],G.prototype,`onCancelKeyboardNavigation`,void 0),W([S()],G.prototype,`openMenuWorkspaceId`,void 0),W([S()],G.prototype,`menuStyle`,void 0),W([S()],G.prototype,`copiedDetailKey`,void 0),G=W([b(`workspace-list`)],G);function yS(e){return`${e.branch??e.label}${e.isMain?` · main`:``}`}function bS(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}function xS(e){return e.slice(-8)}function SS(e){return e.replace(/[/\\]+$/u,``)}function CS(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?xS(e.id):e.firstMessage}var wS=`当前工作区中没有可用的父会话`,TS=new Set([`onSelect`,`onSearch`,`onTogglePin`,`onStart`,`onToggleCollapsed`,`onArchivedCollapsed`,`onFocusPreviousSection`,`onFocusNextSection`,`onCancelKeyboardNavigation`,`onArchive`,`onArchiveWithDescendants`,`onArchiveMany`,`onRestore`,`onDelete`,`onDeleteArchived`,`onDeleteArchivedMany`,`onRename`,`onDetachParent`,`onMarkRead`,`onMarkReadMany`,`onReload`,`onCleanup`]),K=class extends y{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.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(!TS.has(String(t))&&!(t===`sessions`&&MS(n,this.sessions))&&!(t===`selected`&&PS(n,this.selected))&&!(t===`statuses`&&FS(n,this.statuses,this.activities,this.sending,this.sessions,this.authoritativeSessionPersistence,`status`))&&!(t===`activities`&&FS(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,Yx(this.renderRoot,{fallbackSelector:`.section-toggle, h2 button:not([disabled])`})}render(){let e=KS(this.sessions,this.pinnedSessionIds),t=new Set(e.map(e=>e.session.id)),n=e.map(e=>e.session).filter(e=>kS(e)===`current`),r=qS(this.sessions.filter(e=>e.archived===!0&&!t.has(e.id)),this.pinnedSessionIds),i=ES(n,this.unreadSessionIds),a=e.slice(0,this.currentVisibleLimit),o=a.map(e=>e.session).filter(e=>kS(e)===`current`),s=r.slice(0,this.archivedVisibleLimit),c=s.map(e=>e.session);return g`
|
|
1170
1170
|
<section>
|
|
1171
1171
|
${this.renderHeading(e.length+r.length,n,i)}
|
|
1172
1172
|
${this.collapsed?null:g`
|
|
@@ -1195,7 +1195,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1195
1195
|
${this.renderCleanupButton()}
|
|
1196
1196
|
${this.renderStartButton()}
|
|
1197
1197
|
</h2>
|
|
1198
|
-
`;let r=this.selected===void 0?`未选择会话`:
|
|
1198
|
+
`;let r=this.selected===void 0?`未选择会话`:CS(this.selected),i=this.selected?.path??r;return g`
|
|
1199
1199
|
<h2>
|
|
1200
1200
|
<button class="section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} 会话</span>${this.collapsed?g`<small class="section-selected" dir="auto" title=${i}>${r}</small>`:null}</span></button>
|
|
1201
1201
|
${this.renderSearchButton()}
|
|
@@ -1233,18 +1233,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1233
1233
|
`}renderSelectionControls(e,t){let n=this.selectedSessions(e).length,r=t.filter(e=>this.selectedSessionIds.has(e.id)).length;return g`
|
|
1234
1234
|
${n===0?g`<button @click=${()=>{this.selectVisibleSessions(t)}}>选择可见</button>`:g`<button @click=${()=>{this.clearSelection(e)}}>清除所选</button>`}
|
|
1235
1235
|
<small>已选 ${n}${r===n?null:g` · 可见 ${r}`}</small>
|
|
1236
|
-
`}renderSession(e,t){let{session:n}=e,r=Math.min(e.depth,2),i=
|
|
1236
|
+
`}renderSession(e,t){let{session:n}=e,r=Math.min(e.depth,2),i=kS(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=US(n,c,l,this.sending[n.id]===!0),d=WS(n,this.unreadSessionIds),f=this.sessionPersistenceOptions(),p=Bd(n,c,f),m=OS(n,c,f),ee=Vd(n,c,f),te=p&&this.canReload,ne=this.pinnedSessionIds.includes(n.id),re=n.persisted!==!1,ie=this.openMenuSessionId===n.id?jS(this.sessions,n):0;return g`
|
|
1237
1237
|
<div
|
|
1238
1238
|
class="action-row ${this.selected?.id===n.id?`selected`:``} ${s?`bulk-selected`:``} ${n.archived===!0?`archived`:``} ${a?`selecting`:``} ${d?`unread`:``} ${ne?`pinned`:``} ${this.openMenuSessionId===n.id?`menu-open`:``}"
|
|
1239
1239
|
style=${`--depth:${String(r)}`}
|
|
1240
1240
|
tabindex="0"
|
|
1241
1241
|
title=${n.path}
|
|
1242
|
-
@click=${e=>{
|
|
1242
|
+
@click=${e=>{qx(e,()=>{this.activateSessionRow(n,t)})}}
|
|
1243
1243
|
@keydown=${e=>{this.handleSessionKeydown(e,n,t)}}
|
|
1244
1244
|
>
|
|
1245
1245
|
<div class="action-main ${a?`selecting`:``}">
|
|
1246
|
-
${o?g`<input class="session-checkbox" type="checkbox" aria-label=${`选择 ${
|
|
1247
|
-
<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}${
|
|
1246
|
+
${o?g`<input class="session-checkbox" type="checkbox" aria-label=${`选择 ${CS(n)}`} .checked=${s} @click=${e=>{e.stopPropagation()}} @change=${()=>{this.toggleSelected(n.id)}}>`:null}
|
|
1247
|
+
<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}${CS(n)}</span>${this.renderRowBadges(e)}</span><small>${this.renderSessionMetaPrefix(n,c,l)}${String(n.messageCount)} 条消息</small>
|
|
1248
1248
|
${this.renderActivity(u,d)}
|
|
1249
1249
|
</div>
|
|
1250
1250
|
<div class="action-menu">
|
|
@@ -1270,11 +1270,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1270
1270
|
`:null}
|
|
1271
1271
|
</div>
|
|
1272
1272
|
</div>
|
|
1273
|
-
`}renderRowMarker(e){return e.hasMissingParent?g`<span class="tree-marker orphan-marker" title=${
|
|
1273
|
+
`}renderRowMarker(e){return e.hasMissingParent?g`<span class="tree-marker orphan-marker" title=${wS} aria-label=${wS}>↳</span>`:e.depth>0?g`<span class="tree-marker">↳</span>`:null}renderRowBadges(e){return e.depth<=2?null:g`<span class="row-badges"><span class="badge">depth ${e.depth}</span></span>`}handleSessionKeydown(e,t,n){Jx(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)&&kS(e)===t){this.toggleSelected(e.id);return}this.onSelect?.(e)}renameSession(e){this.openMenuSessionId=void 0;let t=DS(e);t!==void 0&&this.onRename?.(e,t)}confirmArchiveWithDescendants(e,t){confirm(`归档“${CS(e)}”及其 ${String(t)} 个后代会话?`)&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(`永久删除已归档会话“${CS(e)}”?此操作无法撤销。`)&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;let e=this.selectedSessions(`archived`);e.length!==0&&confirm(`永久删除 ${String(e.length)} 个所选已归档会话?此操作无法撤销。`)&&(this.selectedSessionIds=AS(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=>Bd(e,this.statuses[e.id],this.sessionPersistenceOptions()));this.selectedSessionIds=AS(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=>kS(t)===e).map(e=>e.id);this.selectedSessionIds=AS(this.selectedSessionIds,t)}toggleSelected(e){let t=new Set(this.selectedSessionIds);t.has(e)?t.delete(e):t.add(e),this.selectedSessionIds=t}selectVisibleSessions(e){this.selectedSessionIds=new Set([...this.selectedSessionIds,...e.map(e=>e.id)])}selectedSessions(e){return this.sessions.filter(t=>this.selectedSessionIds.has(t.id)&&kS(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=zx(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`
|
|
1274
1274
|
<div class="session-load-more-sentinel">
|
|
1275
1275
|
<button data-load-scope=${e} @click=${()=>{this.loadMore(e)}}>加载更多(剩余 ${n-t})</button>
|
|
1276
1276
|
</div>
|
|
1277
|
-
`}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
|
|
1277
|
+
`}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 KS(this.sessions,this.pinnedSessionIds).length>this.currentVisibleLimit}expandVisibleLimitForSelected(){let e=this.selected;if(e===void 0)return;let t=KS(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=qS(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 Vd(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 Px(e,e===`sending`?`正在发送消息`:`会话活跃`,t?`未读会话活动`:void 0)}static{this.styles=[ng,h`
|
|
1278
1278
|
h2 { min-height: 30px; }
|
|
1279
1279
|
h2 > .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
|
|
1280
1280
|
h2 > .section-unread-count { flex: 0 0 auto; display: inline; color: var(--pi-accent); font-size: inherit; text-transform: none; }
|
|
@@ -1312,7 +1312,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1312
1312
|
.pending-session-row.starting-session .activity-indicator { flex: 0 0 auto; margin: 0; }
|
|
1313
1313
|
.action-main.selecting { padding-left: calc(32px + var(--depth, 0) * 16px); }
|
|
1314
1314
|
.session-checkbox { position: absolute; top: 9px; left: calc(8px + var(--depth, 0) * 16px); z-index: 2; margin: 0; }
|
|
1315
|
-
`]}};W([x({attribute:!1})],K.prototype,`scopeKey`,void 0),W([x({attribute:!1})],K.prototype,`sessions`,void 0),W([x({attribute:!1})],K.prototype,`pinnedSessionIds`,void 0),W([x({attribute:!1})],K.prototype,`statuses`,void 0),W([x({attribute:!1})],K.prototype,`activities`,void 0),W([x({attribute:!1})],K.prototype,`sending`,void 0),W([x({attribute:!1})],K.prototype,`unreadSessionIds`,void 0),W([x({attribute:!1})],K.prototype,`selected`,void 0),W([x({type:Number})],K.prototype,`startingCount`,void 0),W([x({type:Boolean})],K.prototype,`canStart`,void 0),W([x({type:Boolean})],K.prototype,`canDeleteArchived`,void 0),W([x({type:Boolean})],K.prototype,`canReload`,void 0),W([x({type:Boolean})],K.prototype,`canCleanup`,void 0),W([x({type:Boolean})],K.prototype,`authoritativeSessionPersistence`,void 0),W([x({type:String})],K.prototype,`archivedDeleteUnavailableMessage`,void 0),W([x({type:String})],K.prototype,`cleanupUnavailableMessage`,void 0),W([x({type:Boolean,reflect:!0})],K.prototype,`collapsible`,void 0),W([x({type:Boolean,reflect:!0})],K.prototype,`collapsed`,void 0),W([x({attribute:!1})],K.prototype,`onSelect`,void 0),W([x({attribute:!1})],K.prototype,`onSearch`,void 0),W([x({attribute:!1})],K.prototype,`onTogglePin`,void 0),W([x({attribute:!1})],K.prototype,`onStart`,void 0),W([x({attribute:!1})],K.prototype,`onToggleCollapsed`,void 0),W([x({attribute:!1})],K.prototype,`onArchivedCollapsed`,void 0),W([x({attribute:!1})],K.prototype,`onFocusPreviousSection`,void 0),W([x({attribute:!1})],K.prototype,`onFocusNextSection`,void 0),W([x({attribute:!1})],K.prototype,`onCancelKeyboardNavigation`,void 0),W([x({attribute:!1})],K.prototype,`onArchive`,void 0),W([x({attribute:!1})],K.prototype,`onArchiveWithDescendants`,void 0),W([x({attribute:!1})],K.prototype,`onArchiveMany`,void 0),W([x({attribute:!1})],K.prototype,`onRestore`,void 0),W([x({attribute:!1})],K.prototype,`onDelete`,void 0),W([x({attribute:!1})],K.prototype,`onDeleteArchived`,void 0),W([x({attribute:!1})],K.prototype,`onDeleteArchivedMany`,void 0),W([x({attribute:!1})],K.prototype,`onRename`,void 0),W([x({attribute:!1})],K.prototype,`onDetachParent`,void 0),W([x({attribute:!1})],K.prototype,`onMarkRead`,void 0),W([x({attribute:!1})],K.prototype,`onMarkReadMany`,void 0),W([x({attribute:!1})],K.prototype,`onReload`,void 0),W([x({attribute:!1})],K.prototype,`onCleanup`,void 0),W([S()],K.prototype,`openMenuSessionId`,void 0),W([S()],K.prototype,`menuStyle`,void 0),W([S()],K.prototype,`archivedExpanded`,void 0),W([S()],K.prototype,`selectionScopes`,void 0),W([S()],K.prototype,`selectedSessionIds`,void 0),W([S()],K.prototype,`currentVisibleLimit`,void 0),W([S()],K.prototype,`archivedVisibleLimit`,void 0),W([C(`.list-body`)],K.prototype,`listBody`,void 0),K=W([b(`session-list`)],K);function
|
|
1315
|
+
`]}};W([x({attribute:!1})],K.prototype,`scopeKey`,void 0),W([x({attribute:!1})],K.prototype,`sessions`,void 0),W([x({attribute:!1})],K.prototype,`pinnedSessionIds`,void 0),W([x({attribute:!1})],K.prototype,`statuses`,void 0),W([x({attribute:!1})],K.prototype,`activities`,void 0),W([x({attribute:!1})],K.prototype,`sending`,void 0),W([x({attribute:!1})],K.prototype,`unreadSessionIds`,void 0),W([x({attribute:!1})],K.prototype,`selected`,void 0),W([x({type:Number})],K.prototype,`startingCount`,void 0),W([x({type:Boolean})],K.prototype,`canStart`,void 0),W([x({type:Boolean})],K.prototype,`canDeleteArchived`,void 0),W([x({type:Boolean})],K.prototype,`canReload`,void 0),W([x({type:Boolean})],K.prototype,`canCleanup`,void 0),W([x({type:Boolean})],K.prototype,`authoritativeSessionPersistence`,void 0),W([x({type:String})],K.prototype,`archivedDeleteUnavailableMessage`,void 0),W([x({type:String})],K.prototype,`cleanupUnavailableMessage`,void 0),W([x({type:Boolean,reflect:!0})],K.prototype,`collapsible`,void 0),W([x({type:Boolean,reflect:!0})],K.prototype,`collapsed`,void 0),W([x({attribute:!1})],K.prototype,`onSelect`,void 0),W([x({attribute:!1})],K.prototype,`onSearch`,void 0),W([x({attribute:!1})],K.prototype,`onTogglePin`,void 0),W([x({attribute:!1})],K.prototype,`onStart`,void 0),W([x({attribute:!1})],K.prototype,`onToggleCollapsed`,void 0),W([x({attribute:!1})],K.prototype,`onArchivedCollapsed`,void 0),W([x({attribute:!1})],K.prototype,`onFocusPreviousSection`,void 0),W([x({attribute:!1})],K.prototype,`onFocusNextSection`,void 0),W([x({attribute:!1})],K.prototype,`onCancelKeyboardNavigation`,void 0),W([x({attribute:!1})],K.prototype,`onArchive`,void 0),W([x({attribute:!1})],K.prototype,`onArchiveWithDescendants`,void 0),W([x({attribute:!1})],K.prototype,`onArchiveMany`,void 0),W([x({attribute:!1})],K.prototype,`onRestore`,void 0),W([x({attribute:!1})],K.prototype,`onDelete`,void 0),W([x({attribute:!1})],K.prototype,`onDeleteArchived`,void 0),W([x({attribute:!1})],K.prototype,`onDeleteArchivedMany`,void 0),W([x({attribute:!1})],K.prototype,`onRename`,void 0),W([x({attribute:!1})],K.prototype,`onDetachParent`,void 0),W([x({attribute:!1})],K.prototype,`onMarkRead`,void 0),W([x({attribute:!1})],K.prototype,`onMarkReadMany`,void 0),W([x({attribute:!1})],K.prototype,`onReload`,void 0),W([x({attribute:!1})],K.prototype,`onCleanup`,void 0),W([S()],K.prototype,`openMenuSessionId`,void 0),W([S()],K.prototype,`menuStyle`,void 0),W([S()],K.prototype,`archivedExpanded`,void 0),W([S()],K.prototype,`selectionScopes`,void 0),W([S()],K.prototype,`selectedSessionIds`,void 0),W([S()],K.prototype,`currentVisibleLimit`,void 0),W([S()],K.prototype,`archivedVisibleLimit`,void 0),W([C(`.list-body`)],K.prototype,`listBody`,void 0),K=W([b(`session-list`)],K);function ES(e,t){return e.filter(e=>WS(e,t)).length}function DS(e){let t=globalThis.prompt(`重命名会话`,CS(e))?.trim();return t===void 0||t===``?void 0:t}function OS(e,t,n){return Bd(e,t,n)}function kS(e){return e.archived===!0?`archived`:`current`}function AS(e,t){let n=new Set(t);return new Set([...e].filter(e=>!n.has(e)))}function jS(e,t){let n=new Map;for(let t of e){if(t.parentSessionPath===void 0)continue;let e=SS(t.parentSessionPath),r=n.get(e)??[];r.push(t),n.set(e,r)}let r=(e,t)=>{let i=SS(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(SS(e.path))||(e.archived!==!0&&(o+=1),o+=r(e,a));return o};return r(t,new Set)}function MS(e,t){return!Array.isArray(e)||e.length!==t.length?!1:t.every((t,n)=>NS(t)===NS(e[n]))}function NS(e){return LS(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]):``}function PS(e,t){return e===void 0||t===void 0?e===t:NS(e)===NS(t)}function FS(e,t,n,r,i,a,o){if(!RS(e))return!1;for(let s of i){let i=zS(o===`status`?e:n,s.id),c=zS(o===`status`?t:n,s.id),l=BS(o===`activity`?e:n,s.id),u=BS(o===`activity`?t:n,s.id);if(IS(s,i,l,r[s.id]===!0,a)!==IS(s,c,u,r[s.id]===!0,a))return!1}return!0}function IS(e,t,n,r,i){return JSON.stringify([US(e,t,n,r),n?.phase,zd(e,t,{authoritative:i})])}function LS(e){return RS(e)&&typeof e.id==`string`&&typeof e.path==`string`}function RS(e){return typeof e==`object`&&!!e}function zS(e,t){if(!RS(e))return;let n=e[t];return VS(n)?n:void 0}function BS(e,t){if(!RS(e))return;let n=e[t];return HS(n)?n:void 0}function VS(e){return RS(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)&&RS(e.tokens)&&typeof e.cost==`number`}function HS(e){return RS(e)&&typeof e.sessionId==`string`&&(e.phase===`active`||e.phase===`idle`||e.phase===`error`)&&typeof e.label==`string`&&typeof e.at==`string`}function US(e,t,n,r){if(!(Yc(e)||e.archived===!0)){if(r)return`sending`;if(As(t,n))return`session`}}function WS(e,t){return Yc(e)||e.archived===!0?!1:t.has(e.id)}function GS(e){return new Map(e.map(e=>[SS(e.path),e]))}function KS(e,t=[]){let n=GS(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:SS(t.parentSessionPath),i=new Set([SS(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:SS(t.parentSessionPath)}}return qS(e.filter(e=>r.has(e.id)),t)}function qS(e,t=[]){let n=GS(e),r=new Map,i=[];for(let t of e){let e=t.parentSessionPath,a=e===void 0?void 0:n.get(SS(e));if(a===void 0){i.push(t);continue}let o=SS(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)=>[SS(e.path),t])),s=new Map,c=(e,t)=>{if(a.has(e.id))return!0;let n=SS(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(SS(e.path))??0)-(o.get(SS(t.path))??0):r},u=[],d=(e,t,i)=>{let a=SS(e.path);if(i.has(a))return;let o=e.parentSessionPath;u.push({session:e,depth:t,hasMissingParent:o!==void 0&&!n.has(SS(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 JS=`button, input, select, textarea, a[href], [tabindex]`,YS=class extends y{constructor(...e){super(...e),this.busy=!1,this.handleKeyDown=e=>{if(e.key===`Tab`){this.trapTabFocus(e);return}if(e.key===`Escape`){if(e.preventDefault(),e.stopPropagation(),this.busy){this.onBusyEscape?.();return}this.onClose?.()}}}connectedCallback(){super.connectedCallback(),this.modalRegistration=Rh({element:this,paintElement:tC(this),focus:()=>{this.focusDialogContent()},onTopChange:()=>{this.requestUpdate()}}),this.addEventListener(`keydown`,this.handleKeyDown)}disconnectedCallback(){this.removeEventListener(`keydown`,this.handleKeyDown);let e=this.modalRegistration;this.modalRegistration=void 0,super.disconnectedCallback(),e?.unregister()}firstUpdated(){this.focusDialog()}focusDialog(){this.modalRegistration?.focus()}focusDialogContent(){let e=this.initialFocusTarget();e!==null&&Yh(e)||this.section!==void 0&&Yh(this.section)}render(){let e=this.modalRegistration?.isTop===!0;return g`
|
|
1316
1316
|
<div class="backdrop" @mousedown=${e=>{this.handleBackdropMouseDown(e)}}>
|
|
1317
1317
|
<section
|
|
1318
1318
|
role="dialog"
|
|
@@ -1323,7 +1323,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1323
1323
|
tabindex="-1"
|
|
1324
1324
|
><slot></slot></section>
|
|
1325
1325
|
</div>
|
|
1326
|
-
`}initialFocusTarget(){if(this.initialFocus===void 0)return null;try{return this.querySelector(this.initialFocus)}catch{return null}}trapTabFocus(e){let t=
|
|
1326
|
+
`}initialFocusTarget(){if(this.initialFocus===void 0)return null;try{return this.querySelector(this.initialFocus)}catch{return null}}trapTabFocus(e){let t=XS(this);if(t.length===0){e.preventDefault(),this.section?.focus();return}let n=Xh(this.ownerDocument),r=t.findIndex(e=>e===n);if(r===-1){e.preventDefault(),(e.shiftKey?t.at(-1):t[0])?.focus();return}let i=!e.shiftKey&&r===t.length-1,a=e.shiftKey&&r===0;!i&&!a||(e.preventDefault(),(e.shiftKey?t.at(-1):t[0])?.focus())}handleBackdropMouseDown(e){e.target!==e.currentTarget||this.busy||this.onClose?.()}static{this.styles=h`
|
|
1327
1327
|
/* Host dialogs tune this shell with custom properties (defaults match a
|
|
1328
1328
|
centered 720px dialog):
|
|
1329
1329
|
--modal-surface-place-items backdrop grid alignment (default center)
|
|
@@ -1334,7 +1334,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1334
1334
|
:host { display: block; width: 100%; height: 100%; }
|
|
1335
1335
|
.backdrop { box-sizing: border-box; width: 100%; height: 100%; display: grid; place-items: var(--modal-surface-place-items, center); padding: var(--modal-surface-backdrop-padding, 0); background: var(--modal-surface-backdrop-background, var(--pi-overlay)); overflow: hidden; }
|
|
1336
1336
|
section[role="dialog"] { box-sizing: border-box; width: var(--modal-surface-width, min(720px, 100%)); max-width: var(--modal-surface-max-width, 100%); height: var(--modal-surface-height, auto); max-height: var(--modal-surface-max-height, 100%); min-height: var(--modal-surface-min-height, auto); display: flex; flex-direction: column; border: var(--modal-surface-border, 1px solid var(--pi-border)); border-radius: var(--modal-surface-radius, 12px); background: var(--pi-bg); box-shadow: var(--modal-surface-shadow, 0 20px 60px var(--pi-shadow-strong)); overflow: hidden; }
|
|
1337
|
-
`}};W([x({attribute:!1})],
|
|
1337
|
+
`}};W([x({attribute:!1})],YS.prototype,`onClose`,void 0),W([x({type:Boolean})],YS.prototype,`busy`,void 0),W([x({attribute:!1})],YS.prototype,`onBusyEscape`,void 0),W([x({attribute:!1})],YS.prototype,`initialFocus`,void 0),W([x({attribute:!1})],YS.prototype,`label`,void 0),W([C(`section`)],YS.prototype,`section`,void 0),YS=W([b(`modal-surface`)],YS);function XS(e){let t=[],n=e=>{e instanceof HTMLElement&&$S(e)&&t.push(e);for(let t of eC(e))n(t)};for(let t of eC(e))n(t);return ZS(t)}function ZS(e){let t=new Map;for(let n of e){let e=QS(n);if(e===null)continue;let r=t.get(e.form)??new Map;t.set(e.form,r);let i=r.get(e.name);(i===void 0||e.checked&&!i.checked)&&r.set(e.name,e)}let n=new Set(Array.from(t.values()).flatMap(e=>Array.from(e.values())));return e.filter(e=>QS(e)===null||n.has(e))}function QS(e){return!(e instanceof HTMLInputElement)||e.type!==`radio`||e.name===``?null:e}function $S(e){return e.matches(`:disabled`)||Zh(e)||e instanceof HTMLInputElement&&e.type===`hidden`?!1:e.matches(JS)&&e.tabIndex>=0}function eC(e){if(e instanceof HTMLSlotElement){let t=e.assignedNodes({flatten:!0}),n=t.length===0?e.childNodes:t;return Array.from(n).filter(e=>e instanceof Element)}let t=e instanceof Element?e.shadowRoot??e:e;return Array.from(t.children)}function tC(e){let t=e.getRootNode();return t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host:e}var nC=class extends y{constructor(...e){super(...e),this.canCleanup=!0,this.unavailableMessage=`请更新并重启此机器上的 Pi-Web 后再清理会话。`,this.loading=!1,this.running=!1,this.error=``,this.draft={...nm},this.formError=``}willUpdate(e){e.has(`preview`)&&(this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd))}render(){let e=rm(this.draft),t=this.selectedPreview(),n=am({canCleanup:this.canCleanup,draft:this.draft,preview:t,loading:this.loading,running:this.running}),r=n?`运行清理`:t!==void 0&&!sm(t)?`至少选择一个项目才能运行清理`:`运行清理前请先预览`;return g`
|
|
1338
1338
|
<modal-surface .onClose=${()=>{this.onClose?.()}} .busy=${this.running} .label=${`清理会话`}>
|
|
1339
1339
|
<header>
|
|
1340
1340
|
<div>
|
|
@@ -1356,25 +1356,25 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1356
1356
|
<button class="danger" ?disabled=${!n} title=${r} @click=${()=>{this.runCleanup()}}>${this.running?`正在运行…`:`运行清理`}</button>
|
|
1357
1357
|
</footer>
|
|
1358
1358
|
</modal-surface>
|
|
1359
|
-
`}renderForm(e){let t=this.loading||this.running,n=
|
|
1359
|
+
`}renderForm(e){let t=this.loading||this.running,n=rm(this.draft),r=this.preview!==void 0&&n.ok&&!om(this.draft,this.preview)&&sm(this.preview);return g`
|
|
1360
1360
|
<fieldset ?disabled=${t}>
|
|
1361
1361
|
<label class="toggle-row">
|
|
1362
|
-
<input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:
|
|
1362
|
+
<input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:rC(e)})}}>
|
|
1363
1363
|
<span>归档空闲超过</span>
|
|
1364
|
-
<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:
|
|
1364
|
+
<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:iC(e)})}}>
|
|
1365
1365
|
<span>天的未归档会话</span>
|
|
1366
1366
|
</label>
|
|
1367
1367
|
<label class="toggle-row delete-row">
|
|
1368
|
-
<input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:
|
|
1368
|
+
<input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:rC(e)})}}>
|
|
1369
1369
|
<span>删除已归档超过</span>
|
|
1370
|
-
<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:
|
|
1370
|
+
<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:iC(e)})}}>
|
|
1371
1371
|
<span>天的已归档会话</span>
|
|
1372
1372
|
</label>
|
|
1373
1373
|
</fieldset>
|
|
1374
1374
|
<p class="warning"><strong>删除是永久操作。</strong>清理只会删除已经归档的会话。</p>
|
|
1375
1375
|
${e===``?null:g`<div class="dialog-error" role="alert">${e}</div>`}
|
|
1376
1376
|
${r?g`<div class="hint" role="status">阈值已更改。运行清理前请重新预览。</div>`:null}
|
|
1377
|
-
`}renderUnavailable(){return g`<div class="unavailable" role="status">${this.unavailableMessage}</div>`}renderMessage(){let e=this.formError||this.error;return e===``?null:g`<div class="dialog-error" role="alert">${e}</div>`}renderPreview(e){let t=this.selectedProjectCwdsForPreview(),n=new Set(t),r=
|
|
1377
|
+
`}renderUnavailable(){return g`<div class="unavailable" role="status">${this.unavailableMessage}</div>`}renderMessage(){let e=this.formError||this.error;return e===``?null:g`<div class="dialog-error" role="alert">${e}</div>`}renderPreview(e){let t=this.selectedProjectCwdsForPreview(),n=new Set(t),r=lm(e,t);return g`
|
|
1378
1378
|
<section class="preview" aria-label="清理预览">
|
|
1379
1379
|
<h2>预览</h2>
|
|
1380
1380
|
${e.projects.length===0?g`<p class="empty">没有会话匹配这些阈值。</p>`:g`
|
|
@@ -1404,7 +1404,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1404
1404
|
${t.length===0?g`<p class="hint" role="status">至少选择一个项目才能运行清理。</p>`:null}
|
|
1405
1405
|
`}renderProjectRow(e,t){return g`
|
|
1406
1406
|
<tr class=${t?``:`unselected`}>
|
|
1407
|
-
<td class="select-cell"><input type="checkbox" aria-label=${`清理 ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${t=>{this.setProjectSelected(e.cwd,
|
|
1407
|
+
<td class="select-cell"><input type="checkbox" aria-label=${`清理 ${e.cwd}`} .checked=${t} ?disabled=${this.running} @change=${t=>{this.setProjectSelected(e.cwd,rC(t))}}></td>
|
|
1408
1408
|
<th title=${e.cwd} dir="auto">${e.cwd}</th>
|
|
1409
1409
|
<td>${e.archiveCount}</td>
|
|
1410
1410
|
<td>${e.deleteCount}</td>
|
|
@@ -1414,7 +1414,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1414
1414
|
<h2>清理完成</h2>
|
|
1415
1415
|
<p>已归档 ${e.archivedSessionIds.length} 个会话;已永久删除 ${e.deletedSessionIds.length} 个已归档会话。</p>
|
|
1416
1416
|
</section>
|
|
1417
|
-
`}updateDraft(e){this.draft={...this.draft,...e},this.formError=``}selectedPreview(){return this.preview===void 0?void 0:
|
|
1417
|
+
`}updateDraft(e){this.draft={...this.draft,...e},this.formError=``}selectedPreview(){return this.preview===void 0?void 0:lm(this.preview,this.selectedProjectCwdsForPreview())}selectedProjectCwdsForPreview(){return this.preview===void 0?[]:cm(this.preview,this.selectedProjectCwds)}selectAllProjects(){this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd)??[],this.formError=``}deselectAllProjects(){this.selectedProjectCwds=[],this.formError=``}setProjectSelected(e,t){let n=this.preview;if(n===void 0)return;let r=new Set(this.selectedProjectCwdsForPreview());t?r.add(e):r.delete(e),this.selectedProjectCwds=n.projects.map(e=>e.cwd).filter(e=>r.has(e)),this.formError=``}previewCleanup(){let e=rm(this.draft);if(!e.ok){this.formError=e.error;return}this.formError=``,this.onPreview?.(e.request)}runCleanup(){let e=rm(this.draft);if(!e.ok){this.formError=e.error;return}let t=this.selectedPreview(),n=this.selectedProjectCwdsForPreview();if(!am({canCleanup:this.canCleanup,draft:this.draft,preview:t})){this.formError=t!==void 0&&!sm(t)?`至少选择一个项目才能运行清理。`:`运行清理前请先预览。`;return}t===void 0||!um(t,e=>confirm(e))||(this.formError=``,this.onRun?.({...e.request,projectCwds:n}))}static{this.styles=h`
|
|
1418
1418
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
1419
1419
|
modal-surface { --modal-surface-backdrop-padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); --modal-surface-width: min(760px, 100%); --modal-surface-max-height: min(760px, 100%); --modal-surface-radius: 14px; }
|
|
1420
1420
|
header, footer { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--pi-border); }
|
|
@@ -1462,7 +1462,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1462
1462
|
table { min-width: 560px; }
|
|
1463
1463
|
thead th:first-child, td.select-cell { width: 58px; }
|
|
1464
1464
|
}
|
|
1465
|
-
`}};W([x({type:Boolean})]
|
|
1465
|
+
`}};W([x({type:Boolean})],nC.prototype,`canCleanup`,void 0),W([x({type:String})],nC.prototype,`unavailableMessage`,void 0),W([x({attribute:!1})],nC.prototype,`preview`,void 0),W([x({attribute:!1})],nC.prototype,`result`,void 0),W([x({type:Boolean})],nC.prototype,`loading`,void 0),W([x({type:Boolean})],nC.prototype,`running`,void 0),W([x({type:String})],nC.prototype,`error`,void 0),W([x({attribute:!1})],nC.prototype,`onPreview`,void 0),W([x({attribute:!1})],nC.prototype,`onRun`,void 0),W([x({attribute:!1})],nC.prototype,`onClose`,void 0),W([S()],nC.prototype,`draft`,void 0),W([S()],nC.prototype,`formError`,void 0),W([S()],nC.prototype,`selectedProjectCwds`,void 0),nC=W([b(`session-cleanup-dialog`)],nC);function rC(e){return e.target instanceof HTMLInputElement&&e.target.checked}function iC(e){return e.target instanceof HTMLInputElement?e.target.value:``}var aC=class extends y{constructor(...e){super(...e),this.query=``,this.searching=!1,this.error=``}render(){let e=this.query.trim()!==``;return g`
|
|
1466
1466
|
<modal-surface .onClose=${()=>{this.onClose?.()}} .initialFocus=${`input`} .label=${`搜索会话内容`}>
|
|
1467
1467
|
<header>
|
|
1468
1468
|
<div>
|
|
@@ -1474,7 +1474,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1474
1474
|
<div class="body">
|
|
1475
1475
|
<label class="search-field">
|
|
1476
1476
|
<span aria-hidden="true">⌕</span>
|
|
1477
|
-
<input type="search" aria-label="搜索用户提问或 AI 回答" .value=${this.query} @input=${e=>{this.onSearch?.(
|
|
1477
|
+
<input type="search" aria-label="搜索用户提问或 AI 回答" .value=${this.query} @input=${e=>{this.onSearch?.(lC(e))}}>
|
|
1478
1478
|
${this.searching?g`<span class="spinner" aria-label="正在搜索"></span>`:null}
|
|
1479
1479
|
</label>
|
|
1480
1480
|
${this.renderStatus(e)}
|
|
@@ -1490,7 +1490,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1490
1490
|
${e.results.map(e=>g`
|
|
1491
1491
|
<section class="session-group">
|
|
1492
1492
|
<div class="session-heading">
|
|
1493
|
-
<strong dir="auto">${
|
|
1493
|
+
<strong dir="auto">${cC(e.session)}</strong>
|
|
1494
1494
|
<span>${e.matches.length} 条匹配</span>
|
|
1495
1495
|
</div>
|
|
1496
1496
|
${e.matches.map(t=>this.renderMatch(e.session,t))}
|
|
@@ -1501,7 +1501,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1501
1501
|
<button class="match-row" @click=${()=>{this.onSelect?.(e,t)}}>
|
|
1502
1502
|
<span class="match-meta"><span class=${`role ${t.role}`}>${n}</span></span>
|
|
1503
1503
|
<span class="excerpts" dir="auto">
|
|
1504
|
-
${t.excerpts.map(e=>g`<span class="excerpt">${
|
|
1504
|
+
${t.excerpts.map(e=>g`<span class="excerpt">${oC(e)}</span>`)}
|
|
1505
1505
|
</span>
|
|
1506
1506
|
<span class="jump" aria-hidden="true">→</span>
|
|
1507
1507
|
</button>
|
|
@@ -1546,7 +1546,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1546
1546
|
.body { padding: 12px; }
|
|
1547
1547
|
.match-row { padding-left: 10px; }
|
|
1548
1548
|
}
|
|
1549
|
-
`}};W([x({type:String})],
|
|
1549
|
+
`}};W([x({type:String})],aC.prototype,`query`,void 0),W([x({attribute:!1})],aC.prototype,`response`,void 0),W([x({type:Boolean})],aC.prototype,`searching`,void 0),W([x({type:String})],aC.prototype,`error`,void 0),W([x({attribute:!1})],aC.prototype,`onSearch`,void 0),W([x({attribute:!1})],aC.prototype,`onSelect`,void 0),W([x({attribute:!1})],aC.prototype,`onClose`,void 0),aC=W([b(`session-search-dialog`)],aC);function oC(e){return g`${sC(e).map(e=>e.highlighted?g`<mark>${e.text}</mark>`:e.text)}`}function sC(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 cC(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?xS(e.id):e.firstMessage}function lC(e){return e.target instanceof HTMLInputElement?e.target.value:``}function uC(e){let t=new Map,n=[];for(let r of e.nodes)t.has(r.id)||(t.set(r.id,r),n.push(r.id));let r=gC(t,n),i=new Map;for(let e of n)i.set(e,[]);let a=[];for(let e of n){let t=r.get(e)??null;if(t===null){a.push(e);continue}i.get(t)?.push(e)}let o=new Map,s=new Map,c=new Set,l=[...a].reverse().map(e=>({id:e,depth:0,branchDepth:0}));for(;l.length>0;){let e=l.pop();if(e===void 0||c.has(e.id))continue;c.add(e.id),o.set(e.id,e.depth),s.set(e.id,e.branchDepth);let t=i.get(e.id)??[],n=e.branchDepth+ +(t.length>1);for(let r=t.length-1;r>=0;--r){let i=t[r];i!==void 0&&l.push({id:i,depth:e.depth+1,branchDepth:n})}}for(let e of n)c.has(e)||(a.push(e),r.set(e,null),o.set(e,0),s.set(e,0));let u=new Map;for(let[e,t]of i)u.set(e,t);let d=e.activeLeafId!==null&&t.has(e.activeLeafId)?e.activeLeafId:null;return{nodesById:t,orderedIds:n,rootIds:a,parentById:r,childrenById:u,depthById:o,branchDepthById:s,activePathIds:d===null?new Set:_C(d,r),activeLeafId:d}}function dC(e,t){let n=[],r=new Set,i=[...e.rootIds].reverse();for(;i.length>0;){let a=i.pop();if(a===void 0||r.has(a))continue;let o=e.nodesById.get(a);if(o===void 0)continue;r.add(a);let s=e.childrenById.get(a)??[];if(n.push({node:o,depth:e.depthById.get(a)??0,branchDepth:e.branchDepthById.get(a)??0,parentId:e.parentById.get(a)??null,childIds:s,activePath:e.activePathIds.has(a),activeLeaf:e.activeLeafId===a}),!t.has(a))for(let e=s.length-1;e>=0;--e){let t=s[e];t!==void 0&&i.push(t)}}return n}function fC(e){return e.activeLeafId===null?e.orderedIds.at(-1):e.activeLeafId}function pC(e,t,n){let r=dC(e,t.foldedIds).map(e=>e.node.id),i=vC(r,t.selectedId),a=i===void 0?-1:r.indexOf(i),o=()=>({...t,selectedId:i,handled:!1}),s=e=>({...t,selectedId:e,handled:!0});switch(n){case`ArrowUp`:return s(a>0?r[a-1]:i);case`ArrowDown`:return s(a>=0&&a<r.length-1?r[a+1]:i);case`Home`:return s(r[0]);case`End`:return s(r.at(-1));case`ArrowLeft`:if(i===void 0)return s(void 0);if((e.childrenById.get(i)??[]).length>0&&!t.foldedIds.has(i)){let e=new Set(t.foldedIds);return e.add(i),{selectedId:i,foldedIds:e,handled:!0}}return s(e.parentById.get(i)??i);case`ArrowRight`:{if(i===void 0)return s(void 0);let n=e.childrenById.get(i)??[];if(n.length===0)return s(i);if(t.foldedIds.has(i)){let e=new Set(t.foldedIds);return e.delete(i),{selectedId:i,foldedIds:e,handled:!0}}return s(n[0])}case`Enter`:return{...t,selectedId:i,handled:!0,...i===void 0?{}:{action:`confirm`}};case`Escape`:return{...t,selectedId:i,handled:!0,action:`cancel`};default:return o()}}function mC(e,t,n){if((e.childrenById.get(n)??[]).length===0)return{...t,selectedId:n};let r=new Set(t.foldedIds);return r.has(n)?r.delete(n):r.add(n),{selectedId:n,foldedIds:r}}function hC(e,t){return e===`none`||e==="default"?{ok:!0,choice:{mode:e}}:t.trim()===``?{ok:!1,error:`请输入自定义摘要重点说明。`}:t.length>1e4?{ok:!1,error:`自定义摘要重点不能超过 ${String(Gt)} 个字符。`}:{ok:!0,choice:{mode:`custom`,instructions:t.trim()}}}function gC(e,t){let n=new Map;for(let r of t){let t=e.get(r)?.parentId??null;n.set(r,t!==null&&t!==r&&e.has(t)?t:null)}let r=new Map;for(let e of t){if(r.has(e))continue;let t=[],i=e;for(;i!==null&&!r.has(i);)r.set(i,`visiting`),t.push(i),i=n.get(i)??null;if(i!==null&&r.get(i)===`visiting`){let e=t.at(-1);e!==void 0&&n.set(e,null)}for(let e of t)r.set(e,`visited`)}return n}function _C(e,t){let n=new Set,r=e;for(;r!==null&&!n.has(r);)n.add(r),r=t.get(r)??null;return n}function vC(e,t){return t!==void 0&&e.includes(t)?t:e.at(-1)}var yC={nodes:[],activeLeafId:null,activePathIds:[]},bC=8,xC={user:{label:`用户`,tone:`user`,bookkeeping:!1},assistant:{label:`助手`,tone:`assistant`,bookkeeping:!1},"tool-result":{label:`工具结果`,tone:`tool`,bookkeeping:!1},bash:{label:`命令`,tone:`shell`,bookkeeping:!1},"custom-message":{label:`自定义消息`,tone:`context`,bookkeeping:!1},compaction:{label:`上下文压缩`,tone:`context`,bookkeeping:!1},"branch-summary":{label:`分支摘要`,tone:`context`,bookkeeping:!1},"model-change":{label:`模型`,tone:`metadata`,bookkeeping:!0},"thinking-level-change":{label:`思考级别`,tone:`metadata`,bookkeeping:!0},"session-info":{label:`会话信息`,tone:`metadata`,bookkeeping:!0},label:{label:`标签`,tone:`metadata`,bookkeeping:!0},custom:{label:`自定义`,tone:`metadata`,bookkeeping:!0},other:{label:`其他`,tone:`metadata`,bookkeeping:!0}},SC=class extends y{constructor(...e){super(...e),this.tree=yC,this.foldedIds=new Set,this.step=`tree`,this.operation=`continue`,this.summaryMode=`none`,this.customInstructions=``,this.busy=!1,this.aborting=!1,this.error=``,this.statusMessage=``,this.model=uC(yC),this.operationGeneration=0}willUpdate(e){e.has(`tree`)&&this.resetTree()}updated(){let e=this.pendingFocus;e!==void 0&&(this.pendingFocus=void 0,e===`tree`?this.focusSelectedTreeItem():e===`custom`?this.renderRoot.querySelector(`#session-tree-custom-focus`)?.focus():e===`operation`?this.renderRoot.querySelector(`input[name='session-tree-operation']:checked`)?.focus():this.renderRoot.querySelector(`input[name='session-tree-summary']:checked`)?.focus())}render(){return g`
|
|
1550
1550
|
<modal-surface .onClose=${()=>{this.requestDismissal()}} .onBusyEscape=${()=>{this.requestBusyEscape()}} .busy=${this.busy} .label=${`浏览会话树`}>
|
|
1551
1551
|
<header>
|
|
1552
1552
|
<div>
|
|
@@ -1558,7 +1558,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1558
1558
|
${this.step===`tree`?this.renderTreeStep():this.renderActionStep()}
|
|
1559
1559
|
${this.renderFooter()}
|
|
1560
1560
|
</modal-surface>
|
|
1561
|
-
`}renderTreeStep(){let e=
|
|
1561
|
+
`}renderTreeStep(){let e=dC(this.model,this.foldedIds);return g`
|
|
1562
1562
|
<div class="body tree-step">
|
|
1563
1563
|
<div class="tree-intro">
|
|
1564
1564
|
<p>选择要从哪一条历史记录继续。</p>
|
|
@@ -1577,7 +1577,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1577
1577
|
</div>
|
|
1578
1578
|
`}
|
|
1579
1579
|
</div>
|
|
1580
|
-
`}renderTreeRow(e){let t=e.node.id===this.selectedId,n=e.childIds.length>0&&!this.foldedIds.has(e.node.id),r=
|
|
1580
|
+
`}renderTreeRow(e){let t=e.node.id===this.selectedId,n=e.childIds.length>0&&!this.foldedIds.has(e.node.id),r=TC(e.node.kind),i=[`tree-row`,t?`selected`:``,e.activePath?`active-path`:``,e.activeLeaf?`active-leaf`:``,r.bookkeeping?`bookkeeping`:``].filter(e=>e!==``).join(` `),a=CC(e.branchDepth);return g`
|
|
1581
1581
|
<div
|
|
1582
1582
|
class=${i}
|
|
1583
1583
|
style=${`--tree-indent: ${String(a*16)}px; --tree-indent-mobile: ${String(a*12)}px;`}
|
|
@@ -1610,7 +1610,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1610
1610
|
${e.node.timestamp===void 0?null:g`<time datetime=${e.node.timestamp}>${e.node.timestamp}</time>`}
|
|
1611
1611
|
</span>
|
|
1612
1612
|
</div>
|
|
1613
|
-
`}renderKindBadge(e){return g`<span class=${`kind kind-tone-${e.tone}`}>${e.label}</span>`}renderActionStep(){let e=this.selectedId===void 0?void 0:this.model.nodesById.get(this.selectedId),t=
|
|
1613
|
+
`}renderKindBadge(e){return g`<span class=${`kind kind-tone-${e.tone}`}>${e.label}</span>`}renderActionStep(){let e=this.selectedId===void 0?void 0:this.model.nodesById.get(this.selectedId),t=hC(this.summaryMode,this.customInstructions);return g`
|
|
1614
1614
|
<div class="body confirmation-step">
|
|
1615
1615
|
<div class="confirmation-card">
|
|
1616
1616
|
<div>
|
|
@@ -1619,7 +1619,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1619
1619
|
</div>
|
|
1620
1620
|
${e===void 0?g`<div class="empty">所选历史条目已不可用。</div>`:g`
|
|
1621
1621
|
<div class="selected-entry">
|
|
1622
|
-
${this.renderKindBadge(
|
|
1622
|
+
${this.renderKindBadge(TC(e.kind))}
|
|
1623
1623
|
<strong dir="auto">${e.summary}</strong>
|
|
1624
1624
|
<p>${this.selectedEntryDescription(e.kind)}</p>
|
|
1625
1625
|
</div>
|
|
@@ -1658,7 +1658,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1658
1658
|
${this.error===``?null:g`<div class="dialog-error" role="alert">${this.error}</div>`}
|
|
1659
1659
|
</div>
|
|
1660
1660
|
</div>
|
|
1661
|
-
`}selectedEntryDescription(e){return this.operation===`fork`?e===`user`?`新会话会在此用户消息之前分叉,并把消息文本恢复为新会话的提示词草稿。`:`新会话会包含此条目以及此前的全部历史记录。`:
|
|
1661
|
+
`}selectedEntryDescription(e){return this.operation===`fork`?e===`user`?`新会话会在此用户消息之前分叉,并把消息文本恢复为新会话的提示词草稿。`:`新会话会包含此条目以及此前的全部历史记录。`:wC(e)?`此消息的文本会返回提示词编辑器,供你选择编辑并重新提交。`:`从此条目继续后,提示词编辑器将为空。`}renderOperationOption(e,t,n){return g`
|
|
1662
1662
|
<label class=${`choice-option${this.operation===e?` selected`:``}`}>
|
|
1663
1663
|
<input
|
|
1664
1664
|
type="radio"
|
|
@@ -1697,7 +1697,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1697
1697
|
${this.primaryActionLabel()}
|
|
1698
1698
|
</button>
|
|
1699
1699
|
</footer>
|
|
1700
|
-
`}resetTree(){this.operationGeneration+=1,this.model=
|
|
1700
|
+
`}resetTree(){this.operationGeneration+=1,this.model=uC(this.tree),this.selectedId=fC(this.model),this.foldedIds=new Set,this.step=`tree`,this.operation=`continue`,this.summaryMode=`none`,this.customInstructions=``,this.busy=!1,this.aborting=!1,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`}selectNode(e){this.model.nodesById.has(e)&&(this.selectedId=e,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`)}toggleNode(e,t){t.preventDefault(),t.stopPropagation();let n=mC(this.model,{selectedId:this.selectedId,foldedIds:this.foldedIds},e);this.selectedId=n.selectedId,this.foldedIds=n.foldedIds,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`}handleTreeKeyDown(e){if(e.key===`Escape`)return;let t=pC(this.model,{selectedId:this.selectedId,foldedIds:this.foldedIds},e.key);if(t.handled){if(e.preventDefault(),e.stopPropagation(),t.action===`confirm`){this.continueToAction();return}this.selectedId=t.selectedId,this.foldedIds=t.foldedIds,this.pendingFocus=`tree`}}continueToAction(){this.busy||this.selectedId===void 0||!this.model.nodesById.has(this.selectedId)||(hC(this.summaryMode,this.customInstructions).ok||(this.summaryMode=`none`,this.customInstructions=``),this.step=`action`,this.error=``,this.statusMessage=``,this.pendingFocus=`operation`)}selectOperation(e){this.busy||(this.operation=e,this.error=``,this.statusMessage=``,this.pendingFocus=`operation`)}returnToTree(){this.busy||(this.step=`tree`,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`)}selectSummaryMode(e){this.busy||(this.summaryMode=e,this.error=``,this.statusMessage=``,this.pendingFocus=e===`custom`?`custom`:`summary`)}handleCustomInstructionsInput(e){e.currentTarget instanceof HTMLTextAreaElement&&(this.customInstructions=e.currentTarget.value,this.error=``,this.statusMessage=``)}primaryActionLabel(){return this.busy?this.operation===`fork`?`正在分叉…`:this.summaryMode===`none`?`正在继续…`:`正在生成摘要…`:this.operation===`continue`?`从此处继续`:`分叉为新会话`}submitSelectedOperation(){return this.operation===`continue`?this.submitNavigation():this.submitFork()}async submitNavigation(){if(this.busy||this.selectedId===void 0)return;let e=hC(this.summaryMode,this.customInstructions);if(!e.ok){this.error=``,this.statusMessage=``,this.pendingFocus=`custom`,this.requestUpdate();return}let t=this.onNavigate;if(t===void 0){this.error=`会话树导航不可用。请关闭并重新打开 /tree,然后重试。`;return}let n=this.selectedId,r=++this.operationGeneration;this.busy=!0,this.aborting=!1,this.error=``,this.statusMessage=``;try{let i=await t(n,e.choice);if(r!==this.operationGeneration||(this.busy=!1,this.aborting=!1,!i.cancelled))return;this.step=`tree`,this.statusMessage=i.aborted===!0?`摘要已取消,所选历史条目未更改。`:`导航已取消,所选历史条目未更改。`,this.pendingFocus=`tree`}catch(e){if(r!==this.operationGeneration)return;this.busy=!1,this.aborting=!1,this.statusMessage=``,this.error=`无法导航会话历史:${EC(e)}`}}async submitFork(){if(this.busy||this.selectedId===void 0)return;let e=this.onFork;if(e===void 0){this.error=`会话树分叉不可用。请关闭并重新打开 /tree,然后重试。`;return}let t=this.selectedId,n=++this.operationGeneration;this.busy=!0,this.error=``,this.statusMessage=``;try{let r=await e(t);if(n!==this.operationGeneration||(this.busy=!1,!r.cancelled))return;this.statusMessage=`分叉已取消,原会话保持不变。`,this.pendingFocus=`operation`}catch(e){if(n!==this.operationGeneration)return;this.busy=!1,this.statusMessage=``,this.error=`无法分叉会话:${EC(e)}`}}async abortNavigation(){if(!this.busy||this.summaryMode===`none`||this.aborting)return;let e=this.onAbort;if(e===void 0){this.error=`无法从此客户端取消摘要。`;return}let t=this.operationGeneration;this.aborting=!0,this.error=``,this.statusMessage=`正在取消摘要…`;try{await e()}catch(e){if(t!==this.operationGeneration)return;this.aborting=!1,this.statusMessage=``,this.error=`无法取消摘要:${EC(e)}`}}requestDismissal(){this.step===`action`?this.returnToTree():this.onCancel?.()}requestBusyEscape(){this.operation===`continue`&&this.summaryMode!==`none`&&this.abortNavigation()}focusSelectedTreeItem(){let e=this.selectedId;if(e===void 0){this.renderRoot.querySelector(`.close-button`)?.focus();return}let t=this.renderRoot.querySelectorAll(`[data-tree-node-id]`);for(let n of t)if(n.dataset.treeNodeId===e){n.focus(),n.scrollIntoView({block:`nearest`});return}}static{this.styles=h`
|
|
1701
1701
|
:host { position: fixed; inset: 0; z-index: 40; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
1702
1702
|
* { box-sizing: border-box; }
|
|
1703
1703
|
modal-surface { --modal-surface-width: 100%; --modal-surface-height: 100dvh; --modal-surface-max-height: 100dvh; --modal-surface-border: 0; --modal-surface-radius: 0; --modal-surface-shadow: none; }
|
|
@@ -1795,7 +1795,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1795
1795
|
.custom-focus, .validation-error { margin-inline-start: 0; }
|
|
1796
1796
|
footer { flex-wrap: wrap; }
|
|
1797
1797
|
}
|
|
1798
|
-
`}};W([x({attribute:!1})],yC.prototype,`tree`,void 0),W([x({attribute:!1})],yC.prototype,`onNavigate`,void 0),W([x({attribute:!1})],yC.prototype,`onFork`,void 0),W([x({attribute:!1})],yC.prototype,`onAbort`,void 0),W([x({attribute:!1})],yC.prototype,`onCancel`,void 0),W([S()],yC.prototype,`selectedId`,void 0),W([S()],yC.prototype,`foldedIds`,void 0),W([S()],yC.prototype,`step`,void 0),W([S()],yC.prototype,`operation`,void 0),W([S()],yC.prototype,`summaryMode`,void 0),W([S()],yC.prototype,`customInstructions`,void 0),W([S()],yC.prototype,`busy`,void 0),W([S()],yC.prototype,`aborting`,void 0),W([S()],yC.prototype,`error`,void 0),W([S()],yC.prototype,`statusMessage`,void 0),yC=W([b(`session-tree-navigator`)],yC);function bC(e){return Math.min(Math.max(0,e),_C)}function xC(e){return e===`user`||e===`custom-message`}function SC(e){return vC[e]}function CC(e){return e instanceof Error?e.message:String(e)}var{I:wC}=ct,TC=e=>e,EC=()=>document.createComment(``),DC=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new wC(r.insertBefore(EC(),i),r.insertBefore(EC(),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=TC(e).nextSibling;TC(r).insertBefore(e,i),e=t}}}return n},OC=(e,t,n=e)=>(e._$AI(t,n),e),kC={},AC=(e,t=kC)=>e._$AH=t,jC=e=>e._$AH,MC=e=>{e._$AR(),e._$AA.remove()},NC=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},PC=mg(class extends hg{constructor(e){if(super(e),e.type!==pg.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=jC(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]=OC(i[d],a[p]),d++,p++;else if(s[f]===o[m])c[m]=OC(i[f],a[m]),f--,m--;else if(s[d]===o[m])c[m]=OC(i[d],a[m]),DC(e,c[m+1],i[d]),d++,m--;else if(s[f]===o[p])c[p]=OC(i[f],a[p]),DC(e,i[d],i[f]),f--,p++;else if(l===void 0&&(l=NC(o,p,m),u=NC(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=DC(e,i[d]);OC(t,a[p]),c[p]=t}else c[p]=OC(n,a[p]),DC(e,i[d],n),i[t]=null;p++}else MC(i[f]),f--;else MC(i[d]),d++;for(;p<=m;){let t=DC(e,c[m+1]);OC(t,a[p]),c[p++]=t}for(;d<=f;){let e=i[d++];e!==null&&MC(e)}return this.ut=o,AC(e,c),Je}}),FC=`pi-web:chat-groups:`,IC={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(RC(e));return t===null||t===``?void 0:zC(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(RC(e),JSON.stringify(t))}catch{}}},LC=class{constructor(e=IC){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&&VC(i,this.openGroupKeys)&&VC(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 RC(e){return`${FC}${e}`}function zC(e){if(Array.isArray(e))return{open:BC(e),closedDefaultOpen:[]};if(HC(e))return{open:Array.isArray(e.open)?BC(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?BC(e.closedDefaultOpen):[]}}function BC(e){return e.filter(e=>typeof e==`string`)}function VC(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function HC(e){return typeof e==`object`&&!!e}function UC(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=>qC(e,t)),s=e.parts.filter(t=>!qC(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(GC(t)){let e=KC(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 WC(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 GC(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function KC(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function qC(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 JC(e,t){let n=XC($C(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function YC(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=ZC(r,t.markerOffset);return}e.scrollTop=QC(e.scrollHeight,t.distanceFromBottom)}function XC(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 ZC(e,t){return e-t}function QC(e,t){return Math.max(0,e-t)}function $C(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 ew=600,tw=1;function nw(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:rw(e)||iw(e)}function rw(e){return e.scrollTop<(e.topThreshold??Math.max(ew,e.clientHeight))}function iw(e){return e.scrollHeight<=e.clientHeight+tw}var aw=`pi-web:chat-scroll:`,ow=180,sw=48,cw=2,lw={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)}},uw={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},dw=class{constructor(e=lw,t=uw){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=ow){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=cw){if(e===``||t===void 0||!mw(t))return`skipped`;try{if(gw(t,r))return this.storage.setItem(fw(e),JSON.stringify({mode:`bottom`})),`saved`;let i=vw(t,n);if(i===void 0)return`skipped`;let a=_w(t,i);return this.storage.setItem(fw(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||!mw(t))return{status:`skipped`};let i=bw(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(fw(e));if(t===null||t===``)return;let n=JSON.parse(t);return pw(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!mw(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function fw(e){return`${aw}${e}`}function pw(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 mw(e){return e.clientHeight>0&&e.scrollHeight>0}function hw(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function gw(e,t=sw){return hw(e)<t}function _w(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:xw(t)??``,offset:t.getBoundingClientRect().top-n}}function vw(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(xw(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 yw(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 bw(e,t){return e.find(e=>xw(e)===t)}function xw(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}var Sw=class extends y{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=ru(e.questions,this.answers),n=iu(e.questions,this.answers);return g`
|
|
1798
|
+
`}};W([x({attribute:!1})],SC.prototype,`tree`,void 0),W([x({attribute:!1})],SC.prototype,`onNavigate`,void 0),W([x({attribute:!1})],SC.prototype,`onFork`,void 0),W([x({attribute:!1})],SC.prototype,`onAbort`,void 0),W([x({attribute:!1})],SC.prototype,`onCancel`,void 0),W([S()],SC.prototype,`selectedId`,void 0),W([S()],SC.prototype,`foldedIds`,void 0),W([S()],SC.prototype,`step`,void 0),W([S()],SC.prototype,`operation`,void 0),W([S()],SC.prototype,`summaryMode`,void 0),W([S()],SC.prototype,`customInstructions`,void 0),W([S()],SC.prototype,`busy`,void 0),W([S()],SC.prototype,`aborting`,void 0),W([S()],SC.prototype,`error`,void 0),W([S()],SC.prototype,`statusMessage`,void 0),SC=W([b(`session-tree-navigator`)],SC);function CC(e){return Math.min(Math.max(0,e),bC)}function wC(e){return e===`user`||e===`custom-message`}function TC(e){return xC[e]}function EC(e){return e instanceof Error?e.message:String(e)}var{I:DC}=ct,OC=e=>e,kC=()=>document.createComment(``),AC=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new DC(r.insertBefore(kC(),i),r.insertBefore(kC(),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=OC(e).nextSibling;OC(r).insertBefore(e,i),e=t}}}return n},jC=(e,t,n=e)=>(e._$AI(t,n),e),MC={},NC=(e,t=MC)=>e._$AH=t,PC=e=>e._$AH,FC=e=>{e._$AR(),e._$AA.remove()},IC=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},LC=_g(class extends vg{constructor(e){if(super(e),e.type!==gg.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=PC(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]=jC(i[d],a[p]),d++,p++;else if(s[f]===o[m])c[m]=jC(i[f],a[m]),f--,m--;else if(s[d]===o[m])c[m]=jC(i[d],a[m]),AC(e,c[m+1],i[d]),d++,m--;else if(s[f]===o[p])c[p]=jC(i[f],a[p]),AC(e,i[d],i[f]),f--,p++;else if(l===void 0&&(l=IC(o,p,m),u=IC(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=AC(e,i[d]);jC(t,a[p]),c[p]=t}else c[p]=jC(n,a[p]),AC(e,i[d],n),i[t]=null;p++}else FC(i[f]),f--;else FC(i[d]),d++;for(;p<=m;){let t=AC(e,c[m+1]);jC(t,a[p]),c[p++]=t}for(;d<=f;){let e=i[d++];e!==null&&FC(e)}return this.ut=o,NC(e,c),Je}}),RC=`pi-web:chat-groups:`,zC={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(VC(e));return t===null||t===``?void 0:HC(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(VC(e),JSON.stringify(t))}catch{}}},BC=class{constructor(e=zC){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&&WC(i,this.openGroupKeys)&&WC(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 VC(e){return`${RC}${e}`}function HC(e){if(Array.isArray(e))return{open:UC(e),closedDefaultOpen:[]};if(GC(e))return{open:Array.isArray(e.open)?UC(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?UC(e.closedDefaultOpen):[]}}function UC(e){return e.filter(e=>typeof e==`string`)}function WC(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function GC(e){return typeof e==`object`&&!!e}function KC(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=>XC(e,t)),s=e.parts.filter(t=>!XC(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(JC(t)){let e=YC(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 qC(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 JC(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function YC(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function XC(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 ZC(e,t){let n=$C(nw(e,t)),r={distanceFromBottom:e.scrollHeight-e.scrollTop};return n===void 0?r:{...r,markerId:n.id,markerOffset:n.offset}}function QC(e,t,n){if(n!==void 0&&t.markerOffset!==void 0){let r=n.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=ew(r,t.markerOffset);return}e.scrollTop=tw(e.scrollHeight,t.distanceFromBottom)}function $C(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 ew(e,t){return e-t}function tw(e,t){return Math.max(0,e-t)}function nw(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 rw=600,iw=1;function aw(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:ow(e)||sw(e)}function ow(e){return e.scrollTop<(e.topThreshold??Math.max(rw,e.clientHeight))}function sw(e){return e.scrollHeight<=e.clientHeight+iw}var cw=`pi-web:chat-scroll:`,lw=180,uw=48,dw=2,fw={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)}},pw={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},mw=class{constructor(e=fw,t=pw){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=lw){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=dw){if(e===``||t===void 0||!_w(t))return`skipped`;try{if(yw(t,r))return this.storage.setItem(hw(e),JSON.stringify({mode:`bottom`})),`saved`;let i=xw(t,n);if(i===void 0)return`skipped`;let a=bw(t,i);return this.storage.setItem(hw(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||!_w(t))return{status:`skipped`};let i=Cw(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(hw(e));if(t===null||t===``)return;let n=JSON.parse(t);return gw(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!_w(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function hw(e){return`${cw}${e}`}function gw(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 _w(e){return e.clientHeight>0&&e.scrollHeight>0}function vw(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function yw(e,t=uw){return vw(e)<t}function bw(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:ww(t)??``,offset:t.getBoundingClientRect().top-n}}function xw(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0;for(let e of t){if(ww(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 Sw(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 Cw(e,t){return e.find(e=>ww(e)===t)}function ww(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}var Tw=class extends y{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=ru(e.questions,this.answers),n=iu(e.questions,this.answers);return g`
|
|
1799
1799
|
<article class="card open-card" aria-labelledby="ask-user-heading">
|
|
1800
1800
|
<header class="card-header">
|
|
1801
1801
|
<h2 id="ask-user-heading">问题</h2>
|
|
@@ -1820,7 +1820,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1820
1820
|
<fieldset
|
|
1821
1821
|
id=${this.questionFieldsetId(n)}
|
|
1822
1822
|
class=${`question${i?` answered`:``}`}
|
|
1823
|
-
aria-describedby=${
|
|
1823
|
+
aria-describedby=${hg(a)}
|
|
1824
1824
|
tabindex="-1"
|
|
1825
1825
|
>
|
|
1826
1826
|
<legend>
|
|
@@ -1894,7 +1894,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
1894
1894
|
<span class=${`header-status ${e.reason}`}>${t}</span>
|
|
1895
1895
|
</header>
|
|
1896
1896
|
<p class="record-summary">
|
|
1897
|
-
${e.reason===`superseded`?`较新的问题组已替代此问题组。下方显示的草稿回答未发送给模型。`:
|
|
1897
|
+
${e.reason===`superseded`?`较新的问题组已替代此问题组。下方显示的草稿回答未发送给模型。`:Ew(e)}
|
|
1898
1898
|
</p>
|
|
1899
1899
|
<div class="record-questions">
|
|
1900
1900
|
${e.questions.map((t,n)=>this.renderQuestionRecord(e,t,n))}
|
|
@@ -2077,7 +2077,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2077
2077
|
.confirmation-actions { justify-content: flex-end; }
|
|
2078
2078
|
.primary-action { min-height: 42px; }
|
|
2079
2079
|
}
|
|
2080
|
-
`}};W([x({attribute:!1})],
|
|
2080
|
+
`}};W([x({attribute:!1})],Tw.prototype,`ask`,void 0),W([x({attribute:!1})],Tw.prototype,`outcome`,void 0),W([x({attribute:!1})],Tw.prototype,`draftSessionId`,void 0),W([x({attribute:!1})],Tw.prototype,`onSubmit`,void 0),W([S()],Tw.prototype,`answers`,void 0),W([S()],Tw.prototype,`confirmingPartialSubmit`,void 0),W([S()],Tw.prototype,`submitting`,void 0),Tw=W([b(`ask-user-card`)],Tw);function Ew(e){let t=e.questions.length,n=`已回答 ${e.answeredCount.toString()}/${t.toString()} 个问题`;return e.unansweredIds.length===0?`${n};全部问题均已回答`:`${n};未回答:${e.unansweredIds.join(`、`)}`}var Dw=1e3;function Ow(e){switch(e){case`answered`:return`已回答`;case`cancelled`:return`已取消`;case`timeout`:return`已超时`;case`aborted`:return`已中止`;case`session-ended`:return`会话已结束`}}function kw(e){switch(e.reason){case`answered`:{let t=e.answer;return t===void 0?`已关闭,但未记录回答。`:typeof t==`boolean`?`回答:${t?`是`:`否`}`:t===``?`回答为空。`:`回答:${t}`}case`cancelled`:return`已取消,未回答。`;case`timeout`:return`对话框超时前未收到回答。`;case`aborted`:return`本轮运行在回答前已中止。`;case`session-ended`:return`会话在回答前已结束。`}}function Aw(e,t){if(e===void 0)return;let n=Date.parse(e);if(!Number.isFinite(n))return;let r=n-t;if(r<=0)return`即将自动取消`;let i=Math.ceil(r/1e3);if(i>=3600){let e=Math.floor(i/3600),t=Math.floor(i%3600/60);return`${String(e)} 小时 ${String(t)} 分钟后自动取消`}if(i>=60){let e=Math.floor(i/60);return`${String(e)} 分 ${String(i%60)} 秒后自动取消`}return`${String(i)} 秒后自动取消`}var jw=class extends y{constructor(...e){super(...e),this.inputValue=``,this.closing=!1,this.countdownNow=0}connectedCallback(){super.connectedCallback(),this.syncCountdownTimer()}disconnectedCallback(){this.stopCountdownTimer(),super.disconnectedCallback()}willUpdate(e){if(!e.has(`dialog`)&&!e.has(`outcome`))return;let t=this.currentIdentity();t!==this.dialogIdentity&&(this.dialogIdentity=t,this.inputValue=``,this.closing=!1),this.syncCountdownTimer()}render(){return this.outcome===void 0?this.dialog===void 0?null:this.renderOpen(this.dialog):this.renderClosed(this.outcome)}renderOpen(e){let t=Aw(e.timeoutAt,this.countdownNow===0?Date.now():this.countdownNow);return g`
|
|
2081
2081
|
<article class="card open-card" aria-labelledby="extension-dialog-heading">
|
|
2082
2082
|
<header class="card-header">
|
|
2083
2083
|
<h2 id="extension-dialog-heading">${e.title}</h2>
|
|
@@ -2108,7 +2108,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2108
2108
|
type="text"
|
|
2109
2109
|
name="dialog-answer"
|
|
2110
2110
|
aria-label="你的回答"
|
|
2111
|
-
placeholder=${
|
|
2111
|
+
placeholder=${hg(e.placeholder)}
|
|
2112
2112
|
maxlength=${String(Wt)}
|
|
2113
2113
|
.value=${this.inputValue}
|
|
2114
2114
|
?disabled=${this.closing}
|
|
@@ -2123,14 +2123,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2123
2123
|
<article class="card closed-card" aria-labelledby="extension-dialog-closed-heading">
|
|
2124
2124
|
<header class="card-header">
|
|
2125
2125
|
<h2 id="extension-dialog-closed-heading">${e.dialog.title}</h2>
|
|
2126
|
-
<span class=${`header-status ${e.reason}`}>${
|
|
2126
|
+
<span class=${`header-status ${e.reason}`}>${Ow(e.reason)}</span>
|
|
2127
2127
|
</header>
|
|
2128
|
-
<p class="closed-summary">${
|
|
2128
|
+
<p class="closed-summary">${kw(e)}</p>
|
|
2129
2129
|
<footer class="dialog-footer">
|
|
2130
2130
|
<button class="secondary-action" type="button" @click=${()=>{this.dismissClosed(e)}}>关闭</button>
|
|
2131
2131
|
</footer>
|
|
2132
2132
|
</article>
|
|
2133
|
-
`}answerDialog(e,t){this.closeWith(e,()=>this.onAnswer?.(e.dialogId,t))}cancelDialog(e){this.closeWith(e,()=>this.onCancel?.(e.dialogId))}submitInput(e,t){e.preventDefault(),this.answerDialog(t,this.inputValue)}closeWith(e,t){if(this.closing)return;this.closing=!0;let n=e.dialogId;Promise.resolve().then(t).catch(()=>{}).finally(()=>{this.dialog?.dialogId===n&&(this.closing=!1)})}changeInput(e){let t=e.currentTarget;t instanceof HTMLInputElement&&(this.inputValue=t.value)}dismissClosed(e){this.onDismiss?.(e.dialog.dialogId)}currentIdentity(){if(this.outcome!==void 0)return`closed:${this.outcome.dialog.dialogId}`;if(this.dialog!==void 0)return`open:${this.dialog.dialogId}`}syncCountdownTimer(){let e=this.isConnected&&this.outcome===void 0&&this.dialog?.timeoutAt!==void 0;if(e&&this.countdownTimer===void 0){this.countdownNow=Date.now(),this.countdownTimer=window.setInterval(()=>{this.countdownNow=Date.now()},
|
|
2133
|
+
`}answerDialog(e,t){this.closeWith(e,()=>this.onAnswer?.(e.dialogId,t))}cancelDialog(e){this.closeWith(e,()=>this.onCancel?.(e.dialogId))}submitInput(e,t){e.preventDefault(),this.answerDialog(t,this.inputValue)}closeWith(e,t){if(this.closing)return;this.closing=!0;let n=e.dialogId;Promise.resolve().then(t).catch(()=>{}).finally(()=>{this.dialog?.dialogId===n&&(this.closing=!1)})}changeInput(e){let t=e.currentTarget;t instanceof HTMLInputElement&&(this.inputValue=t.value)}dismissClosed(e){this.onDismiss?.(e.dialog.dialogId)}currentIdentity(){if(this.outcome!==void 0)return`closed:${this.outcome.dialog.dialogId}`;if(this.dialog!==void 0)return`open:${this.dialog.dialogId}`}syncCountdownTimer(){let e=this.isConnected&&this.outcome===void 0&&this.dialog?.timeoutAt!==void 0;if(e&&this.countdownTimer===void 0){this.countdownNow=Date.now(),this.countdownTimer=window.setInterval(()=>{this.countdownNow=Date.now()},Dw);return}e||this.stopCountdownTimer()}stopCountdownTimer(){this.countdownTimer!==void 0&&(window.clearInterval(this.countdownTimer),this.countdownTimer=void 0)}static{this.styles=h`
|
|
2134
2134
|
:host {
|
|
2135
2135
|
display: block;
|
|
2136
2136
|
box-sizing: border-box;
|
|
@@ -2235,7 +2235,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2235
2235
|
@container (max-width: 580px) {
|
|
2236
2236
|
.primary-action { min-height: 42px; }
|
|
2237
2237
|
}
|
|
2238
|
-
`}};W([x({attribute:!1})],
|
|
2238
|
+
`}};W([x({attribute:!1})],jw.prototype,`dialog`,void 0),W([x({attribute:!1})],jw.prototype,`outcome`,void 0),W([x({attribute:!1})],jw.prototype,`onAnswer`,void 0),W([x({attribute:!1})],jw.prototype,`onCancel`,void 0),W([x({attribute:!1})],jw.prototype,`onDismiss`,void 0),W([S()],jw.prototype,`inputValue`,void 0),W([S()],jw.prototype,`closing`,void 0),W([S()],jw.prototype,`countdownNow`,void 0),jw=W([b(`extension-dialog-card`)],jw);var Mw=class extends y{constructor(...e){super(...e),this.positionPercent=0,this.loadedPercent=100}render(){let e=Nw(this.positionPercent),t=Nw(this.loadedPercent),n=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return g`
|
|
2239
2239
|
<div
|
|
2240
2240
|
class="meter"
|
|
2241
2241
|
style=${`--position:${e.toFixed(2)}%;`}
|
|
@@ -2258,7 +2258,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2258
2258
|
.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); }
|
|
2259
2259
|
.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)); }
|
|
2260
2260
|
.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%); }
|
|
2261
|
-
`}};W([x({type:Number})],
|
|
2261
|
+
`}};W([x({type:Number})],Mw.prototype,`positionPercent`,void 0),W([x({type:Number})],Mw.prototype,`loadedPercent`,void 0),Mw=W([b(`conversation-meter`)],Mw);function Nw(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}var Pw=new H.Renderer;Pw.html=({text:e})=>Rw(e);var Fw=300,Iw=new Map;function Lw(e){let t=Iw.get(e);if(t!==void 0)return t;let n=Bw(H.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:Pw}));if(Iw.set(e,n),Iw.size>Fw){let e=Iw.keys().next().value;e!==void 0&&Iw.delete(e)}return n}function Rw(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}var zw=`table-scroll`;function Bw(e){let t=document.createElement(`template`);return t.innerHTML=e,t.content.querySelectorAll(`script, style, iframe, object, embed`).forEach(e=>{e.remove()}),t.content.querySelectorAll(`*`).forEach(e=>{for(let t of[...e.attributes]){let n=t.name.toLowerCase();n.startsWith(`on`)&&e.removeAttribute(t.name),(n===`href`||n===`src`)&&!Hw(t.value)&&e.removeAttribute(t.name)}e.tagName===`A`&&(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),Vw(t.content),t.innerHTML}function Vw(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(zw)===!0)return;let t=document.createElement(`div`);t.className=zw,t.setAttribute(`role`,`region`),t.setAttribute(`aria-label`,`表格`),t.setAttribute(`tabindex`,`0`),e.before(t),t.append(e)})}function Hw(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}var Uw=h`
|
|
2262
2262
|
:host { display: block; }
|
|
2263
2263
|
.formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
|
|
2264
2264
|
p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
|
|
@@ -2284,18 +2284,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2284
2284
|
th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
|
|
2285
2285
|
th { background: var(--pi-surface); }
|
|
2286
2286
|
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); }
|
|
2287
|
-
`,
|
|
2287
|
+
`,Ww=class extends y{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}>${bg(Lw(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)Gw(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 cS(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=Uw}};W([x()],Ww.prototype,`text`,void 0),W([x()],Ww.prototype,`highlight`,void 0),Ww=W([b(`formatted-text`)],Ww);function Gw(e,t){let n=e.data,r=[...n.matchAll(new RegExp(Kw(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 Kw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}var qw=180,Jw=class extends y{constructor(...e){super(...e),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){let e=this.execution;if(e===void 0)return null;let t=Xw(e.args),n=Qw(e.details),r=e.preview,i=n??r?.diff,a=i===void 0?void 0:$w(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=Yw(e,t);return g`
|
|
2288
2288
|
<section class=${`tool-card ${e.status}`}>
|
|
2289
2289
|
<div class="tool-header">
|
|
2290
2290
|
<div class="tool-title">
|
|
2291
|
-
<span class="status-icon" aria-hidden="true">${
|
|
2291
|
+
<span class="status-icon" aria-hidden="true">${rT(e.status)}</span>
|
|
2292
2292
|
<strong>${e.toolName}</strong>
|
|
2293
2293
|
${this.renderHeaderTarget(l)}
|
|
2294
2294
|
</div>
|
|
2295
2295
|
<div class="tool-meta">
|
|
2296
|
-
${
|
|
2296
|
+
${Zw(e)===void 0?null:g`<span>${Zw(e)}</span>`}
|
|
2297
2297
|
${a===void 0?null:g`<span class="diff-stats"><b class="added">+${a.added}</b><span>/</span><b class="removed">-${a.removed}</b></span>`}
|
|
2298
|
-
<span class="status-label">${
|
|
2298
|
+
<span class="status-label">${iT(e.status)}</span>
|
|
2299
2299
|
</div>
|
|
2300
2300
|
</div>
|
|
2301
2301
|
|
|
@@ -2320,7 +2320,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2320
2320
|
`}
|
|
2321
2321
|
</details>
|
|
2322
2322
|
`}renderDiffBody(e,t,n){let r=e.split(`
|
|
2323
|
-
`),i=!this.showFullDiff&&r.length>
|
|
2323
|
+
`),i=!this.showFullDiff&&r.length>qw,a=i?r.slice(0,qw):r;return g`
|
|
2324
2324
|
<details class="diff-details" ?open=${this.diffOpen} @toggle=${e=>{this.onDiffToggle(e)}}>
|
|
2325
2325
|
<summary>
|
|
2326
2326
|
<span>${t}</span>
|
|
@@ -2331,14 +2331,14 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2331
2331
|
<span>${i?`显示 ${String(a.length)} / ${String(r.length)} 行`:`完整 diff`}</span>
|
|
2332
2332
|
<button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?`已复制`:`复制 diff`}</button>
|
|
2333
2333
|
</div>
|
|
2334
|
-
<pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${
|
|
2334
|
+
<pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>g`<span class=${eT(e)}>${e}</span>`)}</code></pre>
|
|
2335
2335
|
${i?g`
|
|
2336
2336
|
<button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
|
|
2337
2337
|
显示全部 ${String(r.length)} 行 diff
|
|
2338
2338
|
</button>
|
|
2339
2339
|
`:null}
|
|
2340
2340
|
</details>
|
|
2341
|
-
`}onDiffToggle(e){let t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){if(!await
|
|
2341
|
+
`}onDiffToggle(e){let t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){if(!await cS(e)){this.copied=!1;return}this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}static{this.styles=h`
|
|
2342
2342
|
:host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
|
|
2343
2343
|
.tool-card { display: grid; gap: 8px; width: 100%; max-width: 100%; min-width: 0; box-sizing: border-box; overflow: hidden; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); padding: 9px; color: var(--pi-text); }
|
|
2344
2344
|
.tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
|
|
@@ -2382,24 +2382,24 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2382
2382
|
.diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
|
|
2383
2383
|
.diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
|
|
2384
2384
|
.show-more { justify-self: start; }
|
|
2385
|
-
`}};W([x({attribute:!1})],
|
|
2386
|
-
`))
|
|
2385
|
+
`}};W([x({attribute:!1})],Jw.prototype,`execution`,void 0),W([S()],Jw.prototype,`showFullDiff`,void 0),W([S()],Jw.prototype,`copied`,void 0),W([S()],Jw.prototype,`diffOpen`,void 0),Jw=W([b(`tool-execution-view`)],Jw);function Yw(e,t){if(t!==void 0&&t!==``)return{label:`文件`,text:t};let n=sT(e.args,`command`);if(n!==void 0&&n!==``)return{label:`命令`,text:n};if(e.summary!==``)return{label:`输入`,text:e.summary}}function Xw(e){return sT(e,`path`)??sT(e,`file_path`)}function Zw(e){if(e.toolName!==`edit`)return;let t=oT(e.args,`edits`);if(Array.isArray(t))return`${String(t.length)} 处编辑`;if(typeof oT(e.args,`oldText`)==`string`&&typeof oT(e.args,`newText`)==`string`)return`1 处编辑`}function Qw(e){return sT(e,`diff`)}function $w(e){let t=0,n=0;for(let r of e.split(`
|
|
2386
|
+
`))tT(r)?t++:nT(r)&&n++;return{added:t,removed:n}}function eT(e){return tT(e)?`added`:nT(e)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`+++`)||e.startsWith(`---`)?`file`:e.startsWith(`diff `)||e.startsWith(`index `)?`meta`:`context`}function tT(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)}function nT(e){return e.startsWith(`-`)&&!e.startsWith(`---`)}function rT(e){return e===`success`?`✓`:e===`error`?`✖`:e===`running`?`●`:`○`}function iT(e){return e===`success`?`完成`:e===`error`?`失败`:e===`running`?`运行中`:`等待中`}function aT(e){return typeof e==`object`&&!!e}function oT(e,t){return aT(e)?e[t]:void 0}function sT(e,t){let n=oT(e,t);return typeof n==`string`?n:void 0}var cT=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`medium`}),lT=new Intl.DateTimeFormat(void 0,{timeStyle:`short`});function uT(e){return g`
|
|
2387
2387
|
<svg class=${`notification-icon notification-disclosure-icon${e?``:` expanded`}`} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2388
2388
|
<path d="m9 18 6-6-6-6"></path>
|
|
2389
2389
|
</svg>
|
|
2390
|
-
`}function
|
|
2390
|
+
`}function dT(){return g`
|
|
2391
2391
|
<svg class="notification-icon notification-close-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2392
2392
|
<path d="M6 6l12 12"></path>
|
|
2393
2393
|
<path d="M18 6 6 18"></path>
|
|
2394
2394
|
</svg>
|
|
2395
|
-
`}function
|
|
2395
|
+
`}function fT(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 pT(e){return mT(e,0,100)}function mT(e,t,n){return Number.isFinite(e)?Math.min(n,Math.max(t,e)):t}function hT(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 gT(e){return{src:`data:${e.mimeType};base64,${e.data}`,alt:`附加图片`}}function _T(e){return e===void 0||e===``?`工具输出`:`${e} 输出`}var vT={user:`用户`,assistant:`助手`,tool:`工具`,system:`系统`,bash:`命令`,skill:`技能`};function yT(e){return vT[e]}function bT(e){return`m:${String(e)}`}function xT(e){return`g:${String(e)}`}function ST(e){return`e:${String(e)}`}function CT(e){return`g:${String(e)}`}function wT(e){return e?`msg event-group live`:`msg event-group`}function TT(e){return e?`实时事件`:`事件`}function ET(e,t,n){return e.source===`server`&&t&&n}function DT(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 OT(e){let t=e.meta?.timestamp,n=t===void 0?void 0:kT(t),r=AT(e),i=e.meta?.thinkingLevel,a=[n,r,i===void 0||i===``?void 0:Rs(i)].filter(e=>e!==void 0&&e!==``);return a.length===0?`没有可用的 Pi 消息元数据`:a.join(` · `)}function kT(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return cT.format(t)}function AT(e){let t=e.meta?.model;if(t===void 0)return;let n=t.responseId??t.id;return n===void 0||n===``?t.provider:t.provider!==void 0&&t.provider!==``?`${t.provider}/${n}`:n}var q=class extends y{constructor(...e){super(...e),this.messages=[],this.sessionId=``,this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.clientQueuedMessages=[],this.pendingDialogs=[],this.closedDialogs=[],this.askDraftSessionId=``,this.canClearServerQueue=!1,this.warningsVisible=!0,this.pinnedToBottom=!0,this.zoomedImage=void 0,this.collapsedNotificationTargetKeys=new Set,this.disclosures=new BC,this.scrollController=new mw,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.releaseImageZoomModal(),this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.loadMoreCheckFrame!==void 0&&cancelAnimationFrame(this.loadMoreCheckFrame),this.scrollToBottomFrame!==void 0&&cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToOpenAskFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenAskFrame),this.scrollToOpenAskFrame=void 0),this.scrollToOpenDialogFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenDialogFrame),this.scrollToOpenDialogFrame=void 0),this.conversationRailFrame!==void 0&&cancelAnimationFrame(this.conversationRailFrame),window.removeEventListener(`resize`,this.onViewportResize),window.removeEventListener(`pagehide`,this.onPageHide),window.visualViewport?.removeEventListener(`resize`,this.onViewportResize),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),this.scrollToOpenDialogFrame!==void 0&&(cancelAnimationFrame(this.scrollToOpenDialogFrame),this.scrollToOpenDialogFrame=void 0)}willUpdate(e){e.has(`sessionId`)?(this.savePreviousSessionScrollPosition(e.get(`sessionId`)),this.prepareSessionUiState()):e.has(`notificationInbox`)&&this.notificationTargetChanged(e.get(`notificationInbox`))&&(this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0),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`)),n=e.has(`pendingDialogs`)&&this.isNewOpenDialog(e.get(`pendingDialogs`));!e.has(`sessionId`)&&t&&this.pinnedToBottom?this.scrollToOpenAsk():!e.has(`sessionId`)&&n&&this.pinnedToBottom?this.scrollToOpenDialog():!e.has(`sessionId`)&&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`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`))&&this.continuePendingScrollRestore(),(e.has(`messages`)||e.has(`hasMore`)||e.has(`loadingMore`))&&this.requestLoadMoreIfNeeded(),e.has(`notificationInbox`)&&this.pendingNotificationFocus!==void 0&&this.focusPendingNotificationTarget(),e.has(`zoomedImage`)&&this.syncImageZoomDialog()}liveTailContentChanged(e){return e.has(`messages`)||e.has(`pendingAsk`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`)||e.has(`pendingMessageCount`)||e.has(`clientQueuedMessages`)}syncImageZoomDialog(){let e=this.imageZoomDialog;if(e!==void 0){if(this.zoomedImage!==void 0){if(this.imageZoomModalRegistration===void 0){let t=Rh({element:e,nativeTopLayer:!0,focus:()=>{(this.renderRoot.querySelector(`.image-zoom-close`)??e).focus()}});this.imageZoomModalRegistration=t;try{e.open||e.showModal()}catch(e){throw this.imageZoomModalRegistration=void 0,t.unregister(),e}}this.imageZoomModalRegistration.focus();return}e.open&&e.close(),this.releaseImageZoomModal()}}releaseImageZoomModal(){let e=this.imageZoomModalRegistration;this.imageZoomModalRegistration=void 0,e?.unregister()}notificationTargetChanged(e){let t=this.notificationInbox;return!fT(e)||t===void 0?e!==t:Hf(e)!==Hf(t)}render(){let e=this.groupedMessages();return g`
|
|
2396
2396
|
${this.renderTopNotices()}
|
|
2397
2397
|
${this.renderNotificationLiveRegions()}
|
|
2398
2398
|
<div class="chat-wrap">
|
|
2399
2399
|
${this.renderConversationRail()}
|
|
2400
2400
|
<div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${e=>{this.onWheel(e)}} @touchstart=${e=>{this.onTouchStart(e)}} @touchmove=${e=>{this.onTouchMove(e)}}>
|
|
2401
2401
|
${this.renderHistoryBoundary()}
|
|
2402
|
-
${
|
|
2402
|
+
${LC(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))}
|
|
2403
2403
|
${this.renderQueuedMessages()}
|
|
2404
2404
|
${this.renderSessionActivity()}
|
|
2405
2405
|
${this.renderOpenAsk()}
|
|
@@ -2408,10 +2408,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2408
2408
|
${this.renderActivityDock()}
|
|
2409
2409
|
</div>
|
|
2410
2410
|
${this.renderImageZoom()}
|
|
2411
|
-
`}renderTopNotices(){let e=this.renderWarnings(),t=this.renderNotificationTray();return e===null&&t===null?null:g`<div class="top-notices">${e}${t}</div>`}renderNotificationTray(){let e=this.notificationInbox;if(e?.sessionId!==this.sessionId)return null;let t=
|
|
2411
|
+
`}renderTopNotices(){let e=this.renderWarnings(),t=this.renderNotificationTray();return e===null&&t===null?null:g`<div class="top-notices">${e}${t}</div>`}renderNotificationTray(){let e=this.notificationInbox;if(e?.sessionId!==this.sessionId)return null;let t=Hf(e),n=e.pendingDismissedIds.size>0||e.dismissAllPending,r=this.retainedEmptyNotificationTrayTargetKey===t,i=Rf(e);if(i===0&&!n&&!r)return null;let a=Uf(this.collapsedNotificationTargetKeys,e),o=a?`展开通知`:`折叠通知`;return g`
|
|
2412
2412
|
<section class=${`notification-tray${a?` collapsed`:``}`} role="region" aria-labelledby="session-notifications-heading" @focusout=${e=>{this.releaseEmptyNotificationTray(e)}}>
|
|
2413
2413
|
<header class="notification-header" data-notification-focus="header" tabindex="-1">
|
|
2414
|
-
<strong class="notification-heading" id="session-notifications-heading">${
|
|
2414
|
+
<strong class="notification-heading" id="session-notifications-heading">${zf(e)}</strong>
|
|
2415
2415
|
<div class="notification-header-actions">
|
|
2416
2416
|
<button
|
|
2417
2417
|
type="button"
|
|
@@ -2429,38 +2429,38 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2429
2429
|
aria-expanded=${String(!a)}
|
|
2430
2430
|
aria-controls="session-notification-list"
|
|
2431
2431
|
@click=${()=>{this.toggleNotificationTray(e,a)}}
|
|
2432
|
-
>${
|
|
2432
|
+
>${uT(a)}</button>
|
|
2433
2433
|
</div>
|
|
2434
2434
|
</header>
|
|
2435
2435
|
<div class="notification-list" id="session-notification-list" ?hidden=${a}>
|
|
2436
2436
|
${e.discardedCount===0?null:g`
|
|
2437
|
-
<p class="notification-overflow">${
|
|
2437
|
+
<p class="notification-overflow">${Gf(e.discardedCount)}</p>
|
|
2438
2438
|
`}
|
|
2439
|
-
${e.notifications.map(t=>{let n=
|
|
2439
|
+
${e.notifications.map(t=>{let n=If(t.severity),r=Kf(t);return g`
|
|
2440
2440
|
<article class=${`notification-row ${t.severity}`} data-notification-id=${t.id} tabindex="-1">
|
|
2441
2441
|
<div class="notification-metadata">
|
|
2442
2442
|
<strong class="notification-severity">${n}</strong>
|
|
2443
2443
|
<span aria-hidden="true">·</span>
|
|
2444
|
-
<time datetime=${t.receivedAt}>${
|
|
2444
|
+
<time datetime=${t.receivedAt}>${lT.format(new Date(t.receivedAt))}</time>
|
|
2445
2445
|
</div>
|
|
2446
2446
|
<p class="notification-message" dir="auto">${t.message}</p>
|
|
2447
2447
|
${r===void 0?null:g`<p class="notification-truncated">${r}</p>`}
|
|
2448
2448
|
<button
|
|
2449
2449
|
type="button"
|
|
2450
2450
|
class="notification-row-dismiss"
|
|
2451
|
-
aria-label=${
|
|
2451
|
+
aria-label=${Bf(t)}
|
|
2452
2452
|
title="关闭通知"
|
|
2453
2453
|
?disabled=${e.pendingDismissedIds.has(t.id)||e.dismissAllPending||this.onDismissNotification===void 0}
|
|
2454
2454
|
@click=${()=>{this.dismissNotification(t.id)}}
|
|
2455
|
-
>${
|
|
2455
|
+
>${dT()}</button>
|
|
2456
2456
|
</article>
|
|
2457
2457
|
`})}
|
|
2458
2458
|
</div>
|
|
2459
2459
|
</section>
|
|
2460
2460
|
`}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`
|
|
2461
|
-
<div class="visually-hidden notification-live" aria-live="polite" aria-atomic="false">${
|
|
2462
|
-
<div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${
|
|
2463
|
-
`}toggleNotificationTray(e,t){this.collapsedNotificationTargetKeys=
|
|
2461
|
+
<div class="visually-hidden notification-live" aria-live="polite" aria-atomic="false">${LC(t,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${Lf(e)}</span>`)}</div>
|
|
2462
|
+
<div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${LC(n,e=>e.id,e=>g`<span data-announcement-id=${e.id}>${Lf(e)}</span>`)}</div>
|
|
2463
|
+
`}toggleNotificationTray(e,t){this.collapsedNotificationTargetKeys=Wf(this.collapsedNotificationTargetKeys,e,!t)}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=Vf(t.notifications,e),r=Hf(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=Hf(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===Hf(r)&&Rf(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||Hf(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}Rf(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}renderWarnings(){let e=DT(this.status);return!this.warningsVisible||e.length===0?null:g`
|
|
2464
2464
|
<aside class="session-warnings" role="alert" aria-live="polite">
|
|
2465
2465
|
${this.onToggleWarnings===void 0?null:g`
|
|
2466
2466
|
<div class="session-warnings-controls">
|
|
@@ -2481,7 +2481,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2481
2481
|
${e.map(e=>{let t=e.dismissId;return g`
|
|
2482
2482
|
<div class=${e.severityClass}>
|
|
2483
2483
|
<div class="session-warning-head">
|
|
2484
|
-
${
|
|
2484
|
+
${eg(e.severity,`session-warning-icon`)}
|
|
2485
2485
|
${e.source===void 0?null:g`<span class="session-warning-source">${e.source}</span>`}
|
|
2486
2486
|
</div>
|
|
2487
2487
|
<div class="session-warning-body">
|
|
@@ -2507,7 +2507,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2507
2507
|
<img class="image-zoom-full" src=${this.zoomedImage.src} alt=${this.zoomedImage.alt} />
|
|
2508
2508
|
`}
|
|
2509
2509
|
</dialog>
|
|
2510
|
-
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=
|
|
2510
|
+
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=KC(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`
|
|
2511
2511
|
<div class="activity-dock active" aria-live="polite">
|
|
2512
2512
|
<span class="dot"></span>
|
|
2513
2513
|
<span class="activity-text">正在发送你的消息…</span>
|
|
@@ -2517,7 +2517,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2517
2517
|
<span class="dot"></span>
|
|
2518
2518
|
<span class="activity-text">${this.activityText(e)}</span>
|
|
2519
2519
|
</div>
|
|
2520
|
-
`}renderQueuedMessages(){let e=this.status?.queuedMessages??[];return g`${
|
|
2520
|
+
`}renderQueuedMessages(){let e=this.status?.queuedMessages??[];return g`${hT(this.clientQueuedMessages,e).map(e=>this.renderQueuedMessageList(e))}`}renderQueuedMessageList(e){let t=ET(e,this.canClearServerQueue,this.onClearServerQueue!==void 0);return g`
|
|
2521
2521
|
<aside class="queued-messages" aria-live="polite">
|
|
2522
2522
|
<div class="queued-header">
|
|
2523
2523
|
<div class="queued-heading">
|
|
@@ -2543,7 +2543,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2543
2543
|
.onSubmit=${this.onSubmitAsk}
|
|
2544
2544
|
></ask-user-card>
|
|
2545
2545
|
`}renderExtensionDialogs(){let e=this.pendingDialogs[0];if(e===void 0&&this.closedDialogs.length===0)return null;let t=this.pendingDialogs.length-1;return g`
|
|
2546
|
-
${
|
|
2546
|
+
${LC(this.closedDialogs,e=>e.dialog.dialogId,e=>g`
|
|
2547
2547
|
<extension-dialog-card
|
|
2548
2548
|
class="closed-dialog-card"
|
|
2549
2549
|
data-scroll-anchor-id=${`closed-dialog:${e.dialog.dialogId}`}
|
|
@@ -2567,7 +2567,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2567
2567
|
<span>代理正在总结较早的上下文。压缩完成前,新提示词将进入队列。</span>
|
|
2568
2568
|
${this.pendingMessageCount>0?g`<small>${this.pendingMessageCount} 条消息正在排队</small>`:null}
|
|
2569
2569
|
</aside>
|
|
2570
|
-
`: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){return
|
|
2570
|
+
`: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){return jT(e,this.activity)}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?pT(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 pT(mT(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`
|
|
2571
2571
|
<div class="history-boundary">
|
|
2572
2572
|
<button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>加载较早消息</button>
|
|
2573
2573
|
<span>向上滚动以加载较早消息</span>
|
|
@@ -2579,7 +2579,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2579
2579
|
${n||r?null:this.renderMessageHeader(e,String(t))}
|
|
2580
2580
|
${e.parts.map(t=>this.renderPart(t,e))}
|
|
2581
2581
|
</article>
|
|
2582
|
-
`}renderToolImageOutput(e,t,n){let r=
|
|
2582
|
+
`}renderToolImageOutput(e,t,n){let r=_T(n);return g`
|
|
2583
2583
|
${this.renderScrollMarker(this.messageScrollMarkerId(t))}
|
|
2584
2584
|
<article class="msg tool-image-output" data-index=${t} data-scroll-anchor-id=${this.messageAnchorKey(t)}>
|
|
2585
2585
|
${this.renderMessageHeader(e,String(t),r)}
|
|
@@ -2587,10 +2587,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2587
2587
|
</article>
|
|
2588
2588
|
`}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`
|
|
2589
2589
|
${this.renderScrollMarker(this.groupScrollMarkerId(n))}
|
|
2590
|
-
<details class=${
|
|
2590
|
+
<details class=${wT(r)} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${a} @toggle=${e=>{this.onGroupToggle(i,e,r)}}>
|
|
2591
2591
|
<summary>
|
|
2592
|
-
<b class="label">${
|
|
2593
|
-
<span>${
|
|
2592
|
+
<b class="label">${TT(r)}</b>
|
|
2593
|
+
<span>${qC(e)}</span>
|
|
2594
2594
|
</summary>
|
|
2595
2595
|
${a?this.renderMessageGroupBody(e,t):null}
|
|
2596
2596
|
</details>
|
|
@@ -2603,7 +2603,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2603
2603
|
</section>
|
|
2604
2604
|
`})}
|
|
2605
2605
|
</div>
|
|
2606
|
-
`}renderScrollMarker(e){return g`<span class="scroll-marker" data-marker-id=${e} aria-hidden="true"></span>`}renderMessageHeader(e,t,n=
|
|
2606
|
+
`}renderScrollMarker(e){return g`<span class="scroll-marker" data-marker-id=${e} aria-hidden="true"></span>`}renderMessageHeader(e,t,n=yT(e.role)){let r=this.messageMetaLabel(e),i=this.expandedMetaKey===t;return g`
|
|
2607
2607
|
<div class="msg-header">
|
|
2608
2608
|
<b class="label">${n}</b>
|
|
2609
2609
|
<div class="msg-header-trailing">
|
|
@@ -2613,13 +2613,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2613
2613
|
</div>
|
|
2614
2614
|
`}renderMessageActions(e,t){if(!this.isCopyableMessage(e))return null;let n=this.copiedMessageKey===t;return g`
|
|
2615
2615
|
<div class="msg-actions" aria-label="消息操作">
|
|
2616
|
-
<button type="button" class="msg-action" title=${n?`已复制`:`复制消息`} aria-label=${`${n?`已复制`:`复制`}${
|
|
2616
|
+
<button type="button" class="msg-action" title=${n?`已复制`:`复制消息`} aria-label=${`${n?`已复制`:`复制`}${yT(e.role)}消息`} @click=${n=>{this.copyMessage(e,t,n)}}>
|
|
2617
2617
|
<span aria-hidden="true">${n?`✓`:`⧉`}</span>
|
|
2618
2618
|
</button>
|
|
2619
2619
|
</div>
|
|
2620
2620
|
`}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(`
|
|
2621
2621
|
|
|
2622
|
-
`);return this.messageCopyTextCache.set(e,n),n}async copyMessage(e,t,n){n.stopPropagation(),await
|
|
2622
|
+
`);return this.messageCopyTextCache.set(e,n),n}async copyMessage(e,t,n){n.stopPropagation(),await cS(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=OT(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`
|
|
2623
2623
|
<details class="part skill-invocation">
|
|
2624
2624
|
<summary><b>[skill]</b> ${e.name}</summary>
|
|
2625
2625
|
<small>${e.location}</small>
|
|
@@ -2636,36 +2636,36 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2636
2636
|
.outcome=${e.outcome}
|
|
2637
2637
|
.draftSessionId=${this.askDraftSessionId}
|
|
2638
2638
|
></ask-user-card>
|
|
2639
|
-
`;if(e.type===`image`){let{src:t,alt:n}=
|
|
2639
|
+
`;if(e.type===`image`){let{src:t,alt:n}=gT(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`
|
|
2640
2640
|
<details class="part" ?open=${e.isError}>
|
|
2641
2641
|
<summary>${e.isError?`✖`:`✓`} ${e.toolName} result</summary>
|
|
2642
2642
|
<formatted-text .text=${e.text}></formatted-text>
|
|
2643
2643
|
</details>
|
|
2644
|
-
`: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&&nw({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||gw(e)}isAtBottom(){let e=this.chat;return!e||hw(e)<2}canScrollUp(){let e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;let e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}isNewPendingAsk(e){return this.pendingAsk!==void 0&&(typeof e!=`object`||!e||Reflect.get(e,`askId`)!==this.pendingAsk.askId)}isNewOpenDialog(e){let t=this.pendingDialogs[0];if(t===void 0)return!1;let n=(Array.isArray(e)?e:[])[0];return typeof n!=`object`||!n||Reflect.get(n,`dialogId`)!==t.dialogId}scrollToOpenAsk(){this.scrollToOpenAskFrame===void 0&&(this.scrollToBottomFrame!==void 0&&(cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToBottomFrame=void 0),this.scrollToOpenAskFrame=requestAnimationFrame(()=>{this.scrollToOpenAskFrame=void 0,this.withSuppressedScrollSave(()=>{this.alignOpenAskToTop()})}))}alignOpenAskToTop(){let e=this.chat,t=this.renderRoot.querySelector(`.chat > ask-user-card`);return e===void 0||t===null?!1:(e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top,this.syncScrollMetrics(),this.pinnedToBottom=this.isNearBottom(),!0)}scrollToOpenDialog(){this.scrollToOpenDialogFrame===void 0&&(this.scrollToBottomFrame!==void 0&&(cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToBottomFrame=void 0),this.scrollToOpenDialogFrame=requestAnimationFrame(()=>{this.scrollToOpenDialogFrame=void 0,this.withSuppressedScrollSave(()=>{this.alignOpenDialogToTop()})}))}alignOpenDialogToTop(){let e=this.chat,t=this.renderRoot.querySelector(`.chat > extension-dialog-card.open-dialog-card`);return e===void 0||t===null?!1:(e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top,this.syncScrollMetrics(),this.pinnedToBottom=this.isNearBottom(),!0)}restoreScrollPosition(){let e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{if(this.pendingDialogs.length>0&&this.scrollController.readPosition(e)===void 0&&this.alignOpenDialogToTop()||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 JC(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(YC(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=dT(n,0,Math.max(0,e-1));return}this.currentConversationIndex=dT(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 yw(e,this.primaryArticleElements)??yw(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 _T(e)}groupRenderKey(e){return vT(e)}groupAnchorKey(e){return vT(e)}eventAnchorKey(e){return yT(e)}messageScrollMarkerId(e){return _T(e)}groupScrollMarkerId(e){return bT(e)}static{this.styles=eg}};W([x({attribute:!1})],q.prototype,`messages`,void 0),W([x()],q.prototype,`sessionId`,void 0),W([x({type:Number})],q.prototype,`messageStart`,void 0),W([x({type:Number})],q.prototype,`messageEnd`,void 0),W([x({type:Number})],q.prototype,`messageTotal`,void 0),W([x({type:Boolean})],q.prototype,`hasMore`,void 0),W([x({type:Boolean})],q.prototype,`loadingMore`,void 0),W([x({type:Boolean})],q.prototype,`isSendingPrompt`,void 0),W([x({type:Boolean})],q.prototype,`isCompacting`,void 0),W([x({type:Number})],q.prototype,`pendingMessageCount`,void 0),W([x({attribute:!1})],q.prototype,`clientQueuedMessages`,void 0),W([x({attribute:!1})],q.prototype,`status`,void 0),W([x({attribute:!1})],q.prototype,`activity`,void 0),W([x({attribute:!1})],q.prototype,`pendingAsk`,void 0),W([x({attribute:!1})],q.prototype,`pendingDialogs`,void 0),W([x({attribute:!1})],q.prototype,`closedDialogs`,void 0),W([x({attribute:!1})],q.prototype,`onAnswerDialog`,void 0),W([x({attribute:!1})],q.prototype,`onCancelDialog`,void 0),W([x({attribute:!1})],q.prototype,`onDismissClosedDialog`,void 0),W([x({attribute:!1})],q.prototype,`askDraftSessionId`,void 0),W([x({attribute:!1})],q.prototype,`onSubmitAsk`,void 0),W([x({attribute:!1})],q.prototype,`notificationInbox`,void 0),W([x({type:Boolean})],q.prototype,`canClearServerQueue`,void 0),W([x({attribute:!1})],q.prototype,`onClearServerQueue`,void 0),W([x({attribute:!1})],q.prototype,`onDismissWarning`,void 0),W([x({attribute:!1})],q.prototype,`onDismissNotification`,void 0),W([x({attribute:!1})],q.prototype,`onDismissAllNotifications`,void 0),W([x({type:Boolean})],q.prototype,`warningsVisible`,void 0),W([x({attribute:!1})],q.prototype,`onToggleWarnings`,void 0),W([x({attribute:!1})],q.prototype,`onLoadMore`,void 0),W([C(`.chat`)],q.prototype,`chat`,void 0),W([C(`dialog.image-zoom`)],q.prototype,`imageZoomDialog`,void 0),W([S()],q.prototype,`pinnedToBottom`,void 0),W([S()],q.prototype,`zoomedImage`,void 0),W([S()],q.prototype,`expandedMetaKey`,void 0),W([S()],q.prototype,`copiedMessageKey`,void 0),W([S()],q.prototype,`currentConversationIndex`,void 0),W([S()],q.prototype,`collapsedNotificationTargetKeys`,void 0),W([S()],q.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),W([S()],q.prototype,`loadMoreRequested`,void 0),q=W([b(`chat-view`)],q);function OT(e,t){if(t===void 0||e!==`idle`&&t.phase===`idle`)return kT(e);let n=kT(t.label,t.phase);return t.detail!==void 0&&t.detail!==``?`${n}:${t.detail}`:n}function kT(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:kT(e)}var AT=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function jT(e){return typeof e==`string`&&AT.has(e)}function MT(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 NT=`application/octet-stream`,PT=`读取附件失败。`;async function FT(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(zT(i,e))}catch{r=PT}return{attachments:n,...r===void 0?{}:{error:r}}}function IT(e){return e.kind===`image`&&jT(e.mimeType)}function LT(e){return e.every(e=>IT(e))}function RT(e,t){return LT(t)?e:`folder`}function zT(e,t){return jT(e.type)?{kind:`image`,name:VT(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:VT(e),mimeType:BT(e),data:t,size:e.size}}function BT(e){let t=e.type.trim();return t===``?NT:t}function VT(e){return e.name===``?jT(e.type)?`pasted-image.${MT(e.type)}`:`pasted-file.bin`:e.name}var HT=`pi-web:attachment-delivery`;function UT(e=Vc()){try{return e?.getItem(HT)===`folder`?`folder`:`inline`}catch{return`inline`}}function WT(e,t=Vc()){try{t?.setItem(HT,e)}catch{}}var GT=`(pointer: coarse), (max-width: 760px)`,KT=`pi-web.promptEnterPreference`;function qT(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(GT):void 0}function JT(e){return e===`send`||e===`newline`?e:`auto`}function YT(e=eE()){if(e===void 0)return`auto`;try{return JT(e.getItem(KT))}catch{return`auto`}}function XT(e,t=eE()){if(t!==void 0)try{t.setItem(KT,e)}catch{}}function ZT(e=qT(),t=YT()){return t===`send`||t!==`newline`&&e?.matches!==!0}function QT(e,t,n=qT()){return e?n?.matches!==!0||t:!1}function $T(e,t=qT(),n=YT()){let r=ZT(t,n);return e?!r:r}function eE(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function tE(){return _`
|
|
2644
|
+
`: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&&aw({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||yw(e)}isAtBottom(){let e=this.chat;return!e||vw(e)<2}canScrollUp(){let e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;let e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}isNewPendingAsk(e){return this.pendingAsk!==void 0&&(typeof e!=`object`||!e||Reflect.get(e,`askId`)!==this.pendingAsk.askId)}isNewOpenDialog(e){let t=this.pendingDialogs[0];if(t===void 0)return!1;let n=(Array.isArray(e)?e:[])[0];return typeof n!=`object`||!n||Reflect.get(n,`dialogId`)!==t.dialogId}scrollToOpenAsk(){this.scrollToOpenAskFrame===void 0&&(this.scrollToBottomFrame!==void 0&&(cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToBottomFrame=void 0),this.scrollToOpenAskFrame=requestAnimationFrame(()=>{this.scrollToOpenAskFrame=void 0,this.withSuppressedScrollSave(()=>{this.alignOpenAskToTop()})}))}alignOpenAskToTop(){let e=this.chat,t=this.renderRoot.querySelector(`.chat > ask-user-card`);return e===void 0||t===null?!1:(e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top,this.syncScrollMetrics(),this.pinnedToBottom=this.isNearBottom(),!0)}scrollToOpenDialog(){this.scrollToOpenDialogFrame===void 0&&(this.scrollToBottomFrame!==void 0&&(cancelAnimationFrame(this.scrollToBottomFrame),this.scrollToBottomFrame=void 0),this.scrollToOpenDialogFrame=requestAnimationFrame(()=>{this.scrollToOpenDialogFrame=void 0,this.withSuppressedScrollSave(()=>{this.alignOpenDialogToTop()})}))}alignOpenDialogToTop(){let e=this.chat,t=this.renderRoot.querySelector(`.chat > extension-dialog-card.open-dialog-card`);return e===void 0||t===null?!1:(e.scrollTop+=t.getBoundingClientRect().top-e.getBoundingClientRect().top,this.syncScrollMetrics(),this.pinnedToBottom=this.isNearBottom(),!0)}restoreScrollPosition(){let e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{if(this.pendingDialogs.length>0&&this.scrollController.readPosition(e)===void 0&&this.alignOpenDialogToTop()||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 ZC(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(QC(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=mT(n,0,Math.max(0,e-1));return}this.currentConversationIndex=mT(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 Sw(e,this.primaryArticleElements)??Sw(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 bT(e)}groupRenderKey(e){return xT(e)}groupAnchorKey(e){return xT(e)}eventAnchorKey(e){return ST(e)}messageScrollMarkerId(e){return bT(e)}groupScrollMarkerId(e){return CT(e)}static{this.styles=rg}};W([x({attribute:!1})],q.prototype,`messages`,void 0),W([x()],q.prototype,`sessionId`,void 0),W([x({type:Number})],q.prototype,`messageStart`,void 0),W([x({type:Number})],q.prototype,`messageEnd`,void 0),W([x({type:Number})],q.prototype,`messageTotal`,void 0),W([x({type:Boolean})],q.prototype,`hasMore`,void 0),W([x({type:Boolean})],q.prototype,`loadingMore`,void 0),W([x({type:Boolean})],q.prototype,`isSendingPrompt`,void 0),W([x({type:Boolean})],q.prototype,`isCompacting`,void 0),W([x({type:Number})],q.prototype,`pendingMessageCount`,void 0),W([x({attribute:!1})],q.prototype,`clientQueuedMessages`,void 0),W([x({attribute:!1})],q.prototype,`status`,void 0),W([x({attribute:!1})],q.prototype,`activity`,void 0),W([x({attribute:!1})],q.prototype,`pendingAsk`,void 0),W([x({attribute:!1})],q.prototype,`pendingDialogs`,void 0),W([x({attribute:!1})],q.prototype,`closedDialogs`,void 0),W([x({attribute:!1})],q.prototype,`onAnswerDialog`,void 0),W([x({attribute:!1})],q.prototype,`onCancelDialog`,void 0),W([x({attribute:!1})],q.prototype,`onDismissClosedDialog`,void 0),W([x({attribute:!1})],q.prototype,`askDraftSessionId`,void 0),W([x({attribute:!1})],q.prototype,`onSubmitAsk`,void 0),W([x({attribute:!1})],q.prototype,`notificationInbox`,void 0),W([x({type:Boolean})],q.prototype,`canClearServerQueue`,void 0),W([x({attribute:!1})],q.prototype,`onClearServerQueue`,void 0),W([x({attribute:!1})],q.prototype,`onDismissWarning`,void 0),W([x({attribute:!1})],q.prototype,`onDismissNotification`,void 0),W([x({attribute:!1})],q.prototype,`onDismissAllNotifications`,void 0),W([x({type:Boolean})],q.prototype,`warningsVisible`,void 0),W([x({attribute:!1})],q.prototype,`onToggleWarnings`,void 0),W([x({attribute:!1})],q.prototype,`onLoadMore`,void 0),W([C(`.chat`)],q.prototype,`chat`,void 0),W([C(`dialog.image-zoom`)],q.prototype,`imageZoomDialog`,void 0),W([S()],q.prototype,`pinnedToBottom`,void 0),W([S()],q.prototype,`zoomedImage`,void 0),W([S()],q.prototype,`expandedMetaKey`,void 0),W([S()],q.prototype,`copiedMessageKey`,void 0),W([S()],q.prototype,`currentConversationIndex`,void 0),W([S()],q.prototype,`collapsedNotificationTargetKeys`,void 0),W([S()],q.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),W([S()],q.prototype,`loadMoreRequested`,void 0),q=W([b(`chat-view`)],q);function jT(e,t){if(t===void 0||e!==`idle`&&t.phase===`idle`)return MT(e);let n=MT(t.label,t.phase);return t.detail!==void 0&&t.detail!==``?`${n}:${t.detail}`:n}function MT(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:MT(e)}var NT=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function PT(e){return typeof e==`string`&&NT.has(e)}function FT(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 IT=`application/octet-stream`,LT=`读取附件失败。`;async function RT(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(HT(i,e))}catch{r=LT}return{attachments:n,...r===void 0?{}:{error:r}}}function zT(e){return e.kind===`image`&&PT(e.mimeType)}function BT(e){return e.every(e=>zT(e))}function VT(e,t){return BT(t)?e:`folder`}function HT(e,t){return PT(e.type)?{kind:`image`,name:WT(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:WT(e),mimeType:UT(e),data:t,size:e.size}}function UT(e){let t=e.type.trim();return t===``?IT:t}function WT(e){return e.name===``?PT(e.type)?`pasted-image.${FT(e.type)}`:`pasted-file.bin`:e.name}var GT=`pi-web:attachment-delivery`;function KT(e=Vc()){try{return e?.getItem(GT)===`folder`?`folder`:`inline`}catch{return`inline`}}function qT(e,t=Vc()){try{t?.setItem(GT,e)}catch{}}var JT=`(pointer: coarse), (max-width: 760px)`,YT=`pi-web.promptEnterPreference`;function XT(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(JT):void 0}function ZT(e){return e===`send`||e===`newline`?e:`auto`}function QT(e=rE()){if(e===void 0)return`auto`;try{return ZT(e.getItem(YT))}catch{return`auto`}}function $T(e,t=rE()){if(t!==void 0)try{t.setItem(YT,e)}catch{}}function eE(e=XT(),t=QT()){return t===`send`||t!==`newline`&&e?.matches!==!0}function tE(e,t,n=XT()){return e?n?.matches!==!0||t:!1}function nE(e,t=XT(),n=QT()){let r=eE(t,n);return e?!r:r}function rE(){if(!(typeof window>`u`))try{return window.localStorage}catch{return}}function iE(){return _`
|
|
2645
2645
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2646
2646
|
<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>
|
|
2647
2647
|
</svg>
|
|
2648
|
-
`}function
|
|
2648
|
+
`}function aE(){return _`
|
|
2649
2649
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2650
2650
|
<path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
|
|
2651
2651
|
<path d="M21 3 11.5 12.5"></path>
|
|
2652
2652
|
</svg>
|
|
2653
|
-
`}function
|
|
2653
|
+
`}function oE(){return _`
|
|
2654
2654
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2655
2655
|
<path d="M4 7h11"></path>
|
|
2656
2656
|
<path d="M4 12h7"></path>
|
|
2657
2657
|
<path d="M4 17h7"></path>
|
|
2658
2658
|
<path d="m15 14 5 3-5 3z"></path>
|
|
2659
2659
|
</svg>
|
|
2660
|
-
`}function
|
|
2660
|
+
`}function sE(){return aE()}function cE(){return _`
|
|
2661
2661
|
<svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2662
2662
|
<rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
|
|
2663
2663
|
</svg>
|
|
2664
|
-
`}function
|
|
2664
|
+
`}function lE(e){let t=Math.max(e.total,1),n=t>1?1.2:0,r=(18-n*(t-1))/t;return _`
|
|
2665
2665
|
<svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2666
2666
|
${Array.from({length:t},(i,a)=>{let o=3+a*(r+n),s=4+(a+1)/t*12,c=20-s;return _`<rect class=${a<e.filled?`gauge-bar gauge-bar-active`:`gauge-bar`} x=${o} y=${c} width=${r} height=${s} rx="1"></rect>`})}
|
|
2667
2667
|
</svg>
|
|
2668
|
-
`}var
|
|
2668
|
+
`}var uE=_g(class extends vg{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===gg.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){}}),dE=h`
|
|
2669
2669
|
:host { display: block; }
|
|
2670
2670
|
.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); }
|
|
2671
2671
|
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; }
|
|
@@ -2673,22 +2673,22 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2673
2673
|
button.selected, button:hover { background: var(--pi-selection-bg); }
|
|
2674
2674
|
span { color: var(--pi-muted); font-size: 12px; }
|
|
2675
2675
|
small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
2676
|
-
`,
|
|
2676
|
+
`,fE=class extends y{constructor(...e){super(...e),this.items=[],this.selectedIndex=0}render(){return this.items.length?g`
|
|
2677
2677
|
<div class="menu">
|
|
2678
2678
|
${this.items.map((e,t)=>g`
|
|
2679
|
-
<button class=${t===this.selectedIndex?`selected`:``} ${
|
|
2679
|
+
<button class=${t===this.selectedIndex?`selected`:``} ${uE(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
|
|
2680
2680
|
<strong>${e.insertText}</strong>
|
|
2681
2681
|
<span>${e.detail}</span>
|
|
2682
2682
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
2683
2683
|
</button>
|
|
2684
2684
|
`)}
|
|
2685
2685
|
</div>
|
|
2686
|
-
`:null}static{this.styles=
|
|
2686
|
+
`:null}static{this.styles=dE}};W([x({attribute:!1})],fE.prototype,`items`,void 0),W([x({type:Number})],fE.prototype,`selectedIndex`,void 0),W([x({attribute:!1})],fE.prototype,`onPick`,void 0),fE=W([b(`autocomplete-menu`)],fE);var J=class extends y{constructor(...e){super(...e),this.disabled=!1,this.machineId=`local`,this.attachmentsFolder=fs,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=KT(),this.attachmentError=void 0,this.attachmentSeq=0,this.requestVersion=0,this.editableCompartment=new s,this.readOnlyCompartment=new s,this.mobilePromptEnterMedia=XT(),this.explicitShiftKeyActive=!1}willUpdate(e){if([`cwd`,`projectId`,`workspaceId`,`machineId`,`sessionId`].some(t=>e.has(t))&&this.cancelFileCompletion(),!e.has(`sessionId`)&&!e.has(`machineId`))return;let t=e.has(`sessionId`)?e.get(`sessionId`):this.sessionId,n=mE(e.has(`machineId`)?e.get(`machineId`):this.machineId,t);n!==void 0&&Hl(n,this.draft);let r=mE(this.machineId,this.sessionId);this.draft=r===void 0?``:Vl(r),this.attachments=r===void 0?[]:Kl(r),this.attachmentError=void 0,this.currentInputMode=xd(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has(`status`)&&e.size===1?!pE(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.cancelFileCompletion(),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`
|
|
2687
2687
|
<footer class=${t?`shell-mode`:``} @paste=${e=>{this.handlePaste(e)}} @dragover=${e=>{this.handleDragOver(e)}} @drop=${e=>{this.handleDrop(e)}}>
|
|
2688
2688
|
<div class="editor-wrap">
|
|
2689
2689
|
<div class=${`markdown-editor${this.disabled?` markdown-editor-disabled`:``}`} aria-label="给 pi 发送消息" aria-disabled=${this.disabled?`true`:`false`}></div>
|
|
2690
2690
|
<input class="attachment-input" type="file" multiple hidden @change=${e=>{this.handleFileInput(e)}} />
|
|
2691
|
-
<button class="editor-attach icon-button" ?disabled=${r} title="附加文件" aria-label="附加文件" @click=${()=>{this.attachmentInput?.click()}}>${
|
|
2691
|
+
<button class="editor-attach icon-button" ?disabled=${r} title="附加文件" aria-label="附加文件" @click=${()=>{this.attachmentInput?.click()}}>${iE()}</button>
|
|
2692
2692
|
${t?g`<div class="mode-hint">终端命令${e.excludeFromContext?` · 已排除上下文`:``}</div>`:null}
|
|
2693
2693
|
${this.isCompacting&&!t?g`<div class="mode-hint">正在压缩历史 · 消息将排队发送</div>`:null}
|
|
2694
2694
|
${this.renderAttachments()}
|
|
@@ -2696,20 +2696,20 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2696
2696
|
</div>
|
|
2697
2697
|
<div class="actions">
|
|
2698
2698
|
${this.renderCompactStatus()}
|
|
2699
|
-
<button class="icon-button send-button" ?disabled=${r} title=${n?`当前活动结束后排队发送`:`发送`} aria-label=${n?`排队发送`:`发送`} @click=${()=>{this.send(`followUp`)}}>${n?
|
|
2700
|
-
${this.canSteer&&!this.isCompacting?g`<button class="icon-button steer-button" ?disabled=${r} title="在下次模型调用前引导当前回复" aria-label="引导当前回复" @click=${()=>{this.send(`steer`)}}>${
|
|
2701
|
-
<button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?`停止当前工作并清空排队消息`:`当前没有运行任务`} aria-label="停止" @click=${()=>this.onStop?.()}>${
|
|
2699
|
+
<button class="icon-button send-button" ?disabled=${r} title=${n?`当前活动结束后排队发送`:`发送`} aria-label=${n?`排队发送`:`发送`} @click=${()=>{this.send(`followUp`)}}>${n?oE():aE()}</button>
|
|
2700
|
+
${this.canSteer&&!this.isCompacting?g`<button class="icon-button steer-button" ?disabled=${r} title="在下次模型调用前引导当前回复" aria-label="引导当前回复" @click=${()=>{this.send(`steer`)}}>${sE()}</button>`:null}
|
|
2701
|
+
<button class="icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?`停止当前工作并清空排队消息`:`当前没有运行任务`} aria-label="停止" @click=${()=>this.onStop?.()}>${cE()}</button>
|
|
2702
2702
|
</div>
|
|
2703
2703
|
</footer>
|
|
2704
|
-
`}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=
|
|
2704
|
+
`}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=mE(this.machineId,this.sessionId);t!==void 0&&Hl(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.cancelFileCompletion(),this.currentInputMode=xd(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`
|
|
2705
2705
|
<div class="compact-status" aria-label="会话状态">
|
|
2706
2706
|
<button class="select-model" title="选择模型" @click=${()=>this.onSelectModel?.()}>${e.model?.provider!==void 0&&e.model.provider!==``?`${e.model.provider}/`:``}${t}</button>
|
|
2707
|
-
<button class="select-thinking icon-button" title=${`思考级别:${Rs(e.thinkingLevel)}`} aria-label=${`思考级别:${Rs(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${
|
|
2707
|
+
<button class="select-thinking icon-button" title=${`思考级别:${Rs(e.thinkingLevel)}`} aria-label=${`思考级别:${Rs(e.thinkingLevel)}`} @click=${()=>this.onSelectThinking?.()}>${lE(Bs(e.thinkingLevel,this.availableThinkingLevels))}</button>
|
|
2708
2708
|
</div>
|
|
2709
|
-
`}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=
|
|
2709
|
+
`}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=BT(this.attachments),t=this.effectiveAttachmentDelivery();return g`
|
|
2710
2710
|
<div class="attachments" aria-label="待发送附件">
|
|
2711
2711
|
${this.attachments.map(e=>g`
|
|
2712
|
-
<div class=${`attachment-chip ${
|
|
2712
|
+
<div class=${`attachment-chip ${zT(e)?`attachment-chip-image`:`attachment-chip-file`}`} title=${e.name}>
|
|
2713
2713
|
${this.renderAttachmentPreview(e)}
|
|
2714
2714
|
<button type="button" class="attachment-remove" title="移除附件" aria-label=${`移除 ${e.name}`} @click=${()=>{this.removeAttachment(e.id)}}>×</button>
|
|
2715
2715
|
</div>
|
|
@@ -2718,16 +2718,16 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2718
2718
|
<label class="attachment-delivery" title=${e?`附件发送给代理的方式`:`普通文件会保存到工作区并通过引用提及`}>
|
|
2719
2719
|
<select .value=${t} @change=${e=>{this.changeDelivery(e)}}>
|
|
2720
2720
|
<option value="inline" ?disabled=${!e}>附加到消息${e?``:`(仅图片)`}</option>
|
|
2721
|
-
<option value="folder">${
|
|
2721
|
+
<option value="folder">${xE(this.attachmentsFolder)}</option>
|
|
2722
2722
|
</select>
|
|
2723
2723
|
</label>
|
|
2724
2724
|
`:null}
|
|
2725
2725
|
${this.attachmentError===void 0?null:g`<div class="attachment-error">${this.attachmentError}</div>`}
|
|
2726
2726
|
</div>
|
|
2727
|
-
`}renderAttachmentPreview(e){return
|
|
2728
|
-
<div class="attachment-file-preview" aria-hidden="true">${
|
|
2727
|
+
`}renderAttachmentPreview(e){return zT(e)?g`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:g`
|
|
2728
|
+
<div class="attachment-file-preview" aria-hidden="true">${SE(e.name)}</div>
|
|
2729
2729
|
<span class="attachment-file-name">${e.name}</span>
|
|
2730
|
-
`}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;if(t===`inline`&&!LT(this.attachments)){e.target.value=`folder`;return}this.attachmentDelivery=t,WT(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e);let t=dE(this.machineId,this.sessionId);t!==void 0&&ql(t,this.attachments)}async handlePaste(e){let t=hE(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&gE(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=hE(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 FT(e,bE);if(t.length>0){this.attachments=[...this.attachments,...t.map(e=>({id:`attachment-${String(++this.attachmentSeq)}`,...e}))];let e=dE(this.machineId,this.sessionId);e!==void 0&&ql(e,this.attachments)}n!==void 0&&(this.attachmentError=n)}currentAttachments(){return this.attachments.map(e=>_E(e))}effectiveAttachmentDelivery(){return RT(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=>CE(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=dE(this.machineId,this.sessionId);t!==void 0&&Hl(t,this.draft);let n=xd(this.draft);Cd(n,this.currentInputMode)||(this.currentInputMode=n),this.cancelFileCompletion(),this.currentTrigger()?.kind===`file`?(this.completions=[],this.fileCompletionTimer=setTimeout(()=>{this.refreshCompletions()},150)):this.refreshCompletions()}cancelFileCompletion(){clearTimeout(this.fileCompletionTimer),this.fileCompletionTimer=void 0,this.fileCompletionAbort?.abort(),this.fileCompletionAbort=void 0,this.requestVersion+=1}async refreshCompletions(){this.cancelFileCompletion();let e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind===`command`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await L.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(fE);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!==``){this.fileCompletionAbort=new AbortController;let n=await L.files(this.cwd,e.query,{signal:this.fileCompletionAbort.signal,scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(pE);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=gd(t.path,e.quoted===!0,t.path.endsWith(`/`)?e.allPrefix:void 0);return{kind:`file`,replaceFrom:e.from,replaceTo:e.to,insertText:n,detail:t.kind,...t.path.endsWith(`/`)&&n.endsWith(`"`)?{cursorOffset:n.length-1}:{}}})}else if(e.kind===`model`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await L.models({id:this.sessionId,cwd:this.cwd},this.machineId).then(e=>e.models).catch(mE);if(t!==this.requestVersion)return;this.completions=pd(n,e.query).map(t=>({kind:`model`,replaceFrom:e.from,replaceTo:e.to,...t}))}}currentTrigger(){return dd(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=QT(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);return this.explicitShiftKeyActive=!1,this.handleEditorEnter(t,n)}handleEditorKeyUp(e){return e.key===`Shift`&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorEnter(e,t){if(!t&&this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return $T(t,this.mobilePromptEnterMedia,YT())?(this.send(this.canSteer||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(),o=i!==void 0&&a===`folder`?this.attachmentsFolder:void 0;this.resetComposer(),this.onSend?.(t,r,i,i===void 0?void 0:a,o)}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=dE(this.machineId,this.sessionId);e!==void 0&&(Ul(e),Jl(e)),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=rg}};W([x({type:Boolean})],J.prototype,`disabled`,void 0),W([x()],J.prototype,`sessionId`,void 0),W([x()],J.prototype,`cwd`,void 0),W([x()],J.prototype,`machineId`,void 0),W([x()],J.prototype,`projectId`,void 0),W([x()],J.prototype,`workspaceId`,void 0),W([x()],J.prototype,`attachmentsFolder`,void 0),W([x({type:Boolean})],J.prototype,`workspaceScopedFileSuggestions`,void 0),W([x({type:Boolean})],J.prototype,`canSteer`,void 0),W([x({type:Boolean})],J.prototype,`isCompacting`,void 0),W([x({type:Boolean})],J.prototype,`canStop`,void 0),W([x({attribute:!1})],J.prototype,`status`,void 0),W([x({type:Boolean})],J.prototype,`sending`,void 0),W([x({attribute:!1})],J.prototype,`onSend`,void 0),W([x({attribute:!1})],J.prototype,`onStop`,void 0),W([x({attribute:!1})],J.prototype,`onSelectModel`,void 0),W([x({attribute:!1})],J.prototype,`onSelectThinking`,void 0),W([x({attribute:!1})],J.prototype,`availableThinkingLevels`,void 0),W([C(`.markdown-editor`)],J.prototype,`editorHost`,void 0),W([C(`.attachment-input`)],J.prototype,`attachmentInput`,void 0),W([S()],J.prototype,`currentInputMode`,void 0),W([S()],J.prototype,`completions`,void 0),W([S()],J.prototype,`selectedIndex`,void 0),W([S()],J.prototype,`attachments`,void 0),W([S()],J.prototype,`attachmentDelivery`,void 0),W([S()],J.prototype,`attachmentError`,void 0),J=W([b(`prompt-editor`)],J);function uE(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 dE(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return Hs(e,t)}function fE(){return[]}function pE(){return[]}function mE(){return[]}function hE(e){return e===null?[]:Array.from(e.files)}function gE(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function _E(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 vE(e){return`保存到 ${e}`}function yE(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`文件`}function bE(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 xE={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},SE={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function CE(e){return xd(e).kind===`normal`?xE:SE}function wE(e,t){if(!Number.isInteger(e)||e<=0)return;let n=`${String(e)} 条警告`;return{countText:String(e),accessibleLabel:t?`最小化 ${n}`:`在警告区域显示 ${n}`}}var TE=class extends y{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?`上下文 ${kh(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${kh(t.contextWindow)}`:`上下文未知`,r=e.tokens,i=wE(this.warningCount,this.warningsExpanded);return g`
|
|
2730
|
+
`}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;if(t===`inline`&&!BT(this.attachments)){e.target.value=`folder`;return}this.attachmentDelivery=t,qT(this.attachmentDelivery)}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e);let t=mE(this.machineId,this.sessionId);t!==void 0&&ql(t,this.attachments)}async handlePaste(e){let t=vE(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&yE(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=vE(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 RT(e,CE);if(t.length>0){this.attachments=[...this.attachments,...t.map(e=>({id:`attachment-${String(++this.attachmentSeq)}`,...e}))];let e=mE(this.machineId,this.sessionId);e!==void 0&&ql(e,this.attachments)}n!==void 0&&(this.attachmentError=n)}currentAttachments(){return this.attachments.map(e=>bE(e))}effectiveAttachmentDelivery(){return VT(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=>EE(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=mE(this.machineId,this.sessionId);t!==void 0&&Hl(t,this.draft);let n=xd(this.draft);Cd(n,this.currentInputMode)||(this.currentInputMode=n),this.cancelFileCompletion(),this.currentTrigger()?.kind===`file`?(this.completions=[],this.fileCompletionTimer=setTimeout(()=>{this.refreshCompletions()},150)):this.refreshCompletions()}cancelFileCompletion(){clearTimeout(this.fileCompletionTimer),this.fileCompletionTimer=void 0,this.fileCompletionAbort?.abort(),this.fileCompletionAbort=void 0,this.requestVersion+=1}async refreshCompletions(){this.cancelFileCompletion();let e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0){this.completions=[];return}if(e.kind===`command`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await L.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(hE);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!==``){this.fileCompletionAbort=new AbortController;let n=await L.files(this.cwd,e.query,{signal:this.fileCompletionAbort.signal,scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId,workspaceScoped:this.workspaceScopedFileSuggestions}).catch(gE);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=gd(t.path,e.quoted===!0,t.path.endsWith(`/`)?e.allPrefix:void 0);return{kind:`file`,replaceFrom:e.from,replaceTo:e.to,insertText:n,detail:t.kind,...t.path.endsWith(`/`)&&n.endsWith(`"`)?{cursorOffset:n.length-1}:{}}})}else if(e.kind===`model`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await L.models({id:this.sessionId,cwd:this.cwd},this.machineId).then(e=>e.models).catch(_E);if(t!==this.requestVersion)return;this.completions=pd(n,e.query).map(t=>({kind:`model`,replaceFrom:e.from,replaceTo:e.to,...t}))}}currentTrigger(){return dd(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=tE(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 nE(t,this.mobilePromptEnterMedia,QT())?(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(),o=i!==void 0&&a===`folder`?this.attachmentsFolder:void 0;this.resetComposer(),this.onSend?.(t,r,i,i===void 0?void 0:a,o)}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=mE(this.machineId,this.sessionId);e!==void 0&&(Ul(e),Jl(e)),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=og}};W([x({type:Boolean})],J.prototype,`disabled`,void 0),W([x()],J.prototype,`sessionId`,void 0),W([x()],J.prototype,`cwd`,void 0),W([x()],J.prototype,`machineId`,void 0),W([x()],J.prototype,`projectId`,void 0),W([x()],J.prototype,`workspaceId`,void 0),W([x()],J.prototype,`attachmentsFolder`,void 0),W([x({type:Boolean})],J.prototype,`workspaceScopedFileSuggestions`,void 0),W([x({type:Boolean})],J.prototype,`canSteer`,void 0),W([x({type:Boolean})],J.prototype,`isCompacting`,void 0),W([x({type:Boolean})],J.prototype,`canStop`,void 0),W([x({attribute:!1})],J.prototype,`status`,void 0),W([x({type:Boolean})],J.prototype,`sending`,void 0),W([x({attribute:!1})],J.prototype,`onSend`,void 0),W([x({attribute:!1})],J.prototype,`onStop`,void 0),W([x({attribute:!1})],J.prototype,`onSelectModel`,void 0),W([x({attribute:!1})],J.prototype,`onSelectThinking`,void 0),W([x({attribute:!1})],J.prototype,`availableThinkingLevels`,void 0),W([C(`.markdown-editor`)],J.prototype,`editorHost`,void 0),W([C(`.attachment-input`)],J.prototype,`attachmentInput`,void 0),W([S()],J.prototype,`currentInputMode`,void 0),W([S()],J.prototype,`completions`,void 0),W([S()],J.prototype,`selectedIndex`,void 0),W([S()],J.prototype,`attachments`,void 0),W([S()],J.prototype,`attachmentDelivery`,void 0),W([S()],J.prototype,`attachmentError`,void 0),J=W([b(`prompt-editor`)],J);function pE(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 mE(e,t){if(!(typeof e!=`string`||e===``)&&!(typeof t!=`string`||t===``))return Hs(e,t)}function hE(){return[]}function gE(){return[]}function _E(){return[]}function vE(e){return e===null?[]:Array.from(e.files)}function yE(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function bE(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 xE(e){return`保存到 ${e}`}function SE(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():`文件`}function CE(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 wE={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},TE={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function EE(e){return xd(e).kind===`normal`?wE:TE}function DE(e,t){if(!Number.isInteger(e)||e<=0)return;let n=`${String(e)} 条警告`;return{countText:String(e),accessibleLabel:t?`最小化 ${n}`:`在警告区域显示 ${n}`}}var OE=class extends y{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?`上下文 ${Mh(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${Mh(t.contextWindow)}`:`上下文未知`,r=e.tokens,i=DE(this.warningCount,this.warningsExpanded);return g`
|
|
2731
2731
|
<div class="bar">
|
|
2732
2732
|
${i===void 0||this.onToggleWarnings===void 0?null:g`
|
|
2733
2733
|
<button
|
|
@@ -2738,17 +2738,17 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2738
2738
|
aria-expanded=${String(this.warningsExpanded)}
|
|
2739
2739
|
@click=${this.handleToggleWarnings}
|
|
2740
2740
|
>
|
|
2741
|
-
${
|
|
2741
|
+
${eg(`warning`,`warning-toggle-icon`)}
|
|
2742
2742
|
<span>${i.countText}</span>
|
|
2743
2743
|
</button>
|
|
2744
2744
|
`}
|
|
2745
|
-
<span>↑${
|
|
2746
|
-
<span>↓${
|
|
2745
|
+
<span>↑${Mh(r.input)}</span>
|
|
2746
|
+
<span>↓${Mh(r.output)}</span>
|
|
2747
2747
|
<span class="context">${n}</span>
|
|
2748
|
-
<span>${
|
|
2748
|
+
<span>${Fh(e.cost)}</span>
|
|
2749
2749
|
${e.pendingMessageCount>0?g`<span>${String(e.pendingMessageCount)} 条排队中</span>`:null}
|
|
2750
2750
|
</div>
|
|
2751
|
-
`}static{this.styles=
|
|
2751
|
+
`}static{this.styles=ag}};W([x({attribute:!1})],OE.prototype,`status`,void 0),W([x({type:Number})],OE.prototype,`warningCount`,void 0),W([x({type:Boolean})],OE.prototype,`warningsExpanded`,void 0),W([x({attribute:!1})],OE.prototype,`onToggleWarnings`,void 0),OE=W([b(`status-bar`)],OE);function kE(e){return e.composedPath().some(e=>e instanceof HTMLButtonElement||e instanceof HTMLAnchorElement&&e.hasAttribute(`href`))}var AE=h`
|
|
2752
2752
|
:host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
2753
2753
|
.backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
|
|
2754
2754
|
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; }
|
|
@@ -2762,7 +2762,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2762
2762
|
.options button.selected, .options button:hover { background: var(--pi-selection-bg); }
|
|
2763
2763
|
small { display: block; margin-top: 4px; color: var(--pi-muted); }
|
|
2764
2764
|
.empty { padding: 24px; color: var(--pi-muted); text-align: center; }
|
|
2765
|
-
`,
|
|
2765
|
+
`,jE=class extends y{constructor(...e){super(...e),this.title=`选择`,this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=``}render(){let e=this.filteredOptions();return g`
|
|
2766
2766
|
<modal-surface .onClose=${()=>this.onCancel?.()} .initialFocus=${this.searchable?`input`:`.options`} .label=${this.title} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
2767
2767
|
<header>
|
|
2768
2768
|
<strong>${this.title}</strong>
|
|
@@ -2771,7 +2771,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2771
2771
|
${this.searchable?g`<input placeholder="搜索" .value=${this.query} @input=${e=>{this.handleSearchInput(e)}}>`:null}
|
|
2772
2772
|
<div class="options" tabindex="0">
|
|
2773
2773
|
${e.map((e,t)=>g`
|
|
2774
|
-
<button class=${t===this.selectedIndex?`selected`:``} aria-current=${t===this.selectedIndex?`true`:v} ${
|
|
2774
|
+
<button class=${t===this.selectedIndex?`selected`:``} aria-current=${t===this.selectedIndex?`true`:v} ${uE(t===this.selectedIndex,e.value)} @focus=${()=>{this.selectedIndex=t}} @click=${()=>this.onPick?.(e.value)}>
|
|
2775
2775
|
<span>${e.label}</span>
|
|
2776
2776
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
2777
2777
|
</button>
|
|
@@ -2779,10 +2779,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2779
2779
|
${e.length===0?g`<div class="empty">没有匹配选项</div>`:null}
|
|
2780
2780
|
</div>
|
|
2781
2781
|
</modal-surface>
|
|
2782
|
-
`}firstUpdated(){this.selectInitialValue()}selectInitialValue(){if(this.selectedValue===void 0)return;let e=this.filteredOptions().findIndex(e=>e.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){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){if(
|
|
2782
|
+
`}firstUpdated(){this.selectInitialValue()}selectInitialValue(){if(this.selectedValue===void 0)return;let e=this.filteredOptions().findIndex(e=>e.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){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){if(kE(e))return;let t=this.filteredOptions();if(e.key===`ArrowDown`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key===`ArrowUp`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key===`Enter`){e.preventDefault();let n=t[this.selectedIndex];n&&this.onPick?.(n.value)}}static{this.styles=[AE,h`
|
|
2783
2783
|
modal-surface { --modal-surface-width: min(720px, calc(100vw - 40px)); --modal-surface-max-height: min(640px, calc(100vh - 40px)); }
|
|
2784
2784
|
modal-surface > header, modal-surface > .options, modal-surface > input { position: relative; }
|
|
2785
|
-
`]}};W([x()],
|
|
2785
|
+
`]}};W([x()],jE.prototype,`title`,void 0),W([x({type:Boolean})],jE.prototype,`searchable`,void 0),W([x({attribute:!1})],jE.prototype,`options`,void 0),W([x({attribute:!1})],jE.prototype,`selectedValue`,void 0),W([x({attribute:!1})],jE.prototype,`onPick`,void 0),W([x({attribute:!1})],jE.prototype,`onCancel`,void 0),W([S()],jE.prototype,`selectedIndex`,void 0),W([S()],jE.prototype,`query`,void 0),jE=W([b(`command-picker`)],jE);function ME(e){return`${e.provider}/${e.id}`}function NE(e,t){let n=t.trim().toLowerCase();return n===``?[...e]:e.filter(e=>`${e.label} ${e.description??``} ${e.value}`.toLowerCase().includes(n))}function PE(e){return e.every(e=>e.catalogIndex!==void 0)?[...e].sort((e,t)=>(e.catalogIndex??0)-(t.catalogIndex??0)):[...e]}function FE(e,t,n){let r=PE(e),i=new Map(r.map(e=>[ME(e),e])),a=new Set,o=n===void 0?r:[...n.flatMap(e=>{let t=i.get(e);return t===void 0||a.has(e)?[]:(a.add(e),[t])}),...r.filter(e=>!a.has(ME(e)))],s=t.trim().toLowerCase();return{rows:s===``?o:o.filter(e=>`${e.provider} ${e.id} ${e.name??``}`.toLowerCase().includes(s))}}function IE(e,t){let n=e.filter(e=>e.enabled),r=t===void 0?void 0:e.find(e=>ME(e)===t),i=r?.enabled===!0&&n.length===1,a=n.length===0||i?`all`:`current`;return{mode:a,canApply:a===`all`||r!==void 0,hasChanges:a===`all`?n.length<e.length:r!==void 0&&(!r.enabled||n.some(e=>e!==r))}}var LE=class extends y{constructor(...e){super(...e),this.title=`选择模型`,this.options=[],this.catalog=[],this.mode=`enabled`,this.selectedIndex=0,this.query=``,this.pendingToggles=new Set,this.toggleAllPending=!1,this.catalogOrder=[]}render(){let e=this.visibleRows();return g`
|
|
2786
2786
|
<modal-surface .onClose=${()=>this.onCancel?.()} .initialFocus=${`input.search`} .label=${this.title} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
2787
2787
|
<header><strong>${this.title}</strong><button aria-label="关闭" @click=${()=>this.onCancel?.()}>×</button></header>
|
|
2788
2788
|
<div class="scope-toggle" role="group" aria-label="模型范围">
|
|
@@ -2804,22 +2804,22 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2804
2804
|
${e.length===0?g`<div class="empty">没有匹配选项</div>`:null}
|
|
2805
2805
|
</div>
|
|
2806
2806
|
</modal-surface>
|
|
2807
|
-
`}firstUpdated(){this.anchorSelectionToSelectedValue()}willUpdate(e){if(!e.has(`catalog`)||(this.mode===`all`&&(this.catalogScrollTopBeforeUpdate=this.shadowRoot?.querySelector(`.options`)?.scrollTop),this.rememberCatalogOrder(),this.mode!==`all`))return;let t=e.get(`catalog`);if(t===void 0)return;let n=
|
|
2807
|
+
`}firstUpdated(){this.anchorSelectionToSelectedValue()}willUpdate(e){if(!e.has(`catalog`)||(this.mode===`all`&&(this.catalogScrollTopBeforeUpdate=this.shadowRoot?.querySelector(`.options`)?.scrollTop),this.rememberCatalogOrder(),this.mode!==`all`))return;let t=e.get(`catalog`);if(t===void 0)return;let n=FE(t,this.query,this.catalogOrder).rows[this.selectedIndex],r=FE(this.catalog,this.query,this.catalogOrder).rows,i=n===void 0?void 0:ME(n),a=i===void 0?-1:r.findIndex(e=>ME(e)===i);this.selectedIndex=a>=0?a:Math.min(this.selectedIndex,Math.max(r.length-1,0))}updated(e){if(!e.has(`catalog`)||this.catalogScrollTopBeforeUpdate===void 0)return;let t=this.shadowRoot?.querySelector(`.options`);t!=null&&(t.scrollTop=this.catalogScrollTopBeforeUpdate),this.catalogScrollTopBeforeUpdate=void 0}get membershipChangePending(){return this.toggleAllPending||this.pendingToggles.size>0}get modelScopeEditable(){return this.catalog.every(e=>e.editable!==!1)}renderScopeToggleButton(e,t){return g`<button ?disabled=${this.membershipChangePending} aria-pressed=${this.mode===e?`true`:`false`} @click=${()=>{this.selectMode(e)}}>${t}</button>`}renderToggleAllButton(){let e=IE(this.catalog,this.selectedValue),t=e.mode===`all`?`全选`:`除当前模型外全部取消`;return g`
|
|
2808
2808
|
<button class="toggle-all" ?disabled=${!this.modelScopeEditable||!e.canApply||!e.hasChanges||this.toggleAllPending||this.pendingToggles.size>0} aria-describedby="model-scope-status" title=${this.modelScopeEditable?e.canApply?v:`当前模型不可用`:`工作区设置控制模型可用性`} @click=${()=>{this.requestToggleAll()}}>${t}</button>
|
|
2809
2809
|
<span id="model-scope-status" class="scope-status" aria-live="polite">${this.membershipChangePending?`正在更新模型可用性`:this.modelScopeEditable?e.canApply?v:`当前模型不可用`:`工作区设置控制模型可用性`}</span>
|
|
2810
|
-
`}rememberCatalogOrder(){let e=new Set(this.catalogOrder);for(let t of
|
|
2811
|
-
<button class=${t===this.selectedIndex?`selected`:``} ?disabled=${this.membershipChangePending} aria-current=${t===this.selectedIndex?`true`:v} ${
|
|
2810
|
+
`}rememberCatalogOrder(){let e=new Set(this.catalogOrder);for(let t of FE(this.catalog,``).rows){let n=ME(t);e.has(n)||(e.add(n),this.catalogOrder.push(n))}}renderEnabledList(){return NE(this.options,this.query).map((e,t)=>g`
|
|
2811
|
+
<button class=${t===this.selectedIndex?`selected`:``} ?disabled=${this.membershipChangePending} aria-current=${t===this.selectedIndex?`true`:v} ${uE(t===this.selectedIndex,e.value)} @focus=${()=>{this.selectedIndex=t}} @click=${()=>this.onPick?.(e.value)}>
|
|
2812
2812
|
<span>${e.label}</span>
|
|
2813
2813
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
2814
2814
|
</button>
|
|
2815
|
-
`)}renderCatalogList(){let e=
|
|
2816
|
-
<div class="catalog-row ${r?`selected`:``}" data-model-value=${n} ${
|
|
2815
|
+
`)}renderCatalogList(){let e=FE(this.catalog,this.query,this.catalogOrder).rows;return g`${LC(e,ME,(e,t)=>this.renderCatalogRow(e,t))}`}renderCatalogRow(e,t){let n=ME(e),r=t===this.selectedIndex,i=n===this.selectedValue&&e.enabled,a=!this.modelScopeEditable||this.membershipChangePending||i,o=this.modelScopeEditable?i?`不能取消当前模型 ${n}`:`${e.enabled?`禁用`:`启用`} ${n}`:`${n} 的模型可用性由工作区设置控制`;return g`
|
|
2816
|
+
<div class="catalog-row ${r?`selected`:``}" data-model-value=${n} ${uE(r,n)}>
|
|
2817
2817
|
<input type="checkbox" .checked=${e.enabled} ?disabled=${a} aria-label=${o} title=${this.modelScopeEditable?i?`当前模型必须保持启用`:v:`工作区设置控制模型可用性`} @focus=${()=>{this.selectedIndex=t}} @click=${t=>{this.handleEnableToggleClick(e,t)}} />
|
|
2818
2818
|
<button class="membership" ?disabled=${a} aria-label=${o} aria-current=${n===this.selectedValue?`true`:v} @focus=${()=>{this.selectedIndex=t}} @click=${t=>{this.requestEnabledToggle(e,t.currentTarget instanceof HTMLElement?t.currentTarget:void 0)}}>
|
|
2819
2819
|
<span>${e.id}${n===this.selectedValue?` ✓ 当前`:``}</span><small>${e.provider}</small>
|
|
2820
2820
|
</button>
|
|
2821
2821
|
</div>
|
|
2822
|
-
`}visibleRows(){return this.mode===`all`?
|
|
2822
|
+
`}visibleRows(){return this.mode===`all`?FE(this.catalog,this.query,this.catalogOrder).rows.map(e=>({value:ME(e),entry:e})):NE(this.options,this.query).map(e=>({value:e.value}))}anchorSelectionToSelectedValue(){if(this.selectedValue===void 0){this.selectedIndex=0;return}let e=this.visibleRows().findIndex(e=>e.value===this.selectedValue);this.selectedIndex=e>=0?e:0}selectMode(e){e!==this.mode&&(this.mode=e,this.anchorSelectionToSelectedValue())}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}handleKeyDown(e){let t=e.composedPath().find(e=>e instanceof HTMLInputElement&&e.type===`checkbox`);if(t!==void 0){e.key===`Enter`&&(e.preventDefault(),t.click());return}if(kE(e))return;if(this.membershipChangePending&&(e.key===`Enter`||e.key===` `)){e.preventDefault();return}let n=this.visibleRows();if(e.key===`ArrowDown`)e.preventDefault(),n.length>0&&(this.selectedIndex=(this.selectedIndex+1)%n.length);else if(e.key===`ArrowUp`)e.preventDefault(),n.length>0&&(this.selectedIndex=(this.selectedIndex-1+n.length)%n.length);else if(e.key===`Enter`){e.preventDefault();let t=n[this.selectedIndex];t?.entry===void 0?t!==void 0&&this.onPick?.(t.value):this.requestEnabledToggle(t.entry)}else if(e.key===` `&&this.mode===`all`){if(e.composedPath().some(e=>e instanceof HTMLInputElement))return;let t=n[this.selectedIndex];if(t?.entry===void 0)return;e.preventDefault(),this.requestEnabledToggle(t.entry)}}handleEnableToggleClick(e,t){t.preventDefault();let n=t.currentTarget instanceof HTMLInputElement?t.currentTarget:void 0;n!==void 0&&(n.checked=e.enabled),this.requestEnabledToggle(e,n)}requestEnabledToggle(e,t){let n=ME(e);if(!this.modelScopeEditable||n===this.selectedValue&&e.enabled||this.membershipChangePending)return;t!==void 0&&this.shadowRoot?.activeElement===t&&(this.focusAfterToggle=t);let r=new Set(this.pendingToggles);r.add(n),this.pendingToggles=r,this.settleEnabledToggle(n,e)}requestToggleAll(){if(!this.modelScopeEditable||this.toggleAllPending||this.pendingToggles.size>0)return;let e=IE(this.catalog,this.selectedValue);!e.canApply||!e.hasChanges||(this.toggleAllPending=!0,this.settleToggleAll(e.mode))}async settleToggleAll(e){try{await this.onSetScope?.(e)}catch(t){console.warn(`Failed to ${e===`all`?`enable all models`:`keep only the current model`}`,t)}finally{this.toggleAllPending=!1}}async settleEnabledToggle(e,t){try{await this.onToggleEnabled?.(t.provider,t.id,!t.enabled)}catch(t){console.warn(`Failed to toggle model ${e}`,t)}finally{let t=new Set(this.pendingToggles);t.delete(e),this.pendingToggles=t;let n=this.focusAfterToggle;this.focusAfterToggle=void 0,await this.updateComplete,n?.isConnected===!0&&this.shadowRoot?.activeElement===null&&n.focus({preventScroll:!0})}}static{this.styles=h`
|
|
2823
2823
|
:host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
2824
2824
|
modal-surface { --modal-surface-width: min(720px, calc(100vw - 40px)); --modal-surface-max-height: min(640px, calc(100vh - 40px)); }
|
|
2825
2825
|
header { display: flex; align-items: center; justify-content: space-between; padding: 12px; border-bottom: 1px solid var(--pi-border); }
|
|
@@ -2847,7 +2847,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2847
2847
|
.catalog-row .membership { flex: 1; min-width: 0; display: block; padding: 10px 12px; text-align: left; }
|
|
2848
2848
|
small { display: block; margin-top: 4px; color: var(--pi-muted); }
|
|
2849
2849
|
.empty { padding: 24px; color: var(--pi-muted); text-align: center; }
|
|
2850
|
-
`}};W([x()],
|
|
2850
|
+
`}};W([x()],LE.prototype,`title`,void 0),W([x({attribute:!1})],LE.prototype,`options`,void 0),W([x({attribute:!1})],LE.prototype,`catalog`,void 0),W([x({attribute:!1})],LE.prototype,`selectedValue`,void 0),W([x({attribute:!1})],LE.prototype,`onPick`,void 0),W([x({attribute:!1})],LE.prototype,`onCancel`,void 0),W([x({attribute:!1})],LE.prototype,`onToggleEnabled`,void 0),W([x({attribute:!1})],LE.prototype,`onSetScope`,void 0),W([S()],LE.prototype,`mode`,void 0),W([S()],LE.prototype,`selectedIndex`,void 0),W([S()],LE.prototype,`query`,void 0),W([S()],LE.prototype,`pendingToggles`,void 0),W([S()],LE.prototype,`toggleAllPending`,void 0),LE=W([b(`model-picker`)],LE);var RE=h`
|
|
2851
2851
|
:host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
2852
2852
|
modal-surface { --palette-top: min(12dvh, 90px); --palette-bottom: max(20px, env(safe-area-inset-bottom)); --modal-surface-place-items: start center; --modal-surface-backdrop-padding: var(--palette-top) 20px var(--palette-bottom); --modal-surface-max-height: min(640px, calc(100dvh - var(--palette-top) - var(--palette-bottom))); }
|
|
2853
2853
|
header { display: grid; grid-template-columns: 1fr auto; gap: 8px; padding: 10px; border-bottom: 1px solid var(--pi-border); }
|
|
@@ -2864,7 +2864,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2864
2864
|
.group { grid-column: 1 / -1; font-size: 12px; }
|
|
2865
2865
|
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; }
|
|
2866
2866
|
.empty { padding: 24px; color: var(--pi-muted); text-align: center; }
|
|
2867
|
-
`,
|
|
2867
|
+
`,zE=class extends y{constructor(...e){super(...e),this.actions=[],this.queryText=``,this.selectedIndex=0}render(){let e=this.filteredActions();return g`
|
|
2868
2868
|
<modal-surface .onClose=${()=>this.onCancel?.()} .initialFocus=${`input`} .label=${`操作面板`} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
2869
2869
|
<header>
|
|
2870
2870
|
<input
|
|
@@ -2876,19 +2876,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2876
2876
|
</header>
|
|
2877
2877
|
<div class="options">
|
|
2878
2878
|
${e.length===0?g`<div class="empty">未找到操作。</div>`:e.map((e,t)=>g`
|
|
2879
|
-
<button class=${`${t===this.selectedIndex?`selected`:``} ${e.enabled===!1?`disabled`:``}`} ?disabled=${e.enabled===!1} title=${e.disabledReason??e.title} aria-current=${t===this.selectedIndex?`true`:v} ${
|
|
2879
|
+
<button class=${`${t===this.selectedIndex?`selected`:``} ${e.enabled===!1?`disabled`:``}`} ?disabled=${e.enabled===!1} title=${e.disabledReason??e.title} aria-current=${t===this.selectedIndex?`true`:v} ${uE(t===this.selectedIndex,e.id)} @focus=${()=>{this.selectedIndex=t}} @click=${()=>{this.run(e)}}>
|
|
2880
2880
|
<span class="main">
|
|
2881
2881
|
<strong>${e.title}</strong>
|
|
2882
2882
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
2883
2883
|
${e.enabled===!1&&e.disabledReason!==void 0?g`<small class="disabled-reason">${e.disabledReason}</small>`:null}
|
|
2884
2884
|
</span>
|
|
2885
|
-
${e.shortcut===void 0?null:g`<kbd>${
|
|
2885
|
+
${e.shortcut===void 0?null:g`<kbd>${Pp(e.shortcut)}</kbd>`}
|
|
2886
2886
|
${e.group!==void 0&&e.group!==``?g`<small class="group">${e.group}</small>`:null}
|
|
2887
2887
|
</button>
|
|
2888
2888
|
`)}
|
|
2889
2889
|
</div>
|
|
2890
2890
|
</modal-surface>
|
|
2891
|
-
`}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
|
|
2891
|
+
`}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 BE(this.actions,this.queryText)}handleKeyDown(e){if(kE(e))return;let t=this.filteredActions();if(e.key===`ArrowDown`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key===`ArrowUp`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key===`Enter`){e.preventDefault();let n=t[this.selectedIndex];n!==void 0&&this.run(n)}}run(e){e.enabled!==!1&&this.onRun?.(e)}static{this.styles=RE}};W([x({attribute:!1})],zE.prototype,`actions`,void 0),W([x({attribute:!1})],zE.prototype,`onRun`,void 0),W([x({attribute:!1})],zE.prototype,`onCancel`,void 0),W([S()],zE.prototype,`queryText`,void 0),W([S()],zE.prototype,`selectedIndex`,void 0),zE=W([b(`action-palette`)],zE);function BE(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 VE=class extends y{constructor(...e){super(...e),this.selectedIndex=0,this.query=``}render(){let e=this.state;if(e===void 0)return null;let t=e.step===`apiKey`?e.saving===!0:e.step===`oauth`&&e.responding===!0;return g`
|
|
2892
2892
|
<modal-surface .onClose=${()=>{this.cancel()}} .onBusyEscape=${e.step===`oauth`?()=>this.onOAuthCancel?.():void 0} .busy=${t} .initialFocus=${this.initialFocus(e)} .label=${this.dialogTitle(e)} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
2893
2893
|
<header>
|
|
2894
2894
|
<strong>${this.dialogTitle(e)}</strong>
|
|
@@ -2909,13 +2909,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2909
2909
|
`:null}
|
|
2910
2910
|
<div class="options">
|
|
2911
2911
|
${n.length===0?g`<div class="empty">${i}</div>`:r.length===0?g`<div class="empty">没有匹配的提供商</div>`:r.map((e,t)=>g`
|
|
2912
|
-
<button class=${t===this.selectedIndex?`selected`:``} aria-current=${t===this.selectedIndex?`true`:v} ${
|
|
2912
|
+
<button class=${t===this.selectedIndex?`selected`:``} aria-current=${t===this.selectedIndex?`true`:v} ${uE(t===this.selectedIndex,e.key)} @focus=${()=>{this.selectedIndex=t}} @click=${()=>{e.run()}}>
|
|
2913
2913
|
<span>${e.title}</span>
|
|
2914
2914
|
<small>${e.detail}</small>
|
|
2915
2915
|
</button>
|
|
2916
2916
|
`)}
|
|
2917
2917
|
</div>
|
|
2918
|
-
`}optionsFor(e,t=e.target.projectName===void 0?`当前模式`:`当前项目`){switch(e.step){case`method`:return[{key:`oauth`,title:`使用订阅`,detail:`ChatGPT Plus/Pro、Claude Pro/Max 或 GitHub Copilot`,searchText:`使用订阅`,run:()=>{this.onChooseMethod?.(`oauth`)}},{key:`api_key`,title:`使用 API key`,detail:`将 API key 存入${t}的 auth.json`,searchText:`使用 API key`,run:()=>{this.onChooseMethod?.(`api_key`)}}];case`providers`:return e.providers.map(e=>({key:`${e.id}:${e.authType}`,title:g`${e.name}${e.status.source===void 0?null:g` <em>${
|
|
2918
|
+
`}optionsFor(e,t=e.target.projectName===void 0?`当前模式`:`当前项目`){switch(e.step){case`method`:return[{key:`oauth`,title:`使用订阅`,detail:`ChatGPT Plus/Pro、Claude Pro/Max 或 GitHub Copilot`,searchText:`使用订阅`,run:()=>{this.onChooseMethod?.(`oauth`)}},{key:`api_key`,title:`使用 API key`,detail:`将 API key 存入${t}的 auth.json`,searchText:`使用 API key`,run:()=>{this.onChooseMethod?.(`api_key`)}}];case`providers`:return e.providers.map(e=>({key:`${e.id}:${e.authType}`,title:g`${e.name}${e.status.source===void 0?null:g` <em>${YE(e)}</em>`}`,detail:`${e.id} · ${qE(e.authType)}`,searchText:e.name,run:()=>{this.onSelectProvider?.(e.id,e.authType)}}));case`logout`:return e.providers.map(e=>({key:`${e.id}:${e.authType}`,title:e.name,detail:`${e.id} · ${qE(e.authType)}`,searchText:e.name,run:()=>{this.onLogoutProvider?.(e.id)}}));case`apiKey`:case`oauth`:return}}stepHasSearch(e){return e.step===`providers`||e.step===`logout`}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(e){let t=this.query.trim().toLowerCase();return t===``?e:e.filter(e=>`${e.searchText} ${e.detail} ${e.key}`.toLowerCase().includes(t))}visibleOptions(e){return this.filteredOptions(this.optionsFor(e)??[])}renderOAuth(e){let t=e.flow,n=t.prompt,r=t.select,i=HE(n?.promptType),a=KE(e,window.location.hostname);return g`
|
|
2919
2919
|
<div class="form">
|
|
2920
2920
|
${t.auth===void 0?g`<p>正在启动登录流程…</p>`:g`
|
|
2921
2921
|
<p>打开此授权链接:</p>
|
|
@@ -2946,10 +2946,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2946
2946
|
`)}</div>
|
|
2947
2947
|
`}
|
|
2948
2948
|
${e.error!==void 0&&e.error!==``?g`<div class="error-text">${e.error}</div>`:null}
|
|
2949
|
-
${t.status===`error`||t.status===`cancelled`?g`<div class="error-text">${t.error??
|
|
2949
|
+
${t.status===`error`||t.status===`cancelled`?g`<div class="error-text">${t.error??XE(t.status)}</div><div class="actions"><button @click=${()=>{this.cancel()}}>关闭</button></div>`:null}
|
|
2950
2950
|
${n===void 0&&r===void 0&&t.status===`running`?g`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>取消</button></div>`:null}
|
|
2951
2951
|
</div>
|
|
2952
|
-
`}focusInputIfNeeded(){let e=
|
|
2952
|
+
`}focusInputIfNeeded(){let e=JE(this.state);if(e===void 0){this.lastFocusedInputKey=void 0;return}e!==this.lastFocusedInputKey&&(this.lastFocusedInputKey=e,this.modalSurface?.focusDialog())}handleKeyDown(e){let t=this.state;if(!(t===void 0||kE(e))){if(e.key===`ArrowDown`||e.key===`ArrowUp`){let n=this.visibleOptions(t);if(n.length===0)return;e.preventDefault();let r=e.key===`ArrowDown`?1:-1;this.selectedIndex=(this.selectedIndex+r+n.length)%n.length;return}if(e.key===`Enter`)if(t.step===`apiKey`)e.preventDefault(),this.onSaveApiKey?.();else if(t.step===`oauth`&&t.flow.prompt!==void 0)e.preventDefault(),this.onOAuthRespond?.();else{let n=this.visibleOptions(t)[this.selectedIndex];if(n===void 0)return;e.preventDefault(),n.run()}}}cancel(){this.state?.step===`oauth`?this.onOAuthCancel?.():this.onCancel?.()}initialFocus(e){return e.step===`apiKey`||e.step===`oauth`&&e.flow.prompt!==void 0||(e.step===`providers`||e.step===`logout`)&&e.providers.length>0?`input`:`button`}static{this.styles=[AE,h`
|
|
2953
2953
|
modal-surface { --modal-surface-width: min(720px, calc(100vw - 40px)); --modal-surface-max-height: min(640px, calc(100vh - 40px)); }
|
|
2954
2954
|
.form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
|
|
2955
2955
|
.form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
|
|
@@ -2968,12 +2968,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2968
2968
|
.inline-options button { display: grid; gap: 2px; text-align: left; }
|
|
2969
2969
|
.inline-options small { color: var(--pi-muted); }
|
|
2970
2970
|
em { color: var(--pi-success); font-style: normal; font-size: 12px; }
|
|
2971
|
-
`]}};W([x({attribute:!1})],
|
|
2972
|
-
<modal-surface .onClose=${this.mode===`change`?()=>this.onCancel?.():void 0} .busy=${this.loading} .initialFocus=${`input`} .label=${
|
|
2971
|
+
`]}};W([x({attribute:!1})],VE.prototype,`state`,void 0),W([x({attribute:!1})],VE.prototype,`onChooseMethod`,void 0),W([x({attribute:!1})],VE.prototype,`onSelectProvider`,void 0),W([x({attribute:!1})],VE.prototype,`onApiKeyInput`,void 0),W([x({attribute:!1})],VE.prototype,`onSaveApiKey`,void 0),W([x({attribute:!1})],VE.prototype,`onLogoutProvider`,void 0),W([x({attribute:!1})],VE.prototype,`onOAuthInput`,void 0),W([x({attribute:!1})],VE.prototype,`onOAuthRespond`,void 0),W([x({attribute:!1})],VE.prototype,`onOAuthCancel`,void 0),W([x({attribute:!1})],VE.prototype,`onCancel`,void 0),W([C(`modal-surface`)],VE.prototype,`modalSurface`,void 0),W([S()],VE.prototype,`selectedIndex`,void 0),W([S()],VE.prototype,`query`,void 0),VE=W([b(`auth-dialog`)],VE);function HE(e){return e===`secret`?`password`:`text`}var UE=new Set([`localhost`,`127.0.0.1`,`::1`]);function WE(e){return UE.has(e.trim().replace(/^\[|\]$/gu,``).toLowerCase())}function GE(e,t){return e!==`local`||!WE(t)}function KE(e,t){return GE(e.target.machineId,t)&&e.flow.status===`running`&&e.flow.prompt?.promptType===`manual_code`}function qE(e){return e===`oauth`?`订阅`:`API key`}function JE(e){if((e?.step===`providers`||e?.step===`logout`)&&e.providers.length>0)return`provider-search:${e.step}`;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 YE(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 XE(e){return e===`cancelled`?`已取消`:e===`error`?`错误`:e}var ZE=class extends y{constructor(...e){super(...e),this.mode=`login`,this.loading=!1,this.error=``,this.currentPassword=``,this.password=``,this.confirmPassword=``,this.localError=``}render(){return g`
|
|
2972
|
+
<modal-surface .onClose=${this.mode===`change`?()=>this.onCancel?.():void 0} .busy=${this.loading} .initialFocus=${`input`} .label=${QE(this.mode)}>
|
|
2973
2973
|
<header>
|
|
2974
2974
|
<div>
|
|
2975
2975
|
<span class="eyebrow">普通模式</span>
|
|
2976
|
-
<h1>${
|
|
2976
|
+
<h1>${QE(this.mode)}</h1>
|
|
2977
2977
|
</div>
|
|
2978
2978
|
${this.mode===`change`?g`<button class="close-button" title="关闭" aria-label="关闭" @click=${()=>this.onCancel?.()}>×</button>`:null}
|
|
2979
2979
|
</header>
|
|
@@ -2981,17 +2981,17 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
2981
2981
|
${this.mode===`change`?g`
|
|
2982
2982
|
<label>
|
|
2983
2983
|
<span>当前密码</span>
|
|
2984
|
-
<input type="password" .value=${this.currentPassword} autocomplete="current-password" @input=${e=>{this.currentPassword=
|
|
2984
|
+
<input type="password" .value=${this.currentPassword} autocomplete="current-password" @input=${e=>{this.currentPassword=eD(e),this.localError=``}}>
|
|
2985
2985
|
</label>
|
|
2986
2986
|
`:null}
|
|
2987
2987
|
<label>
|
|
2988
2988
|
<span>${this.mode===`login`?`密码`:`新密码`}</span>
|
|
2989
|
-
<input type="password" .value=${this.password} autocomplete=${this.mode===`login`?`current-password`:`new-password`} @input=${e=>{this.password=
|
|
2989
|
+
<input type="password" .value=${this.password} autocomplete=${this.mode===`login`?`current-password`:`new-password`} @input=${e=>{this.password=eD(e),this.localError=``}}>
|
|
2990
2990
|
</label>
|
|
2991
2991
|
${this.mode===`login`?null:g`
|
|
2992
2992
|
<label>
|
|
2993
2993
|
<span>确认密码</span>
|
|
2994
|
-
<input type="password" .value=${this.confirmPassword} autocomplete="new-password" @input=${e=>{this.confirmPassword=
|
|
2994
|
+
<input type="password" .value=${this.confirmPassword} autocomplete="new-password" @input=${e=>{this.confirmPassword=eD(e),this.localError=``}}>
|
|
2995
2995
|
</label>
|
|
2996
2996
|
`}
|
|
2997
2997
|
${this.message()===``?null:g`<p class="message">${this.message()}</p>`}
|
|
@@ -3001,7 +3001,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3001
3001
|
</footer>
|
|
3002
3002
|
</form>
|
|
3003
3003
|
</modal-surface>
|
|
3004
|
-
`}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
|
|
3004
|
+
`}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=$E(this.mode,t);if(n!==void 0){this.localError=n;return}this.localError=``,await this.onSubmit?.(t)}static{this.styles=h`
|
|
3005
3005
|
:host { position: fixed; inset: 0; z-index: 40; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
3006
3006
|
modal-surface { --modal-surface-backdrop-padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); --modal-surface-backdrop-background: var(--pi-bg); --modal-surface-width: min(420px, 100%); }
|
|
3007
3007
|
header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 16px; border-bottom: 1px solid var(--pi-border); }
|
|
@@ -3018,7 +3018,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3018
3018
|
.close-button { width: 34px; height: 34px; display: grid; place-items: center; border: 0; background: transparent; color: var(--pi-muted); padding: 0; font-size: 24px; }
|
|
3019
3019
|
.message { margin: 0; border: 1px solid var(--pi-danger-border); border-radius: 8px; background: var(--pi-danger-surface); color: var(--pi-danger); padding: 10px; }
|
|
3020
3020
|
footer { display: flex; justify-content: flex-end; gap: 8px; }
|
|
3021
|
-
`}};W([x()],
|
|
3021
|
+
`}};W([x()],ZE.prototype,`mode`,void 0),W([x({type:Boolean})],ZE.prototype,`loading`,void 0),W([x()],ZE.prototype,`error`,void 0),W([x({attribute:!1})],ZE.prototype,`onSubmit`,void 0),W([x({attribute:!1})],ZE.prototype,`onCancel`,void 0),W([S()],ZE.prototype,`currentPassword`,void 0),W([S()],ZE.prototype,`password`,void 0),W([S()],ZE.prototype,`confirmPassword`,void 0),W([S()],ZE.prototype,`localError`,void 0),ZE=W([b(`normal-auth-dialog`)],ZE);function QE(e){return e===`setup`?`设置进入密码`:e===`change`?`修改进入密码`:`输入密码`}function $E(e,t){if(e===`change`&&(t.currentPassword??``)===``)return`请输入当前密码。`;if(t.password===``)return`请输入密码。`;if(e!==`login`&&t.password!==(t.confirmPassword??``))return`两次输入的密码不一致。`}function eD(e){return e.target instanceof HTMLInputElement?e.target.value:``}var tD=class extends y{constructor(...e){super(...e),this.machineId=`local`,this.path=``,this.createMissing=!0,this.suggestions=[],this.selected=0,this.loading=!1,this.requestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}async loadSuggestions(){let e=++this.requestId;this.loading=!0;try{let t=await L.projectDirectories(this.path,this.machineId);if(e!==this.requestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.requestId&&(this.suggestions=[])}finally{e===this.requestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.loadSuggestions()}pick(e){this.setPath(e.path)}submit(){this.path.trim()!==``&&this.onSubmit?.(this.path,this.createMissing)}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}onKeyDown(e){if(e.target===this.pathInput){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`
|
|
3022
3022
|
<modal-surface .onClose=${()=>this.onCancel?.()} .initialFocus=${`input`} .label=${`添加项目`} @keydown=${e=>{this.onKeyDown(e)}}>
|
|
3023
3023
|
<header>
|
|
3024
3024
|
<strong>添加项目</strong>
|
|
@@ -3065,7 +3065,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3065
3065
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
3066
3066
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
3067
3067
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
3068
|
-
`}};W([x({attribute:!1})],
|
|
3068
|
+
`}};W([x({attribute:!1})],tD.prototype,`onSubmit`,void 0),W([x({attribute:!1})],tD.prototype,`onCancel`,void 0),W([x()],tD.prototype,`machineId`,void 0),W([S()],tD.prototype,`path`,void 0),W([S()],tD.prototype,`createMissing`,void 0),W([S()],tD.prototype,`suggestions`,void 0),W([S()],tD.prototype,`selected`,void 0),W([S()],tD.prototype,`loading`,void 0),W([C(`input`)],tD.prototype,`pathInput`,void 0),tD=W([b(`project-dialog`)],tD);var nD=class extends y{constructor(...e){super(...e),this.error=``,this.url=``,this.name=``,this.token=``,this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=``}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;let t=e.target.value,n=rD(t);(!this.nameEdited||this.name.trim()===``||this.name===this.previousSuggestedName)&&(this.name=n),this.previousSuggestedName=n,this.url=t}handleNameInput(e){e.target instanceof HTMLInputElement&&(this.nameEdited=!0,this.name=e.target.value)}handleTokenInput(e){e.target instanceof HTMLInputElement&&(this.token=e.target.value)}handleKeyDown(e){e.key===`Enter`&&e.target instanceof HTMLInputElement&&e.target.name===`baseUrl`&&iD(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===``||iD(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?iD(this.url):void 0,n=this.validInput()!==void 0&&!this.submitting;return g`
|
|
3069
3069
|
<modal-surface .onClose=${()=>this.onCancel?.()} .busy=${this.submitting} .initialFocus=${`input[name='baseUrl']`} .label=${`添加机器`} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
3070
3070
|
<form @submit=${e=>{this.handleSubmit(e)}}>
|
|
3071
3071
|
<header>
|
|
@@ -3117,7 +3117,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3117
3117
|
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
3118
3118
|
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
3119
3119
|
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
3120
|
-
`}};W([x({attribute:!1})]
|
|
3120
|
+
`}};W([x({attribute:!1})],nD.prototype,`onSubmit`,void 0),W([x({attribute:!1})],nD.prototype,`onCancel`,void 0),W([x()],nD.prototype,`error`,void 0),W([S()],nD.prototype,`url`,void 0),W([S()],nD.prototype,`name`,void 0),W([S()],nD.prototype,`token`,void 0),W([S()],nD.prototype,`submitting`,void 0),W([C(`input[name='name']`)],nD.prototype,`nameInput`,void 0),nD=W([b(`machine-dialog`)],nD);function rD(e){let t=e.trim();if(t===``)return``;let n=aD(t)??aD(`http://${t.replace(/^\/+/u,``)}`);return n!==void 0&&n.hostname!==``?n.hostname.replace(/^\[(.*)\]$/u,`$1`):oD(t)}function iD(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 aD(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:void 0}catch{return}}function oD(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 sD={availability:`error`,error:`error`,success:`success`,security:`warning`,warning:`warning`,info:`info`};function cD(e){return e.tone??sD[e.type]}var lD=class extends y{constructor(...e){super(...e),this.heading=``,this.description=``,this.actionLabel=``,this.actionTitle=``,this.actionDisabled=!1,this.notices=[]}render(){return g`
|
|
3121
3121
|
<section class="panel" aria-label=${this.heading||`设置面板`}>
|
|
3122
3122
|
<header class="section-heading">
|
|
3123
3123
|
<div class="heading-copy">
|
|
@@ -3140,7 +3140,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3140
3140
|
<div class="notice-stack" aria-label="设置通知">
|
|
3141
3141
|
${this.notices.map(e=>this.renderNotice(e))}
|
|
3142
3142
|
</div>
|
|
3143
|
-
`}renderNotice(e){let t=
|
|
3143
|
+
`}renderNotice(e){let t=cD(e),n=e.role??uD(t),r=e.title;return g`
|
|
3144
3144
|
<article class=${`notice ${t}`} role=${n}>
|
|
3145
3145
|
${r===void 0||r===``?v:g`<strong class="notice-title">${r}</strong>`}
|
|
3146
3146
|
<div class="notice-content">${e.content}</div>
|
|
@@ -3173,13 +3173,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3173
3173
|
.section-heading { display: grid; gap: 12px; }
|
|
3174
3174
|
.heading-actions { justify-self: start; }
|
|
3175
3175
|
}
|
|
3176
|
-
`}};W([x()],
|
|
3177
|
-
`):``}}function
|
|
3178
|
-
`)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``,attachmentDefaultFolder:e.attachments?.defaultFolder??``}}function
|
|
3179
|
-
`).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!
|
|
3176
|
+
`}};W([x()],lD.prototype,`heading`,void 0),W([x({attribute:!1})],lD.prototype,`description`,void 0),W([x()],lD.prototype,`actionLabel`,void 0),W([x()],lD.prototype,`actionTitle`,void 0),W([x({type:Boolean})],lD.prototype,`actionDisabled`,void 0),W([x({attribute:!1})],lD.prototype,`notices`,void 0),W([x({attribute:!1})],lD.prototype,`onAction`,void 0),lD=W([b(`settings-panel-frame`)],lD);function uD(e){switch(e){case`error`:return`alert`;case`success`:return`status`;case`warning`:case`info`:return`note`}}function dD(){return{host:``,port:``,allowedHostsMode:`list`,allowedHostsText:``}}function fD(){return{allowedPathsText:``,uploadDefaultFolder:``,attachmentDefaultFolder:``}}function pD(){return{command:``,dir:``}}function mD(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(`
|
|
3177
|
+
`):``}}function hD(e){return{allowedPathsText:e.pathAccess?.allowedPaths?.join(`
|
|
3178
|
+
`)??``,uploadDefaultFolder:e.uploads?.defaultFolder??``,attachmentDefaultFolder:e.attachments?.defaultFolder??``}}function gD(e){return{command:e.agent?.command??``,dir:e.agent?.dir??``}}function _D(e){let t=e.command.trim(),n=e.dir.trim();return{agent:{...t===``?{}:{command:t},...n===``?{}:{dir:n}}}}function vD(e,t){let n=_D(e).agent??{},r=t.agent??{};return n.command===r.command&&n.dir===r.dir}function yD(e,t={}){let n=xD(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`||SD(e.allowedHostsText),n}function bD(e){let t=CD(e.allowedPathsText),n=wD(e.uploadDefaultFolder,`上传默认文件夹`),r=wD(e.attachmentDefaultFolder,`附件默认文件夹`);return{pathAccess:{allowedPaths:t},uploads:n===``?{}:{defaultFolder:n},attachments:r===``?{}:{defaultFolder:r}}}function xD(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.attachments===void 0?{}:{attachments:e.attachments},...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 SD(e){return e.split(/[\n,]/u).map(e=>e.trim()).filter(e=>e!==``)}function CD(e){let t=e.split(`
|
|
3179
|
+
`).map(e=>e.trim()).filter(e=>e!==``),n=t.find(e=>!TD(e));if(n!==void 0)throw Error(`允许的外部路径必须是绝对路径或以 ~ 开头:${n}`);return t}function wD(e,t){let n=e.trim();if(n===``)return``;if(ED(n))throw Error(`${t}必须是工作区相对路径。`);let r=n.split(/[\\/]+/u).filter(e=>e!==``&&e!==`.`);if(r.length===0)return``;if(r.some(e=>e===`..`))throw Error(`${t}不能包含路径穿越。`);return r.join(`/`)}function TD(e){return e===`~`||e.startsWith(`~/`)||e.startsWith(`~\\`)||e.startsWith(`/`)||e.startsWith(`\\`)||/^[A-Za-z]:[\\/]/u.test(e)}function ED(e){let t=e.replace(/\\/g,`/`);return t.startsWith(`/`)||/^[A-Za-z]:\//u.test(t)}function DD(e){return g`网关服务器字段用于编辑当前本地网关;文件访问和上传默认值用于编辑 ${e}。`}var Y=class extends y{constructor(...e){super(...e),this.loading=!1,this.machineLoading=!1,this.saving=!1,this.error=``,this.machineError=``,this.savedMessage=``,this.targetLabel=`selected machine`,this.gatewayDraft=dD(),this.machineDraft=fD(),this.gatewayLocalError=``,this.machineLocalError=``}willUpdate(e){e.has(`configResponse`)&&this.configResponse!==void 0&&(this.gatewayDraft=mD(this.configResponse.config),this.gatewayLocalError=``),e.has(`machineConfigResponse`)&&this.machineConfigResponse!==void 0&&(this.machineDraft=hD(this.machineConfigResponse.config),this.machineLocalError=``)}render(){return g`
|
|
3180
3180
|
<settings-panel-frame
|
|
3181
3181
|
heading="通用配置"
|
|
3182
|
-
.description=${
|
|
3182
|
+
.description=${DD(this.targetLabel)}
|
|
3183
3183
|
actionLabel="重新加载"
|
|
3184
3184
|
.actionDisabled=${this.loading||this.machineLoading}
|
|
3185
3185
|
.notices=${this.panelNotices()}
|
|
@@ -3208,7 +3208,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3208
3208
|
<span>主机地址</span>
|
|
3209
3209
|
${this.renderOverrideBadge(`host`)}
|
|
3210
3210
|
</span>
|
|
3211
|
-
<input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:
|
|
3211
|
+
<input .value=${this.gatewayDraft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${e=>{this.updateGatewayDraft({host:AD(e)})}}>
|
|
3212
3212
|
<small>Web 服务器应绑定的地址。留空则使用 PI WEB 默认值。</small>
|
|
3213
3213
|
</label>
|
|
3214
3214
|
|
|
@@ -3217,7 +3217,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3217
3217
|
<span>端口</span>
|
|
3218
3218
|
${this.renderOverrideBadge(`port`)}
|
|
3219
3219
|
</span>
|
|
3220
|
-
<input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:
|
|
3220
|
+
<input .value=${this.gatewayDraft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${e=>{this.updateGatewayDraft({port:AD(e)})}}>
|
|
3221
3221
|
<small>TCP 端口,范围 1 到 65535。留空则使用 PI WEB 默认值。</small>
|
|
3222
3222
|
</label>
|
|
3223
3223
|
|
|
@@ -3226,11 +3226,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3226
3226
|
<span>允许的主机名</span>
|
|
3227
3227
|
${this.renderOverrideBadge(`allowedHosts`)}
|
|
3228
3228
|
</span>
|
|
3229
|
-
<select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:
|
|
3229
|
+
<select .value=${this.gatewayDraft.allowedHostsMode} @change=${e=>{this.updateGatewayDraft({allowedHostsMode:jD(e)===`all`?`all`:`list`})}}>
|
|
3230
3230
|
<option value="list">仅允许列出的主机名</option>
|
|
3231
3231
|
<option value="all">允许所有主机名</option>
|
|
3232
3232
|
</select>
|
|
3233
|
-
<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:
|
|
3233
|
+
<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:MD(e)})}}></textarea>
|
|
3234
3234
|
<small>每行输入一个主机名,或选择“允许所有主机名”写入 <code>true</code>。</small>
|
|
3235
3235
|
</div>
|
|
3236
3236
|
|
|
@@ -3260,7 +3260,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3260
3260
|
<span class="field-heading">
|
|
3261
3261
|
<span>外部文件系统根目录</span>
|
|
3262
3262
|
</span>
|
|
3263
|
-
<textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs /opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:
|
|
3263
|
+
<textarea .value=${this.machineDraft.allowedPathsText} rows="4" placeholder="~/SDKs /opt/reference" spellcheck="false" @input=${e=>{this.updateMachineDraft({allowedPathsText:MD(e)})}}></textarea>
|
|
3264
3264
|
<small>${this.targetLabel} 上允许用于绝对路径 <code>@</code> 补全和工作区外文件读取的目录。每行输入一个绝对路径、Windows 绝对路径或以 <code>~</code> 开头的路径。留空则默认禁止外部路径。</small>
|
|
3265
3265
|
</label>
|
|
3266
3266
|
|
|
@@ -3268,7 +3268,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3268
3268
|
<span class="field-heading">
|
|
3269
3269
|
<span>默认上传文件夹</span>
|
|
3270
3270
|
</span>
|
|
3271
|
-
<input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${Wo} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:
|
|
3271
|
+
<input .value=${this.machineDraft.uploadDefaultFolder} placeholder=${Wo} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({uploadDefaultFolder:AD(e)})}}>
|
|
3272
3272
|
<small>${this.targetLabel} 上手动上传文件使用的工作区相对目录。留空则使用 PI WEB 默认值 <code>${Wo}</code>。</small>
|
|
3273
3273
|
</label>
|
|
3274
3274
|
|
|
@@ -3276,7 +3276,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3276
3276
|
<span class="field-heading">
|
|
3277
3277
|
<span>默认附件文件夹</span>
|
|
3278
3278
|
</span>
|
|
3279
|
-
<input .value=${this.machineDraft.attachmentDefaultFolder} placeholder=${fs} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({attachmentDefaultFolder:
|
|
3279
|
+
<input .value=${this.machineDraft.attachmentDefaultFolder} placeholder=${fs} autocomplete="off" spellcheck="false" @input=${e=>{this.updateMachineDraft({attachmentDefaultFolder:AD(e)})}}>
|
|
3280
3280
|
<small>${this.targetLabel} 上保存提示附件使用的工作区相对目录。留空则使用 PI WEB 默认值 <code>${fs}</code>。</small>
|
|
3281
3281
|
</label>
|
|
3282
3282
|
|
|
@@ -3294,19 +3294,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3294
3294
|
<dl>
|
|
3295
3295
|
<div><dt>主机地址</dt><dd>${e.host??g`<span class="muted">默认 127.0.0.1</span>`}</dd></div>
|
|
3296
3296
|
<div><dt>端口</dt><dd>${e.port??g`<span class="muted">默认 8504</span>`}</dd></div>
|
|
3297
|
-
<div><dt>允许的主机名</dt><dd>${
|
|
3297
|
+
<div><dt>允许的主机名</dt><dd>${OD(e.allowedHosts)}</dd></div>
|
|
3298
3298
|
</dl>
|
|
3299
3299
|
</section>
|
|
3300
3300
|
`}renderMachineEffectiveConfig(){let e=this.machineConfigResponse?.effectiveConfig??{};return g`
|
|
3301
3301
|
<section class="effective-card" aria-label="所选机器最终生效的文件访问和上传摘要">
|
|
3302
3302
|
<h3>所选机器的生效配置</h3>
|
|
3303
3303
|
<dl>
|
|
3304
|
-
<div><dt>外部根目录</dt><dd>${
|
|
3304
|
+
<div><dt>外部根目录</dt><dd>${kD(e.pathAccess?.allowedPaths)}</dd></div>
|
|
3305
3305
|
<div><dt>上传文件夹</dt><dd>${e.uploads?.defaultFolder??g`<span class="muted">默认 ${`.pi-web/uploads`}</span>`}</dd></div>
|
|
3306
3306
|
<div><dt>附件文件夹</dt><dd>${e.attachments?.defaultFolder??g`<span class="muted">默认 ${`.pi-web/attachments`}</span>`}</dd></div>
|
|
3307
3307
|
</dl>
|
|
3308
3308
|
</section>
|
|
3309
|
-
`}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(
|
|
3309
|
+
`}reloadAll(){this.onReload?.(),this.onReloadMachine?.()}async saveGatewayConfig(e){e.preventDefault(),this.gatewayLocalError=``;try{await this.onSave?.(yD(this.gatewayDraft,this.configResponse?.config??{}))}catch(e){this.gatewayLocalError=ND(e)}}async saveMachineAccessConfig(e){e.preventDefault(),this.machineLocalError=``;try{await this.onSaveMachineConfig?.(bD(this.machineDraft))}catch(e){this.machineLocalError=ND(e)}}updateGatewayDraft(e){this.gatewayDraft={...this.gatewayDraft,...e},this.gatewayLocalError=``}updateMachineDraft(e){this.machineDraft={...this.machineDraft,...e},this.machineLocalError=``}static{this.styles=h`
|
|
3310
3310
|
:host { display: block; }
|
|
3311
3311
|
.card-heading { display: grid; gap: 6px; min-width: 0; }
|
|
3312
3312
|
h3, p { margin: 0; }
|
|
@@ -3337,10 +3337,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3337
3337
|
@media (max-width: 760px) {
|
|
3338
3338
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
3339
3339
|
}
|
|
3340
|
-
`}};W([x({attribute:!1})],Y.prototype,`configResponse`,void 0),W([x({attribute:!1})],Y.prototype,`machineConfigResponse`,void 0),W([x({type:Boolean})],Y.prototype,`loading`,void 0),W([x({type:Boolean})],Y.prototype,`machineLoading`,void 0),W([x({type:Boolean})],Y.prototype,`saving`,void 0),W([x()],Y.prototype,`error`,void 0),W([x()],Y.prototype,`machineError`,void 0),W([x()],Y.prototype,`savedMessage`,void 0),W([x()],Y.prototype,`targetLabel`,void 0),W([x({attribute:!1})],Y.prototype,`onReload`,void 0),W([x({attribute:!1})],Y.prototype,`onReloadMachine`,void 0),W([x({attribute:!1})],Y.prototype,`onSave`,void 0),W([x({attribute:!1})],Y.prototype,`onSaveMachineConfig`,void 0),W([S()],Y.prototype,`gatewayDraft`,void 0),W([S()],Y.prototype,`machineDraft`,void 0),W([S()],Y.prototype,`gatewayLocalError`,void 0),W([S()],Y.prototype,`machineLocalError`,void 0),Y=W([b(`settings-general-panel`)],Y);function
|
|
3340
|
+
`}};W([x({attribute:!1})],Y.prototype,`configResponse`,void 0),W([x({attribute:!1})],Y.prototype,`machineConfigResponse`,void 0),W([x({type:Boolean})],Y.prototype,`loading`,void 0),W([x({type:Boolean})],Y.prototype,`machineLoading`,void 0),W([x({type:Boolean})],Y.prototype,`saving`,void 0),W([x()],Y.prototype,`error`,void 0),W([x()],Y.prototype,`machineError`,void 0),W([x()],Y.prototype,`savedMessage`,void 0),W([x()],Y.prototype,`targetLabel`,void 0),W([x({attribute:!1})],Y.prototype,`onReload`,void 0),W([x({attribute:!1})],Y.prototype,`onReloadMachine`,void 0),W([x({attribute:!1})],Y.prototype,`onSave`,void 0),W([x({attribute:!1})],Y.prototype,`onSaveMachineConfig`,void 0),W([S()],Y.prototype,`gatewayDraft`,void 0),W([S()],Y.prototype,`machineDraft`,void 0),W([S()],Y.prototype,`gatewayLocalError`,void 0),W([S()],Y.prototype,`machineLocalError`,void 0),Y=W([b(`settings-general-panel`)],Y);function OD(e){return e===!0?`任意 host`:Array.isArray(e)?e.length===0?g`<span class="muted">未列出</span>`:e.join(`, `):g`<span class="muted">未设置</span>`}function kD(e){return e===void 0||e.length===0?g`<span class="muted">已禁止外部路径</span>`:e.join(`, `)}function AD(e){return e.target instanceof HTMLInputElement?e.target.value:``}function jD(e){return e.target instanceof HTMLSelectElement?e.target.value:``}function MD(e){return e.target instanceof HTMLTextAreaElement?e.target.value:``}function ND(e){return e instanceof Error?e.message:String(e)}function PD(e){return{spawnSessions:e}}function FD(e){return{subsessions:e}}function ID(e){return{askUser:e}}function LD(e,t){let n=e?.effectiveConfig.agent;return n?.command===void 0||n.dir===void 0||t===void 0?`unavailable`:n.command===t.command&&n.dir===t.dir&&BD(t.sessionDirEnvKeys,[`PI_WEB_AGENT_SESSION_DIR`,`PI_CODING_AGENT_SESSION_DIR`])?`active`:`restart-required`}function RD(e,t){return e?.agentDirSource===`pi-web`||e?.agentDirSource===`pi-compatibility`||e?.agentDir===!0}function zD(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 BD(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var VD=class extends y{constructor(...e){super(...e),this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.targetLabel=`本机(本地网关)`,this.agentProfileSupport={state:`supported`},this.agentDraft=pD(),this.agentDraftDirty=!1,this.agentLocalError=``}willUpdate(e){if(e.has(`configResponse`)){if(this.configResponse===void 0){this.agentDraft=pD(),this.agentDraftDirty=!1,this.agentLocalError=``;return}(!this.agentDraftDirty||vD(this.agentDraft,this.configResponse.config))&&(this.agentDraft=gD(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=RD(e?.envOverrides,u),f=e?.envOverrides.agentDir===!0,p=e?.effectiveConfig.agent,m=LD(e,this.activeAgentProfile);return g`
|
|
3341
3341
|
<settings-panel-frame
|
|
3342
3342
|
heading="会话守护进程"
|
|
3343
|
-
.description=${
|
|
3343
|
+
.description=${GD(this.targetLabel)}
|
|
3344
3344
|
actionLabel="重新加载"
|
|
3345
3345
|
.actionDisabled=${this.loading}
|
|
3346
3346
|
.notices=${this.panelNotices(e)}
|
|
@@ -3366,7 +3366,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3366
3366
|
.value=${this.agentDraft.command}
|
|
3367
3367
|
placeholder="pi"
|
|
3368
3368
|
?disabled=${this.loading||this.saving||!l||c}
|
|
3369
|
-
@input=${e=>{this.updateAgentDraft({command:
|
|
3369
|
+
@input=${e=>{this.updateAgentDraft({command:UD(e)})}}
|
|
3370
3370
|
>
|
|
3371
3371
|
<small>设置诊断和更新检查所用的 Pi 兼容配套 CLI。内嵌会话运行时仍使用 PI WEB 捆绑的 Pi SDK。</small>
|
|
3372
3372
|
</label>
|
|
@@ -3383,7 +3383,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3383
3383
|
.value=${this.agentDraft.dir}
|
|
3384
3384
|
placeholder="~/.pi/agent 或 ~/agent-profiles/work"
|
|
3385
3385
|
?disabled=${this.loading||this.saving||!l||d}
|
|
3386
|
-
@input=${e=>{this.updateAgentDraft({dir:
|
|
3386
|
+
@input=${e=>{this.updateAgentDraft({dir:UD(e)})}}
|
|
3387
3387
|
>
|
|
3388
3388
|
<small>选择 PI WEB 读取的 Pi 兼容认证、模型、设置和会话目录。备用命令会与其所需状态目录一并保存。</small>
|
|
3389
3389
|
</label>
|
|
@@ -3447,7 +3447,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3447
3447
|
<div><dt>期望状态目录</dt><dd>${p?.dir??g`<span class="muted">不可用</span>`}</dd></div>
|
|
3448
3448
|
<div><dt>当前命令</dt><dd>${this.activeAgentProfile?.command??g`<span class="muted">不可用</span>`}</dd></div>
|
|
3449
3449
|
<div><dt>当前状态目录</dt><dd>${this.activeAgentProfile?.dir??g`<span class="muted">不可用</span>`}</dd></div>
|
|
3450
|
-
<div><dt>配置档案状态</dt><dd>${
|
|
3450
|
+
<div><dt>配置档案状态</dt><dd>${HD(m)}</dd></div>
|
|
3451
3451
|
<div><dt>派生会话</dt><dd>${n?`已启用`:g`<span class="muted">已禁用</span>`}</dd></div>
|
|
3452
3452
|
<div><dt>子会话</dt><dd>${i?`已启用`:g`<span class="muted">已禁用</span>`}</dd></div>
|
|
3453
3453
|
<div><dt>代理提问</dt><dd>${a?s?`已启用`:g`<span class="muted">已禁用</span>`:g`<span class="muted">不可用</span>`}</dd></div>
|
|
@@ -3455,7 +3455,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3455
3455
|
</section>
|
|
3456
3456
|
`}
|
|
3457
3457
|
</settings-panel-frame>
|
|
3458
|
-
`}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}),
|
|
3458
|
+
`}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}),LD(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?.(_D(this.agentDraft))}catch(e){this.agentLocalError=WD(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?.(PD(t))}async toggleSubsessions(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(FD(t))}async toggleAskUser(e){let t=e.target instanceof HTMLInputElement&&e.target.checked;await this.onSave?.(ID(t))}static{this.styles=h`
|
|
3459
3459
|
:host { display: block; }
|
|
3460
3460
|
h3 { margin: 0; font-size: 13px; line-height: 1.3; }
|
|
3461
3461
|
button, input { font: inherit; }
|
|
@@ -3499,10 +3499,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3499
3499
|
@media (max-width: 760px) {
|
|
3500
3500
|
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
3501
3501
|
}
|
|
3502
|
-
`}};W([x({attribute:!1})],
|
|
3502
|
+
`}};W([x({attribute:!1})],VD.prototype,`configResponse`,void 0),W([x({type:Boolean})],VD.prototype,`loading`,void 0),W([x({type:Boolean})],VD.prototype,`saving`,void 0),W([x()],VD.prototype,`error`,void 0),W([x()],VD.prototype,`savedMessage`,void 0),W([x()],VD.prototype,`targetLabel`,void 0),W([x({attribute:!1})],VD.prototype,`activeAgentProfile`,void 0),W([x({attribute:!1})],VD.prototype,`agentProfileSupport`,void 0),W([x({attribute:!1})],VD.prototype,`onReload`,void 0),W([x({attribute:!1})],VD.prototype,`onSave`,void 0),W([S()],VD.prototype,`agentDraft`,void 0),W([S()],VD.prototype,`agentDraftDirty`,void 0),W([S()],VD.prototype,`agentLocalError`,void 0),VD=W([b(`settings-sessiond-panel`)],VD);function HD(e){return e===`active`?`已生效`:e===`restart-required`?`需要重启`:g`<span class="muted">不可用</span>`}function UD(e){return e.target instanceof HTMLInputElement?e.target.value:``}function WD(e){return e instanceof Error?e.message:String(e)}function GD(e){return`这些设置会影响 ${e} 上长生命周期的会话运行时。更改会立即保存,但只有在该机器的会话守护进程重启后才会生效。`}function KD(e){return e===void 0?{id:`local`,name:`本机`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function qD(e){return e.kind===`local`?`${e.name}(本地网关)`:`${e.name}(远程机器)`}function JD(e,t){return e.kind===`local`||t?.ok===!0?{state:`supported`}:{state:`unknown`}}function YD(e){return`${e.state}:${e.message??``}`}function XD(e){return e?.state===`unsupported`}function ZD(e){return`${e.name} 不支持 Pi 包管理。请更新并重启该机器上的 PI WEB,然后重试。`}function QD(e){return e.kind===`local`}function $D(e){return e.trim()}function eO(e){if($D(e)===``)return`请输入 Pi 支持的包来源,例如 npm:@scope/package、Git/URL 来源或本地路径。`}function tO(e){return e.scope===`project`?`项目范围`:`用户范围`}function nO(e){return e.filtered?`已被当前 Pi 包设置过滤`:`可用于此 PI WEB 进程`}function rO(e){return e.installedPath??`Pi 未报告安装路径`}function iO(e){return{packages:e.packages,...e.installableKnownPackages===void 0?{}:{installableKnownPackages:e.installableKnownPackages}}}function aO(e){return e.scope===`user`}function oO(e){if(!aO(e))return`此处会列出项目范围的 Pi 包,但 PI WEB 只能在此界面安全更新用户范围的 Pi 包。`}function sO(e){return e.length>0&&e.every(aO)}function cO(e){if(e.length===0)return`尚未配置 Pi 包。`;if(!sO(e))return`列表中包含项目范围的 Pi 包,无法全部更新;请逐个更新用户范围的包。`}function lO(e,t,n){return e?.kind===t?n===void 0||e.source===n:!1}function uO(e,t=KD(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 dO(e,t){let n=e.trim();return t.kind===`remote`?fO(n)?ZD(t):n===`Remote machine timeout`?`联系 ${t.name} 进行 Pi 包管理时超时。包操作可能仍在远端运行;重试前请重新加载包列表。`:n===`Remote machine unavailable`?`无法连接 ${t.name} 进行 Pi 包管理。请检查机器连接后重试。`:n:n}function fO(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 pO=class extends y{constructor(...e){super(...e),this.loading=!1,this.error=``,this.operationMessage=``,this.installSource=``,this.validationMessage=``}render(){let e=this.packagesResponse?.packages??[],t=this.packageTarget,n=qD(t),r=this.packageManagementUnavailable,i=this.packagesResponse!==void 0&&!r;return g`
|
|
3503
3503
|
<settings-panel-frame
|
|
3504
3504
|
heading="Pi 包"
|
|
3505
|
-
.description=${
|
|
3505
|
+
.description=${mO(n)}
|
|
3506
3506
|
actionLabel="重新加载"
|
|
3507
3507
|
actionTitle=${r?this.packageManagementUnavailableMessage(n):`从 ${n} 重新加载 Pi 包`}
|
|
3508
3508
|
.actionDisabled=${this.loading||this.isOperating||r}
|
|
@@ -3523,7 +3523,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3523
3523
|
${t.map(e=>this.renderInstallableKnownPackage(e))}
|
|
3524
3524
|
</div>
|
|
3525
3525
|
</section>
|
|
3526
|
-
`}renderInstallableKnownPackage(e){let t=
|
|
3526
|
+
`}renderInstallableKnownPackage(e){let t=lO(this.operation,`install`,e.source);return g`
|
|
3527
3527
|
<article class="known-package-card">
|
|
3528
3528
|
<div class="package-main">
|
|
3529
3529
|
<strong>${e.label}</strong>
|
|
@@ -3536,12 +3536,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3536
3536
|
<label for="package-source">Pi 包来源</label>
|
|
3537
3537
|
<div class="install-row">
|
|
3538
3538
|
<input id="package-source" .value=${this.installSource} ?disabled=${this.isOperating} placeholder="npm:@scope/package、Git URL 或本地路径" @input=${e=>{this.updateInstallSource(e)}}>
|
|
3539
|
-
<button type="submit" title="安装此 Pi 包" ?disabled=${this.isOperating}>${
|
|
3539
|
+
<button type="submit" title="安装此 Pi 包" ?disabled=${this.isOperating}>${lO(this.operation,`install`)?`正在安装…`:`安装`}</button>
|
|
3540
3540
|
</div>
|
|
3541
3541
|
${this.validationMessage===``?null:g`<div class="field-error">${this.validationMessage}</div>`}
|
|
3542
3542
|
<small>安装操作在 ${e} 上运行并使用 Pi 的默认包位置,等同于 <code>pi install <source></code>。PI WEB 不会要求你选择安装位置。</small>
|
|
3543
3543
|
</form>
|
|
3544
|
-
`}renderPackageList(e,t){let n=
|
|
3544
|
+
`}renderPackageList(e,t){let n=qD(t),r=this.packageManagementUnavailable?this.packageManagementUnavailableMessage(n):cO(e),i=r!==void 0&&e.length>0;return g`
|
|
3545
3545
|
<section class="package-section" aria-label="已配置的 Pi 包">
|
|
3546
3546
|
<div class="package-toolbar">
|
|
3547
3547
|
<div>
|
|
@@ -3549,7 +3549,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3549
3549
|
<p>此列表来自 ${n} 上的 Pi 包管理器设置。</p>
|
|
3550
3550
|
</div>
|
|
3551
3551
|
<button class="secondary" title=${r??`更新所有用户范围的 Pi 包`} ?disabled=${this.isOperating||r!==void 0} @click=${()=>{this.updatePackage()}}>
|
|
3552
|
-
${
|
|
3552
|
+
${lO(this.operation,`update-all`)?`正在更新…`:`全部更新`}
|
|
3553
3553
|
</button>
|
|
3554
3554
|
</div>
|
|
3555
3555
|
${i?g`<div class="action-note">${r}</div>`:null}
|
|
@@ -3560,12 +3560,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3560
3560
|
<div class="package-list">
|
|
3561
3561
|
${e.map(e=>this.renderPackage(e))}
|
|
3562
3562
|
</div>
|
|
3563
|
-
`}renderPackage(e){let t=
|
|
3563
|
+
`}renderPackage(e){let t=qD(this.packageTarget),n=this.packageManagementUnavailable,r=n?this.packageManagementUnavailableMessage(t):oO(e),i=n?this.packageManagementUnavailableMessage(t):`移除此 Pi 包`,a=lO(this.operation,`update`,e.source),o=lO(this.operation,`remove`,e.source);return g`
|
|
3564
3564
|
<article class=${`package-card${e.filtered?` filtered`:``}`}>
|
|
3565
3565
|
<div class="package-main">
|
|
3566
3566
|
<strong>${e.source}</strong>
|
|
3567
|
-
<small>${
|
|
3568
|
-
<small>安装路径:<code>${
|
|
3567
|
+
<small>${tO(e)} · ${nO(e)}</small>
|
|
3568
|
+
<small>安装路径:<code>${rO(e)}</code></small>
|
|
3569
3569
|
${r===void 0?null:g`<small class="action-note">${r}</small>`}
|
|
3570
3570
|
</div>
|
|
3571
3571
|
<div class="package-actions">
|
|
@@ -3573,7 +3573,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3573
3573
|
<button class="danger" title=${i} ?disabled=${this.isOperating||n} @click=${()=>{this.removePackage(e)}}>${o?`正在移除…`:`移除`}</button>
|
|
3574
3574
|
</div>
|
|
3575
3575
|
</article>
|
|
3576
|
-
`}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=
|
|
3576
|
+
`}updateInstallSource(e){this.installSource=e.target instanceof HTMLInputElement?e.target.value:``,this.validationMessage=``}async installPackage(e){e.preventDefault();let t=eO(this.installSource);if(t!==void 0){this.validationMessage=t;return}let n=$D(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 installKnownPackage(e){try{await this.onInstallPackage?.(e)}catch{}}async updatePackage(e){try{await this.onUpdatePackage?.(e)}catch{}}get packageTarget(){return this.targetMachine??KD(void 0)}get packageManagementUnavailable(){return XD(this.managementSupport)}packageManagementUnavailableMessage(e){return this.managementSupport?.message??`${e} 不支持 Pi 包管理。`}get isOperating(){return this.operation!==void 0}static{this.styles=h`
|
|
3577
3577
|
:host { display: block; }
|
|
3578
3578
|
.package-toolbar { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
3579
3579
|
.package-toolbar > div, .package-main { display: grid; gap: 6px; min-width: 0; }
|
|
@@ -3611,10 +3611,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3611
3611
|
.package-actions { justify-self: start; flex-wrap: wrap; }
|
|
3612
3612
|
.package-main strong, .package-main small { white-space: normal; }
|
|
3613
3613
|
}
|
|
3614
|
-
`}};W([x({attribute:!1})],
|
|
3614
|
+
`}};W([x({attribute:!1})],pO.prototype,`packagesResponse`,void 0),W([x({type:Boolean})],pO.prototype,`loading`,void 0),W([x({attribute:!1})],pO.prototype,`operation`,void 0),W([x({attribute:!1})],pO.prototype,`targetMachine`,void 0),W([x({attribute:!1})],pO.prototype,`managementSupport`,void 0),W([x()],pO.prototype,`error`,void 0),W([x()],pO.prototype,`operationMessage`,void 0),W([x({attribute:!1})],pO.prototype,`onReload`,void 0),W([x({attribute:!1})],pO.prototype,`onInstallPackage`,void 0),W([x({attribute:!1})],pO.prototype,`onRemovePackage`,void 0),W([x({attribute:!1})],pO.prototype,`onUpdatePackage`,void 0),W([S()],pO.prototype,`installSource`,void 0),W([S()],pO.prototype,`validationMessage`,void 0),pO=W([b(`settings-packages-panel`)],pO);function mO(e){return g`管理 <strong>${e}</strong> 上的 Pi 包。你可以安装、移除和更新所选机器上由 Pi 管理的包。Pi 包可提供扩展、技能、提示词模板、主题、上下文/系统提示文件以及 PI WEB 浏览器插件。`}var hO=class extends y{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`
|
|
3615
3615
|
<settings-panel-frame
|
|
3616
3616
|
heading="PI WEB 插件"
|
|
3617
|
-
.description=${
|
|
3617
|
+
.description=${gO(this.targetLabel)}
|
|
3618
3618
|
actionLabel="重新加载"
|
|
3619
3619
|
actionTitle=${`从 ${this.targetLabel} 重新加载 PI WEB 插件`}
|
|
3620
3620
|
.actionDisabled=${this.loading}
|
|
@@ -3632,7 +3632,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3632
3632
|
<article class=${`plugin-card${e.enabled?``:` disabled`}`}>
|
|
3633
3633
|
<div class="plugin-main">
|
|
3634
3634
|
<strong>${e.id}</strong>
|
|
3635
|
-
<small>${
|
|
3635
|
+
<small>${_O(e.source)} · ${vO(e.scope)}${e.machineSpecific?` · 机器专属`:``}</small>
|
|
3636
3636
|
<small>${n}</small>
|
|
3637
3637
|
</div>
|
|
3638
3638
|
<label class="toggle">
|
|
@@ -3660,10 +3660,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3660
3660
|
.plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
3661
3661
|
.toggle { justify-self: start; }
|
|
3662
3662
|
}
|
|
3663
|
-
`}};W([x({attribute:!1})],
|
|
3663
|
+
`}};W([x({attribute:!1})],hO.prototype,`pluginsResponse`,void 0),W([x({attribute:!1})],hO.prototype,`configResponse`,void 0),W([x({type:Boolean})],hO.prototype,`loading`,void 0),W([x({type:Boolean})],hO.prototype,`saving`,void 0),W([x()],hO.prototype,`error`,void 0),W([x()],hO.prototype,`savedMessage`,void 0),W([x()],hO.prototype,`targetLabel`,void 0),W([x({attribute:!1})],hO.prototype,`onReload`,void 0),W([x({attribute:!1})],hO.prototype,`onTogglePlugin`,void 0),hO=W([b(`settings-plugins-panel`)],hO);function gO(e){return g`启用或禁用 <strong>${e}</strong> 上发现的 PI WEB 浏览器插件。这与安装 Pi 包相互独立;请重新加载浏览器标签页以应用插件运行时更改。`}function _O(e){return e===`bundled`?`内置`:e===`local`?`本地`:e===`dev`?`开发`:e}function vO(e){switch(e){case`bundled`:return`内置范围`;case`local`:return`本地范围`;case`user`:return`用户范围`;case`project`:return`项目范围`}}var yO={capture:!0},bO=[{value:`auto`,label:`自动/默认`,description:`桌面环境按 Enter 发送;移动设备、粗略指针或窄屏环境按 Enter 换行。`},{value:`send`,label:`Enter 发送消息`,description:`Enter 发送聊天消息;支持时 Shift+Enter 插入新行。`},{value:`newline`,label:`Enter 插入新行`,description:`Enter 插入换行;支持时 Shift+Enter 发送聊天消息。`}];function xO(){return g`按操作编辑应用快捷键。输入 <code>mod+k</code> 或 <code>mod+g p</code> 这类快捷键,也可以从键盘录制、设为无或恢复默认。快捷键冲突时,自定义快捷键优先于默认值;同级按操作 ID 排序,较短快捷键会遮蔽相同前缀的较长序列。`}var SO=class extends y{constructor(...e){super(...e),this.actions=[],this.loading=!1,this.saving=!1,this.error=``,this.savedMessage=``,this.drafts={},this.localError=``,this.promptEnterPreference=QT(),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=Fp(e);if(n===void 0){this.localError=`请按字母、数字、标点、功能键或导航键。按 Esc 取消录制。`;return}if(t.tokens.length===0&&!Ip(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=EO(this.actions),t=this.shortcutResolutions();return g`
|
|
3664
3664
|
<settings-panel-frame
|
|
3665
3665
|
heading="键盘快捷键"
|
|
3666
|
-
.description=${
|
|
3666
|
+
.description=${xO()}
|
|
3667
3667
|
actionLabel="重新加载"
|
|
3668
3668
|
.actionDisabled=${this.loading}
|
|
3669
3669
|
.notices=${this.panelNotices()}
|
|
@@ -3694,7 +3694,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3694
3694
|
<p>选择当前浏览器中 Enter 键的行为。支持时 Shift+Enter 执行相反操作;为避免误发送,会忽略触摸键盘的自动大写状态。</p>
|
|
3695
3695
|
</div>
|
|
3696
3696
|
<div class="prompt-enter-options" role="radiogroup" aria-label="聊天输入框中的 Enter 和 Shift Enter 行为">
|
|
3697
|
-
${
|
|
3697
|
+
${bO.map(e=>g`
|
|
3698
3698
|
<label class="prompt-enter-option">
|
|
3699
3699
|
<input
|
|
3700
3700
|
type="radio"
|
|
@@ -3711,19 +3711,19 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3711
3711
|
`)}
|
|
3712
3712
|
</div>
|
|
3713
3713
|
</section>
|
|
3714
|
-
`}updatePromptEnterPreference(e){this.promptEnterPreference=e
|
|
3715
|
-
<article class=${
|
|
3714
|
+
`}updatePromptEnterPreference(e){this.promptEnterPreference=e,$T(e)}renderShortcutRow(e,t){let n=this.configResponse?.config.shortcuts,r=OO(e.id,n),i=jO(e,n),a=this.shortcutInputText(e),o=a.trim()===``?void 0:Mp(a),s=o?.ok===!0?o.shortcut:AO(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=TO(t);return g`
|
|
3715
|
+
<article class=${CO(t)}>
|
|
3716
3716
|
<div class="shortcut-main">
|
|
3717
3717
|
<strong>${e.title}</strong>
|
|
3718
3718
|
${e.description!==void 0&&e.description!==``?g`<small>${e.description}</small>`:null}
|
|
3719
3719
|
<small class="shortcut-id">${e.id}</small>
|
|
3720
|
-
<small>${e.shortcut!==void 0&&e.shortcut!==``?g`默认:<kbd>${
|
|
3720
|
+
<small>${e.shortcut!==void 0&&e.shortcut!==``?g`默认:<kbd>${Pp(e.shortcut)}</kbd>`:`无默认快捷键`}</small>
|
|
3721
3721
|
</div>
|
|
3722
3722
|
<div class="shortcut-editor">
|
|
3723
3723
|
<div class="shortcut-status">
|
|
3724
|
-
${s!==void 0&&s!==``?g`<kbd>${
|
|
3725
|
-
<small class=${u}>${
|
|
3726
|
-
${f===void 0?null:g`<small class=${
|
|
3724
|
+
${s!==void 0&&s!==``?g`<kbd>${Pp(s)}</kbd>`:g`<span class="unassigned">${i===`disabled`?`已禁用`:`未分配`}</span>`}
|
|
3725
|
+
<small class=${u}>${MO(u)}${l?` · 未保存`:``}</small>
|
|
3726
|
+
${f===void 0?null:g`<small class=${wO(t)}>${f}</small>`}
|
|
3727
3727
|
</div>
|
|
3728
3728
|
<label class="shortcut-input-label">
|
|
3729
3729
|
<span>快捷键</span>
|
|
@@ -3736,7 +3736,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3736
3736
|
autocapitalize="off"
|
|
3737
3737
|
spellcheck="false"
|
|
3738
3738
|
?disabled=${this.saving}
|
|
3739
|
-
@input=${t=>{this.updateDraft(e.id,
|
|
3739
|
+
@input=${t=>{this.updateDraft(e.id,NO(t))}}
|
|
3740
3740
|
>
|
|
3741
3741
|
</label>
|
|
3742
3742
|
${d===``?null:g`<small class="recording-hint">${d}</small>`}
|
|
@@ -3748,7 +3748,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3748
3748
|
</div>
|
|
3749
3749
|
</div>
|
|
3750
3750
|
</article>
|
|
3751
|
-
`}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=
|
|
3751
|
+
`}shortcutInputText(e){let t=this.drafts[e.id];if(t!==void 0)return t;let n=OO(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 取消。`:`正在录制:${Pp(t.tokens.join(` `))}。继续按键可添加序列,或等待录制完成。`:``}updateDraft(e,t){this.drafts={[e]:t},this.localError=``}async saveShortcut(e){this.stopRecording();let t=Mp(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?kO(r,e):{...r,[e]:t};Object.keys(i).length===0?delete n.shortcuts:n.shortcuts=i,await this.onSave?.(n)}shortcutResolutions(){return new Map(jp(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=Mp(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()},Op)}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,yO),!0)}removeRecordingListener(){this.recordingListenerActive&&=(window.removeEventListener(`keydown`,this.onRecordKeyDown,yO),!1)}static{this.styles=h`
|
|
3752
3752
|
:host { display: block; }
|
|
3753
3753
|
h3, p { margin: 0; }
|
|
3754
3754
|
h3 { font-size: 13px; line-height: 1.3; }
|
|
@@ -3804,7 +3804,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3804
3804
|
.shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
3805
3805
|
.shortcut-status, .shortcut-actions { justify-content: flex-start; }
|
|
3806
3806
|
}
|
|
3807
|
-
`}};W([x({attribute:!1})],
|
|
3807
|
+
`}};W([x({attribute:!1})],SO.prototype,`actions`,void 0),W([x({attribute:!1})],SO.prototype,`configResponse`,void 0),W([x({type:Boolean})],SO.prototype,`loading`,void 0),W([x({type:Boolean})],SO.prototype,`saving`,void 0),W([x()],SO.prototype,`error`,void 0),W([x()],SO.prototype,`savedMessage`,void 0),W([x({attribute:!1})],SO.prototype,`onReload`,void 0),W([x({attribute:!1})],SO.prototype,`onSave`,void 0),W([S()],SO.prototype,`drafts`,void 0),W([S()],SO.prototype,`localError`,void 0),W([S()],SO.prototype,`promptEnterPreference`,void 0),W([S()],SO.prototype,`recording`,void 0),SO=W([b(`settings-shortcuts-panel`)],SO);function CO(e){return e?.active===!1?`shortcut-row shadowed`:e?.active===!0&&e.shadows.length>0?`shortcut-row shadowing`:`shortcut-row`}function wO(e){return e?.active===!1?`conflict shadowed`:`conflict shadowing`}function TO(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 EO(e){let t=new Map;for(let n of[...e].sort(DO)){let e=n.group??`其他`;t.set(e,[...t.get(e)??[],n])}return[...t.entries()].map(([e,t])=>({name:e,actions:t}))}function DO(e,t){return(e.group??`其他`).localeCompare(t.group??`其他`)||e.title.localeCompare(t.title)}function OO(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function kO(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function AO(e,t){let n=OO(e.id,t);if(n!==null)return n??e.shortcut}function jO(e,t){let n=OO(e.id,t);return n===null?`disabled`:n===void 0?e.shortcut===void 0||e.shortcut===``?`unassigned`:`default`:`custom`}function MO(e){switch(e){case`default`:return`默认`;case`custom`:return`配置覆盖`;case`disabled`:return`配置禁用`;case`unassigned`:return`无默认值`}}function NO(e){return e.target instanceof HTMLInputElement?e.target.value:``}async function PO(e){let[t,n]=await Promise.allSettled([e.loadConfig(),e.loadPlugins()]),r={error:``},i=[];return t.status===`fulfilled`?r.config=t.value:i.push(`配置:${IO(t.reason)}`),n.status===`fulfilled`?r.plugins=n.value:i.push(`PI WEB 插件:${IO(n.reason)}`),i.length>0&&(r.error=`加载设置失败:${i.join(`;`)}`),r}async function FO(e,t,n){if(XD(n))return{error:n.message??`${qD(e)} 不支持 Pi 包管理。`,skipped:!0};try{return{packagesResponse:await t(e.id),error:``}}catch(t){return{error:`从 ${qD(e)} 加载 Pi 包失败:${dO(IO(t),e)}`}}}function IO(e){return e instanceof Error?e.message:String(e)}function LO(e,t){return{...e,config:RO(e.config,t.config),effectiveConfig:RO(e.effectiveConfig,t.effectiveConfig)}}function RO(e,t){return{...e,...t.pathAccess===void 0?{}:{pathAccess:t.pathAccess},...t.uploads===void 0?{}:{uploads:t.uploads},...t.attachments===void 0?{}:{attachments:t.attachments},...t.maxUploadBytes===void 0?{}:{maxUploadBytes:t.maxUploadBytes}}}function zO(e){return e===void 0?{id:`local`,name:`本机`,kind:`local`}:{id:e.id,name:e.name,kind:e.kind}}function X(e){return e.kind===`local`?`${e.name}(本地网关)`:`${e.name}(远程机器)`}function BO(e,t){return e.kind===`local`||t?.ok===!0?{state:`supported`}:{state:`unknown`}}function VO(e,t){return e.kind===`local`||t?.ok===!0?{state:`supported`}:{state:`unknown`,message:`无法确认 ${e.name} 是否支持 Pi 兼容代理配置档案。更改配置档案前请重新加载机器状态。`}}function HO(e){return`${e.state}:${e.message??``}`}function UO(e){return e?.state===`unsupported`}function WO(e){return e?.state===`supported`}function GO(e){return`${e.name} 不支持所选机器设置。请更新并重启该机器上的 PI WEB,然后重试。`}function KO(e,t){let n=e.trim();return t.kind===`remote`?qO(n)?GO(t):n===`Remote machine timeout`?`联系 ${t.name} 获取所选机器设置时超时。操作可能仍在远端运行;请重新加载后再重试。`:n===`Remote machine unavailable`?`无法连接 ${t.name} 以获取所选机器设置。请检查机器连接后重试。`:n:n}function qO(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 JO(e,t,n){let r=e.plugins??{},i=r[t]??{};return{plugins:{...r,[t]:{...i,enabled:n}}}}function YO(e,t){return{...e,config:XO(e.config,t.config),effectiveConfig:XO(e.effectiveConfig,t.effectiveConfig)}}function XO(e,t){return t.plugins===void 0?e:{...e,plugins:t.plugins}}var Z=class extends y{constructor(...e){super(...e),this.section=`general`,this.actions=[],this.loading=!0,this.accessLoading=!0,this.sessiondLoading=!0,this.pluginLoading=!0,this.packageLoading=!0,this.saving=!1,this.error=``,this.accessError=``,this.sessiondError=``,this.pluginError=``,this.packageError=``,this.savedMessage=``,this.packageMessage=``,this.loadRequestSeq=0,this.accessLoadRequestSeq=0,this.sessiondLoadRequestSeq=0,this.pluginLoadRequestSeq=0,this.packageLoadRequestSeq=0,this.packageMutationSeq=0}connectedCallback(){super.connectedCallback(),this.loadConfig(),this.loadAccessConfigForTarget(),this.reloadSessiondState(),this.loadPluginsForTarget(),this.loadPackagesForTarget()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}updated(e){let t=this.settingsTarget();if(e.has(`machine`)&&zO(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`
|
|
3808
3808
|
<modal-surface .onClose=${()=>this.onClose?.()} .busy=${this.saving} .label=${`PI WEB 设置`}>
|
|
3809
3809
|
<header class="settings-header">
|
|
3810
3810
|
<div>
|
|
@@ -3897,7 +3897,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3897
3897
|
<strong>${t}</strong>
|
|
3898
3898
|
<small>${n}</small>
|
|
3899
3899
|
</button>
|
|
3900
|
-
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await
|
|
3900
|
+
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){let e=++this.loadRequestSeq;this.loading=!0,this.error=``;try{let t=await PO({loadConfig:()=>bo.config(),loadPlugins:()=>So.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(UO(n)){this.accessConfigResponse=void 0,this.accessLoading=!1,this.accessError=n.message??`${X(e)} 不支持所选机器设置。`;return}this.accessLoading=!0,this.accessError=``;try{let n=await bo.config(e.id);if(!this.isCurrentAccessLoad(t,e))return;this.accessConfigResponse=n}catch(n){this.isCurrentAccessLoad(t,e)&&(this.accessError=`从 ${X(e)} 加载文件访问/上传配置失败:${KO(ZO(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(UO(n)){this.sessiondConfigResponse=void 0,this.sessiondLoading=!1,this.sessiondError=n.message??`${X(e)} 不支持所选机器设置。`;return}this.sessiondLoading=!0,this.sessiondError=``;try{let n=await bo.config(e.id);if(!this.isCurrentSessiondLoad(t,e))return;this.sessiondConfigResponse=n}catch(n){this.isCurrentSessiondLoad(t,e)&&(this.sessiondError=`从 ${X(e)} 加载会话守护进程配置失败:${KO(ZO(n),e)}`)}finally{this.isCurrentSessiondLoad(t,e)&&(this.sessiondLoading=!1)}}async loadPluginsForTarget(e=this.settingsTarget()){let t=++this.pluginLoadRequestSeq,n=this.selectedMachineSettingsSupport(e);if(UO(n)){this.selectedPluginConfigResponse=void 0,this.selectedPluginsResponse=void 0,this.pluginLoading=!1,this.pluginError=n.message??`${X(e)} 不支持所选机器设置。`;return}this.pluginLoading=!0,this.pluginError=``;try{let[n,r]=await Promise.allSettled([bo.config(e.id),So.plugins(e.id)]);if(!this.isCurrentPluginLoad(t,e))return;let i=[];n.status===`fulfilled`?this.selectedPluginConfigResponse=n.value:i.push(`配置:${KO(ZO(n.reason),e)}`),r.status===`fulfilled`?this.selectedPluginsResponse=r.value:i.push(`PI WEB 插件:${KO(ZO(r.reason),e)}`),this.pluginError=i.length===0?``:`从 ${X(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 FO(e,e=>wo.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(UO(r)){this.pluginError=r.message??`${X(n)} 不支持所选机器设置。`;return}if(this.selectedPluginConfigResponse===void 0){this.pluginError=`尚未加载 ${X(n)} 的插件配置。更改插件启用状态前请重新加载。`;return}let i=JO(this.selectedPluginConfigResponse.config,e,t);this.saving=!0,this.pluginError=``,this.savedMessage=``;try{let e=await bo.saveConfig(i,n.id);if(!this.isCurrentSettingsTarget(n))return;this.selectedPluginConfigResponse=e,n.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=YO(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=`在 ${X(n)} 上保存 PI WEB 插件配置失败:${KO(ZO(e),n)}`)}finally{this.saving=!1}}async saveConfig(e){if(!this.saving){this.saving=!0,this.error=``,this.savedMessage=``;try{let t=await bo.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.effectiveConfig),this.showSavedMessage()}catch(e){this.error=`保存配置失败:${ZO(e)}`}finally{this.saving=!1}}}async saveMachineAccessConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(UO(n)){this.accessError=n.message??`${X(t)} 不支持所选机器设置。`;return}this.saving=!0,this.accessError=``,this.savedMessage=``;try{let n=await bo.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.accessConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=LO(this.configResponse,n),this.onConfigSaved?.(this.configResponse.effectiveConfig)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.accessError=`在 ${X(t)} 上保存文件访问/上传配置失败:${KO(ZO(e),t)}`)}finally{this.saving=!1}}async saveSessiondConfig(e){if(this.saving)return;let t=this.settingsTarget(),n=this.selectedMachineSettingsSupport(t);if(UO(n)){this.sessiondError=n.message??`${X(t)} 不支持所选机器设置。`;return}if(e.agent!==void 0){let e=this.agentProfileSettingsSupport(t);if(!WO(e)){this.sessiondError=e.message??`${X(t)} 不支持 Pi 兼容代理配置档案设置。`;return}}this.saving=!0,this.sessiondError=``,this.savedMessage=``;try{let n=await bo.saveConfig(e,t.id);if(!this.isCurrentSettingsTarget(t))return;this.sessiondConfigResponse=n,t.kind===`local`&&this.configResponse!==void 0&&(this.configResponse=zD(this.configResponse,n)),this.showSavedMessage()}catch(e){this.isCurrentSettingsTarget(t)&&(this.sessiondError=`在 ${X(t)} 上保存会话守护进程配置失败:${KO(ZO(e),t)}`)}finally{this.saving=!1}}async installPiPackage(e){let t=this.packageTarget();await this.runPiPackageMutation({kind:`install`,source:e},`安装 Pi 包`,t,()=>wo.install(e,t.id))}async removePiPackage(e,t){let n=this.packageTarget();await this.runPiPackageMutation({kind:`remove`,source:e},`移除 Pi 包`,n,()=>wo.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,()=>wo.update(e,t.id))}async runPiPackageMutation(e,t,n,r){let i=this.packageManagementSupport(n);if(XD(i))throw this.packageError=i.message??`${qD(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=iO(e);let t=QD(n)?await this.refreshGatewayPlugins():void 0;if(!this.isCurrentPackageMutation(a,n))return;t!==void 0&&(this.packageError=t),this.packageMessage=uO(e.action,n)}catch(e){throw this.isCurrentPackageMutation(a,n)&&(this.packageError=`在 ${qD(n)} 上${t}失败:${dO(ZO(e),n)}`),e}finally{this.packageMutationSeq===a&&(this.packageOperation=void 0,this.saving=!1)}}async refreshGatewayPlugins(){try{this.pluginsResponse=await So.plugins();return}catch(e){return`刷新网关 PI WEB 插件失败:${ZO(e)}`}}async refreshPluginsForTarget(e){try{let t=await So.plugins(e.id);this.isCurrentSettingsTarget(e)&&(this.selectedPluginsResponse=t);return}catch(t){return`配置已保存,但从 ${X(e)} 刷新 PI WEB 插件失败:${KO(ZO(t),e)}`}}settingsTarget(){return zO(this.machine)}packageTarget(){return this.settingsTarget()}selectedMachineSettingsSupport(e=this.settingsTarget()){return BO(e,this.machineRuntime)}agentProfileSettingsSupport(e=this.settingsTarget()){return VO(e,this.machineRuntime)}selectedMachineSettingsSupportNeedsReload(e,t){let n=BO(t,e),r=this.selectedMachineSettingsSupport(t);return HO(n)!==HO(r)}packageManagementSupport(e=this.packageTarget()){return JD(e,this.machineRuntime)}packageManagementSupportNeedsReload(e,t){let n=JD(t,e),r=this.packageManagementSupport(t);return YD(n)===YD(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)}static{this.styles=h`
|
|
3901
3901
|
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
3902
3902
|
modal-surface { --modal-surface-backdrop-padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); --modal-surface-width: min(980px, 100%); --modal-surface-max-height: min(760px, 100%); --modal-surface-min-height: min(620px, 100%); --modal-surface-radius: 14px; }
|
|
3903
3903
|
.settings-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--pi-border); }
|
|
@@ -3922,7 +3922,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3922
3922
|
.settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
|
|
3923
3923
|
.settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
|
|
3924
3924
|
}
|
|
3925
|
-
`}};W([x({attribute:!1})],Z.prototype,`section`,void 0),W([x({attribute:!1})],Z.prototype,`actions`,void 0),W([x({attribute:!1})],Z.prototype,`machine`,void 0),W([x({attribute:!1})],Z.prototype,`machineRuntime`,void 0),W([x({attribute:!1})],Z.prototype,`onNavigate`,void 0),W([x({attribute:!1})],Z.prototype,`onClose`,void 0),W([x({attribute:!1})],Z.prototype,`onConfigSaved`,void 0),W([x({attribute:!1})],Z.prototype,`onRefreshMachineRuntime`,void 0),W([S()],Z.prototype,`configResponse`,void 0),W([S()],Z.prototype,`accessConfigResponse`,void 0),W([S()],Z.prototype,`sessiondConfigResponse`,void 0),W([S()],Z.prototype,`pluginsResponse`,void 0),W([S()],Z.prototype,`selectedPluginConfigResponse`,void 0),W([S()],Z.prototype,`selectedPluginsResponse`,void 0),W([S()],Z.prototype,`packagesResponse`,void 0),W([S()],Z.prototype,`loading`,void 0),W([S()],Z.prototype,`accessLoading`,void 0),W([S()],Z.prototype,`sessiondLoading`,void 0),W([S()],Z.prototype,`pluginLoading`,void 0),W([S()],Z.prototype,`packageLoading`,void 0),W([S()],Z.prototype,`saving`,void 0),W([S()],Z.prototype,`packageOperation`,void 0),W([S()],Z.prototype,`error`,void 0),W([S()],Z.prototype,`accessError`,void 0),W([S()],Z.prototype,`sessiondError`,void 0),W([S()],Z.prototype,`pluginError`,void 0),W([S()],Z.prototype,`packageError`,void 0),W([S()],Z.prototype,`savedMessage`,void 0),W([S()],Z.prototype,`packageMessage`,void 0),Z=W([b(`settings-dialog`)],Z);function
|
|
3925
|
+
`}};W([x({attribute:!1})],Z.prototype,`section`,void 0),W([x({attribute:!1})],Z.prototype,`actions`,void 0),W([x({attribute:!1})],Z.prototype,`machine`,void 0),W([x({attribute:!1})],Z.prototype,`machineRuntime`,void 0),W([x({attribute:!1})],Z.prototype,`onNavigate`,void 0),W([x({attribute:!1})],Z.prototype,`onClose`,void 0),W([x({attribute:!1})],Z.prototype,`onConfigSaved`,void 0),W([x({attribute:!1})],Z.prototype,`onRefreshMachineRuntime`,void 0),W([S()],Z.prototype,`configResponse`,void 0),W([S()],Z.prototype,`accessConfigResponse`,void 0),W([S()],Z.prototype,`sessiondConfigResponse`,void 0),W([S()],Z.prototype,`pluginsResponse`,void 0),W([S()],Z.prototype,`selectedPluginConfigResponse`,void 0),W([S()],Z.prototype,`selectedPluginsResponse`,void 0),W([S()],Z.prototype,`packagesResponse`,void 0),W([S()],Z.prototype,`loading`,void 0),W([S()],Z.prototype,`accessLoading`,void 0),W([S()],Z.prototype,`sessiondLoading`,void 0),W([S()],Z.prototype,`pluginLoading`,void 0),W([S()],Z.prototype,`packageLoading`,void 0),W([S()],Z.prototype,`saving`,void 0),W([S()],Z.prototype,`packageOperation`,void 0),W([S()],Z.prototype,`error`,void 0),W([S()],Z.prototype,`accessError`,void 0),W([S()],Z.prototype,`sessiondError`,void 0),W([S()],Z.prototype,`pluginError`,void 0),W([S()],Z.prototype,`packageError`,void 0),W([S()],Z.prototype,`savedMessage`,void 0),W([S()],Z.prototype,`packageMessage`,void 0),Z=W([b(`settings-dialog`)],Z);function ZO(e){return e instanceof Error?e.message:String(e)}var QO=h`
|
|
3926
3926
|
: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; }
|
|
3927
3927
|
header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
|
|
3928
3928
|
.workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
|
|
@@ -3981,7 +3981,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
3981
3981
|
.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); }
|
|
3982
3982
|
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; }
|
|
3983
3983
|
p { margin: 10px; }
|
|
3984
|
-
|
|
3984
|
+
`,$O=class extends y{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`
|
|
3985
3985
|
${this.hideToolTabs?null:g`
|
|
3986
3986
|
<header>
|
|
3987
3987
|
<div class=${this.workspaceHeaderFrameClass()}>
|
|
@@ -4011,37 +4011,37 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4011
4011
|
<h2>${e.title}</h2>
|
|
4012
4012
|
${e.body===void 0?null:g`<p>${e.body}</p>`}
|
|
4013
4013
|
</section>
|
|
4014
|
-
`}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=
|
|
4014
|
+
`}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=QO}};W([x({attribute:!1})],$O.prototype,`workspace`,void 0),W([x({attribute:!1})],$O.prototype,`panelContext`,void 0),W([x({attribute:!1})],$O.prototype,`emptyState`,void 0),W([x()],$O.prototype,`tool`,void 0),W([x({attribute:!1})],$O.prototype,`panels`,void 0),W([x({type:Boolean})],$O.prototype,`hideToolTabs`,void 0),W([x({attribute:!1})],$O.prototype,`onSelectTool`,void 0),W([C(`.workspace-header-strip`)],$O.prototype,`workspaceHeaderStrip`,void 0),W([S()],$O.prototype,`workspaceHeaderCanScrollLeft`,void 0),W([S()],$O.prototype,`workspaceHeaderCanScrollRight`,void 0),$O=W([b(`workspace-panel`)],$O);function ek(e){return e.kind===`local`||e.baseUrl===void 0?Dt(`favicon.svg`):new URL(`favicon.svg`,e.baseUrl.endsWith(`/`)?e.baseUrl:`${e.baseUrl}/`).toString()}function tk(e){let t=new URL(e);return`${t.host}${t.pathname.replace(/\/+$/,``)}`}function nk(){return tk(Dt(``))}var rk=class extends y{constructor(...e){super(...e),this.machines=[],this.locationIndicator=!1,this.canScrollLeft=!1,this.canScrollRight=!1,this.hideBrokenIcon=e=>{e.currentTarget instanceof HTMLImageElement&&(e.currentTarget.style.display=`none`)},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=ik(this.machine,this.machines),t=this.machines.length>1,n=t||this.locationIndicator,r=e===void 0?`context-chip machine-chip empty`:`context-chip machine-chip`,i=lk(this.project),a=dk(this.workspace),o=pk(this.session);return g`
|
|
4015
4015
|
<nav class=${this.contextBarClass()} aria-label="当前位置">
|
|
4016
4016
|
<span class="context-bar-label">位置</span>
|
|
4017
4017
|
<ol class="context-items" @scroll=${this.onContextScroll}>
|
|
4018
4018
|
${n?g`
|
|
4019
4019
|
<li class="context-item">
|
|
4020
4020
|
${t?g`
|
|
4021
|
-
<button type="button" class=${r} title=${
|
|
4021
|
+
<button type="button" class=${r} title=${ck(e)} aria-label=${`机器:${ak(e)}。打开机器选择。`} @click=${()=>{this.onOpenSection?.(`machines`)}}>
|
|
4022
4022
|
${this.renderMachineChipContent(e,this.locationIndicator)}
|
|
4023
4023
|
</button>
|
|
4024
4024
|
`:g`
|
|
4025
|
-
<span class="${r} static" title=${
|
|
4025
|
+
<span class="${r} static" title=${ck(e)}>
|
|
4026
4026
|
${this.renderMachineChipContent(e,!0)}
|
|
4027
4027
|
</span>
|
|
4028
4028
|
`}
|
|
4029
4029
|
</li>
|
|
4030
4030
|
`:null}
|
|
4031
4031
|
<li class="context-item">
|
|
4032
|
-
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${
|
|
4032
|
+
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${uk(this.project)} aria-label=${`项目:${i}。打开项目选择。`} @click=${()=>{this.onOpenSection?.(`projects`)}}>
|
|
4033
4033
|
<span class="context-kind">项目</span>
|
|
4034
4034
|
<span class="context-value">${i}</span>
|
|
4035
4035
|
</button>
|
|
4036
4036
|
</li>
|
|
4037
4037
|
<li class="context-item">
|
|
4038
|
-
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${
|
|
4038
|
+
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${fk(this.workspace)} aria-label=${`工作区:${a}。打开工作区选择。`} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
|
|
4039
4039
|
<span class="context-kind">工作区</span>
|
|
4040
4040
|
<span class="context-value">${a}</span>
|
|
4041
4041
|
</button>
|
|
4042
4042
|
</li>
|
|
4043
4043
|
<li class="context-item">
|
|
4044
|
-
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${
|
|
4044
|
+
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${mk(this.session)} aria-label=${`会话:${o}。打开会话选择。`} @click=${()=>{this.onOpenSection?.(`sessions`)}}>
|
|
4045
4045
|
<span class="context-kind">会话</span>
|
|
4046
4046
|
<span class="context-value">${o}</span>
|
|
4047
4047
|
</button>
|
|
@@ -4049,9 +4049,9 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4049
4049
|
</ol>
|
|
4050
4050
|
${this.hasContextActions()?g`<div class="context-actions">${this.renderActionsButton()}${this.refreshControl}</div>`:null}
|
|
4051
4051
|
</nav>
|
|
4052
|
-
`}renderMachineChipContent(e,t){if(e===void 0)return g`<span class="context-value">未选择机器</span>`;if(!t)return g`<span class="context-value">${
|
|
4053
|
-
<img class="context-chip-icon" src=${
|
|
4054
|
-
${this.machines.length>1?g`<span class="context-value">${
|
|
4052
|
+
`}renderMachineChipContent(e,t){if(e===void 0)return g`<span class="context-value">未选择机器</span>`;if(!t)return g`<span class="context-value">${ok(e)}</span>`;let n=sk(e,nk());return g`
|
|
4053
|
+
<img class="context-chip-icon" src=${ek(e)} alt="" @error=${this.hideBrokenIcon} />
|
|
4054
|
+
${this.machines.length>1?g`<span class="context-value">${ak(e)}</span>`:null}
|
|
4055
4055
|
${n===void 0?null:g`<span class=${this.machines.length>1?`context-detail`:`context-value`}>${n}</span>`}
|
|
4056
4056
|
`}renderActionsButton(){return this.onShowActions===void 0?null:g`
|
|
4057
4057
|
<button type="button" class="context-action-button" title="显示操作" aria-label="显示操作" @click=${e=>{e.stopPropagation(),this.onShowActions?.()}}>
|
|
@@ -4087,7 +4087,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4087
4087
|
.context-kind { display: none; }
|
|
4088
4088
|
.context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
|
|
4089
4089
|
button { cursor: pointer; }
|
|
4090
|
-
`}};W([x({attribute:!1})],
|
|
4090
|
+
`}};W([x({attribute:!1})],rk.prototype,`machines`,void 0),W([x({attribute:!1})],rk.prototype,`machine`,void 0),W([x({type:Boolean})],rk.prototype,`locationIndicator`,void 0),W([x({attribute:!1})],rk.prototype,`project`,void 0),W([x({attribute:!1})],rk.prototype,`workspace`,void 0),W([x({attribute:!1})],rk.prototype,`session`,void 0),W([x({attribute:!1})],rk.prototype,`refreshControl`,void 0),W([x({attribute:!1})],rk.prototype,`onOpenSection`,void 0),W([x({attribute:!1})],rk.prototype,`onShowActions`,void 0),W([C(`.context-items`)],rk.prototype,`contextItems`,void 0),W([S()],rk.prototype,`canScrollLeft`,void 0),W([S()],rk.prototype,`canScrollRight`,void 0),rk=W([b(`app-context-bar`)],rk);function ik(e,t){return e??t.find(e=>e.id===`local`)??t[0]}function ak(e){return e?.name??`未选择机器`}function ok(e){return`${e.name}${e.kind===`remote`?` · 远程`:``}`}function sk(e,t){if(e.kind===`local`||e.baseUrl===void 0)return t;try{return new URL(e.baseUrl).host}catch{return}}function ck(e){return e===void 0?`未选择机器`:e.baseUrl??e.name}function lk(e){return e?.name??`未选择项目`}function uk(e){return e===void 0?`未选择项目`:`${e.name} — ${e.path}`}function dk(e){return e===void 0?`未选择工作区`:`${e.label}${e.isMain?` · 主工作区`:``} · ${e.path}`}function fk(e){return e===void 0?`未选择工作区`:`${e.label}${e.isMain?` · 主工作区`:``} — ${e.path}`}function pk(e){let t=e?.name?.trim(),n=e?.firstMessage.trim();return t!==void 0&&t!==``?t:n!==void 0&&n!==``?n:e===void 0?`未选择会话`:xS(e.id)}function mk(e){return e===void 0?`未选择会话`:e.path}var hk=class extends y{constructor(...e){super(...e),this.tabs=[],this.selectedView=`chat`,this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.mobileTabsResizeObserver?.disconnect(),this.mobileTabsResizeObserver=void 0,this.observedMobileTabs=void 0,super.disconnectedCallback()}firstUpdated(){this.observeMobileTabs(),this.updateScrollState()}updated(){this.observeMobileTabs(),this.updateScrollState()}render(){let e=this.fallbackLabels();return g`
|
|
4091
4091
|
<div class=${this.frameClass()}>
|
|
4092
4092
|
<div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
|
|
4093
4093
|
${this.tabs.map(t=>{let n=this.selectedView===t.id;return g`
|
|
@@ -4099,7 +4099,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4099
4099
|
`})}
|
|
4100
4100
|
</div>
|
|
4101
4101
|
</div>
|
|
4102
|
-
`}frameClass(){return`mobile-tabs-frame${this.canScrollLeft?` can-scroll-left`:``}${this.canScrollRight?` can-scroll-right`:``}`}tabClass(e){return[...e.className===void 0?[]:[e.className],...this.selectedView===e.id?[`selected`]:[]].join(` `)}tabAriaLabel(e){let t=e.badgeLabel??(typeof e.badge==`string`||typeof e.badge==`number`?String(e.badge).trim():``);return t===``?e.label:`${e.label}, ${t}`}renderBadge(e,t){return e===void 0||e===``?null:g`<span class=${`tab-badge${t===void 0?``:` ${t}`}`}>${e}</span>`}renderTabMark(e,t){return e.icon===void 0?g`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:
|
|
4102
|
+
`}frameClass(){return`mobile-tabs-frame${this.canScrollLeft?` can-scroll-left`:``}${this.canScrollRight?` can-scroll-right`:``}`}tabClass(e){return[...e.className===void 0?[]:[e.className],...this.selectedView===e.id?[`selected`]:[]].join(` `)}tabAriaLabel(e){let t=e.badgeLabel??(typeof e.badge==`string`||typeof e.badge==`number`?String(e.badge).trim():``);return t===``?e.label:`${e.label}, ${t}`}renderBadge(e,t){return e===void 0||e===``?null:g`<span class=${`tab-badge${t===void 0?``:` ${t}`}`}>${e}</span>`}renderTabMark(e,t){return e.icon===void 0?g`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:Ah(e.icon)}fallbackLabels(){let e=this.tabs.filter(e=>e.icon===void 0),t=new Map;for(let n of e){let e=this.initialsLabel(n.label);t.set(e,(t.get(e)??0)+1)}let n=new Map;for(let r of e){let e=this.initialsLabel(r.label);n.set(r.id,(t.get(e)??0)>1?this.fullFallbackLabel(r.label):e)}return n}initialsLabel(e){let t=(e.match(/[\p{L}\p{N}]+/gu)??[]).map(e=>Array.from(e)[0]??``).join(``).toLocaleUpperCase();return t===``?`?`:t}fullFallbackLabel(e){let t=e.trim();return t===``?`?`:t}observeMobileTabs(){let e=this.mobileTabsElement();this.observedMobileTabs!==e&&(this.mobileTabsResizeObserver?.disconnect(),this.observedMobileTabs=e,this.mobileTabsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>`u`)&&(this.mobileTabsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.mobileTabsResizeObserver.observe(e)))}updateScrollState(){let e=this.mobileTabsElement(),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.canScrollLeft!==n&&(this.canScrollLeft=n),this.canScrollRight!==r&&(this.canScrollRight=r)}mobileTabsElement(){let e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}static{this.styles=h`
|
|
4103
4103
|
:host { flex: 0 0 auto; min-width: 0; }
|
|
4104
4104
|
.mobile-tabs-frame { position: relative; display: flex; flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); background: var(--pi-bg); }
|
|
4105
4105
|
.mobile-tabs-frame::before, .mobile-tabs-frame::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 20px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
|
|
@@ -4126,12 +4126,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4126
4126
|
.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; }
|
|
4127
4127
|
.tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
|
|
4128
4128
|
}
|
|
4129
|
-
`}};W([x({attribute:!1})],
|
|
4129
|
+
`}};W([x({attribute:!1})],hk.prototype,`tabs`,void 0),W([x({attribute:!1})],hk.prototype,`selectedView`,void 0),W([x({attribute:!1})],hk.prototype,`onSelect`,void 0),W([C(`.mobile-tabs`)],hk.prototype,`mobileTabs`,void 0),W([S()],hk.prototype,`canScrollLeft`,void 0),W([S()],hk.prototype,`canScrollRight`,void 0),hk=W([b(`app-mobile-main-tabs`)],hk);var gk=class extends y{constructor(...e){super(...e),this.machines=[],this.locationIndicator=!1,this.statuses={},this.activities={},this.unreadMachineIds=new Set,this.statusSnapshots={},this.open=!1,this.menuStyle=``,this.actionMenuStyle=``,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.open=!1,this.openActionsMachineId=void 0)},this.hideBrokenIcon=e=>{e.currentTarget instanceof HTMLImageElement&&(e.currentTarget.style.display=`none`)}}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.open&&this.machines.length<=1&&(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;if(this.machines.length<=1)return this.locationIndicator?this.renderMachineInfo(e):null;let t=_k(e,this.statuses),n=e.name;return g`
|
|
4130
4130
|
<div class="machine-switcher">
|
|
4131
4131
|
<button
|
|
4132
4132
|
type="button"
|
|
4133
4133
|
class="machine-switcher-button"
|
|
4134
|
-
title=${
|
|
4134
|
+
title=${yk(e)}
|
|
4135
4135
|
aria-label=${this.machineSwitcherAriaLabel(e)}
|
|
4136
4136
|
aria-expanded=${String(this.open)}
|
|
4137
4137
|
@click=${e=>{this.toggleMenu(e.currentTarget)}}
|
|
@@ -4143,7 +4143,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4143
4143
|
<span class="machine-switcher-kicker">机器</span>
|
|
4144
4144
|
<span class="machine-switcher-label">${n}</span>
|
|
4145
4145
|
</span>
|
|
4146
|
-
<span class=${`machine-status ${t}`}>${
|
|
4146
|
+
<span class=${`machine-status ${t}`}>${vk(t)}</span>
|
|
4147
4147
|
<span class="machine-chevron" aria-hidden="true">▾</span>
|
|
4148
4148
|
</button>
|
|
4149
4149
|
${this.open?g`
|
|
@@ -4152,18 +4152,18 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4152
4152
|
</div>
|
|
4153
4153
|
`:null}
|
|
4154
4154
|
</div>
|
|
4155
|
-
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=
|
|
4155
|
+
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=_k(e,this.statuses),r=aS(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return g`
|
|
4156
4156
|
<div class=${`machine-option ${t?`selected`:``} ${r?``:`no-actions`}`}>
|
|
4157
4157
|
<button
|
|
4158
4158
|
type="button"
|
|
4159
4159
|
class="machine-option-main"
|
|
4160
|
-
title=${
|
|
4160
|
+
title=${yk(e)}
|
|
4161
4161
|
data-machine-id=${e.id}
|
|
4162
4162
|
@click=${()=>{this.select(e)}}
|
|
4163
4163
|
@keydown=${e=>{this.handleMachineOptionKeydown(e)}}
|
|
4164
4164
|
>
|
|
4165
4165
|
<span class="machine-option-name">${this.renderMachineIcon(e)}${this.renderActivity(e)}<span>${e.name}</span></span>
|
|
4166
|
-
<small>${
|
|
4166
|
+
<small>${bk(e)} · ${vk(n)}</small>
|
|
4167
4167
|
</button>
|
|
4168
4168
|
${r?g`
|
|
4169
4169
|
<div class="machine-option-actions">
|
|
@@ -4184,12 +4184,12 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4184
4184
|
`:null}
|
|
4185
4185
|
</div>
|
|
4186
4186
|
`}renderMachineInfo(e){return g`
|
|
4187
|
-
<div class="machine-info" title=${
|
|
4187
|
+
<div class="machine-info" title=${bk(e)}>
|
|
4188
4188
|
${this.renderMachineIcon(e)}
|
|
4189
4189
|
${this.renderActivity(e)}
|
|
4190
|
-
<span class="machine-info-url">${
|
|
4190
|
+
<span class="machine-info-url">${bk(e)}</span>
|
|
4191
4191
|
</div>
|
|
4192
|
-
`}renderMachineIcon(e){let t=
|
|
4192
|
+
`}renderMachineIcon(e){let t=_k(e,this.statuses);return g`<img class=${t===`offline`||t===`error`?`machine-icon dimmed`:`machine-icon`} src=${ek(e)} alt="" @error=${this.hideBrokenIcon} />`}renderActivity(e){let t=_k(e,this.statuses),n=this.statusSnapshots[e.id],r=n?.machine,i=t===`offline`||t===`error`?void 0:n===void 0?Pc(this.activities[e.id]):Fx(r),a=n===void 0?this.unreadMachineIds.has(e.id)?`此机器上有未读会话`:void 0:Ix(r)?`此机器上有未读会话`:void 0;return Nx(i,i===`terminal`?`机器终端活动中`:`机器活动中`,a)}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=xk(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=xk(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=zx(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`
|
|
4193
4193
|
:host { min-width: 0; display: block; }
|
|
4194
4194
|
.machine-switcher { min-width: 0; }
|
|
4195
4195
|
.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; }
|
|
@@ -4230,7 +4230,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4230
4230
|
.machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
|
|
4231
4231
|
.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); }
|
|
4232
4232
|
@keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
|
|
4233
|
-
`}};W([x({attribute:!1})],
|
|
4233
|
+
`}};W([x({attribute:!1})],gk.prototype,`machines`,void 0),W([x({attribute:!1})],gk.prototype,`selected`,void 0),W([x({type:Boolean})],gk.prototype,`locationIndicator`,void 0),W([x({attribute:!1})],gk.prototype,`statuses`,void 0),W([x({attribute:!1})],gk.prototype,`activities`,void 0),W([x({attribute:!1})],gk.prototype,`unreadMachineIds`,void 0),W([x({attribute:!1})],gk.prototype,`statusSnapshots`,void 0),W([x({attribute:!1})],gk.prototype,`onSelect`,void 0),W([x({attribute:!1})],gk.prototype,`onRemove`,void 0),W([x({attribute:!1})],gk.prototype,`onFocusNextSection`,void 0),W([x({attribute:!1})],gk.prototype,`onCancelKeyboardNavigation`,void 0),W([S()],gk.prototype,`open`,void 0),W([S()],gk.prototype,`menuStyle`,void 0),W([S()],gk.prototype,`openActionsMachineId`,void 0),W([S()],gk.prototype,`actionMenuStyle`,void 0),gk=W([b(`machine-switcher`)],gk);function _k(e,t){return t[e.id]?.status??e.status??`unknown`}function vk(e){return e===`online`?`在线`:e===`offline`?`离线`:e===`error`?`错误`:`未知`}function yk(e){return e.baseUrl??e.name}function bk(e){return e.kind===`local`?nk():e.baseUrl??`远程 PI WEB`}function xk(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: ${Sk(t.bottom)};`,`left: ${Sk(r)};`,`width: ${Sk(n)};`,`max-height: ${Sk(i)};`].join(` `)}function Sk(e){return`${String(Math.round(e))}px`}var Q=class extends y{constructor(...e){super(...e),this.machines=[],this.locationIndicator=!1,this.machineStatuses={},this.machineActivities={},this.machineStatusSnapshots={},this.projects=[],this.workspaces=[],this.sessions=[],this.pinnedSessionIds=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.unreadSessionIds=new Set,this.unreadPresence=Em,this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.showBrand=!0,this.managementMode=!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(){let e=wk(this.machines),t=e||this.locationIndicator,n=this.refreshControl!==void 0||this.onShowActions!==void 0;return g`
|
|
4234
4234
|
${this.showBrand||t||n?g`<header>
|
|
4235
4235
|
${this.showBrand?g`<strong>PI WEB</strong>`:null}
|
|
4236
4236
|
${t?g`
|
|
@@ -4307,7 +4307,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4307
4307
|
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
4308
4308
|
></workspace-list>
|
|
4309
4309
|
<session-list
|
|
4310
|
-
.scopeKey=${
|
|
4310
|
+
.scopeKey=${Ck(this.selectedMachine?.id,this.selectedWorkspace?.id)}
|
|
4311
4311
|
.sessions=${this.sessions}
|
|
4312
4312
|
.pinnedSessionIds=${this.pinnedSessionIds}
|
|
4313
4313
|
.statuses=${this.sessionStatuses}
|
|
@@ -4348,7 +4348,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4348
4348
|
.onFocusNextSection=${()=>{this.focusNextFrom(`sessions`)}}
|
|
4349
4349
|
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
4350
4350
|
></session-list>
|
|
4351
|
-
`}selectedMachineStatusSnapshot(){return this.machineStatusSnapshots[this.selectedMachine?.id??`local`]}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=
|
|
4351
|
+
`}selectedMachineStatusSnapshot(){return this.machineStatusSnapshots[this.selectedMachine?.id??`local`]}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=Tk(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(Ek(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=h`
|
|
4352
4352
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
|
|
4353
4353
|
:host([compact]) { flex: 1 1 auto; }
|
|
4354
4354
|
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); }
|
|
@@ -4362,7 +4362,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4362
4362
|
workspace-list[collapsed],
|
|
4363
4363
|
session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
4364
4364
|
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
4365
|
-
`}};W([x({attribute:!1})],Q.prototype,`machines`,void 0),W([x({attribute:!1})],Q.prototype,`selectedMachine`,void 0),W([x({type:Boolean})],Q.prototype,`locationIndicator`,void 0),W([x({attribute:!1})],Q.prototype,`machineStatuses`,void 0),W([x({attribute:!1})],Q.prototype,`machineActivities`,void 0),W([x({attribute:!1})],Q.prototype,`machineStatusSnapshots`,void 0),W([x({attribute:!1})],Q.prototype,`projects`,void 0),W([x({attribute:!1})],Q.prototype,`selectedProject`,void 0),W([x({attribute:!1})],Q.prototype,`workspaces`,void 0),W([x({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),W([x({attribute:!1})],Q.prototype,`sessions`,void 0),W([x({attribute:!1})],Q.prototype,`pinnedSessionIds`,void 0),W([x({attribute:!1})],Q.prototype,`selectedSession`,void 0),W([x({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),W([x({attribute:!1})],Q.prototype,`sessionActivities`,void 0),W([x({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),W([x({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),W([x({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),W([x({attribute:!1})],Q.prototype,`unreadPresence`,void 0),W([x({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),W([x({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),W([x({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),W([x({attribute:!1})],Q.prototype,`refreshControl`,void 0),W([x({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),W([x({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),W([x({type:Boolean})],Q.prototype,`showBrand`,void 0),W([x({type:Boolean})],Q.prototype,`managementMode`,void 0),W([x({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),W([x({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),W([x({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),W([x({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),W([x({type:Number})],Q.prototype,`startingSessionCount`,void 0),W([x({type:Boolean})],Q.prototype,`canStartSession`,void 0),W([x({type:Boolean})],Q.prototype,`canDeleteArchivedSessions`,void 0),W([x({type:Boolean})],Q.prototype,`canReloadSessions`,void 0),W([x({type:Boolean})],Q.prototype,`canCleanupSessions`,void 0),W([x({type:Boolean})],Q.prototype,`authoritativeSessionPersistence`,void 0),W([x({type:String})],Q.prototype,`archivedDeleteUnavailableMessage`,void 0),W([x({type:String})],Q.prototype,`cleanupUnavailableMessage`,void 0),W([x({attribute:!1})],Q.prototype,`onShowActions`,void 0),W([x({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),W([x({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),W([x({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),W([x({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),W([x({attribute:!1})],Q.prototype,`onSelectProject`,void 0),W([x({attribute:!1})],Q.prototype,`onCloseProject`,void 0),W([x({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),W([x({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),W([x({attribute:!1})],Q.prototype,`onStartSession`,void 0),W([x({attribute:!1})],Q.prototype,`onSelectSession`,void 0),W([x({attribute:!1})],Q.prototype,`onSearchSessions`,void 0),W([x({attribute:!1})],Q.prototype,`onToggleSessionPin`,void 0),W([x({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),W([x({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),W([x({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),W([x({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),W([x({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),W([x({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),W([x({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),W([x({attribute:!1})],Q.prototype,`onRenameSession`,void 0),W([x({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),W([x({attribute:!1})],Q.prototype,`onMarkSessionRead`,void 0),W([x({attribute:!1})],Q.prototype,`onMarkSessionsRead`,void 0),W([x({attribute:!1})],Q.prototype,`onReloadSession`,void 0),W([x({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),W([x({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),W([x({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),W([x({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),W([x({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),W([x({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),W([C(`machine-list`)],Q.prototype,`machineList`,void 0),W([C(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),W([C(`project-list`)],Q.prototype,`projectList`,void 0),W([C(`workspace-list`)],Q.prototype,`workspaceList`,void 0),W([C(`session-list`)],Q.prototype,`sessionList`,void 0),Q=W([b(`app-navigation-panel`)],Q);function
|
|
4365
|
+
`}};W([x({attribute:!1})],Q.prototype,`machines`,void 0),W([x({attribute:!1})],Q.prototype,`selectedMachine`,void 0),W([x({type:Boolean})],Q.prototype,`locationIndicator`,void 0),W([x({attribute:!1})],Q.prototype,`machineStatuses`,void 0),W([x({attribute:!1})],Q.prototype,`machineActivities`,void 0),W([x({attribute:!1})],Q.prototype,`machineStatusSnapshots`,void 0),W([x({attribute:!1})],Q.prototype,`projects`,void 0),W([x({attribute:!1})],Q.prototype,`selectedProject`,void 0),W([x({attribute:!1})],Q.prototype,`workspaces`,void 0),W([x({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),W([x({attribute:!1})],Q.prototype,`sessions`,void 0),W([x({attribute:!1})],Q.prototype,`pinnedSessionIds`,void 0),W([x({attribute:!1})],Q.prototype,`selectedSession`,void 0),W([x({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),W([x({attribute:!1})],Q.prototype,`sessionActivities`,void 0),W([x({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),W([x({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),W([x({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),W([x({attribute:!1})],Q.prototype,`unreadPresence`,void 0),W([x({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),W([x({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),W([x({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),W([x({attribute:!1})],Q.prototype,`refreshControl`,void 0),W([x({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),W([x({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),W([x({type:Boolean})],Q.prototype,`showBrand`,void 0),W([x({type:Boolean})],Q.prototype,`managementMode`,void 0),W([x({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),W([x({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),W([x({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),W([x({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),W([x({type:Number})],Q.prototype,`startingSessionCount`,void 0),W([x({type:Boolean})],Q.prototype,`canStartSession`,void 0),W([x({type:Boolean})],Q.prototype,`canDeleteArchivedSessions`,void 0),W([x({type:Boolean})],Q.prototype,`canReloadSessions`,void 0),W([x({type:Boolean})],Q.prototype,`canCleanupSessions`,void 0),W([x({type:Boolean})],Q.prototype,`authoritativeSessionPersistence`,void 0),W([x({type:String})],Q.prototype,`archivedDeleteUnavailableMessage`,void 0),W([x({type:String})],Q.prototype,`cleanupUnavailableMessage`,void 0),W([x({attribute:!1})],Q.prototype,`onShowActions`,void 0),W([x({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),W([x({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),W([x({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),W([x({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),W([x({attribute:!1})],Q.prototype,`onSelectProject`,void 0),W([x({attribute:!1})],Q.prototype,`onCloseProject`,void 0),W([x({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),W([x({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),W([x({attribute:!1})],Q.prototype,`onStartSession`,void 0),W([x({attribute:!1})],Q.prototype,`onSelectSession`,void 0),W([x({attribute:!1})],Q.prototype,`onSearchSessions`,void 0),W([x({attribute:!1})],Q.prototype,`onToggleSessionPin`,void 0),W([x({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),W([x({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),W([x({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),W([x({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),W([x({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),W([x({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),W([x({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),W([x({attribute:!1})],Q.prototype,`onRenameSession`,void 0),W([x({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),W([x({attribute:!1})],Q.prototype,`onMarkSessionRead`,void 0),W([x({attribute:!1})],Q.prototype,`onMarkSessionsRead`,void 0),W([x({attribute:!1})],Q.prototype,`onReloadSession`,void 0),W([x({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),W([x({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),W([x({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),W([x({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),W([x({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),W([x({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),W([C(`machine-list`)],Q.prototype,`machineList`,void 0),W([C(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),W([C(`project-list`)],Q.prototype,`projectList`,void 0),W([C(`workspace-list`)],Q.prototype,`workspaceList`,void 0),W([C(`session-list`)],Q.prototype,`sessionList`,void 0),Q=W([b(`app-navigation-panel`)],Q);function Ck(e,t){return JSON.stringify([e??``,t??``])}function wk(e){return e.length>1}function Tk(e,t){let n=Dk(t);return n[n.indexOf(e)-1]}function Ek(e,t){let n=Dk(t);return n[n.indexOf(e)+1]??`chat`}function Dk(e){return zb.filter(t=>t!==`machines`||wk(e))}var Ok=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),kk=420,Ak=4,jk=class extends y{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`
|
|
4366
4366
|
${this.renderResizeHandle()}
|
|
4367
4367
|
<button
|
|
4368
4368
|
type="button"
|
|
@@ -4392,7 +4392,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4392
4392
|
@dblclick=${e=>{this.onResizeDoubleClick(e)}}
|
|
4393
4393
|
@keydown=${e=>{this.onResizeKeyDown(e)}}
|
|
4394
4394
|
></div>
|
|
4395
|
-
`}resizeAriaValueNow(){return this.panelWidth===void 0?v:String(Math.round(this.panelWidth))}renderIcon(){return g`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${this.iconDirection()===`left`?`M15 18l-6-6 6-6`:`M9 18l6-6-6-6`}/></svg>`}iconDirection(){return this.side===`navigation`?this.collapsed?`right`:`left`:this.collapsed?`left`:`right`}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;let t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=this.resizeStartWidth();n!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:n,handle:t,moved:!1},this.toggleAttribute(`resizing`,!0))}onResizePointerMove(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=
|
|
4395
|
+
`}resizeAriaValueNow(){return this.panelWidth===void 0?v:String(Math.round(this.panelWidth))}renderIcon(){return g`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${this.iconDirection()===`left`?`M15 18l-6-6 6-6`:`M9 18l6-6-6-6`}/></svg>`}iconDirection(){return this.side===`navigation`?this.collapsed?`right`:`left`:this.collapsed?`left`:`right`}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;let t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=this.resizeStartWidth();n!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:n,handle:t,moved:!1},this.toggleAttribute(`resizing`,!0))}onResizePointerMove(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=Ak)&&(t.moved=!0,this.commitPanelWidth(rx(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||!Ok.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=ix(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<=kk){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 ax(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(ax(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=tx(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=h`
|
|
4396
4396
|
: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; }
|
|
4397
4397
|
:host([side="navigation"]) { grid-column: 2; }
|
|
4398
4398
|
:host([side="workspace"]) { grid-column: 4; }
|
|
@@ -4411,7 +4411,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4411
4411
|
@media (max-width: 760px) {
|
|
4412
4412
|
:host([side="navigation"]) { display: none; }
|
|
4413
4413
|
}
|
|
4414
|
-
`}};W([x({reflect:!0})],
|
|
4414
|
+
`}};W([x({reflect:!0})],jk.prototype,`side`,void 0),W([x({type:Boolean,reflect:!0})],jk.prototype,`collapsed`,void 0),W([x({type:Boolean})],jk.prototype,`resizable`,void 0),W([x({type:Number})],jk.prototype,`panelWidth`,void 0),W([x({type:Number})],jk.prototype,`minWidth`,void 0),W([x({type:Number})],jk.prototype,`maxWidth`,void 0),W([x()],jk.prototype,`controls`,void 0),W([x()],jk.prototype,`resizeLabel`,void 0),W([x()],jk.prototype,`expandLabel`,void 0),W([x()],jk.prototype,`collapseLabel`,void 0),W([x({attribute:!1})],jk.prototype,`onToggle`,void 0),W([x({attribute:!1})],jk.prototype,`onResizeStart`,void 0),W([x({attribute:!1})],jk.prototype,`onResize`,void 0),W([x({attribute:!1})],jk.prototype,`onResizeEnd`,void 0),W([x({attribute:!1})],jk.prototype,`onReset`,void 0),jk=W([b(`app-panel-edge-control`)],jk);var Mk=class extends y{constructor(...e){super(...e),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){let e=`完整重载页面`;return g`
|
|
4415
4415
|
<button
|
|
4416
4416
|
class="app-refresh-button"
|
|
4417
4417
|
title=${e}
|
|
@@ -4430,10 +4430,10 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4430
4430
|
:host, :host * { -webkit-user-select: none; user-select: none; }
|
|
4431
4431
|
.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; }
|
|
4432
4432
|
.app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
4433
|
-
`}};W([x({attribute:!1})],
|
|
4433
|
+
`}};W([x({attribute:!1})],Mk.prototype,`onReload`,void 0),Mk=W([b(`app-refresh-control`)],Mk);function Nk(e,t,n=`error`){if(e===``)return null;let r=`关闭${Pk(n)}`;return g`<div class=${`error ${n}`} role="alert">
|
|
4434
4434
|
<span class="error-text">${e}</span>
|
|
4435
4435
|
<button type="button" class="error-dismiss" aria-label=${r} title=${r} @click=${()=>{t()}}>✕</button>
|
|
4436
|
-
</div>`}function
|
|
4436
|
+
</div>`}function Pk(e){return e===`error`?`错误`:e===`warning`?`警告`:`信息`}var Fk=h`
|
|
4437
4437
|
/* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
|
|
4438
4438
|
: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; }
|
|
4439
4439
|
:host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
|
|
@@ -4524,7 +4524,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4524
4524
|
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
4525
4525
|
.empty { margin: auto; color: var(--pi-muted); }
|
|
4526
4526
|
.error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
|
|
4527
|
-
`,Nk=900*1e3,Pk=5e3,Fk=750,Ik=[1e3,3e3,8e3,15e3,3e4],Lk={capture:!0},Rk=`auto:on`,zk=`auto:off`,Bk=`theme:`,Vk=Qs(`core:workspace.files`),Hk=Qs(`core:workspace.git`),Uk=Qs(`core:workspace.terminal`),Wk=320,Gk=2,Kk=`(min-width: 1181px)`,$=class extends y{constructor(...e){super(...e),this.state=gs(),this.browserErrors=new Es(()=>this.state,e=>{this.setState(e)}),this.apiScope=Yk(),this.sessionUnread=new hm({onChange:e=>{this.syncUnreadPresence(),z(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(z(this.state),this.state.sessions),this.unreadPresence=Cm,this.unreadConnected=!1,this.modelDialogInstanceId=0,this.modelDialogMutationInFlight=0,this.modelDialogRefreshPending=!1,this.modelDialogScopeInvalidation=0,this.notifications=new Zf(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new cf(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Xd,{socket:new Td(this.apiScope),notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},onModelScopeChanged:()=>{this.modelDialogScopeInvalidation+=1,this.refreshOpenModelDialog()},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(z(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)}}),this.projectActivityOwnership=new Lc(()=>this.state,e=>{this.setState(e)},{api:Ao,onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Ws(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.machineStatus=new Dc(()=>this.state,e=>{this.setState(e)}),this.auth=new qs(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)},{scope:this.apiScope}),this.workspaces=new ap(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new rp),this.projects=new kc(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new wc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebStatusController=new zc(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}),this.files=new dc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Cc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Dp,this.realtime=new Ed(this.apiScope),this.serverNotices=new Hm({onChange:e=>{z(this.state)===e&&this.requestUpdate()},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} server notices for ${t}`,n)}}),this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new lp,this.terminalSelection=new Sp,this.appShell=new Db(this),this.browserResume=new jb({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new qb(this),this.panelResize=new Zb(this),this.navigationSections=new Wb(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=Jk(),this.pluginLoads=new _b((e,t)=>this.registerExternalPlugins(e,t),(e,t)=>this.plugins.shouldLoadRemotePlugin(e,t)),this.themePreference=Qm()??Jm,this.activeThemeId=qm,this.isRefreshingApp=!1,this.sessionSearchDialogOpen=!1,this.settingsSection=vx(),this.normalAuthLoading=!0,this.normalAuthError=``,this.shortcutConfig={},this.workspaceUploadDefaultFolder=qo(void 0),this.workspaceAttachmentsDefaultFolder=ps(void 0),this.sessionWarningVisibility=Nm(),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.isRenderedModalOpen()||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleSendPrompt=(e,t,n,r,i)=>{this.sendPrompt(e,t,n,r,i)},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.handleAnswerDialog=(e,t)=>this.sessions.answerDialog(e,t),this.handleCancelDialog=e=>this.sessions.cancelDialog(e),this.handleDismissClosedDialog=e=>{this.sessions.dismissClosedDialog(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=Rm(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleToggleModelEnabled=async(e,t,n)=>{if(this.apiScope!==`normal`)return;let r=this.currentModelDialog();if(r!==void 0){this.modelDialogMutationInFlight+=1;try{this.applyModelDialogCatalog(r,await this.sessions.setModelEnabled(e,t,n))}finally{this.finishModelDialogMutation()}}},this.handleSetModelScope=async e=>{if(this.apiScope!==`normal`)return;let t=this.currentModelDialog();if(t!==void 0){this.modelDialogMutationInFlight+=1;try{this.applyModelDialogCatalog(t,await this.sessions.setModelScope(e))}finally{this.finishModelDialogMutation()}}},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=$k(this.state),this.syncSelectedSessionReadState()}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=Fm(this.sessionWarningVisibility,e===void 0?void 0:Hs(z(this.state),e.id),this.state.status?.warnings)}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=z(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}markSessionsRead(e){let t=z(this.state);for(let n of e)this.sessionUnread.acknowledge(t,n)}async commitReadyChatAfterRender(e,t){let n=Qk(e,t);await this.updateComplete,!(!this.unreadConnected||$k(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(z(this.state),this.state.sessions);aA(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncUnreadPresence(){let e=wm({machineIds:this.state.machines.map(e=>e.id),projectionFor:e=>this.sessionUnread.projection(e),selectedMachineId:z(this.state),projects:this.state.projects,workspaces:this.state.workspaces,workspacesByProjectId:this.state.workspacesByProjectId});Am(e,this.unreadPresence)||(this.unreadPresence=e)}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=Qk(e,t);return $k(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isRenderedModalOpen()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isRenderedModalOpen(){return Ih(this.ownerDocument)}connectedCallback(){super.connectedCallback(),this.normalAuthInitSeq+=1,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),this.browserResume.connect(),this.git.connect(),window.addEventListener(`keydown`,this.onKeyDown,Lk),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.apiScope===`normal`&&(this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},Nk)),this.scheduleSelectedSessionRefresh(),this.refreshWorkspaceActivity(),this.refreshMachineStatusSnapshots(),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 xo.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=`检查普通模式密码失败:${dA(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,Lk),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.notifications.dispose(),this.serverNotices.retainMachines(new Set),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.selectedSessionRefreshTimer!==void 0&&window.clearTimeout(this.selectedSessionRefreshTimer),this.selectedSessionRefreshTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!iA(this.state,e))return;let t=this.state;this.state={...this.state,...e},qk(t.status)!==qk(this.state.status)&&this.state.modelDialog!==void 0&&(this.state={...this.state,modelDialog:void 0}),$k(t)!==$k(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),eA(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.syncUnreadPresence(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),tA(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=px();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.refreshMachineStatusSnapshots(),this.refreshWorkspaceDeletionRuns(),this.workspaces.refreshSelectedProjectTopology()])}schedulePiWebStatusRefresh(e=Fk){this.apiScope!==`management`&&(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=z(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?[z(this.state)]:this.state.machines.filter(e=>rA(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}scheduleSelectedSessionRefresh(e=this.normalAuthInitSeq){!this.isConnected||!this.authenticatedAppRunning||e!==this.normalAuthInitSeq||(this.selectedSessionRefreshTimer!==void 0&&window.clearTimeout(this.selectedSessionRefreshTimer),this.selectedSessionRefreshTimer=window.setTimeout(()=>{this.selectedSessionRefreshTimer=void 0,this.refreshSelectedTranscript().finally(()=>{this.scheduleSelectedSessionRefresh(e)})},Pk))}async refreshSelectedTranscript(){let e=this.state.selectedSession,t=this.state.status;e===void 0||e.archived===!0||document.visibilityState!==`visible`||t?.isStreaming===!0||t?.isCompacting===!0||t?.isBashRunning===!0||(t?.pendingMessageCount??0)>0||await this.sessions.refreshSelectedSession(e.id,{silent:!0})}async refreshMachineStatusSnapshots(){let e=this.state.machines.length===0?[z(this.state)]:this.state.machines.filter(e=>rA(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(async e=>{try{await this.machineStatus.refresh(e)}catch(t){console.warn(`Failed to refresh machine status for ${e}`,t)}}))}async loadClientConfig(){if(this.apiScope!==`management`)try{this.applyClientConfig((await bo.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEB config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=qo(e),this.workspaceAttachmentsDefaultFolder=ps(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 xo.setup(e.password):t===`change`?await xo.changePassword(e.currentPassword??``,e.password):await xo.login(e.password);let n=await xo.status();this.normalAuthStatus=n,this.normalAuthDialogMode=void 0,n.authenticated&&this.startAuthenticatedApp()}catch(e){this.normalAuthError=dA(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):await this.invalidateWorkspacePanels(t)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(px(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=z(this.state),a=e.projectId===void 0||e.projectId===``?cA():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),z(this.state)!==i&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?cA():{selectedFilePath:ec(Vk,`file`),selectedDiffPath:ec(Hk,`diff`),selectedTerminalId:ec(Uk,`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){mx(e,{replace:!0}),tc(Vk,`file`,void 0,{replace:!0}),tc(Hk,`diff`,void 0,{replace:!0}),tc(Uk,`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=uA(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=R(t),r=this.state.browserErrors[bs(n)],i=()=>this.state.browserErrors[bs(n)]!==r,a=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(a?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i()){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i()){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>=Ik.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],a=R(n),o=this.state.browserErrors[bs(a)]?.message,s=i?.error??(o!==void 0&&!o.startsWith(`${r} 暂不可用`)&&!o.startsWith(`${r} 仍不可用`)?o:void 0),c=t.exhausted===!0?`${r} 仍不可用。`:`${r} 暂不可用,正在重新连接…`;this.browserErrors.report(a,`${c}${s===void 0?``:` ${s}`}`)}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){let n=e.machineId??`local`;if(this.state.selectedMachine?.id===n)return;let r=this.state.machines.find(e=>e.id===n);r!==void 0&&await this.machines.selectMachine(r,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??`local`)===(this.state.selectedMachine?.id??`local`)&&e.workspaceId!==void 0&&e.workspaceId!==``&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e===`core:workspace.files`?(await this.files.refreshFiles(),t!==void 0&&await this.files.restoreFile(t)):e===`core:workspace.git`?await this.git.refreshGit():e!==void 0&&e!==`core:workspace.terminal`&&await this.invalidateWorkspacePanels(e)}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await pA(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return!this.isRenderedModalOpen()&&this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){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(),mx({machineId:this.state.selectedMachine?.id,projectId:this.state.selectedProject?.id,workspaceId:this.state.selectedWorkspace?.id,sessionId:this.state.selectedSession?.id,tool:this.state.workspaceTool,view:this.state.mainView===`navigation`?void 0:this.state.mainView},e),this.syncWorkspaceRouteSurfaceToUrl()}rememberCurrentMachineNavigation(){this.machineNavigation.remember(dp(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(dp(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){mx(fp(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){tc(Vk,`file`,e.selectedFilePath,{replace:!0}),tc(Hk,`diff`,e.selectedDiffPath,{replace:!0}),tc(Uk,`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)??up(e.id);if(await this.restoreRouteFor(fp(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){let t=this.state.browserErrors[bs(R(z(this.state)))];return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&(this.state.error!==``||t!==void 0)}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=z(this.state)){let n=lA(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=Tx(e,{api:{runTerminalCommand:(e,n)=>Mo.runTerminalCommand(e,n,t),listCommandRuns:e=>Mo.listCommandRuns(e,t),getCommandRun:e=>Mo.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((z(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`),z(this.state)!==e)){this.browserErrors.report(R(e),`找不到用于运行终端命令的机器`);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){tc(Uk,`terminal`,e,t)}terminalWorkspaceKey(e){return`${z(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,yx(e)}closeSettings(){this.settingsSection=void 0,yx(void 0)}navigateSettings(e){this.settingsSection=e,yx(e)}restoreSettingsRoute(){this.settingsSection=vx()}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,z(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`:`supported`;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(z(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=z(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.renegotiateUnreadMachine(e),this.apiScope===`normal`&&this.serverNotices.refresh(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t),this.refreshWorkspaceActivity(e),this.machineStatus.refresh(e).catch(t=>{console.warn(`Failed to refresh machine status for ${e}`,t)})},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new Ed(this.apiScope);e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t),this.machineStatus.refresh(t).catch(e=>{console.warn(`Failed to refresh machine status for ${t}`,e)})},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=z(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>nA(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):t.type===`machine.status`&&this.machineStatus.apply(e,t.status)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`notices.updated`?this.serverNotices.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity):t.type===`machine.status`?this.machineStatus.apply(e,t.status):sA(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=z(this.state);try{let n=await Mo.terminals(e.projectId,e.id,t);if(z(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=oA(e),r=oA(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():e!==`core:workspace.terminal`&&this.invalidateWorkspacePanels(e)}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
|
|
4527
|
+
`,Ik=900*1e3,Lk=5e3,Rk=750,zk=[1e3,3e3,8e3,15e3,3e4],Bk={capture:!0},Vk=`auto:on`,Hk=`auto:off`,Uk=`theme:`,Wk=Qs(`core:workspace.files`),Gk=Qs(`core:workspace.git`),Kk=Qs(`core:workspace.terminal`),qk=320,Jk=2,Yk=`(min-width: 1181px)`,$=class extends y{constructor(...e){super(...e),this.state=gs(),this.browserErrors=new Es(()=>this.state,e=>{this.setState(e)}),this.apiScope=Qk(),this.sessionUnread=new vm({onChange:e=>{this.syncUnreadPresence(),z(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(z(this.state),this.state.sessions),this.unreadPresence=Em,this.unreadConnected=!1,this.modelDialogInstanceId=0,this.modelDialogMutationInFlight=0,this.modelDialogRefreshPending=!1,this.modelDialogScopeInvalidation=0,this.notifications=new ep(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessions=new df(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Xd,{socket:new Td(this.apiScope),notifications:this.notifications,onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},onModelScopeChanged:()=>{this.modelDialogScopeInvalidation+=1,this.refreshOpenModelDialog()},replacePromptEditorText:async({machineId:e,sessionId:t,text:n})=>{await this.updateComplete,!(z(this.state)!==e||this.state.selectedSession?.id!==t)&&this.promptEditor?.replaceText(n)}}),this.projectActivityOwnership=new Lc(()=>this.state,e=>{this.setState(e)},{api:Ao,onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Ws(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.machineStatus=new Dc(()=>this.state,e=>{this.setState(e)}),this.auth=new qs(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)},{scope:this.apiScope}),this.workspaces=new cp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new op),this.projects=new kc(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)}}),this.machines=new wc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.piWebStatusController=new zc(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}),this.files=new dc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Cc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Ap,this.realtime=new Ed(this.apiScope),this.serverNotices=new Gm({onChange:e=>{z(this.state)===e&&this.requestUpdate()},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} server notices for ${t}`,n)}}),this.machineRealtimeSockets=new Map,this.unreadRuntimeRefreshes=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new fp,this.terminalSelection=new Tp,this.appShell=new Ab(this),this.browserResume=new Pb({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new Xb(this),this.panelResize=new ex(this),this.navigationSections=new qb(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=Zk(),this.pluginLoads=new bb((e,t)=>this.registerExternalPlugins(e,t),(e,t)=>this.plugins.shouldLoadRemotePlugin(e,t)),this.themePreference=th()??Zm,this.activeThemeId=Xm,this.isRefreshingApp=!1,this.sessionSearchDialogOpen=!1,this.settingsSection=xx(),this.normalAuthLoading=!0,this.normalAuthError=``,this.shortcutConfig={},this.workspaceUploadDefaultFolder=qo(void 0),this.workspaceAttachmentsDefaultFolder=ps(void 0),this.sessionWarningVisibility=Im(),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.isRenderedModalOpen()||this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleSendPrompt=(e,t,n,r,i)=>{this.sendPrompt(e,t,n,r,i)},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.handleAnswerDialog=(e,t)=>this.sessions.answerDialog(e,t),this.handleCancelDialog=e=>this.sessions.cancelDialog(e),this.handleDismissClosedDialog=e=>{this.sessions.dismissClosedDialog(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=Vm(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleToggleModelEnabled=async(e,t,n)=>{if(this.apiScope!==`normal`)return;let r=this.currentModelDialog();if(r!==void 0){this.modelDialogMutationInFlight+=1;try{this.applyModelDialogCatalog(r,await this.sessions.setModelEnabled(e,t,n))}finally{this.finishModelDialogMutation()}}},this.handleSetModelScope=async e=>{if(this.apiScope!==`normal`)return;let t=this.currentModelDialog();if(t!==void 0){this.modelDialogMutationInFlight+=1;try{this.applyModelDialogCatalog(t,await this.sessions.setModelScope(e))}finally{this.finishModelDialogMutation()}}},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=nA(this.state),this.syncSelectedSessionReadState()}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=Rm(this.sessionWarningVisibility,e===void 0?void 0:Hs(z(this.state),e.id),this.state.status?.warnings)}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=z(this.state);this.isSessionSeen(t,e)&&this.sessionUnread.acknowledge(t,e)}markSessionsRead(e){let t=z(this.state);for(let n of e)this.sessionUnread.acknowledge(t,n)}async commitReadyChatAfterRender(e,t){let n=tA(e,t);await this.updateComplete,!(!this.unreadConnected||nA(this.state)!==n)&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(z(this.state),this.state.sessions);cA(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncUnreadPresence(){let e=Dm({machineIds:this.state.machines.map(e=>e.id),projectionFor:e=>this.sessionUnread.projection(e),selectedMachineId:z(this.state),projects:this.state.projects,workspaces:this.state.workspaces,workspacesByProjectId:this.state.workspacesByProjectId});Nm(e,this.unreadPresence)||(this.unreadPresence=e)}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=tA(e,t);return nA(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isRenderedModalOpen()?!1:this.state.mainView===`chat`?!0:this.state.mainView===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isRenderedModalOpen(){return zh(this.ownerDocument)}connectedCallback(){super.connectedCallback(),this.normalAuthInitSeq+=1,window.addEventListener(`popstate`,this.onPopState),window.addEventListener(`pageshow`,this.onPageShow),this.browserResume.connect(),this.git.connect(),window.addEventListener(`keydown`,this.onKeyDown,Bk),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.apiScope===`normal`&&(this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},Ik)),this.scheduleSelectedSessionRefresh(),this.refreshWorkspaceActivity(),this.refreshMachineStatusSnapshots(),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 xo.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=`检查普通模式密码失败:${mA(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,Bk),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.notifications.dispose(),this.serverNotices.retainMachines(new Set),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.selectedSessionRefreshTimer!==void 0&&window.clearTimeout(this.selectedSessionRefreshTimer),this.selectedSessionRefreshTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!sA(this.state,e))return;let t=this.state;this.state={...this.state,...e},Xk(t.status)!==Xk(this.state.status)&&this.state.modelDialog!==void 0&&(this.state={...this.state,modelDialog:void 0}),nA(t)!==nA(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0),rA(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.syncUnreadPresence(),this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),iA(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state)}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=gx();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.refreshMachineStatusSnapshots(),this.refreshWorkspaceDeletionRuns(),this.workspaces.refreshSelectedProjectTopology()])}schedulePiWebStatusRefresh(e=Rk){this.apiScope!==`management`&&(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=z(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?[z(this.state)]:this.state.machines.filter(e=>oA(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}scheduleSelectedSessionRefresh(e=this.normalAuthInitSeq){!this.isConnected||!this.authenticatedAppRunning||e!==this.normalAuthInitSeq||(this.selectedSessionRefreshTimer!==void 0&&window.clearTimeout(this.selectedSessionRefreshTimer),this.selectedSessionRefreshTimer=window.setTimeout(()=>{this.selectedSessionRefreshTimer=void 0,this.refreshSelectedTranscript().finally(()=>{this.scheduleSelectedSessionRefresh(e)})},Lk))}async refreshSelectedTranscript(){let e=this.state.selectedSession,t=this.state.status;e===void 0||e.archived===!0||document.visibilityState!==`visible`||t?.isStreaming===!0||t?.isCompacting===!0||t?.isBashRunning===!0||(t?.pendingMessageCount??0)>0||await this.sessions.refreshSelectedSession(e.id,{silent:!0})}async refreshMachineStatusSnapshots(){let e=this.state.machines.length===0?[z(this.state)]:this.state.machines.filter(e=>oA(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(async e=>{try{await this.machineStatus.refresh(e)}catch(t){console.warn(`Failed to refresh machine status for ${e}`,t)}}))}async loadClientConfig(){if(this.apiScope!==`management`)try{this.applyClientConfig((await bo.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEB config`,e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{},this.workspaceUploadDefaultFolder=qo(e),this.workspaceAttachmentsDefaultFolder=ps(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 xo.setup(e.password):t===`change`?await xo.changePassword(e.currentPassword??``,e.password):await xo.login(e.password);let n=await xo.status();this.normalAuthStatus=n,this.normalAuthDialogMode=void 0,n.authenticated&&this.startAuthenticatedApp()}catch(e){this.normalAuthError=mA(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):await this.invalidateWorkspacePanels(t)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(gx(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r){let i=z(this.state),a=e.projectId===void 0||e.projectId===``?dA():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),z(this.state)!==i&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?dA():{selectedFilePath:ec(Wk,`file`),selectedDiffPath:ec(Gk,`diff`),selectedTerminalId:ec(Kk,`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){_x(e,{replace:!0}),tc(Wk,`file`,void 0,{replace:!0}),tc(Gk,`diff`,void 0,{replace:!0}),tc(Kk,`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=pA(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=R(t),r=this.state.browserErrors[bs(n)],i=()=>this.state.browserErrors[bs(n)]!==r,a=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(a?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i()){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i()){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>=zk.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],a=R(n),o=this.state.browserErrors[bs(a)]?.message,s=i?.error??(o!==void 0&&!o.startsWith(`${r} 暂不可用`)&&!o.startsWith(`${r} 仍不可用`)?o:void 0),c=t.exhausted===!0?`${r} 仍不可用。`:`${r} 暂不可用,正在重新连接…`;this.browserErrors.report(a,`${c}${s===void 0?``:` ${s}`}`)}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){let n=e.machineId??`local`;if(this.state.selectedMachine?.id===n)return;let r=this.state.machines.find(e=>e.id===n);r!==void 0&&await this.machines.selectMachine(r,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??`local`)===(this.state.selectedMachine?.id??`local`)&&e.workspaceId!==void 0&&e.workspaceId!==``&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e===`core:workspace.files`?(await this.files.refreshFiles(),t!==void 0&&await this.files.restoreFile(t)):e===`core:workspace.git`?await this.git.refreshGit():e!==void 0&&e!==`core:workspace.terminal`&&await this.invalidateWorkspacePanels(e)}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await gA(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return!this.isRenderedModalOpen()&&this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){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(),_x({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(mp(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(mp(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){_x(hp(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){tc(Wk,`file`,e.selectedFilePath,{replace:!0}),tc(Gk,`diff`,e.selectedDiffPath,{replace:!0}),tc(Kk,`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)??pp(e.id);if(await this.restoreRouteFor(hp(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){let t=this.state.browserErrors[bs(R(z(this.state)))];return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&(this.state.error!==``||t!==void 0)}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=z(this.state)){let n=fA(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;let i=Ox(e,{api:{runTerminalCommand:(e,n)=>Mo.runTerminalCommand(e,n,t),listCommandRuns:e=>Mo.listCommandRuns(e,t),getCommandRun:e=>Mo.getCommandRun(e,t)},openTerminal:(e,n)=>{this.openRuntimeTerminal(t,e,n)}});return this.terminalCommandRunRuntimes.set(n,i),i}async openRuntimeTerminal(e,t,n){if((z(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`),z(this.state)!==e)){this.browserErrors.report(R(e),`找不到用于运行终端命令的机器`);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){tc(Kk,`terminal`,e,t)}terminalWorkspaceKey(e){return`${z(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,Sx(e)}closeSettings(){this.settingsSection=void 0,Sx(void 0)}navigateSettings(e){this.settingsSection=e,Sx(e)}restoreSettingsRoute(){this.settingsSection=xx()}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,z(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`:`supported`;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(z(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=z(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.renegotiateUnreadMachine(e),this.apiScope===`normal`&&this.serverNotices.refresh(e);let t=this.state.selectedWorkspace;t!==void 0&&this.refreshActiveTerminals(t),this.refreshWorkspaceActivity(e),this.machineStatus.refresh(e).catch(t=>{console.warn(`Failed to refresh machine status for ${e}`,t)})},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new Ed(this.apiScope);e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t),this.machineStatus.refresh(t).catch(e=>{console.warn(`Failed to refresh machine status for ${t}`,e)})},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=z(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>aA(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):t.type===`machine.status`&&this.machineStatus.apply(e,t.status)}handleRealtimeEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`notices.updated`?this.serverNotices.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity):t.type===`machine.status`?this.machineStatus.apply(e,t.status):uA(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=z(this.state);try{let n=await Mo.terminals(e.projectId,e.id,t);if(z(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=lA(e),r=lA(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():e!==`core:workspace.terminal`&&this.invalidateWorkspacePanels(e)}renderWorkspacePanel(){let e=this.state.selectedWorkspace;return g`
|
|
4528
4528
|
<workspace-panel
|
|
4529
4529
|
id="workspace-panel"
|
|
4530
4530
|
.workspace=${e}
|
|
@@ -4570,7 +4570,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4570
4570
|
.onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
|
|
4571
4571
|
.onReset=${()=>{this.resetResizablePanel(`workspace`)}}
|
|
4572
4572
|
></app-panel-edge-control>
|
|
4573
|
-
`}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-
|
|
4573
|
+
`}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-Jk-qk);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(Yk).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(){return!0}canReloadSessions(){return this.selectedMachineRuntime()?.ok===!0}canClearServerQueue(){return this.selectedMachineRuntime()?.ok===!0}canCleanupSessions(){let e=this.selectedMachineRuntime();return this.apiScope===`management`&&this.state.selectedProject===void 0?!1:e?.ok===!0}hasAuthoritativeSessionPersistence(){return Ld(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=z(this.state)){return e===`local`||this.state.machineRuntimes[e]?.ok===!0}archivedDeleteUnavailableMessage(){return`请更新并重启 ${this.state.selectedMachine?.name??`此机器`} 上的 Pi-Web 后再删除已归档会话。`}sessionCleanupUnavailableMessage(){return fm(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[z(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=z(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let e=await jo.cleanupPreview(t,n);if(z(this.state)!==n)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:e,previewRequest:t,result:void 0,loading:!1,error:``}}catch(e){z(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:`预览清理失败:${mA(e)}`})}}async runSessionCleanup(e){let t=this.sessionCleanupRequestForCurrentProject(e),n=this.sessionCleanupDialog;if(n?.preview===void 0||im(n.previewRequest)!==im(t)){this.sessionCleanupDialog={...n??{},error:`运行清理前请先预览。`};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...n,error:this.sessionCleanupUnavailableMessage(),running:!1};return}let r=z(this.state);this.sessionCleanupDialog={...n,running:!0,error:``};try{let e=await jo.cleanup(t,r);if(z(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){z(this.state)===r&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:`运行清理失败:${mA(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`
|
|
4574
4574
|
<app-navigation-panel
|
|
4575
4575
|
.machines=${this.state.machines}
|
|
4576
4576
|
.selectedMachine=${this.state.selectedMachine}
|
|
@@ -4588,7 +4588,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4588
4588
|
.workspacesByProjectId=${this.state.workspacesByProjectId}
|
|
4589
4589
|
.workspaces=${this.state.workspaces}
|
|
4590
4590
|
.selectedWorkspace=${this.state.selectedWorkspace}
|
|
4591
|
-
.deletingWorkspaceIds=${
|
|
4591
|
+
.deletingWorkspaceIds=${hh(this.state.workspaceDeletionRuns)}
|
|
4592
4592
|
.sessions=${this.state.sessions}
|
|
4593
4593
|
.pinnedSessionIds=${this.state.pinnedSessionIds}
|
|
4594
4594
|
.sessionStatuses=${this.state.sessionStatuses}
|
|
@@ -4643,7 +4643,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4643
4643
|
.onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
|
|
4644
4644
|
.onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
|
|
4645
4645
|
></app-navigation-panel>
|
|
4646
|
-
`}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 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`&&!
|
|
4646
|
+
`}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 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`&&!wk(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 gA(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!==`chat`&&this.selectMainView(`chat`),await this.updateComplete,await gA(),!this.isRenderedModalOpen()&&this.promptEditor?.focusInput()}async navigateSessionTree(e,t){let n=z(this.state),r=this.state.selectedSession?.id,i=await this.sessions.navigateTree(e,t);return!i.cancelled&&r!==void 0&&z(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer(),i}forkSessionTree(e){return this.sessions.forkFromTree(e)}closeSessionTreeNavigator(){this.sessions.closeTreeDialog(),this.focusChatComposer()}renderSessionTreeNavigator(e){return e.treeDialog===void 0?null:g`
|
|
4647
4647
|
<session-tree-navigator
|
|
4648
4648
|
.tree=${e.treeDialog}
|
|
4649
4649
|
.onNavigate=${(e,t)=>this.navigateSessionTree(e,t)}
|
|
@@ -4651,8 +4651,8 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4651
4651
|
.onAbort=${()=>this.sessions.abortTreeNavigation()}
|
|
4652
4652
|
.onCancel=${()=>{this.closeSessionTreeNavigator()}}
|
|
4653
4653
|
></session-tree-navigator>
|
|
4654
|
-
`}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=Xk(this.state),n=r=>{let i=nb(r,e,t.id);return By({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),...i===void 0?{}:{backend:i},host:this.createWorkspaceHost()},n)};return n(Zk())}createWorkspaceFiles(e,t){return{readFile:n=>Ao.workspaceFile(e.projectId,e.id,n,t),readOptionalFile:n=>Ao.optionalWorkspaceFile(e.projectId,e.id,n,t),listFiles:n=>Ao.workspaceTree(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await Ao.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await Ao.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await Ao.moveWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){let t=Xk(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i.registrationPluginId,n),o=nb(i,e,n);return zy({machine:t,workspace:e,...o===void 0?{}:{backend:o},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,selectedFileLoadError:this.state.selectedFileLoadError,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:Jo(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({registrationPluginId:`core`,sourcePluginId:`core`})}invalidateWorkspacePanels(e){let t=this.state.selectedWorkspace;return t===void 0?Promise.resolve():this.plugins.invalidateWorkspacePanels(this.createWorkspacePanelContext(t),e)}getActions(){return Sx(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.apiScope===`management`?Promise.resolve():this.pluginLoads.ensureGatewayLoaded().then(()=>void 0)}async loadPluginsForSelectedMachine(){let e=this.state.selectedMachine;e?.kind===`remote`&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){this.apiScope!==`management`&&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=>Ry({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(),refreshWorkspacePanels:e=>this.invalidateWorkspacePanels(e),refreshAppData:()=>this.refreshAppData(),checkForPiWebUpdates:()=>this.piWebStatusController.checkForUpdates(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:e=>this.deleteWorkspace(e),startSession:()=>this.withChatScrollTransition(()=>this.startSessionAndOpenChat()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;let t=z(this.state),n=vs(t,e.projectId,e.id);if(!ch(e)){this.browserErrors.report(n,`当前工作区不支持移除`);return}if(ph(this.state,e))return;let r=e.removal,i=lh(e);if(!(r===void 0||i===void 0||!confirm(i)))try{let n=await Ao.deleteWorkspace(e.projectId,e.id,r.precondition,t);if(z(this.state)!==t)return;this.recordWorkspaceDeletionRun(n,t);let i=await this.workspaceForCommandRun(n);if(z(this.state)!==t)return;i!==void 0&&this.openRuntimeTerminal(t,i,{terminalId:n.terminalId})}catch(r){await this.reportWorkspaceRemovalFailure(e,t,n,r)}}async reportWorkspaceRemovalFailure(e,t,n,r){let i=dA(r);if(this.apiScope===`management`||!(r instanceof jt)||i.startsWith(`Session daemon unavailable:`)){this.browserErrors.report(n,`启动工作区删除失败:${i}`);return}let a=`工作区移除失败:${i}`,o=()=>this.serverNotices.hasNotice(t,t=>{let n=t.context??{};return t.source===`workspace.delete`&&t.message===a&&n.projectId===e.projectId&&n.workspaceId===e.id});o()||await this.serverNotices.refresh(t),o()||this.browserErrors.report(n,`启动工作区删除失败:${i}`)}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(z(this.state)!==t)return;let n=mh(e);n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;let e=z(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(uh(t.id));if(z(this.state)!==e)return;let r=dh(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))hh(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(hh);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=z(this.state)){if(z(this.state)!==t)return;let n=lA(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=mh(e);if(r!==void 0){if(this.handledWorkspaceDeletionRunIds.add(n),e.status===`succeeded`){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,r),z(this.state)!==t)return;this.browserErrors.discard(vs(t,e.projectId,r)),this.setState({workspaceDeletionRuns:fA(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&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.browserErrors.report({kind:`global`},`操作失败:${n}`)})}async openModelDialog(){let e=this.state.selectedSession;if(e===void 0)return;let t={machineId:z(this.state),sessionId:e.id,cwd:e.cwd},{models:n,catalog:r}=await this.loadModelDialogData();if(!this.modelDialogOriginIsCurrent(t))return;let i=this.currentModelValue();this.setState({modelDialog:{instanceId:++this.modelDialogInstanceId,origin:t,title:`选择模型`,...i===void 0?{}:{selectedValue:i},options:this.modelDialogOptions(n),...r===void 0?{}:{catalog:r}}})}async loadModelDialogData(){for(;;){let e=this.modelDialogScopeInvalidation,[t,n]=await Promise.all([this.sessions.listModels(),this.apiScope===`normal`?this.sessions.listModelCatalog():Promise.resolve(void 0)]);if(e===this.modelDialogScopeInvalidation)return{models:t,...n===void 0?{}:{catalog:n}}}}async refreshOpenModelDialog(){if(this.modelDialogMutationInFlight>0){this.modelDialogRefreshPending=!0;return}let e=this.currentModelDialog();if(e===void 0)return;let{origin:t,instanceId:n}=e,{models:r,catalog:i}=await this.loadModelDialogData();if(this.modelDialogMutationInFlight>0||this.state.modelDialog?.instanceId!==n||!this.modelDialogOriginIsCurrent(t))return;let a={...e,options:this.modelDialogOptions(r),...i===void 0?{}:{catalog:i}},o=this.currentModelValue();o===void 0?delete a.selectedValue:a.selectedValue=o,this.setState({modelDialog:a})}currentModelValue(){return qk(this.state.status)}modelDialogOptions(e){let t=this.currentModelValue();return e.map(e=>{let n=e.provider??``,r=e.id??``,i=`${n}/${r}`;return{value:i,label:`${r}${i===t?` ✓ 当前`:``}`,description:n}})}async pickModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?zk:Rk;this.setState({themeDialog:{title:`选择主题`,selectedValue:n===void 0?r:`${Bk}${n}`,options:[{value:r,label:`自动 ${this.themePreference.auto?`✓ 开启`:`关闭`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${Bk}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===Rk||e===zk){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===Rk},this.applyPreferredTheme(!0);return}if(!e.startsWith(Bk))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,eh(t),e&&$m(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return th({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return rh(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=zs(e);return{value:e,label:`${Rs(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,i){let a=n!==void 0&&n.length>0;if(!(!a&&t===void 0&&this.auth.handleSlashCommand(e))){if(!a&&t===void 0&&(e.trim()===`/model`||e.trim()===`/scoped-models`)){this.openModelDialog();return}this.sessions.send(e,t,n,r,i)}}finishModelDialogMutation(){--this.modelDialogMutationInFlight,!(this.modelDialogMutationInFlight!==0||!this.modelDialogRefreshPending)&&(this.modelDialogRefreshPending=!1,this.refreshOpenModelDialog())}currentModelDialog(){let e=this.state.modelDialog;if(e!==void 0&&this.modelDialogOriginIsCurrent(e.origin))return e;e!==void 0&&this.setState({modelDialog:void 0})}modelDialogOriginIsCurrent(e){let t=this.state.selectedSession;return t!==void 0&&e.machineId===z(this.state)&&e.sessionId===t.id&&e.cwd===t.cwd}applyModelDialogCatalog(e,t){t===void 0||this.state.modelDialog?.instanceId!==e.instanceId||!this.modelDialogOriginIsCurrent(e.origin)||this.setState({modelDialog:{...e,catalog:t,options:this.modelDialogOptions(t.filter(e=>e.enabled))}})}renderChatView(e,t){return g`
|
|
4655
|
-
<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} .pendingDialogs=${e.pendingDialogs} .closedDialogs=${e.closedDialogs} .onAnswerDialog=${this.handleAnswerDialog} .onCancelDialog=${this.handleCancelDialog} .onDismissClosedDialog=${this.handleDismissClosedDialog} .askDraftSessionId=${Hs(z(e),t.id)} .onSubmitAsk=${this.handleSubmitAsk} .notificationInbox=${
|
|
4654
|
+
`}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=$k(this.state),n=r=>{let i=ab(r,e,t.id);return Uy({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),...i===void 0?{}:{backend:i},host:this.createWorkspaceHost()},n)};return n(eA())}createWorkspaceFiles(e,t){return{readFile:n=>Ao.workspaceFile(e.projectId,e.id,n,t),readOptionalFile:n=>Ao.optionalWorkspaceFile(e.projectId,e.id,n,t),listFiles:n=>Ao.workspaceTree(e.projectId,e.id,n,t),writeFile:async(n,r,i)=>{let a=await Ao.writeWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a},deleteFile:async n=>{let r=await Ao.deleteWorkspaceFile(e.projectId,e.id,n,t);return this.files.refreshFiles(),r},moveFile:async(n,r,i)=>{let a=await Ao.moveWorkspaceFile(e.projectId,e.id,n,r,i,t);return this.files.refreshFiles(),a}}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){let t=$k(this.state),n=t.id,r=i=>{let a=this.terminalCommandRunsForOrigin(i.registrationPluginId,n),o=ab(i,e,n);return Hy({machine:t,workspace:e,...o===void 0?{}:{backend:o},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,selectedFileLoadError:this.state.selectedFileLoadError,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:Jo(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({registrationPluginId:`core`,sourcePluginId:`core`})}invalidateWorkspacePanels(e){let t=this.state.selectedWorkspace;return t===void 0?Promise.resolve():this.plugins.invalidateWorkspacePanels(this.createWorkspacePanelContext(t),e)}getActions(){return Tx(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.apiScope===`management`?Promise.resolve():this.pluginLoads.ensureGatewayLoaded().then(()=>void 0)}async loadPluginsForSelectedMachine(){let e=this.state.selectedMachine;e?.kind===`remote`&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){this.apiScope!==`management`&&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=>Vy({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(),refreshWorkspacePanels:e=>this.invalidateWorkspacePanels(e),refreshAppData:()=>this.refreshAppData(),checkForPiWebUpdates:()=>this.piWebStatusController.checkForUpdates(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:e=>this.deleteWorkspace(e),startSession:()=>this.withChatScrollTransition(()=>this.startSessionAndOpenChat()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;let t=z(this.state),n=vs(t,e.projectId,e.id);if(!dh(e)){this.browserErrors.report(n,`当前工作区不支持移除`);return}if(gh(this.state,e))return;let r=e.removal,i=fh(e);if(!(r===void 0||i===void 0||!confirm(i)))try{let n=await Ao.deleteWorkspace(e.projectId,e.id,r.precondition,t);if(z(this.state)!==t)return;this.recordWorkspaceDeletionRun(n,t);let i=await this.workspaceForCommandRun(n);if(z(this.state)!==t)return;i!==void 0&&this.openRuntimeTerminal(t,i,{terminalId:n.terminalId})}catch(r){await this.reportWorkspaceRemovalFailure(e,t,n,r)}}async reportWorkspaceRemovalFailure(e,t,n,r){let i=mA(r);if(this.apiScope===`management`||!(r instanceof jt)||i.startsWith(`Session daemon unavailable:`)){this.browserErrors.report(n,`启动工作区删除失败:${i}`);return}let a=`工作区移除失败:${i}`,o=()=>this.serverNotices.hasNotice(t,t=>{let n=t.context??{};return t.source===`workspace.delete`&&t.message===a&&n.projectId===e.projectId&&n.workspaceId===e.id});o()||await this.serverNotices.refresh(t),o()||this.browserErrors.report(n,`启动工作区删除失败:${i}`)}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(z(this.state)!==t)return;let n=_h(e);n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;let e=z(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(ph(t.id));if(z(this.state)!==e)return;let r=mh(n);this.setState({workspaceDeletionRuns:r});for(let t of Object.values(r))vh(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(vh);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=z(this.state)){if(z(this.state)!==t)return;let n=fA(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(n))return;let r=_h(e);if(r!==void 0){if(this.handledWorkspaceDeletionRunIds.add(n),e.status===`succeeded`){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,r),z(this.state)!==t)return;this.browserErrors.discard(vs(t,e.projectId,r)),this.setState({workspaceDeletionRuns:hA(this.state.workspaceDeletionRuns,r)}),this.updateWorkspaceDeletionPolling();return}e.status===`failed`&&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.browserErrors.report({kind:`global`},`操作失败:${n}`)})}async openModelDialog(){let e=this.state.selectedSession;if(e===void 0)return;let t={machineId:z(this.state),sessionId:e.id,cwd:e.cwd},{models:n,catalog:r}=await this.loadModelDialogData();if(!this.modelDialogOriginIsCurrent(t))return;let i=this.currentModelValue();this.setState({modelDialog:{instanceId:++this.modelDialogInstanceId,origin:t,title:`选择模型`,...i===void 0?{}:{selectedValue:i},options:this.modelDialogOptions(n),...r===void 0?{}:{catalog:r}}})}async loadModelDialogData(){for(;;){let e=this.modelDialogScopeInvalidation,[t,n]=await Promise.all([this.sessions.listModels(),this.apiScope===`normal`?this.sessions.listModelCatalog():Promise.resolve(void 0)]);if(e===this.modelDialogScopeInvalidation)return{models:t,...n===void 0?{}:{catalog:n}}}}async refreshOpenModelDialog(){if(this.modelDialogMutationInFlight>0){this.modelDialogRefreshPending=!0;return}let e=this.currentModelDialog();if(e===void 0)return;let{origin:t,instanceId:n}=e,{models:r,catalog:i}=await this.loadModelDialogData();if(this.modelDialogMutationInFlight>0||this.state.modelDialog?.instanceId!==n||!this.modelDialogOriginIsCurrent(t))return;let a={...e,options:this.modelDialogOptions(r),...i===void 0?{}:{catalog:i}},o=this.currentModelValue();o===void 0?delete a.selectedValue:a.selectedValue=o,this.setState({modelDialog:a})}currentModelValue(){return Xk(this.state.status)}modelDialogOptions(e){let t=this.currentModelValue();return e.map(e=>{let n=e.provider??``,r=e.id??``,i=`${n}/${r}`;return{value:i,label:`${r}${i===t?` ✓ 当前`:``}`,description:n}})}async pickModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){let e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),n=t.selectedTheme?.id,r=this.themePreference.auto?Hk:Vk;this.setState({themeDialog:{title:`选择主题`,selectedValue:n===void 0?r:`${Uk}${n}`,options:[{value:r,label:`自动 ${this.themePreference.auto?`✓ 开启`:`关闭`}`,description:this.autoThemeDescription(t)},...e.map(e=>({value:`${Uk}${e.id}`,label:this.themeOptionLabel(e,n),description:this.themeOptionDescription(e)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===Vk||e===Hk){let t=this.resolveCurrentThemePreference().selectedTheme?.id;if(t===void 0)return;this.themePreference={themeId:t,auto:e===Vk},this.applyPreferredTheme(!0);return}if(!e.startsWith(Uk))return;let t=e.slice(6),n=this.plugins.getThemes().find(e=>e.id===t);n!==void 0&&(this.themePreference={themeId:n.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){let t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,rh(t),e&&nh(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return ih({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return oh(this.plugins.getThemePairs(),e)}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}autoThemeDescription(e){return!this.themePreference.auto||e.selectedTheme===void 0?`当所选主题有配对主题时,跟随系统明暗偏好。`: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=zs(e);return{value:e,label:`${Rs(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,i){let a=n!==void 0&&n.length>0;if(!(!a&&t===void 0&&this.auth.handleSlashCommand(e))){if(!a&&t===void 0&&(e.trim()===`/model`||e.trim()===`/scoped-models`)){this.openModelDialog();return}this.sessions.send(e,t,n,r,i)}}finishModelDialogMutation(){--this.modelDialogMutationInFlight,!(this.modelDialogMutationInFlight!==0||!this.modelDialogRefreshPending)&&(this.modelDialogRefreshPending=!1,this.refreshOpenModelDialog())}currentModelDialog(){let e=this.state.modelDialog;if(e!==void 0&&this.modelDialogOriginIsCurrent(e.origin))return e;e!==void 0&&this.setState({modelDialog:void 0})}modelDialogOriginIsCurrent(e){let t=this.state.selectedSession;return t!==void 0&&e.machineId===z(this.state)&&e.sessionId===t.id&&e.cwd===t.cwd}applyModelDialogCatalog(e,t){t===void 0||this.state.modelDialog?.instanceId!==e.instanceId||!this.modelDialogOriginIsCurrent(e.origin)||this.setState({modelDialog:{...e,catalog:t,options:this.modelDialogOptions(t.filter(e=>e.enabled))}})}renderChatView(e,t){return g`
|
|
4655
|
+
<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} .pendingDialogs=${e.pendingDialogs} .closedDialogs=${e.closedDialogs} .onAnswerDialog=${this.handleAnswerDialog} .onCancelDialog=${this.handleCancelDialog} .onDismissClosedDialog=${this.handleDismissClosedDialog} .askDraftSessionId=${Hs(z(e),t.id)} .onSubmitAsk=${this.handleSubmitAsk} .notificationInbox=${Ff(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>
|
|
4656
4656
|
`}renderStatusBar(e){let t=this.sessionWarningVisibility.warningCount;return g`
|
|
4657
4657
|
<status-bar .status=${e.status} .warningCount=${t} .warningsExpanded=${t>0&&!this.sessionWarningVisibility.collapsed} .onToggleWarnings=${this.handleToggleWarnings}></status-bar>
|
|
4658
4658
|
`}renderContextBar(){return this.appShell.isMobileNavigationLayout?g`
|
|
@@ -4673,15 +4673,15 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4673
4673
|
.selectedView=${this.state.mainView}
|
|
4674
4674
|
.onSelect=${e=>{this.selectMainView(e)}}
|
|
4675
4675
|
></app-mobile-main-tabs>
|
|
4676
|
-
`}mobileMainTabs(){let e=
|
|
4676
|
+
`}mobileMainTabs(){let e=ES(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>`}renderServerNoticeBanners(){let e=z(this.state),t=this.serverNotices.projection(e),n=t?.status===`fresh`?Um(t.notices,ws(this.state)):[];return n.length===0?null:g`${n.map(t=>Nk(t.message,()=>{this.serverNotices.dismiss(e,t.id)},t.severity))}`}renderBrowserErrorBanners(e){let t=Ts(e.browserErrors,ws(e));return t.length===0?null:g`${t.map(e=>Nk(e.message,()=>{this.dismissBrowserError(e)}))}`}dismissBrowserError(e){let t=Ss(this.state.browserErrors,e.scope,e.message);t!==this.state.browserErrors&&this.setState({browserErrors:t})}render(){let e=this.state,t=this.normalAuthGateMode();return this.apiScope===`normal`&&(t!==void 0||this.normalAuthStatus===void 0)?this.renderNormalAuthDialog(t??`login`):g`
|
|
4677
4677
|
<div class=${this.panelCollapse.shellClass(e.mainView)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints(`navigation`),workspace:this.resizablePanelConstraints(`workspace`)})}>
|
|
4678
4678
|
<aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
|
|
4679
4679
|
${this.renderNavigationPanelEdgeControl()}
|
|
4680
|
-
<main class=${
|
|
4680
|
+
<main class=${Zb(e.mainView)}>
|
|
4681
4681
|
${this.renderContextBar()}
|
|
4682
4682
|
${this.renderMobileMainTabs()}
|
|
4683
4683
|
${this.renderServerNoticeBanners()}
|
|
4684
|
-
${
|
|
4684
|
+
${Nk(e.error,()=>{this.setState({error:``})})}
|
|
4685
4685
|
${this.renderBrowserErrorBanners(e)}
|
|
4686
4686
|
<div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
|
|
4687
4687
|
${e.selectedSession?g`
|
|
@@ -4714,4 +4714,4 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
4714
4714
|
.onSubmit=${e=>{this.submitNormalAuth(e)}}
|
|
4715
4715
|
.onCancel=${()=>{this.normalAuthDialogMode=void 0,this.normalAuthError=``}}
|
|
4716
4716
|
></normal-auth-dialog>
|
|
4717
|
-
`}static{this.styles=
|
|
4717
|
+
`}static{this.styles=Fk}};W([S()],$.prototype,`state`,void 0),W([C(`chat-view`)],$.prototype,`chatView`,void 0),W([C(`prompt-editor`)],$.prototype,`promptEditor`,void 0),W([C(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),W([C(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),W([C(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),W([S()],$.prototype,`unreadSessionIds`,void 0),W([S()],$.prototype,`unreadPresence`,void 0),W([S()],$.prototype,`activeThemeId`,void 0),W([S()],$.prototype,`isRefreshingApp`,void 0),W([S()],$.prototype,`sessionCleanupDialog`,void 0),W([S()],$.prototype,`sessionSearchDialogOpen`,void 0),W([S()],$.prototype,`settingsSection`,void 0),W([S()],$.prototype,`normalAuthStatus`,void 0),W([S()],$.prototype,`normalAuthLoading`,void 0),W([S()],$.prototype,`normalAuthError`,void 0),W([S()],$.prototype,`normalAuthDialogMode`,void 0),W([S()],$.prototype,`shortcutConfig`,void 0),W([S()],$.prototype,`workspaceUploadDefaultFolder`,void 0),W([S()],$.prototype,`workspaceAttachmentsDefaultFolder`,void 0),$=W([b(`pi-web-app`)],$);function Xk(e){let t=e?.model?.provider,n=e?.model?.id;return t!==void 0&&n!==void 0?`${t}/${n}`:void 0}function Zk(){let e=new Ly;return e.register({id:`core`,plugin:uy}),e.register({id:`themes`,plugin:my}),e}function Qk(){let e=_t()?`management`:`normal`;return Nt(e),e}function $k(e){let t=e.selectedMachine;return t===void 0?{id:`local`,name:`本机`,kind:`local`}:{id:t.id,name:t.name,kind:t.kind}}function eA(){return{registrationPluginId:`core`,sourcePluginId:`core`}}function tA(e,t){return JSON.stringify([e,t.id,t.cwd])}function nA(e){let t=e.selectedSession;return t===void 0?void 0:tA(z(e),t)}function rA(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function iA(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function aA(e,t){return oA(e,t)}function oA(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function sA(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function cA(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function lA(e){return As(e.status,e.activity)}function uA(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function dA(){return{}}function fA(e,t){return JSON.stringify([e,t])}function pA(e){return zk[Math.min(e,zk.length-1)]??3e4}function mA(e){return e instanceof Error?e.message:String(e)}function hA(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function gA(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}export{h as _,gg as a,Vo as c,S as d,x as f,g,Je as h,vg as i,Mo as l,y as m,W as n,Dp as o,b as p,_g as r,Ep as s,cS as t,C as u};
|