@chainingintention/pi-web-cn 1.202606.5 → 1.202606.7
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/README.md +1 -1
- package/dist/client/assets/{CodeViewer-DRxmEzh1.js → CodeViewer-8znVN61S.js} +1 -1
- package/dist/client/assets/{TerminalPanel-BcGKwlLZ.js → TerminalPanel-DrdWnF1y.js} +1 -1
- package/dist/client/assets/index-BiGrW6IC.js +2169 -0
- package/dist/client/index.html +1 -1
- package/dist/plugin-api.d.ts +17 -11
- package/dist/server/app.js +7 -0
- package/dist/server/app.js.map +1 -1
- package/dist/server/machines/machinePluginProxyRoutes.js +179 -0
- package/dist/server/machines/machinePluginProxyRoutes.js.map +1 -0
- package/dist/server/machines/machineProxyRoutes.js +1 -0
- package/dist/server/machines/machineProxyRoutes.js.map +1 -1
- package/dist/server/managementEmbed.js +45 -15
- package/dist/server/managementEmbed.js.map +1 -1
- package/dist/server/sessions/piSessionService.js +19 -5
- package/dist/server/sessions/piSessionService.js.map +1 -1
- package/dist/server/sessions/sessionNameGenerator.js +2 -0
- package/dist/server/sessions/sessionNameGenerator.js.map +1 -1
- package/dist/server/sessions/sessionRoutes.js +1 -1
- package/dist/server/sessions/sessionRoutes.js.map +1 -1
- package/dist/server/terminalProxyRoutes.js +10 -0
- package/dist/server/terminalProxyRoutes.js.map +1 -1
- package/dist/server/terminals/terminalRoutes.js +11 -0
- package/dist/server/terminals/terminalRoutes.js.map +1 -1
- package/dist/server/terminals/terminalService.js +6 -0
- package/dist/server/terminals/terminalService.js.map +1 -1
- package/dist/server/workspaceExplorerRoutes.js +86 -0
- package/dist/server/workspaceExplorerRoutes.js.map +1 -1
- package/dist/server/workspaces/fileOperationService.js +95 -0
- package/dist/server/workspaces/fileOperationService.js.map +1 -0
- package/dist/server/workspaces/fileUploadService.js +23 -0
- package/dist/server/workspaces/fileUploadService.js.map +1 -0
- package/dist/server/workspaces/workspaceDeletionRoutes.js +127 -0
- package/dist/server/workspaces/workspaceDeletionRoutes.js.map +1 -0
- package/dist/shared/apiTypes.d.ts +12 -0
- package/dist/shared/federatedRoutes.js +9 -0
- package/dist/shared/federatedRoutes.js.map +1 -1
- package/dist/shared/machinePluginIds.js +41 -0
- package/dist/shared/machinePluginIds.js.map +1 -0
- package/dist/shared/workspaceDeletion.js +12 -0
- package/dist/shared/workspaceDeletion.js.map +1 -0
- package/docs/plugins.md +88 -12
- package/package.json +1 -1
- package/dist/client/assets/index-BZE2v69K.js +0 -2002
|
@@ -0,0 +1,2169 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/CodeViewer-8znVN61S.js","assets/vendor-editor-core-B4Sq6exx.js","assets/vendor-editor-languages-DznYbTkJ.js","assets/vendor-editor-legacy-B4QLsWF8.js","assets/TerminalPanel-DrdWnF1y.js","assets/vendor-terminal-DjQ08hXu.js","assets/vendor-terminal-DDGTF8rc.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{Q as ho,w as Ye,J as Li,R as ka,S as $a,G as Pa,U as Ca,V as Ia,A as Ta,W as Ma,X as Ra,Y as Aa,Z as uo,x as fo,_ as Ea}from"./vendor-editor-core-B4Sq6exx.js";import{m as Da,i as Wa,d as Oa}from"./vendor-editor-languages-DznYbTkJ.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))s(o);new MutationObserver(o=>{for(const r of o)if(r.type==="childList")for(const n of r.addedNodes)n.tagName==="LINK"&&n.rel==="modulepreload"&&s(n)}).observe(document,{childList:!0,subtree:!0});function i(o){const r={};return o.integrity&&(r.integrity=o.integrity),o.referrerPolicy&&(r.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?r.credentials="include":o.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(o){if(o.ep)return;o.ep=!0;const r=i(o);fetch(o.href,r)}})();const Jt=globalThis,Cs=Jt.ShadowRoot&&(Jt.ShadyCSS===void 0||Jt.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Is=Symbol(),go=new WeakMap;let Kr=class{constructor(t,i,s){if(this._$cssResult$=!0,s!==Is)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=t,this.t=i}get styleSheet(){let t=this.o;const i=this.t;if(Cs&&t===void 0){const s=i!==void 0&&i.length===1;s&&(t=go.get(i)),t===void 0&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),s&&go.set(i,t))}return t}toString(){return this.cssText}};const _a=e=>new Kr(typeof e=="string"?e:e+"",void 0,Is),A=(e,...t)=>{const i=e.length===1?e[0]:t.reduce((s,o,r)=>s+(n=>{if(n._$cssResult$===!0)return n.cssText;if(typeof n=="number")return n;throw Error("Value passed to 'css' function must be a 'css' function result: "+n+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(o)+e[r+1],e[0]);return new Kr(i,e,Is)},La=(e,t)=>{if(Cs)e.adoptedStyleSheets=t.map(i=>i instanceof CSSStyleSheet?i:i.styleSheet);else for(const i of t){const s=document.createElement("style"),o=Jt.litNonce;o!==void 0&&s.setAttribute("nonce",o),s.textContent=i.cssText,e.appendChild(s)}},mo=Cs?e=>e:e=>e instanceof CSSStyleSheet?(t=>{let i="";for(const s of t.cssRules)i+=s.cssText;return _a(i)})(e):e;const{is:ja,defineProperty:Na,getOwnPropertyDescriptor:Fa,getOwnPropertyNames:za,getOwnPropertySymbols:Ba,getPrototypeOf:Ua}=Object,ki=globalThis,vo=ki.trustedTypes,Ha=vo?vo.emptyScript:"",qa=ki.reactiveElementPolyfillSupport,xt=(e,t)=>e,ii={toAttribute(e,t){switch(t){case Boolean:e=e?Ha:null;break;case Object:case Array:e=e==null?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=e!==null;break;case Number:i=e===null?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch{i=null}}return i}},Ts=(e,t)=>!ja(e,t),bo={attribute:!0,type:String,converter:ii,reflect:!1,useDefault:!1,hasChanged:Ts};Symbol.metadata??=Symbol("metadata"),ki.litPropertyMetadata??=new WeakMap;let it=class extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,i=bo){if(i.state&&(i.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((i=Object.create(i)).wrapped=!0),this.elementProperties.set(t,i),!i.noAccessor){const s=Symbol(),o=this.getPropertyDescriptor(t,s,i);o!==void 0&&Na(this.prototype,t,o)}}static getPropertyDescriptor(t,i,s){const{get:o,set:r}=Fa(this.prototype,t)??{get(){return this[i]},set(n){this[i]=n}};return{get:o,set(n){const a=o?.call(this);r?.call(this,n),this.requestUpdate(t,a,s)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??bo}static _$Ei(){if(this.hasOwnProperty(xt("elementProperties")))return;const t=Ua(this);t.finalize(),t.l!==void 0&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(xt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(xt("properties"))){const i=this.properties,s=[...za(i),...Ba(i)];for(const o of s)this.createProperty(o,i[o])}const t=this[Symbol.metadata];if(t!==null){const i=litPropertyMetadata.get(t);if(i!==void 0)for(const[s,o]of i)this.elementProperties.set(s,o)}this._$Eh=new Map;for(const[i,s]of this.elementProperties){const o=this._$Eu(i,s);o!==void 0&&this._$Eh.set(o,i)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(t){const i=[];if(Array.isArray(t)){const s=new Set(t.flat(1/0).reverse());for(const o of s)i.unshift(mo(o))}else t!==void 0&&i.push(mo(t));return i}static _$Eu(t,i){const s=i.attribute;return s===!1?void 0:typeof s=="string"?s:typeof t=="string"?t.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(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),this.renderRoot!==void 0&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,i=this.constructor.elementProperties;for(const s of i.keys())this.hasOwnProperty(s)&&(t.set(s,this[s]),delete this[s]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return La(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,i,s){this._$AK(t,s)}_$ET(t,i){const s=this.constructor.elementProperties.get(t),o=this.constructor._$Eu(t,s);if(o!==void 0&&s.reflect===!0){const r=(s.converter?.toAttribute!==void 0?s.converter:ii).toAttribute(i,s.type);this._$Em=t,r==null?this.removeAttribute(o):this.setAttribute(o,r),this._$Em=null}}_$AK(t,i){const s=this.constructor,o=s._$Eh.get(t);if(o!==void 0&&this._$Em!==o){const r=s.getPropertyOptions(o),n=typeof r.converter=="function"?{fromAttribute:r.converter}:r.converter?.fromAttribute!==void 0?r.converter:ii;this._$Em=o;const a=n.fromAttribute(i,r.type);this[o]=a??this._$Ej?.get(o)??a,this._$Em=null}}requestUpdate(t,i,s,o=!1,r){if(t!==void 0){const n=this.constructor;if(o===!1&&(r=this[t]),s??=n.getPropertyOptions(t),!((s.hasChanged??Ts)(r,i)||s.useDefault&&s.reflect&&r===this._$Ej?.get(t)&&!this.hasAttribute(n._$Eu(t,s))))return;this.C(t,i,s)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(t,i,{useDefault:s,reflect:o,wrapped:r},n){s&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,n??i??this[t]),r!==!0||n!==void 0)||(this._$AL.has(t)||(this.hasUpdated||s||(i=void 0),this._$AL.set(t,i)),o===!0&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(i){Promise.reject(i)}const t=this.scheduleUpdate();return t!=null&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[o,r]of this._$Ep)this[o]=r;this._$Ep=void 0}const s=this.constructor.elementProperties;if(s.size>0)for(const[o,r]of s){const{wrapped:n}=r,a=this[o];n!==!0||this._$AL.has(o)||a===void 0||this.C(o,void 0,r,a)}}let t=!1;const i=this._$AL;try{t=this.shouldUpdate(i),t?(this.willUpdate(i),this._$EO?.forEach(s=>s.hostUpdate?.()),this.update(i)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(i)}willUpdate(t){}_$AE(t){this._$EO?.forEach(i=>i.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(i=>this._$ET(i,this[i])),this._$EM()}updated(t){}firstUpdated(t){}};it.elementStyles=[],it.shadowRootOptions={mode:"open"},it[xt("elementProperties")]=new Map,it[xt("finalized")]=new Map,qa?.({ReactiveElement:it}),(ki.reactiveElementVersions??=[]).push("2.1.2");const Ms=globalThis,wo=e=>e,si=Ms.trustedTypes,yo=si?si.createPolicy("lit-html",{createHTML:e=>e}):void 0,Vr="$lit$",je=`lit$${Math.random().toFixed(9).slice(2)}$`,Gr="?"+je,Ka=`<${Gr}>`,Ke=document,$t=()=>Ke.createComment(""),Pt=e=>e===null||typeof e!="object"&&typeof e!="function",Rs=Array.isArray,Va=e=>Rs(e)||typeof e?.[Symbol.iterator]=="function",ji=`[
|
|
3
|
+
\f\r]`,ht=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,xo=/-->/g,So=/>/g,Fe=RegExp(`>|${ji}(?:([^\\s"'>=/]+)(${ji}*=${ji}*(?:[^
|
|
4
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),ko=/'/g,$o=/"/g,Jr=/^(?:script|style|textarea|title)$/i,Zr=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),l=Zr(1),st=Zr(2),Ne=Symbol.for("lit-noChange"),_=Symbol.for("lit-nothing"),Po=new WeakMap,He=Ke.createTreeWalker(Ke,129);function Qr(e,t){if(!Rs(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return yo!==void 0?yo.createHTML(t):t}const Ga=(e,t)=>{const i=e.length-1,s=[];let o,r=t===2?"<svg>":t===3?"<math>":"",n=ht;for(let a=0;a<i;a++){const c=e[a];let p,u,h=-1,f=0;for(;f<c.length&&(n.lastIndex=f,u=n.exec(c),u!==null);)f=n.lastIndex,n===ht?u[1]==="!--"?n=xo:u[1]!==void 0?n=So:u[2]!==void 0?(Jr.test(u[2])&&(o=RegExp("</"+u[2],"g")),n=Fe):u[3]!==void 0&&(n=Fe):n===Fe?u[0]===">"?(n=o??ht,h=-1):u[1]===void 0?h=-2:(h=n.lastIndex-u[2].length,p=u[1],n=u[3]===void 0?Fe:u[3]==='"'?$o:ko):n===$o||n===ko?n=Fe:n===xo||n===So?n=ht:(n=Fe,o=void 0);const b=n===Fe&&e[a+1].startsWith("/>")?" ":"";r+=n===ht?c+Ka:h>=0?(s.push(p),c.slice(0,h)+Vr+c.slice(h)+je+b):c+je+(h===-2?a:b)}return[Qr(e,r+(e[i]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),s]};class Ct{constructor({strings:t,_$litType$:i},s){let o;this.parts=[];let r=0,n=0;const a=t.length-1,c=this.parts,[p,u]=Ga(t,i);if(this.el=Ct.createElement(p,s),He.currentNode=this.el.content,i===2||i===3){const h=this.el.content.firstChild;h.replaceWith(...h.childNodes)}for(;(o=He.nextNode())!==null&&c.length<a;){if(o.nodeType===1){if(o.hasAttributes())for(const h of o.getAttributeNames())if(h.endsWith(Vr)){const f=u[n++],b=o.getAttribute(h).split(je),P=/([.?@])?(.*)/.exec(f);c.push({type:1,index:r,name:P[2],strings:b,ctor:P[1]==="."?Za:P[1]==="?"?Qa:P[1]==="@"?Xa:$i}),o.removeAttribute(h)}else h.startsWith(je)&&(c.push({type:6,index:r}),o.removeAttribute(h));if(Jr.test(o.tagName)){const h=o.textContent.split(je),f=h.length-1;if(f>0){o.textContent=si?si.emptyScript:"";for(let b=0;b<f;b++)o.append(h[b],$t()),He.nextNode(),c.push({type:2,index:++r});o.append(h[f],$t())}}}else if(o.nodeType===8)if(o.data===Gr)c.push({type:2,index:r});else{let h=-1;for(;(h=o.data.indexOf(je,h+1))!==-1;)c.push({type:7,index:r}),h+=je.length-1}r++}}static createElement(t,i){const s=Ke.createElement("template");return s.innerHTML=t,s}}function rt(e,t,i=e,s){if(t===Ne)return t;let o=s!==void 0?i._$Co?.[s]:i._$Cl;const r=Pt(t)?void 0:t._$litDirective$;return o?.constructor!==r&&(o?._$AO?.(!1),r===void 0?o=void 0:(o=new r(e),o._$AT(e,i,s)),s!==void 0?(i._$Co??=[])[s]=o:i._$Cl=o),o!==void 0&&(t=rt(e,o._$AS(e,t.values),o,s)),t}class Ja{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,o=(t?.creationScope??Ke).importNode(i,!0);He.currentNode=o;let r=He.nextNode(),n=0,a=0,c=s[0];for(;c!==void 0;){if(n===c.index){let p;c.type===2?p=new at(r,r.nextSibling,this,t):c.type===1?p=new c.ctor(r,c.name,c.strings,this,t):c.type===6&&(p=new Ya(r,this,t)),this._$AV.push(p),c=s[++a]}n!==c?.index&&(r=He.nextNode(),n++)}return He.currentNode=Ke,o}p(t){let i=0;for(const s of this._$AV)s!==void 0&&(s.strings!==void 0?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class at{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,o){this.type=2,this._$AH=_,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=o,this._$Cv=o?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return i!==void 0&&t?.nodeType===11&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=rt(this,t,i),Pt(t)?t===_||t==null||t===""?(this._$AH!==_&&this._$AR(),this._$AH=_):t!==this._$AH&&t!==Ne&&this._(t):t._$litType$!==void 0?this.$(t):t.nodeType!==void 0?this.T(t):Va(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==_&&Pt(this._$AH)?this._$AA.nextSibling.data=t:this.T(Ke.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,o=typeof s=="number"?this._$AC(t):(s.el===void 0&&(s.el=Ct.createElement(Qr(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===o)this._$AH.p(i);else{const r=new Ja(o,this),n=r.u(this.options);r.p(i),this.T(n),this._$AH=r}}_$AC(t){let i=Po.get(t.strings);return i===void 0&&Po.set(t.strings,i=new Ct(t)),i}k(t){Rs(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,o=0;for(const r of t)o===i.length?i.push(s=new at(this.O($t()),this.O($t()),this,this.options)):s=i[o],s._$AI(r),o++;o<i.length&&(this._$AR(s&&s._$AB.nextSibling,o),i.length=o)}_$AR(t=this._$AA.nextSibling,i){for(this._$AP?.(!1,!0,i);t!==this._$AB;){const s=wo(t).nextSibling;wo(t).remove(),t=s}}setConnected(t){this._$AM===void 0&&(this._$Cv=t,this._$AP?.(t))}}let $i=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,o,r){this.type=1,this._$AH=_,this._$AN=void 0,this.element=t,this.name=i,this._$AM=o,this.options=r,s.length>2||s[0]!==""||s[1]!==""?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=_}_$AI(t,i=this,s,o){const r=this.strings;let n=!1;if(r===void 0)t=rt(this,t,i,0),n=!Pt(t)||t!==this._$AH&&t!==Ne,n&&(this._$AH=t);else{const a=t;let c,p;for(t=r[0],c=0;c<r.length-1;c++)p=rt(this,a[s+c],i,c),p===Ne&&(p=this._$AH[c]),n||=!Pt(p)||p!==this._$AH[c],p===_?t=_:t!==_&&(t+=(p??"")+r[c+1]),this._$AH[c]=p}n&&!o&&this.j(t)}j(t){t===_?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},Za=class extends $i{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===_?void 0:t}},Qa=class extends $i{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==_)}},Xa=class extends $i{constructor(t,i,s,o,r){super(t,i,s,o,r),this.type=5}_$AI(t,i=this){if((t=rt(this,t,i,0)??_)===Ne)return;const s=this._$AH,o=t===_&&s!==_||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,r=t!==_&&(s===_||o);o&&this.element.removeEventListener(this.name,this,s),r&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){typeof this._$AH=="function"?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}};class Ya{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){rt(this,t)}}const el={I:at},tl=Ms.litHtmlPolyfillSupport;tl?.(Ct,at),(Ms.litHtmlVersions??=[]).push("3.3.2");const il=(e,t,i)=>{const s=i?.renderBefore??t;let o=s._$litPart$;if(o===void 0){const r=i?.renderBefore??null;s._$litPart$=o=new at(t.insertBefore($t(),r),r,void 0,i??{})}return o._$AI(e),o};const As=globalThis;let T=class extends it{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const i=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=il(i,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ne}};T._$litElement$=!0,T.finalized=!0,As.litElementHydrateSupport?.({LitElement:T});const sl=As.litElementPolyfillSupport;sl?.({LitElement:T});(As.litElementVersions??=[]).push("4.2.2");const R=e=>(t,i)=>{i!==void 0?i.addInitializer(()=>{customElements.define(e,t)}):customElements.define(e,t)};const ol={attribute:!0,type:String,converter:ii,reflect:!1,hasChanged:Ts},rl=(e=ol,t,i)=>{const{kind:s,metadata:o}=i;let r=globalThis.litPropertyMetadata.get(o);if(r===void 0&&globalThis.litPropertyMetadata.set(o,r=new Map),s==="setter"&&((e=Object.create(e)).wrapped=!0),r.set(i.name,e),s==="accessor"){const{name:n}=i;return{set(a){const c=t.get.call(this);t.set.call(this,a),this.requestUpdate(n,c,e,!0,a)},init(a){return a!==void 0&&this.C(n,void 0,e,a),a}}}if(s==="setter"){const{name:n}=i;return function(a){const c=this[n];t.call(this,a),this.requestUpdate(n,c,e,!0,a)}}throw Error("Unsupported decorator location: "+s)};function d(e){return(t,i)=>typeof i=="object"?rl(e,t,i):((s,o,r)=>{const n=o.hasOwnProperty(r);return o.constructor.createProperty(r,s),n?Object.getOwnPropertyDescriptor(o,r):void 0})(e,t,i)}function w(e){return d({...e,state:!0,attribute:!1})}const nl=(e,t,i)=>(i.configurable=!0,i.enumerable=!0,Reflect.decorate&&typeof t!="object"&&Object.defineProperty(e,t,i),i);function N(e,t){return(i,s,o)=>{const r=n=>n.renderRoot?.querySelector(e)??null;return nl(i,s,{get(){return r(this)}})}}function Es(e,t=Yr()){if(t===void 0)return e;const i=Xr(t);if(i===void 0)return e;const s=new URL(e,t.origin);return s.searchParams.set("embed",i.embed),s.searchParams.set("token",i.token),`${s.pathname}${s.search}${s.hash}`}function Ds(e,t=Yr()){if(t===void 0)return e;const i=Xr(t);if(i===void 0)return e;const s=new URL(e);return s.searchParams.set("embed",i.embed),s.searchParams.set("token",i.token),s.toString()}function Xr(e){const t=e.searchParams.get("embed"),i=e.searchParams.get("token")?.trim();if(!(t!=="management"||i===void 0||i===""))return{embed:t,token:i}}function Yr(){if(typeof globalThis.location>"u")return;const e=globalThis.location;if(typeof e.href=="string"&&e.href!=="")return new URL(e.href);const t=typeof e.protocol=="string"&&e.protocol!==""?e.protocol:"http:",i=typeof e.host=="string"&&e.host!==""?e.host:"localhost",s=typeof e.search=="string"?e.search:"";return new URL(`${t}//${i}/${s}`)}async function v(e,t,i){const s=new Headers(i?.headers);i?.body!==void 0&&s.set("content-type","application/json");const o=await fetch(Es(e),{...i,headers:s});if(!o.ok){const n=await o.json().catch(()=>({}));throw new Error(al(n)??o.statusText)}const r=await o.json();return t(r)}function al(e){if(ll(e))return typeof e.error=="string"?e.error:void 0}function ll(e){return typeof e=="object"&&e!==null}function St(e){return typeof e=="object"&&e!==null}function y(e){if(!St(e))throw new Error("Expected object response");return e}function m(e,t){const i=e[t];if(typeof i!="string")throw new Error(`Expected string field: ${t}`);return i}function C(e,t){const i=e[t];if(i!==void 0){if(typeof i!="string")throw new Error(`Expected optional string field: ${t}`);return i}}function ne(e,t){const i=e[t];if(typeof i!="number")throw new Error(`Expected number field: ${t}`);return i}function E(e,t){const i=e[t];if(typeof i!="boolean")throw new Error(`Expected boolean field: ${t}`);return i}function j(e){return t=>{if(!Array.isArray(t))throw new Error("Expected array response");return t.map(e)}}function cl(e){if(!Array.isArray(e))throw new Error("Expected array response");return e}function dl(e,t){if(!Array.isArray(e)||!e.every(i=>typeof i=="string"))throw new Error(`Expected string array field: ${t}`);return e}function pl(e){if(Array.isArray(e))return{messages:e,start:0,total:e.length};const t=y(e);return{messages:cl(t.messages),start:ne(t,"start"),total:ne(t,"total")}}function hl(e){const t=y(e);return j(en)(t.machines)}function en(e){const t=y(e),i=fl(t,"kind"),s=C(t,"baseUrl"),o=tn(t,"status"),r=C(t,"statusMessage");return{id:m(t,"id"),name:m(t,"name"),kind:i,...s===void 0?{}:{baseUrl:s},createdAt:m(t,"createdAt"),updatedAt:m(t,"updatedAt"),...o===void 0?{}:{status:o},...r===void 0?{}:{statusMessage:r}}}function ul(e){const t=y(e),i=tn(t,"status"),s=C(t,"error");return{machineId:m(t,"machineId"),ok:E(t,"ok"),checkedAt:m(t,"checkedAt"),...i===void 0?{}:{status:i},...t.web===void 0?{}:{web:oi(t.web)},...t.sessiond===void 0?{}:{sessiond:oi(t.sessiond)},...s===void 0?{}:{error:s}}}function fl(e,t){const i=m(e,t);if(i!=="local"&&i!=="remote")throw new Error(`Expected machine kind field: ${t}`);return i}function tn(e,t){const i=C(e,t);if(i!==void 0){if(i!=="unknown"&&i!=="online"&&i!=="offline"&&i!=="error")throw new Error(`Expected machine status field: ${t}`);return i}}function Co(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),path:m(t,"path"),createdAt:m(t,"createdAt")}}function gl(e){const t=y(e),i=C(t,"branch");return{id:m(t,"id"),projectId:m(t,"projectId"),path:m(t,"path"),label:m(t,"label"),...i===void 0?{}:{branch:i},isMain:E(t,"isMain"),isGitRepo:E(t,"isGitRepo"),isGitWorktree:E(t,"isGitWorktree")}}function cs(e){const t=y(e),i=C(t,"name"),s=C(t,"parentSessionPath"),o=C(t,"archivedAt");return{id:m(t,"id"),path:m(t,"path"),cwd:m(t,"cwd"),...i===void 0?{}:{name:i},created:m(t,"created"),modified:m(t,"modified"),messageCount:ne(t,"messageCount"),firstMessage:m(t,"firstMessage"),...s===void 0?{}:{parentSessionPath:s},...t.archived===!0?{archived:!0}:{},...o===void 0?{}:{archivedAt:o}}}function ut(e){const t=y(e);return{sessionId:m(t,"sessionId"),isStreaming:E(t,"isStreaming"),isCompacting:E(t,"isCompacting"),isBashRunning:E(t,"isBashRunning"),pendingMessageCount:ne(t,"pendingMessageCount"),queuedMessages:t.queuedMessages===void 0?[]:j(ml)(t.queuedMessages),...x("messageCount",Te(t,"messageCount")),tokens:vl(t.tokens),cost:ne(t,"cost"),...bl(t.model),...Al(t.contextUsage),...x("thinkingLevel",C(t,"thinkingLevel"))}}function ml(e){const t=y(e),i=m(t,"kind");if(i!=="steer"&&i!=="followUp")throw new Error("Invalid queued message kind");return{kind:i,text:m(t,"text")}}function vl(e){const t=y(e);return{input:ne(t,"input"),output:ne(t,"output"),cacheRead:ne(t,"cacheRead"),cacheWrite:ne(t,"cacheWrite"),total:ne(t,"total")}}function sn(e){const t=y(e);return{...x("provider",C(t,"provider")),...x("id",C(t,"id")),...x("name",C(t,"name")),...x("contextWindow",Te(t,"contextWindow")),...x("reasoning",t.reasoning)}}function bl(e){return e===void 0?{}:{model:sn(e)}}function wl(e){const t=y(e);return{models:j(sn)(t.models)}}function yl(e){if(e!=="off"&&e!=="minimal"&&e!=="low"&&e!=="medium"&&e!=="high"&&e!=="xhigh")throw new Error("Invalid thinking level");return e}function xl(e){const t=y(e);return{levels:j(yl)(t.levels)}}function Sl(e){if(e!=="oauth"&&e!=="api_key")throw new Error("Invalid auth type");return e}function kl(e){if(e!=="stored"&&e!=="runtime"&&e!=="environment"&&e!=="fallback"&&e!=="models_json_key"&&e!=="models_json_command")throw new Error("Invalid auth status source");return e}function $l(e){const t=y(e),i=t.source===void 0?void 0:kl(t.source);return{configured:E(t,"configured"),...x("source",i),...x("label",C(t,"label"))}}function Pl(e){const t=y(e);return{id:m(t,"id"),name:m(t,"name"),authType:Sl(t.authType),status:$l(t.status)}}function Cl(e){const t=y(e);return{providers:j(Pl)(t.providers)}}function jt(e){const t=y(e);return{flowId:m(t,"flowId"),providerId:m(t,"providerId"),providerName:m(t,"providerName"),status:Il(t.status),progress:j(s=>{if(typeof s!="string")throw new Error("Expected progress item string");return s})(t.progress),...x("error",C(t,"error")),...x("auth",Tl(t.auth)),...x("prompt",Ml(t.prompt)),...x("select",Rl(t.select))}}function Il(e){if(e!=="running"&&e!=="complete"&&e!=="error"&&e!=="cancelled")throw new Error("Invalid OAuth flow status");return e}function Tl(e){if(e===void 0)return;const t=y(e);return{url:m(t,"url"),...x("instructions",C(t,"instructions"))}}function Ml(e){if(e===void 0)return;const t=y(e),i=m(t,"kind");if(i!=="prompt"&&i!=="manual")throw new Error("Invalid OAuth prompt kind");return{requestId:m(t,"requestId"),message:m(t,"message"),kind:i,...x("placeholder",C(t,"placeholder")),...t.allowEmpty===!0?{allowEmpty:!0}:{}}}function Rl(e){if(e===void 0)return;const t=y(e);return{requestId:m(t,"requestId"),message:m(t,"message"),options:j(rn)(t.options)}}function Al(e){if(e===void 0)return{};const t=y(e);return{contextUsage:{tokens:Wo(t,"tokens"),contextWindow:ne(t,"contextWindow"),percent:Wo(t,"percent")}}}function El(e){const t=y(e),i=m(t,"source");if(i!=="extension"&&i!=="prompt"&&i!=="skill"&&i!=="builtin")throw new Error("Invalid command source");return{name:m(t,"name"),source:i,...x("description",C(t,"description"))}}function on(e){const t=y(e),i=m(t,"kind");if(i!=="tracked"&&i!=="untracked"&&i!=="other")throw new Error("Invalid file kind");return{path:m(t,"path"),kind:i}}function Dl(e){const t=y(e);return{path:m(t,"path"),entries:j(Wl)(t.entries),scannedAt:m(t,"scannedAt"),truncated:E(t,"truncated")}}function Wl(e){const t=y(e),i=m(t,"type");if(i!=="file"&&i!=="directory"&&i!=="symlink")throw new Error("Invalid file tree entry type");return{name:m(t,"name"),path:m(t,"path"),type:i,...x("size",Te(t,"size")),...x("modifiedAt",C(t,"modifiedAt"))}}function Ol(e){const t=y(e),i=m(t,"encoding");if(i!=="utf8")throw new Error("Invalid file encoding");return{path:m(t,"path"),...x("language",C(t,"language")),...x("mediaType",_l(t.mediaType)),...x("mimeType",C(t,"mimeType")),encoding:i,size:ne(t,"size"),modifiedAt:m(t,"modifiedAt"),content:m(t,"content"),truncated:E(t,"truncated"),binary:E(t,"binary")}}function Io(e){const t=y(e);return{path:m(t,"path"),size:ne(t,"size"),modifiedAt:m(t,"modifiedAt")}}function Ni(e){const t=y(e);return{path:m(t,"path")}}function To(e){const t=y(e);if(t.deleted!==!0)throw new Error("Expected deleted response");return{deleted:!0,path:m(t,"path")}}function _l(e){if(e!==void 0){if(e!=="image")throw new Error("Invalid file media type");return e}}function Ll(e){const t=y(e);return{isGitRepo:E(t,"isGitRepo"),hash:m(t,"hash"),...x("branch",C(t,"branch")),...x("upstream",C(t,"upstream")),...x("ahead",Te(t,"ahead")),...x("behind",Te(t,"behind")),files:j(jl)(t.files)}}function jl(e){const t=y(e);return{path:m(t,"path"),...x("oldPath",C(t,"oldPath")),index:Mo(t.index),workingTree:Mo(t.workingTree)}}function Mo(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 new Error("Invalid git file state")}}function Nl(e){const t=y(e);return{...x("path",C(t,"path")),staged:E(t,"staged"),hash:m(t,"hash"),diff:m(t,"diff"),truncated:E(t,"truncated")}}function Fi(e){const t=y(e);return{id:m(t,"id"),cwd:m(t,"cwd"),name:m(t,"name"),createdAt:m(t,"createdAt"),exited:E(t,"exited"),...x("exitCode",Te(t,"exitCode")),...x("commandRunId",C(t,"commandRunId"))}}function kt(e){const t=y(e);return{id:m(t,"id"),origin:m(t,"origin"),projectId:m(t,"projectId"),workspaceId:m(t,"workspaceId"),terminalId:m(t,"terminalId"),title:m(t,"title"),command:m(t,"command"),status:Fl(t.status),...x("exitCode",Te(t,"exitCode")),createdAt:m(t,"createdAt"),...x("startedAt",C(t,"startedAt")),...x("completedAt",C(t,"completedAt")),metadata:zl(t.metadata,"metadata")}}function Fl(e){if(e!=="queued"&&e!=="running"&&e!=="succeeded"&&e!=="failed")throw new Error("Invalid terminal command run status");return e}function zl(e,t){const i=y(e);return Object.fromEntries(Object.entries(i).map(([s,o])=>{if(typeof o!="string")throw new Error(`Expected string record field: ${t}.${s}`);return[s,o]}))}function Bl(e){const t=y(e);return{cwd:m(t,"cwd"),hasSessionActivity:E(t,"hasSessionActivity"),hasTerminalActivity:E(t,"hasTerminalActivity"),updatedAt:m(t,"updatedAt")}}function Ul(e){const t=y(e);return{workspaces:j(Bl)(t.workspaces),generatedAt:m(t,"generatedAt")}}function Ro(e){const t=y(e);return{path:m(t,"path"),exists:E(t,"exists"),config:Ao(t.config),effectiveConfig:Ao(t.effectiveConfig),envOverrides:Vl(t.envOverrides)}}function Ao(e){const t=y(e);return{...x("host",C(t,"host")),...x("port",Te(t,"port")),...x("allowedHosts",Hl(t.allowedHosts)),...x("shortcuts",ql(t.shortcuts)),...x("plugins",Kl(t.plugins))}}function Hl(e){if(e!==void 0){if(e===!0)return!0;if(Array.isArray(e)&&e.every(t=>typeof t=="string"))return e;throw new Error("Invalid PI WEB allowedHosts field")}}function ql(e){if(e!==void 0){if(!St(e)||Array.isArray(e))throw new Error("Invalid PI WEB shortcuts field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(i!==null&&(typeof i!="string"||i===""))throw new Error("Invalid PI WEB shortcut field");return[t,i]}))}}function Kl(e){if(e!==void 0){if(!St(e)||Array.isArray(e))throw new Error("Invalid PI WEB plugins field");return Object.fromEntries(Object.entries(e).map(([t,i])=>{if(!St(i)||Array.isArray(i))throw new Error("Invalid PI WEB plugin config field");const s=i.enabled;if(s!==void 0&&typeof s!="boolean")throw new Error("Invalid PI WEB plugin enabled field");const o=i.settings;if(o!==void 0&&(!St(o)||Array.isArray(o)))throw new Error("Invalid PI WEB plugin settings field");return[t,i]}))}}function Vl(e){const t=y(e);return{host:E(t,"host"),port:E(t,"port"),allowedHosts:E(t,"allowedHosts")}}function Gl(e){const t=y(e);return{plugins:j(Jl)(t.plugins)}}function Jl(e){const t=y(e);return{id:m(t,"id"),module:m(t,"module"),source:m(t,"source"),scope:Zl(t.scope),enabled:E(t,"enabled")}}function Zl(e){if(e!=="bundled"&&e!=="local"&&e!=="user"&&e!=="project")throw new Error("Invalid PI WEB plugin scope");return e}function Ql(e){const t=y(e);return{packageName:m(t,"packageName"),generatedAt:m(t,"generatedAt"),components:Xl(t.components),release:ec(t.release),commands:tc(t.commands),messages:j(ic)(t.messages)}}function Xl(e){const t=y(e);return{web:oi(t.web),sessiond:oi(t.sessiond)}}function oi(e){const t=y(e);return{component:sc(t.component),label:m(t,"label"),...x("runtimeVersion",C(t,"runtimeVersion")),...x("installedVersion",C(t,"installedVersion")),stale:E(t,"stale"),available:E(t,"available"),...x("installation",Yl(t.installation)),...x("error",C(t,"error"))}}function Yl(e){if(e===void 0)return;const t=y(e),i=m(t,"kind");if(i!=="pi-package"&&i!=="npm-global"&&i!=="local"&&i!=="unknown")throw new Error("Invalid PI WEB installation kind");const s=t.scope;if(s!==void 0&&s!=="user"&&s!=="project")throw new Error("Invalid PI WEB installation scope");return{kind:i,...x("path",C(t,"path")),...x("source",C(t,"source")),...s===void 0?{}:{scope:s},...x("npmRoot",C(t,"npmRoot"))}}function ec(e){const t=y(e);return{packageName:m(t,"packageName"),...x("latestVersion",C(t,"latestVersion")),updateAvailable:E(t,"updateAvailable"),...x("checkedAt",C(t,"checkedAt")),...t.skipped===!0?{skipped:!0}:{},...x("error",C(t,"error"))}}function tc(e){const t=y(e);return{...x("update",C(t,"update")),...x("restart",C(t,"restart")),...x("restartWeb",C(t,"restartWeb")),...x("restartSessiond",C(t,"restartSessiond")),...x("status",C(t,"status"))}}function ic(e){const t=y(e);return{id:m(t,"id"),severity:oc(t.severity),title:m(t,"title"),body:m(t,"body"),...x("command",C(t,"command"))}}function sc(e){if(e!=="web"&&e!=="sessiond")throw new Error("Invalid PI WEB service component");return e}function oc(e){if(e!=="info"&&e!=="warning"&&e!=="error")throw new Error("Invalid PI WEB status severity");return e}function Eo(e){const t=y(e),i=m(t,"type");if(i==="unsupported")return{type:i,message:m(t,"message")};if(i==="select")return{type:i,requestId:m(t,"requestId"),title:m(t,"title"),options:j(rn)(t.options)};if(i==="done")return{type:i,...x("message",C(t,"message")),...rc(t.session),...x("promptDraft",C(t,"promptDraft"))};throw new Error("Invalid command result type")}function rn(e){const t=y(e);return{value:m(t,"value"),label:m(t,"label"),...x("description",C(t,"description"))}}function rc(e){return e===void 0?{}:{session:cs(e)}}function Nt(e){if(y(e).accepted!==!0)throw new Error("Expected accepted response");return{accepted:!0}}function ds(e){if(y(e).closed!==!0)throw new Error("Expected closed response");return{closed:!0}}function nc(e){if(y(e).aborted!==!0)throw new Error("Expected aborted response");return{aborted:!0}}function ac(e){if(y(e).stopped!==!0)throw new Error("Expected stopped response");return{stopped:!0}}function Do(e){const t=y(e);if(t.archived!==!0)throw new Error("Expected archived response");const i=t.sessionIds===void 0?void 0:dl(t.sessionIds,"sessionIds"),s=Te(t,"archivedCount"),o=Te(t,"skippedAlreadyArchivedCount");return{archived:!0,...i===void 0?{}:{sessionIds:i},...s===void 0?{}:{archivedCount:s},...o===void 0?{}:{skippedAlreadyArchivedCount:o}}}function lc(e){if(y(e).restored!==!0)throw new Error("Expected restored response");return{restored:!0}}function cc(e){if(y(e).detached!==!0)throw new Error("Expected detached response");return{detached:!0}}function Te(e,t){const i=e[t];if(i!==void 0){if(typeof i!="number")throw new Error(`Expected optional number field: ${t}`);return i}}function Wo(e,t){const i=e[t];if(i===null)return null;if(typeof i!="number")throw new Error(`Expected number|null field: ${t}`);return i}function x(e,t){return t===void 0?{}:{[e]:t}}function dc(e,t,i,s){const o=new URLSearchParams;s?.path!==void 0&&o.set("path",s.path),s?.staged===!0&&o.set("staged","true");const r=o.toString();return`/api/machines/${encodeURIComponent(e)}/projects/${encodeURIComponent(t)}/workspaces/${encodeURIComponent(i)}/git/diff${r?`?${r}`:""}`}function pc(e,t,i="local"){const s=new URLSearchParams;t?.limit!==void 0&&s.set("limit",String(t.limit)),t?.before!==void 0&&s.set("before",String(t.before));const o=s.toString();return`/api/machines/${encodeURIComponent(i)}/sessions/${e}/messages${o?`?${o}`:""}`}function hc(e,t,i,s){const o=new URLSearchParams;return o.set("path",i),s?.modifiedAt!==void 0&&o.set("v",s.modifiedAt),`${`/api/machines/${encodeURIComponent(s?.machineId??"local")}`}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/preview?${o.toString()}`}function nn(e,t,i,s){const o=new URLSearchParams;o.set("path",i);const r=`/api/machines/${encodeURIComponent(s?.machineId??"local")}`;return Es(`${r}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file/download?${o.toString()}`)}const S=(e="local")=>`/api/machines/${encodeURIComponent(e)}`,an={piWebStatus:()=>v("/api/pi-web/status",Ql)},uc={machines:()=>v("/api/machines",hl),addMachine:e=>v("/api/machines",en,{method:"POST",body:JSON.stringify(e)}),deleteMachine:e=>v(`/api/machines/${encodeURIComponent(e)}`,t=>t,{method:"DELETE"}),health:e=>v(`/api/machines/${encodeURIComponent(e)}/health`,ul)},ri={config:()=>v("/api/config",Ro),saveConfig:e=>v("/api/config",Ro,{method:"PUT",body:JSON.stringify({config:e})})},ps={plugins:()=>v("/api/plugins",Gl)},ln={workspaceActivity:(e="local")=>v(`${S(e)}/activity`,Ul)},fc={projects:(e="local")=>v(`${S(e)}/projects`,j(Co)),addProject:(e,t,i,s="local")=>v(`${S(s)}/projects`,Co,{method:"POST",body:JSON.stringify({path:e,name:t,create:i})}),closeProject:(e,t="local")=>v(`${S(t)}/projects/${encodeURIComponent(e)}`,ds,{method:"DELETE"}),projectDirectories:(e,t="local")=>v(`${S(t)}/project-directories?q=${encodeURIComponent(e)}`,j(on))},hs={workspaces:(e,t="local")=>v(`${S(t)}/projects/${e}/workspaces`,j(gl)),deleteWorkspace:(e,t,i="local")=>v(`${S(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}`,kt,{method:"DELETE"}),workspaceTree:(e,t,i="",s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/tree?path=${encodeURIComponent(i)}`,Dl),workspaceFile:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,Ol),uploadWorkspaceFile:async(e,t,i,s,o="local")=>v(`${S(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,Io,{method:"POST",body:JSON.stringify({path:i,contentBase64:await gc(s)})}),createWorkspaceFile:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,Io,{method:"POST",body:JSON.stringify({path:i,contentBase64:""})}),moveWorkspaceFile:(e,t,i,s,o="local")=>v(`${S(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file`,Ni,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceFile:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/file?path=${encodeURIComponent(i)}`,To,{method:"DELETE"}),createWorkspaceDirectory:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Ni,{method:"POST",body:JSON.stringify({path:i})}),moveWorkspaceDirectory:(e,t,i,s,o="local")=>v(`${S(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory`,Ni,{method:"PATCH",body:JSON.stringify({fromPath:i,toPath:s})}),deleteWorkspaceDirectory:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/directory?path=${encodeURIComponent(i)}`,To,{method:"DELETE"}),workspaceDownloadUrl:(e,t,i,s="local")=>nn(e,t,i,{machineId:s}),downloadWorkspaceFile:(e,t,i,s="local")=>vc(e,t,i,s)};async function gc(e){return mc(await e.arrayBuffer())}function mc(e){const t=new Uint8Array(e),i=32768;let s="";for(let o=0;o<t.length;o+=i)s+=String.fromCharCode(...t.subarray(o,o+i));return btoa(s)}async function vc(e,t,i,s){const o=await fetch(nn(e,t,i,{machineId:s}));if(!o.ok){const a=await o.json().catch(()=>({}));throw new Error(cn(a)??o.statusText)}const r=URL.createObjectURL(await o.blob()),n=document.createElement("a");n.href=r,n.download=bc(i,o.headers.get("content-disposition")),document.body.append(n),n.click(),n.remove(),URL.revokeObjectURL(r)}function bc(e,t){const s=t?.match(/filename\*=UTF-8''([^;]+)/u)?.[1];if(s!==void 0)try{const n=decodeURIComponent(s).trim();if(n!=="")return n}catch{}const r=t?.match(/filename="([^"]+)"/u)?.[1]?.trim();return r!==void 0&&r!==""?r:e.split("/").filter(n=>n!=="").at(-1)??"download"}const wc={sessions:(e,t="local")=>v(`${S(t)}/sessions?cwd=${encodeURIComponent(e)}`,j(cs)),startSession:(e,t="local")=>v(`${S(t)}/sessions`,cs,{method:"POST",body:JSON.stringify({cwd:e})}),messages:(e,t,i="local")=>v(pc(e,t,i),pl),status:(e,t="local")=>v(`${S(t)}/sessions/${e}/status`,ut),models:(e,t="local")=>v(`${S(t)}/sessions/${e}/models`,wl),setModel:(e,t,i,s="local")=>v(`${S(s)}/sessions/${e}/model`,ut,{method:"POST",body:JSON.stringify({provider:t,modelId:i})}),cycleModel:(e,t,i="local")=>v(`${S(i)}/sessions/${e}/model/cycle`,ut,{method:"POST",body:JSON.stringify({direction:t})}),thinkingLevels:(e,t="local")=>v(`${S(t)}/sessions/${e}/thinking-levels`,xl),setThinkingLevel:(e,t,i="local")=>v(`${S(i)}/sessions/${e}/thinking-level`,ut,{method:"POST",body:JSON.stringify({level:t})}),cycleThinkingLevel:(e,t="local")=>v(`${S(t)}/sessions/${e}/thinking-level/cycle`,ut,{method:"POST"}),commands:(e,t="local")=>v(`${S(t)}/sessions/${e}/commands`,j(El)),prompt:(e,t,i,s="local")=>v(`${S(s)}/sessions/${e}/prompt`,Nt,{method:"POST",body:JSON.stringify(i===void 0?{text:t}:{text:t,streamingBehavior:i})}),shell:(e,t,i="local")=>v(`${S(i)}/sessions/${e}/shell`,Nt,{method:"POST",body:JSON.stringify({text:t})}),runCommand:(e,t,i="local")=>v(`${S(i)}/sessions/${e}/commands/run`,Eo,{method:"POST",body:JSON.stringify({text:t})}),respondToCommand:(e,t,i,s="local")=>v(`${S(s)}/sessions/${e}/commands/respond`,Eo,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),abort:(e,t="local")=>v(`${S(t)}/sessions/${e}/abort`,nc,{method:"POST"}),stop:(e,t="local")=>v(`${S(t)}/sessions/${e}/stop`,ac,{method:"POST"}),archive:(e,t="local")=>v(`${S(t)}/sessions/${e}/archive`,Do,{method:"POST"}),archiveWithDescendants:(e,t="local")=>v(`${S(t)}/sessions/${e}/archive-tree`,Do,{method:"POST"}),restore:(e,t="local")=>v(`${S(t)}/sessions/${e}/restore`,lc,{method:"POST"}),detachParent:(e,t="local")=>v(`${S(t)}/sessions/${e}/detach-parent`,cc,{method:"POST"}),authProviders:e=>{const t=new URLSearchParams;e?.mode!==void 0&&t.set("mode",e.mode),e?.authType!==void 0&&t.set("authType",e.authType);const i=t.toString();return v(`${S(e?.machineId)}/auth/providers${i===""?"":`?${i}`}`,Cl)},saveApiKey:(e,t,i="local")=>v(`${S(i)}/auth/api-key`,Nt,{method:"POST",body:JSON.stringify({providerId:e,key:t})}),logoutProvider:(e,t="local")=>v(`${S(t)}/auth/logout`,Nt,{method:"POST",body:JSON.stringify({providerId:e})}),startOAuthLogin:(e,t="local")=>v(`${S(t)}/auth/oauth`,jt,{method:"POST",body:JSON.stringify({providerId:e})}),oauthFlow:(e,t="local")=>v(`${S(t)}/auth/oauth/${encodeURIComponent(e)}`,jt),respondOAuthFlow:(e,t,i,s="local")=>v(`${S(s)}/auth/oauth/${encodeURIComponent(e)}/respond`,jt,{method:"POST",body:JSON.stringify({requestId:t,value:i})}),cancelOAuthFlow:(e,t="local")=>v(`${S(t)}/auth/oauth/${encodeURIComponent(e)}/cancel`,jt,{method:"POST"})},ot={terminals:(e,t,i="local")=>v(`${S(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,j(Fi)),startTerminal:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,Fi,{method:"POST",body:JSON.stringify(i??{})}),closeWorkspaceTerminals:(e,t,i="local")=>v(`${S(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals`,ds,{method:"DELETE"}),closeTerminal:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}`,ds,{method:"DELETE"}),continueTerminal:(e,t,i,s="local")=>v(`${S(s)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/continue`,Fi,{method:"POST"}),runTerminalCommand:(e,t,i="local")=>v(`${S(i)}/projects/${encodeURIComponent(t.workspace.projectId)}/workspaces/${encodeURIComponent(t.workspace.id)}/terminal-command-runs`,kt,{method:"POST",body:JSON.stringify({origin:e,title:t.title,command:t.command,metadata:t.metadata??{}})}),listCommandRuns:(e,t="local")=>v(`${S(t)}/terminal-command-runs${xc(e)}`,j(kt)),getCommandRun:(e,t="local")=>yc(e,t),cancelCommandRun:(e,t="local")=>v(`${S(t)}/terminal-command-runs/${encodeURIComponent(e)}/cancel`,kt,{method:"POST"})};async function yc(e,t){const i=await fetch(Es(`${S(t)}/terminal-command-runs/${encodeURIComponent(e)}`));if(i.status!==404){if(!i.ok){const s=await i.json().catch(()=>({}));throw new Error(cn(s)??i.statusText)}return kt(await i.json())}}function xc(e){if(e===void 0)return"";const 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));const i=t.toString();return i===""?"":`?${i}`}function cn(e){if(!Sc(e))return;const t=e.error;return typeof t=="string"?t:void 0}function Sc(e){return typeof e=="object"&&e!==null}const kc={files:(e,t,i={})=>{const s=new URLSearchParams({cwd:e,q:t});return i.kind!==void 0&&s.set("kind",i.kind),i.mode!==void 0&&s.set("mode",i.mode),i.scope!==void 0&&s.set("scope",i.scope),v(`${S(i.machineId)}/files?${s.toString()}`,j(on))}},$c={gitStatus:(e,t,i="local")=>v(`${S(i)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/git/status`,Ll),gitDiff:(e,t,i,s="local")=>v(dc(s,e,t,i),Nl)},B={...an,...uc,...ri,...ps,...ln,...fc,...hs,...wc,...ot,...kc,...$c};function Pc(e,t="local"){return new WebSocket(Ds(`${Os()}${Ws(t)}/sessions/${e}/events`))}function Tb(e,t,i,s,o="local"){const r=s===void 0?"":`?cols=${encodeURIComponent(String(s.cols))}&rows=${encodeURIComponent(String(s.rows))}`;return new WebSocket(Ds(`${Os()}${Ws(o)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/terminals/${encodeURIComponent(i)}/socket${r}`))}function Cc(e="local"){return new WebSocket(Ds(`${Os()}${Ws(e)}/events`))}function Ws(e){return`/api/machines/${encodeURIComponent(e)}`}function Os(){return`${location.protocol==="https:"?"wss:":"ws:"}//${location.host}`}function Zt(){return{sessions:[],fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,selectedTerminalId:void 0,error:""}}function Ic(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},projects:[],workspaces:[],sessions:[],messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:"core:workspace.files",mainView:"chat",fileTree:[],expandedDirs:{},selectedFilePath:void 0,selectedFileContent:void 0,fileTreeStale:!1,gitStatus:void 0,selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0,gitStale:!1,activeTerminalCount:0,selectedTerminalId:void 0,piWebStatus:void 0,error:""}}function Pi(e,t){return t?.phase==="active"||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}function dn(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}const pn="local";function zi(e,t){return`${e}:${t}`}function hn(e,t){return`${e}:${t}`}function g(e){return e.selectedMachine?.id??pn}class Tc{constructor(t,i,s={}){this.getState=t,this.setState=i,this.api=s.api??ln}async refresh(t=g(this.getState())){this.applyMachineActivitySnapshot(t,Mc(await this.api.workspaceActivity(t)))}applyWorkspaceActivity(t,i=g(this.getState())){const s=this.getState(),o=g(s)===i,r=s.machineActivities[i]??(o?s.workspaceActivities:{}),n=Rc(r,t);this.setState({machineActivities:{...s.machineActivities,[i]:n},...o?{workspaceActivities:n}:{}})}applyMachineActivitySnapshot(t,i){const s=this.getState();this.setState({machineActivities:{...s.machineActivities,[t]:i},...g(s)===t?{workspaceActivities:i}:{}})}}function Mc(e){const t={};for(const i of e.workspaces)dn(i)&&(t[i.cwd]=i);return t}function Rc(e,t){const i={...e};return dn(t)?(i[t.cwd]=t,i):Object.fromEntries(Object.entries(i).filter(([s])=>s!==t.cwd))}class Ac{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.applyStatus=s,this.api=o.api??B,this.pollIntervalMs=o.pollIntervalMs??1e3}dispose(){this.stopPolling()}handleSlashCommand(t){const i=Ec(t);return i===void 0?!1:(i.command==="login"?this.openLogin(i.providerId):this.openLogout(i.providerId),!0)}async openLogin(t){if(t!==void 0&&t!==""){await this.openLoginProvider(t);return}this.setState({authDialog:{step:"method"}})}async chooseLoginMethod(t){try{const{providers:i}=await this.api.authProviders({mode:"login",authType:t,machineId:g(this.getState())});this.setState({authDialog:{step:"providers",mode:"login",authType:t,providers:i}})}catch(i){this.setState({error:String(i)})}}async selectLoginProvider(t,i){const s=this.getState().authDialog;if(s?.step!=="providers")return;const o=s.providers.find(r=>r.id===t&&(i===void 0||r.authType===i));o!==void 0&&(o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}}))}updateApiKey(t){const i=this.getState().authDialog;if(i?.step!=="apiKey")return;const s={...i};delete s.error,this.setState({authDialog:{...s,value:t}})}async saveApiKey(){const t=this.getState().authDialog;if(t?.step!=="apiKey")return;const i=t.value.trim();if(i===""){this.setState({authDialog:{...t,error:"API key is required"}});return}const s={...t};delete s.error,this.setState({authDialog:{...s,saving:!0}});try{await this.api.saveApiKey(t.provider.id,i,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({authDialog:{...t,saving:!1,error:String(o)}})}}async openLogout(t){try{const{providers:i}=await this.api.authProviders({mode:"logout",machineId:g(this.getState())});if(t!==void 0&&t!==""){const s=i.find(o=>o.id===t);s!==void 0&&!this.rejectRemoteOAuth("logout",s)?await this.logoutProvider(s.id):s===void 0&&this.setState({error:`No stored credentials for ${t}`});return}this.setState({authDialog:{step:"logout",providers:i}})}catch(i){this.setState({error:String(i)})}}async logoutProvider(t){const i=this.getState().authDialog,s=i?.step==="logout"?i.providers.find(o=>o.id===t):void 0;if(!(s!==void 0&&this.rejectRemoteOAuth("logout",s)))try{await this.api.logoutProvider(t,g(this.getState())),this.closeDialog(),this.refreshStatus()}catch(o){this.setState({error:String(o)})}}updateOAuthInput(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s={...i};delete s.error,this.setState({authDialog:{...s,inputValue:t}})}async respondOAuth(t){const i=this.getState().authDialog;if(i?.step!=="oauth")return;const s=i.flow.prompt??i.flow.select;if(s===void 0)return;const o=t??i.inputValue??"",r={...i};delete r.error,this.setState({authDialog:{...r,responding:!0}});try{const n=await this.api.respondOAuthFlow(i.flow.flowId,s.requestId,o,g(this.getState()));this.updateOAuthFlow(n)}catch(n){this.setState({authDialog:{...i,responding:!1,error:String(n)}})}}async cancelOAuth(){const t=this.getState().authDialog;if(t?.step!=="oauth"){this.closeDialog();return}this.stopPolling();try{await this.api.cancelOAuthFlow(t.flow.flowId,g(this.getState()))}catch{}this.closeDialog()}closeDialog(){this.stopPolling(),this.setState({authDialog:void 0})}async openLoginProvider(t){try{const{providers:i}=await this.api.authProviders({mode:"login",machineId:g(this.getState())}),s=i.filter(r=>r.id===t);if(s.length===0){this.setState({error:`Auth provider not found: ${t}`});return}if(s.length>1){this.setState({authDialog:{step:"providers",mode:"login",providers:s}});return}const o=s[0];if(o===void 0)return;o.authType==="oauth"?await this.startOAuth(o):this.setState({authDialog:{step:"apiKey",provider:o,value:""}})}catch(i){this.setState({error:String(i)})}}async startOAuth(t){if(!this.rejectRemoteOAuth("login",t))try{const i=await this.api.startOAuthLogin(t.id,g(this.getState()));this.updateOAuthFlow(i),this.startPolling(i.flowId)}catch(i){this.setState({error:String(i)})}}rejectRemoteOAuth(t,i){const s=this.getState().selectedMachine;if(i.authType!=="oauth"||s?.kind!=="remote")return!1;const o=s.baseUrl??"that remote PI WEB instance";return this.setState({error:`OAuth ${t} for remote machines must be configured directly on ${o}.`}),!0}updateOAuthFlow(t){if(t.status==="complete"){this.stopPolling(),this.closeDialog(),this.refreshStatus();return}(t.status==="error"||t.status==="cancelled")&&this.stopPolling();const i=this.getState().authDialog,s=i?.step==="oauth"&&i.flow.flowId===t.flowId?i.inputValue??"":"",o=i?.step==="oauth"?i.flow.prompt?.requestId??i.flow.select?.requestId:void 0,r=t.prompt?.requestId??t.select?.requestId,n=o!==void 0&&o===r,a=n?s:"",c=n&&i?.step==="oauth"?i.responding===!0:!1;this.setState({authDialog:{step:"oauth",flow:t,inputValue:a,responding:c}})}startPolling(t){this.stopPolling(),this.pollTimer=window.setInterval(()=>{this.poll(t)},this.pollIntervalMs)}stopPolling(){this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(t){const i=this.getState().authDialog;if(i?.step!=="oauth"||i.flow.flowId!==t){this.stopPolling();return}try{this.updateOAuthFlow(await this.api.oauthFlow(t,g(this.getState())))}catch(s){this.stopPolling(),this.setState({authDialog:{...i,error:String(s)}})}}async refreshStatus(){const t=this.sessionId();if(t!==void 0)try{this.applyStatus(await this.api.status(t,g(this.getState())))}catch{}}sessionId(){const t=this.getState().selectedSession;if(!(t===void 0||t.archived===!0))return t.id}}function Ec(e){const t=e.trim(),i=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(i===null)return;const s=i[1];if(s!=="login"&&s!=="logout")return;const o=i[2];return o===void 0||o===""?{command:s}:{command:s,providerId:o}}function Mt(e){return e.replaceAll(":",".")}function Dc(e){const t=new URLSearchParams(window.location.search),i=`${e}--`,s={};for(const[o,r]of t.entries()){if(!o.startsWith(i))continue;const n=o.slice(i.length),a=s[n];a===void 0?s[n]=r:Array.isArray(a)?a.push(r):s[n]=[a,r]}return s}function Bi(e,t){const i=Dc(e)[t];return Array.isArray(i)?i[0]:i===""?void 0:i}function re(e,t,i,s){const o=new URL(window.location.href),r=`${e}--${t}`;if(o.searchParams.delete(r),i!=null&&i!=="")if(Array.isArray(i))for(const n of i)o.searchParams.append(r,String(n));else o.searchParams.set(r,String(i));Wc(o,s)}function Wc(e,t){const i=`${e.pathname}${e.search}${e.hash}`,s=`${window.location.pathname}${window.location.search}${window.location.hash}`;i!==s&&(t?.replace===!0?window.history.replaceState({},"",e):window.history.pushState({},"",e))}const Ft=Mt("core:workspace.files");class Oc{constructor(t,i,s,o={}){this.getState=t,this.setState=i,this.updateUrl=s,this.api=o.api??B}async refreshFiles(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=g(this.getState()),o=await this.api.workspaceTree(t.id,i.id,"",s),r=await Promise.all(Object.keys(this.getState().expandedDirs).map(async a=>{try{const c=await this.api.workspaceTree(t.id,i.id,a,s);return[a,c.entries]}catch(c){if(Oo(c))return;throw c}})),n=Object.fromEntries(r.filter(a=>a!==void 0));this.setState({fileTree:o.entries,expandedDirs:n,fileTreeStale:!1,error:""})}catch(s){this.setState({error:String(s)})}}async expandDir(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){if(this.getState().expandedDirs[t]!==void 0){this.setState({expandedDirs:_c(this.getState().expandedDirs,t)});return}try{const o=await this.api.workspaceTree(i.id,s.id,t,g(this.getState()));this.setState({expandedDirs:{...this.getState().expandedDirs,[t]:o.entries},error:""})}catch(o){this.setState({error:String(o)})}}}async selectFile(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),re(Ft,"file",t),this.updateUrl({replace:!0}),await this.restoreFile(t)}selectDirectory(t){this.setState({selectedFilePath:t,selectedFileContent:void 0,workspaceTool:"core:workspace.files",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.files"}),re(Ft,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}async restoreFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0)){this.setState({selectedFilePath:t,selectedFileContent:void 0});try{const o=await this.api.workspaceFile(i.id,s.id,t,g(this.getState()));this.getState().selectedFilePath===t&&this.setState({selectedFileContent:o,error:""})}catch(o){if(this.getState().selectedFilePath!==t)return;if(Oo(o)){this.setState({selectedFilePath:void 0,selectedFileContent:void 0,error:""}),re(Ft,"file",void 0,{replace:!0}),this.updateUrl({replace:!0});return}this.setState({error:String(o)})}}}async uploadFiles(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t.length===0))try{const o=g(this.getState()),r=Lc(this.getState()),n=[];for(const c of t){const p=Nc(r,jc(c));await this.api.uploadWorkspaceFile(i.id,s.id,p,c,o),n.push(p)}await this.refreshFiles();const a=n.at(-1);a!==void 0&&await this.selectFile(a),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async createFile(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceFile(i.id,s.id,t,g(this.getState())),await this.refreshFiles(),await this.selectFile(t),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async createDirectory(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0||t===""))try{await this.api.createWorkspaceDirectory(i.id,s.id,t,g(this.getState())),await this.refreshFiles(),this.selectDirectory(t),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async moveSelectedPath(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace,o=this.getState().selectedFilePath;if(!(i===void 0||s===void 0||o===void 0||o===""||t===""))try{const r=g(this.getState());Ui(this.getState())==="directory"?(await this.api.moveWorkspaceDirectory(i.id,s.id,o,t,r),await this.refreshFiles(),this.selectDirectory(t)):(await this.api.moveWorkspaceFile(i.id,s.id,o,t,r),await this.refreshFiles(),await this.selectFile(t)),this.setState({error:""})}catch(r){this.setState({error:String(r)})}}async deleteSelectedPath(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""))try{const o=g(this.getState());Ui(this.getState())==="directory"?await this.api.deleteWorkspaceDirectory(t.id,i.id,s,o):await this.api.deleteWorkspaceFile(t.id,i.id,s,o),await this.refreshFiles(),this.clearSelection(),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}async downloadSelectedFile(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace,s=this.getState().selectedFilePath;if(!(t===void 0||i===void 0||s===void 0||s===""||Ui(this.getState())==="directory"))try{await this.api.downloadWorkspaceFile(t.id,i.id,s,g(this.getState())),this.setState({error:""})}catch(o){this.setState({error:String(o)})}}clearSelection(){this.setState({selectedFilePath:void 0,selectedFileContent:void 0}),re(Ft,"file",void 0,{replace:!0}),this.updateUrl({replace:!0})}}function Oo(e){const t=String(e);return t.includes("Path does not exist")||t.includes("ENOENT")||t.includes("no such file or directory")}function _c(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Lc(e){const t=e.selectedFilePath;if(t===void 0||t==="")return"";if(un(e.fileTree,e.expandedDirs,t)?.type==="directory")return t;const s=t.lastIndexOf("/");return s===-1?"":t.slice(0,s)}function Ui(e){const t=e.selectedFilePath;return t===void 0?"file":un(e.fileTree,e.expandedDirs,t)?.type==="directory"?"directory":"file"}function un(e,t,i){const s=e.find(o=>o.path===i);if(s!==void 0)return s;for(const o of Object.values(t)){const r=o.find(n=>n.path===i);if(r!==void 0)return r}}function jc(e){return e.name.split(/[\\/]+/u).filter(t=>t!=="").at(-1)??e.name}function Nc(e,t){return e===""?t:`${e}/${t}`}const _o=Mt("core:workspace.git");class Fc{constructor(t,i,s){this.getState=t,this.setState=i,this.updateUrl=s}dispose(){this.pollTimer!==void 0&&window.clearInterval(this.pollTimer),this.pollTimer=void 0}async refreshGit(){const t=this.getState().selectedProject,i=this.getState().selectedWorkspace;if(!(t===void 0||i===void 0))try{const s=await B.gitStatus(t.id,i.id,g(this.getState()));this.setState({gitStatus:s,gitStale:!1,error:""});const o=this.getState().selectedDiffPath;o!==void 0&&(s.files.some(r=>r.path===o)?await this.refreshDiff(o):(this.setState({selectedDiffPath:void 0,selectedDiff:void 0,selectedStagedDiff:void 0}),re(_o,"diff",void 0,{replace:!0})))}catch(s){this.setState({error:String(s)})}}async selectDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0,workspaceTool:"core:workspace.git",mainView:this.getState().mainView==="chat"?"chat":"core:workspace.git"}),re(_o,"diff",t),this.updateUrl({replace:!0}),await this.refreshDiff(t)}async restoreDiff(t){this.setState({selectedDiffPath:t,selectedDiff:void 0,selectedStagedDiff:void 0}),await this.refreshDiff(t)}async refreshDiff(t){const i=this.getState().selectedProject,s=this.getState().selectedWorkspace;if(!(i===void 0||s===void 0))try{const[o,r]=await Promise.all([B.gitDiff(i.id,s.id,{path:t},g(this.getState())),B.gitDiff(i.id,s.id,{path:t,staged:!0},g(this.getState()))]);this.setState({selectedDiff:o,selectedStagedDiff:r,error:""})}catch(o){this.setState({error:String(o)})}}updatePolling(){this.dispose();const t=this.getState();(t.workspaceTool==="core:workspace.git"||t.mainView==="core:workspace.git")&&(this.pollTimer=window.setInterval(()=>{this.refreshGit()},8e3))}}class zc{constructor(t,i,s,o){this.getState=t,this.setState=i,this.updateUrl=s,this.projects=o}async loadMachines(t){this.setState({error:"",isLoadingMachines:!0});try{const i=await B.machines(),s=await this.selectInitialMachine(i,t),o=new Set(i.map(r=>r.id));this.setState({machines:i,selectedMachine:s,machineActivities:Bc(this.getState().machineActivities,o)}),this.refreshMachineHealthFor(i)}catch(i){this.setState({error:String(i)})}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(t,i={}){this.getState().selectedMachine?.id!==t.id&&(this.setState({selectedMachine:t,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:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},activeTerminalCount:0,...Zt()}),i.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(t.id))}async addMachine(t){this.setState({error:""});try{const i=await B.addMachine(t);return this.setState({machines:[...this.getState().machines.filter(s=>s.id!==i.id),i]}),await this.selectMachine(i),i}catch(i){this.setState({error:String(i)});return}}async deleteMachine(t=this.getState().selectedMachine,i={}){if(t!==void 0){if(t.kind==="local"){this.setState({error:"The local machine cannot be removed."});return}try{const s=this.getState().selectedMachine?.id===t.id;await B.deleteMachine(t.id);const o=this.getState().machines.filter(n=>n.id!==t.id),r=o.find(n=>n.id==="local")??o[0];return this.setState({machines:o,machineStatuses:Lo(this.getState().machineStatuses,t.id),machineActivities:Lo(this.getState().machineActivities,t.id)}),s&&r!==void 0?(i.selectFallback===!1||await this.selectMachine(r),r):void 0}catch(s){this.setState({error:String(s)});return}}}async refreshMachineHealth(t=this.getState().selectedMachine?.id??"local"){try{const i=await B.health(t);this.setState({machineStatuses:{...this.getState().machineStatuses,[i.machineId]:i}})}catch(i){this.setState({error:String(i)})}}async selectInitialMachine(t,i){const s=t.find(n=>n.id===(i??"local"));if(s?.kind!=="remote")return s??this.localMachine(t);const o=await this.safeRemoteHealth(s);if(o.ok)return s;const r=this.localMachine(t);return this.setState({error:`${s.name} is offline; showing ${r?.name??"another machine"} instead.`,machineStatuses:{...this.getState().machineStatuses,[o.machineId]:o}}),r??s}async safeRemoteHealth(t){try{return await B.health(t.id)}catch(i){return{machineId:t.id,ok:!1,checkedAt:new Date().toISOString(),status:"offline",error:i instanceof Error?i.message:String(i)}}}localMachine(t){return t.find(i=>i.id==="local")??t[0]}async refreshMachineHealthFor(t){const i=await Promise.allSettled(t.map(o=>B.health(o.id))),s=Object.fromEntries(i.flatMap(o=>o.status==="fulfilled"?[[o.value.machineId,o.value]]:[]));Object.keys(s).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...s}})}}function Lo(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function Bc(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>t.has(i)))}class Uc{constructor(t,i,s){this.getState=t,this.setState=i,this.workspaces=s}async loadProjects(){const t=g(this.getState());this.setState({error:"",isLoadingProjects:!0});try{const i=await B.projects(t);if(g(this.getState())!==t)return;const s=new Set(i.map(r=>r.id)),o=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([r])=>s.has(r)));this.setState({projects:i,workspacesByProjectId:o})}catch(i){g(this.getState())===t&&this.setState({error:String(i)})}finally{g(this.getState())===t&&this.setState({isLoadingProjects:!1})}}async addProject(t,i){if(t.trim()!=="")try{const s=await B.addProject(t.trim(),void 0,i,g(this.getState())),o=this.getState().projects;this.setState({projects:[...o.filter(r=>r.id!==s.id),s],projectDialogOpen:!1}),await this.workspaces.selectProject(s)}catch(s){this.setState({error:String(s)})}}async closeProject(t){try{await B.closeProject(t,g(this.getState())),this.workspaces.forgetProject(t);const i=this.getState();this.setState({projects:i.projects.filter(s=>s.id!==t)}),i.selectedProject?.id===t&&this.workspaces.clearSelection()}catch(i){this.setState({error:String(i)})}}}const us="pi-web:cached-new-sessions:v1",Hc="browserCachedNew",lt="local";function Rt(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function jo(e,t=lt,i=Rt()){if(e.messageCount!==0||e.archived===!0)return;const s=_s(i).filter(o=>o.id!==e.id||o.machineId!==t);Ls([fs(e,t),...s],i)}function fs(e,t=lt){return{...e,browserCachedNew:!0,machineId:t}}function No(e,t=lt,i=Rt()){const s=_s(i).filter(o=>o.id!==e||o.machineId!==t);Ls(s,i)}function qc(e,t,i=lt,s=Rt()){const o=new Set(t.map(c=>c.id)),r=_s(s),n=r.filter(c=>c.machineId!==i||!o.has(c.id));return n.length!==r.length&&Ls(n,s),[...n.filter(c=>c.machineId===i&&c.cwd===e),...t]}function Ce(e){return e===void 0?!1:Gc(e)&&e.browserCachedNew===!0}function Kc(e){return{id:e.id,path:e.path,cwd:e.cwd,...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:lt},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function _s(e=Rt()){try{const t=e?.getItem(us);if(t==null||t==="")return[];const i=JSON.parse(t);return Array.isArray(i)?i.flatMap(s=>Vc(s)):[]}catch{return[]}}function Ls(e,t=Rt()){try{e.length===0?t?.removeItem(us):t?.setItem(us,JSON.stringify(e))}catch{}}function Vc(e){if(!Jc(e))return[];const t=et(e,"id"),i=et(e,"path"),s=et(e,"cwd"),o=et(e,"created"),r=et(e,"modified"),n=et(e,"firstMessage"),a=Zc(e,"messageCount");if(t===void 0||i===void 0||s===void 0||o===void 0||r===void 0||n===void 0||a!==0)return[];const c=Hi(e,"name"),p=Hi(e,"parentSessionPath"),u=Hi(e,"machineId")??lt;return[{id:t,path:i,cwd:s,...c===void 0?{}:{name:c},created:o,modified:r,messageCount:a,firstMessage:n,...p===void 0?{}:{parentSessionPath:p},machineId:u,browserCachedNew:!0}]}function Gc(e){return Hc in e}function Jc(e){return typeof e=="object"&&e!==null}function et(e,t){const i=e[t];return typeof i=="string"?i:void 0}function Hi(e,t){const i=e[t];return i===void 0||typeof i!="string"?void 0:i}function Zc(e,t){const i=e[t];return typeof i=="number"?i:void 0}function Qc(e){return hd(e.flatMap(js)).filter(t=>t.parts.length>0)}function Ie(e,t){return{role:e,parts:[{type:"text",text:t}]}}function zt(e,t){const i=od(t);return i===void 0?e:{...e,meta:i}}function Xc(e,t,i){if(i==="")return e;const s=e.at(-1),o=s?.parts.at(-1);return s?.role===t&&o?.type==="text"?[...e.slice(0,-1),{...s,parts:[...s.parts.slice(0,-1),{...o,text:o.text+i}]}]:s?.role===t?[...e.slice(0,-1),{...s,parts:[...s.parts,{type:"text",text:i}]}]:[...e,Ie(t,i)]}function Yc(e,t){if(t==="")return e;const i=e.at(-1),s=i?.parts.at(-1);return i?.role==="assistant"&&s?.type==="thinking"?[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+t}]}]:i?.role==="assistant"?[...e.slice(0,-1),{...i,parts:[...i.parts,{type:"thinking",text:t}]}]:[...e,{role:"assistant",parts:[{type:"thinking",text:t}]}]}function js(e){if(ed(e))return[e];if(W(e,"role")==="bashExecution")return[zt(ad(e),e)];const t=ld(W(e,"role")),i=cd(pe(e,"content"),e),s=t==="user"?td(i):void 0;if(s!==void 0)return s.map(a=>zt(a,e));const o=sd(e);if(t==="tool")return[zt({role:t,parts:i,...o===void 0?{}:{source:o}},e)];const r=i.filter(a=>a.type!=="empty"),n=t==="assistant"&&r.length>0&&r.every(a=>a.type==="skillRead")?"skill":t;return r.length>0?[zt({role:n,parts:r,...o===void 0?{}:{source:o}},e)]:[]}function ed(e){const t=W(e,"role");return(t==="user"||t==="assistant"||t==="tool"||t==="system"||t==="bash"||t==="skill")&&Array.isArray(pe(e,"parts"))}function td(e){if(e.length!==1||e[0]?.type!=="text")return;const t=id(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 id(e){const t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;const i=t[4]?.trim();return{name:t[1]??"skill",location:t[2]??"",content:t[3]??"",...i===void 0||i===""?{}:{userMessage:i}}}function sd(e){const t=W(e,"source");if(t==="compaction"||t==="branch_summary")return t}function od(e){const t=rd(pe(e,"timestamp")),i=nd(e);if(!(t===void 0&&i===void 0))return{...t===void 0?{}:{timestamp:t},...i===void 0?{}:{model:i}}}function rd(e){if(typeof e=="number"&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!="string"||e==="")return;const t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function nd(e){if(W(e,"role")!=="assistant")return;const t=W(e,"provider"),i=W(e,"model"),s=W(e,"responseModel");if(!((t===void 0||t==="")&&(i===void 0||i==="")&&(s===void 0||s==="")))return{...t===void 0||t===""?{}:{provider:t},...i===void 0||i===""?{}:{id:i},...s===void 0||s===""?{}:{responseId:s}}}function ad(e){const t=W(e,"command")??"",i=Qt(e,"excludeFromContext")===!0?["不加入上下文","",`$ ${t}`]:[`$ ${t}`],s=pe(e,"output");s!=null&&i.push("",ai(s));const o=pe(e,"exitCode");o!=null&&i.push("",`exit ${ai(o)}`),Qt(e,"cancelled")===!0&&i.push("","cancelled"),Qt(e,"truncated")===!0&&i.push("","output truncated");const r=W(e,"fullOutputPath");return r!==void 0&&r!==""&&i.push("",`完整输出:${r}`),{role:"bash",parts:[{type:"text",text:i.join(`
|
|
5
|
+
`)}]}}function ld(e){return e==="assistant"?"assistant":e==="user"?"user":e==="toolResult"?"tool":"system"}function cd(e,t){return typeof e=="string"?e!==""?[{type:"text",text:e}]:[]:Array.isArray(e)?e.flatMap(i=>{const s=W(i,"type"),o=W(i,"text");if(s==="text")return o!==void 0&&o!==""?[{type:"text",text:o}]:[];if(s==="thinking"){const r=W(i,"thinking")??o;return r!==void 0&&r!==""?[{type:"thinking",text:r}]:[]}if(s==="toolCall"){const r=W(i,"name")??"tool",n=pe(i,"arguments"),a=r==="read"?pd(W(n,"path")):void 0;if(a!==void 0)return[{type:"skillRead",...a}];const c=W(i,"id");return[{type:"toolCall",...c===void 0?{}:{toolCallId:c},toolName:r,summary:At(n),...n===void 0?{}:{args:n}}]}return s==="image"?[{type:"text",text:"[image]"}]:Fo(i)}).map(i=>i.type==="text"&&W(t,"role")==="toolResult"?dd(i.text,t):i):Fo(e)}function dd(e,t){const i=W(t,"toolCallId"),s=pe(t,"content"),o=pe(t,"details");return{type:"toolResult",...i===void 0?{}:{toolCallId:i},toolName:W(t,"toolName")??"tool",text:e,...s===void 0?{}:{content:s},...o===void 0?{}:{details:o},isError:Qt(t,"isError")===!0}}function pd(e){if(e===void 0||e==="")return;const t=e.replace(/\\/g,"/");if(!t.endsWith("/SKILL.md")&&t!=="SKILL.md")return;const i=t.split("/").at(-2);if(!(i===void 0||i===""))return{name:i,path:e}}function hd(e){const t=[],i=new Map;for(const s of e){let o=[];const r={...s.source===void 0?{}:{source:s.source},...s.meta===void 0?{}:{meta:s.meta}},n=()=>{o.length!==0&&(t.push({role:s.role,parts:o,...r}),o=[])};for(const a of s.parts){if(a.type==="toolCall"){n();const c=ud(a),p=t.length;t.push({role:"tool",parts:[c],...r}),c.toolCallId!==void 0&&i.set(c.toolCallId,{lineIndex:p,partIndex:0});continue}if(a.type==="toolResult"){const c=a.toolCallId===void 0?void 0:i.get(a.toolCallId);if(c!==void 0&&fd(t,c,a)){i.delete(a.toolCallId??"");continue}}o.push(a)}n()}return t}function ud(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 fd(e,t,i){const s=e[t.lineIndex],o=s?.parts[t.partIndex];if(s===void 0||o?.type!=="toolExecution")return!1;const r=ni(i.details)??o.preview,n={...o,status:i.isError?"error":"success",resultText:i.text,...i.content===void 0?{}:{content:i.content},...i.details===void 0?{}:{details:i.details},...r===void 0?{}:{preview:r}};return e[t.lineIndex]={...s,parts:[...s.parts.slice(0,t.partIndex),n,...s.parts.slice(t.partIndex+1)]},!0}function ni(e){const t=pe(e,"preview");if(!Ns(t))return;const i=W(t,"diff"),s=W(t,"error"),o=md(t,"firstChangedLine");if(!(i===void 0&&s===void 0&&o===void 0))return{...i===void 0?{}:{diff:i},...s===void 0?{}:{error:s},...o===void 0?{}:{firstChangedLine:o}}}function Fo(e){return e==null?[]:typeof e=="object"?[{type:"text",text:At(e)}]:[{type:"text",text:ai(e)}]}function At(e){if(!Ns(e))return ai(e);const t=W(e,"command");if(t!==void 0)return t;const i=W(e,"path");if(i!==void 0)return i;if(typeof e.oldText=="string"&&typeof e.newText=="string")return"edit text replacement";const s=e.edits;return Array.isArray(s)?`${String(s.length)} 处编辑`:Object.entries(e).filter(([,r])=>r!=null).slice(0,3).map(([r,n])=>`${r}: ${gd(n)}`).join(" · ")}function gd(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)} 项`:typeof e=="object"&&e!==null?"object":""}function Ns(e){return typeof e=="object"&&e!==null}function pe(e,t){return Ns(e)?e[t]:void 0}function W(e,t){const i=pe(e,t);return typeof i=="string"?i:void 0}function Qt(e,t){const i=pe(e,t);return typeof i=="boolean"?i:void 0}function md(e,t){const i=pe(e,t);return typeof i=="number"&&Number.isFinite(i)?i:void 0}function ai(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"?String(e):""}const vd="pi-web:prompt-draft:";function li(e){return`${vd}${e}`}function Ci(){try{return typeof localStorage>"u"?void 0:localStorage}catch{return}}function fn(e,t=Ci()){try{return t?.getItem(li(e))??""}catch{return""}}function ci(e,t,i=Ci()){try{t?i?.setItem(li(e),t):i?.removeItem(li(e))}catch{}}function Fs(e,t=Ci()){try{t?.removeItem(li(e))}catch{}}function bd(e,t,i=Ci()){const s=fn(e,i);s!==""&&(ci(t,s,i),Fs(e,i))}function wd(e,t){return Ie("bash",`${t===!0?`不加入上下文
|
|
6
|
+
|
|
7
|
+
`:""}$ ${e}`)}function yd(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return[...e,Ie("bash",t)];const o=Sd(s.text)?"":`
|
|
8
|
+
|
|
9
|
+
`;return[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:s.text+o+t}]}]}function xd(e,t){const i=e.at(-1),s=i?.parts.at(-1);if(i?.role!=="bash"||s?.type!=="text")return e;const o=[];return!s.text.includes(`
|
|
10
|
+
|
|
11
|
+
`)&&(t.output===void 0||t.output==="")&&o.push("(no output)"),t.isError===!0&&o.push(t.output??"Bash 命令失败"),t.exitCode!=null&&o.push(`exit ${String(t.exitCode)}`),t.cancelled===!0&&o.push("cancelled"),t.truncated===!0&&o.push("output truncated"),t.fullOutputPath!==void 0&&t.fullOutputPath!==""&&o.push(`完整输出:${t.fullOutputPath}`),o.length===0?e:[...e.slice(0,-1),{...i,parts:[...i.parts.slice(0,-1),{...s,text:`${s.text}
|
|
12
|
+
|
|
13
|
+
${o.join(`
|
|
14
|
+
`)}`}]}]}function Sd(e){const t=e.lastIndexOf(`
|
|
15
|
+
|
|
16
|
+
`),i=e.lastIndexOf("$ ");return t>i}function kd(e,t){if(t.type==="message.append")return Dd(e,t.message);if(t.type==="assistant.delta")return Xc(e,"assistant",t.text);if(t.type==="assistant.thinking.delta")return Yc(e,t.text);if(t.type==="tool.start")return Id(e,t);if(t.type==="tool.update")return mn(e,t.toolCallId,i=>Td(i,t));if(t.type==="tool.end")return gn(e,t.toolCallId,t.toolName,At(t.content),t.text,t.isError,t.content,t.details);if(t.type==="shell.start")return[...e,wd(t.command,t.excludeFromContext)];if(t.type==="shell.chunk")return yd(e,t.chunk);if(t.type==="shell.end")return xd(e,t);if(t.type==="command.output")return[...e,Ie(t.level==="error"?"system":"tool",t.message)];if(t.type==="session.error")return[...e,Ie("system",t.message)];if(t.type==="message.end")return t.message===void 0?void 0:$d(e,t.message)}function $d(e,t){const i=Md(t);if(i!==void 0)return gn(e,i.toolCallId,i.toolName,At(i.content),i.text,i.isError,i.content,i.details);const s=js(t)[0];if(s===void 0)return;const o=s.role==="assistant"?Pd(s):s;if(o.parts.length===0)return e;const r=Rd(e,o);if(r>=0)return[...e.slice(0,r),o,...e.slice(r+1)];const n=e.at(-1);return n?.role!==o.role?[...e,o]:o.role==="assistant"||Ed(n,o)?[...e.slice(0,-1),o]:[...e,o]}function Pd(e){return{...e,parts:e.parts.filter(t=>t.type!=="toolCall")}}function Cd(e){if(e===void 0||e==="")return;const t=e.replace(/\\/g,"/");if(!t.endsWith("/SKILL.md")&&t!=="SKILL.md")return;const i=t.split("/").at(-2);if(!(i===void 0||i===""))return{name:i,path:e}}function Id(e,t){const i=t.toolName==="read"?Cd(qe(t.args,"path")):void 0;if(i!==void 0)return Wd(e,{role:"skill",parts:[{type:"skillRead",...i}]});const s={type:"toolExecution",...t.toolCallId===""?{}:{toolCallId:t.toolCallId},toolName:t.toolName,summary:t.summary||At(t.args),...t.args===void 0?{}:{args:t.args},status:"running"};return[...e,{role:"tool",parts:[s]}]}function Td(e,t){const i=ni(t.details)??e.preview;return{...e,status:e.status==="pending"?"running":e.status,...t.text===""?{}:{resultText:t.text},...t.content===void 0?{}:{content:t.content},...t.details===void 0?{}:{details:t.details},...i===void 0?{}:{preview:i}}}function gn(e,t,i,s,o,r,n,a){const c=mn(e,t,h=>{const f=ni(a)??h.preview;return{...h,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...f===void 0?{}:{preview:f}}});if(c!==e)return c;const p=ni(a),u={type:"toolExecution",...t===void 0||t===""?{}:{toolCallId:t},toolName:i,summary:s,status:r?"error":"success",resultText:o,...n===void 0?{}:{content:n},...a===void 0?{}:{details:a},...p===void 0?{}:{preview:p}};return[...e,{role:"tool",parts:[u]}]}function mn(e,t,i){if(t===void 0||t==="")return e;for(let s=e.length-1;s>=0;s--){const o=e[s];if(o===void 0)continue;const r=o.parts.findIndex(c=>c.type==="toolExecution"&&c.toolCallId===t);if(r<0)continue;const n=o.parts[r];if(n?.type!=="toolExecution")continue;const a={...o,parts:[...o.parts.slice(0,r),i(n),...o.parts.slice(r+1)]};return[...e.slice(0,s),a,...e.slice(s+1)]}return e}function Md(e){if(qe(e,"role")!=="toolResult")return;const t=qe(e,"toolCallId"),i=pi(e,"content");return{...t===void 0?{}:{toolCallId:t},toolName:qe(e,"toolName")??"tool",text:vn(i),isError:_d(e,"isError")===!0,content:i,details:pi(e,"details")}}function vn(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.map(vn).filter(t=>t!=="").join(`
|
|
17
|
+
`);if(typeof e=="object"&&e!==null){const t=qe(e,"text")??qe(e,"content")??qe(e,"output");if(t!==void 0)return t}return""}function Rd(e,t){const i=di(t);if(i.length===0)return-1;for(let s=e.length-1;s>=0;s--){const o=e[s];if(o?.role!=="skill")continue;const r=di(o);if(bn(r,i))return s}return-1}function di(e){return e===void 0?[]:e.parts.filter(t=>t.type==="skillRead")}function bn(e,t){return e.length===t.length&&e.every((i,s)=>Ad(i,t[s]))}function Ad(e,t){return t===void 0?!1:zo(e.path)===zo(t.path)||e.name===t.name}function zo(e){return e.replace(/\\/g,"/")}function Ed(e,t){return Bo(e)===Bo(t)}function Bo(e){return e.parts.filter(t=>t.type==="text").map(t=>t.text).join(`
|
|
18
|
+
|
|
19
|
+
`)}function Dd(e,t){const i=js(t);return i.length===0?e:[...e,...i]}function Wd(e,t){const i=e.at(-1);return t.role==="skill"&&bn(di(i),di(t))?e:i?.role===t.role&&t.role!=="skill"?[...e.slice(0,-1),{...i,parts:[...i.parts,...t.parts]}]:[...e,t]}function Od(e){return typeof e=="object"&&e!==null}function pi(e,t){return Od(e)?e[t]:void 0}function qe(e,t){const i=pi(e,t);return typeof i=="string"?i:void 0}function _d(e,t){const i=pi(e,t);return typeof i=="boolean"?i:void 0}const Ld="pi-web:chat-history:v2:",jd=1800*1e3;function Nd(e){try{const t=sessionStorage.getItem(gs(e));if(t===null||t==="")return;const i=JSON.parse(t);if(!Hd(i))return;if(Date.now()-i.savedAt>jd){sessionStorage.removeItem(gs(e));return}return{messages:i.messages,start:i.start,total:i.total}}catch{return}}function Fd(e,t){try{sessionStorage.setItem(gs(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function zd(e,t){if(e===void 0||!ms(e))return t;if(!ms(t))return e;if(Bd(e,t))return t;const i=Math.min(e.start,t.start),s=Math.max(e.start+e.messages.length,t.start+t.messages.length),o=new Array(s-i);return Uo(o,i,e),Uo(o,i,t),Ud(o)?t:{start:i,total:Math.max(e.total,t.total),messages:o}}function Bd(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function Ud(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function Uo(e,t,i){i.messages.forEach((s,o)=>{e[i.start-t+o]=s})}function gs(e){return`${Ld}${e}`}function Hd(e){if(typeof e!="object"||e===null||!("messages"in e)||!("start"in e)||!("total"in e)||!("savedAt"in e))return!1;const{messages:t,start:i,total:s,savedAt:o}=e;return Array.isArray(t)&&typeof i=="number"&&typeof s=="number"&&typeof o=="number"&&ms({messages:t,start:i,total:s})}function ms(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(qd)}function qd(e){return typeof e=="object"&&e!==null&&"role"in e&&"parts"in e&&!("content"in e)&&typeof e.role=="string"&&Array.isArray(e.parts)}const Kd={read:Nd,write:Fd};class Vd{constructor(t=Kd){this.cache=t,this.rawHistoryPages=new Map}cachedView(t){return Ho(this.rawHistoryPage(t))}mergeHistory(t,i){const s=zd(this.rawHistoryPage(t),i);return this.rawHistoryPages.set(t,s),this.cache.write(t,s),Ho(s)}applyLiveEvent(t,i){return kd(t,i)}rawHistoryPage(t){const i=this.rawHistoryPages.get(t)??this.cache.read(t);return i!==void 0&&this.rawHistoryPages.set(t,i),i}}function Ho(e){const t=e?.start??0;return{messages:Qc(e?.messages??[]),messagePageStart:t,messagePageEnd:t+(e?.messages.length??0),messagePageTotal:e?.total??0}}function zs(e){const t=e.trimStart();return t.startsWith("!@")?{kind:"file"}:t.startsWith("!")?{kind:"shell",excludeFromContext:t.startsWith("!!")}:wn(e).startsWith("/")?{kind:"command"}:Jd(e)?{kind:"file"}:{kind:"normal"}}function Gd(e){return zs(e).kind==="shell"}function wn(e){const t=Math.max(e.lastIndexOf(" "),e.lastIndexOf(`
|
|
20
|
+
`))+1;return e.slice(t)}function Jd(e){const t=wn(e);if(t.startsWith("@")||t.startsWith("!@"))return!0;const i=e.length-t.length;if(e.slice(0,i).endsWith("@ "))return!0;const s=e.lastIndexOf('"');if(s===-1)return!1;const o=e.slice(0,s);return o.endsWith("@")||o.endsWith("@ ")||o.endsWith("!@")}class Zd{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId="local"}connect(t,i,s,o="local"){this.close(),this.machineId=o,this.sessionId=t,this.onEvent=i,this.onReconnect=s,this.shouldReconnect=!0,this.open()}setHandler(t){this.onEvent=t}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),xn(this.socket),this.socket=void 0,this.sessionId=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.hasOpened=!1,this.machineId="local"}open(){if(this.sessionId===void 0||this.sessionId===""||!this.shouldReconnect)return;const t=Pc(this.sessionId,this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.hasOpened&&this.onReconnect?.(),this.hasOpened=!0},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await yn(t);Qd(i)&&this.onEvent?.(i)}}class qo{constructor(){this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId="local"}connect(t,i,s="local"){this.close(),this.machineId=s,this.onEvent=t,this.onOpen=i,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),xn(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId="local"}open(){if(!this.shouldReconnect)return;const t=Cc(this.machineId);this.socket=t,t.onopen=()=>{this.reconnectDelay=500,this.onOpen?.()},t.onmessage=i=>{this.handleMessage(i.data)},t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0),this.scheduleReconnect()}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);const t=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},t)}async handleMessage(t){const i=await yn(t);Yd(i)&&this.onEvent?.(i)}}function Qd(e){const t=Bs(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","pi.event"].includes(t)}function Xd(e){const t=Bs(e);return t==="status.update"||t==="activity.update"||t==="session.name"}function Yd(e){const t=Bs(e);return Xd(e)||t==="terminal.created"||t==="terminal.exited"||t==="terminal.closed"||t==="workspace.activity"}function Bs(e){if(typeof e!="object"||e===null||!("type"in e))return"";const t=e.type;return typeof t=="string"?t:""}async function yn(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 xn(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 Et(){try{return typeof sessionStorage>"u"?void 0:sessionStorage}catch{return}}class Ii{constructor(t,i,s=Et()){this.storageKey=t,this.parseValue=i,this.storage=s,this.values=new Map;for(const[o,r]of ep(t,i,s))this.values.set(o,r)}get(t){return this.values.get(t)}set(t,i){this.values.set(t,i),this.save()}delete(t){this.values.delete(t),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}const t={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(t))}catch{}}}function Us(e){return typeof e=="string"&&e!==""?e:void 0}function ep(e,t,i){try{const s=i?.getItem(e);if(s==null||s==="")return[];const o=JSON.parse(s);if(!tp(o))return[];const r=[];for(const n of o.entries){const a=n[0],c=t(n[1]);c!==void 0&&r.push([a,c])}return r}catch{return[]}}function tp(e){return!ip(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(t=>Array.isArray(t)&&t.length===2&&typeof t[0]=="string"&&t[0]!=="")}function ip(e){return typeof e=="object"&&e!==null}class sp{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}const op="pi-web:session-selection:v1";class rp{constructor(t=Et()){this.sessionIdsByCwd=new Ii(op,Us,t)}latestSessionId(t){return this.sessionIdsByCwd.get(t)}rememberSession(t){this.sessionIdsByCwd.set(t.cwd,t.id)}forgetWorkspace(t){this.sessionIdsByCwd.delete(t)}}function np(e,t){const i=t?.targetSessionId;if(i!==void 0&&i!=="")return lp(e,i);const s=t?.latestSessionId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>o.archived!==!0):e.find(o=>o.archived!==!0)}function ap(e,t){return t?.archived!==!0?!1:!e.some(i=>i.archived!==!0)}function lp(e,t){return e.find(i=>i.id===t||i.id.startsWith(t))}function cp(e,t,i){return Sn(e,[t],i)}function Sn(e,t,i){const s=new Set(t);return e.map(o=>s.has(o.id)?{...o,archived:!0,archivedAt:i}:o)}function dp(e,t,i){return kn(e,t,[i])}function kn(e,t,i){if(t===void 0||!i.includes(t))return{type:"unchanged"};const s=new Set(i),o=e.find(r=>!s.has(r.id)&&r.archived!==!0);return o===void 0?{type:"clear"}:{type:"select",session:o}}const ft=100;class pp{constructor(t,i,s,o=new sp,r={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessionSelection=o,this.selectionSeq=0,this.pendingTranscriptEvents=[],this.socket=r.socket??new Zd,this.api=r.api??B,this.transcripts=r.transcripts??new Vd}applyGlobalEvent(t){t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):this.applySessionName(t.sessionId,t.name)}dispose(){this.socket.close(),this.clearPendingTranscriptEvents()}clearActiveSession(){this.selectionSeq+=1,this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0})}deselectSession(t){const i=this.getState(),s=i.selectedSession?.cwd??i.selectedWorkspace?.path;t?.forgetRememberedSelection===!0&&s!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(s)),this.clearActiveSession(),t?.updateUrl!==!1&&this.updateUrl()}clearSelectionAfterArchivedCollapse(){const t=this.getState();ap(t.sessions,t.selectedSession)&&this.deselectSession({forgetRememberedSelection:!0})}async startSession(){const t=this.getState().selectedWorkspace;if(t)try{const i=g(this.getState()),s=await this.api.startSession(t.path,i);jo(s,i);const o=fs(s,i);this.setState({sessions:[o,...this.getState().sessions]}),await this.selectSession(o)}catch(i){this.setState({error:String(i)})}}preferredSession(t,i,s){return np(i,{targetSessionId:s,latestSessionId:this.sessionSelection.latestSessionId(this.workspaceSelectionKey(t))})}async selectSession(t,i){this.sessionSelection.rememberSession({...t,cwd:this.workspaceSelectionKey(t.cwd)});const s=++this.selectionSeq;this.socket.close(),this.catchupStreamSessionId=void 0,this.clearPendingTranscriptEvents();const o=this.sessionCacheKey(t.id),r=this.transcripts.cachedView(o);this.setState({selectedSession:t,...r,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:t.archived===!0?void 0:this.getState().sessionStatuses[t.id],activity:t.archived===!0?void 0:this.getState().sessionActivities[t.id]});try{if(t.archived===!0){const h=await this.api.messages(t.id,{limit:ft},g(this.getState()));if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const f=this.transcripts.mergeHistory(o,h);this.setState({...f,isLoadingEarlierMessages:!1,isReceivingPartialStream:!1,status:void 0,activity:void 0}),i?.updateUrl!==!1&&this.updateUrl();return}const n=[];this.socket.connect(t.id,h=>n.push(h),()=>{this.refreshSelectedSession(t.id)},g(this.getState()));const[a,c]=await Promise.all([this.api.messages(t.id,{limit:ft},g(this.getState())),this.api.status(t.id,g(this.getState()))]);if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;const p=this.transcripts.mergeHistory(o,a),u=c.isStreaming;this.catchupStreamSessionId=u?t.id:void 0,this.setState({...p,isLoadingEarlierMessages:!1,isReceivingPartialStream:u,status:c,activity:this.getState().sessionActivities[t.id]}),this.applyStatus(c);for(const h of n)this.applyEvent(h);this.socket.setHandler(h=>{this.applyEvent(h)}),i?.updateUrl!==!1&&this.updateUrl()}catch(n){if(s!==this.selectionSeq||this.getState().selectedSession?.id!==t.id)return;if(Ce(t)&&mp(n)){await this.recreateCachedNewSession(t,i);return}this.setState({error:String(n)})}}async loadEarlierMessages(){const t=this.getState(),i=t.selectedSession;if(!(!i||t.isLoadingEarlierMessages||t.messagePageStart<=0)){this.setState({isLoadingEarlierMessages:!0});try{const s=await this.api.messages(i.id,{before:t.messagePageStart,limit:ft},g(this.getState()));if(this.getState().selectedSession?.id!==i.id)return;const o=this.transcripts.mergeHistory(this.sessionCacheKey(i.id),s);this.setState(o)}catch(s){this.setState({error:String(s)})}finally{this.getState().selectedSession?.id===i.id&&this.setState({isLoadingEarlierMessages:!1})}}}async send(t,i){if(t.trim().startsWith("/"))return this.runCommand(t);if(Gd(t))return this.runShell(t);const o=this.getState().selectedSession;if(!(!o||o.archived===!0))try{await this.api.prompt(o.id,t,i,g(this.getState())),this.markCachedNewSessionPersisted(o)}catch(r){this.setState({error:String(r)})}}async runShell(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Ie("user",t)]});try{await this.api.shell(i.id,t,g(this.getState())),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Ie("system",String(s))],error:String(s)})}}}async runCommand(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0)){this.setState({messages:[...this.getState().messages,Ie("user",t)]});try{this.applyCommandResult(await this.api.runCommand(i.id,t,g(this.getState()))),this.markCachedNewSessionPersisted(i)}catch(s){this.setState({messages:[...this.getState().messages,Ie("system",String(s))],error:String(s)})}}}async respondToCommand(t,i){const s=this.getState().selectedSession;if(s){this.setState({commandDialog:void 0});try{this.applyCommandResult(await this.api.respondToCommand(s.id,t,i,g(this.getState())))}catch(o){this.setState({error:String(o)})}}}cancelCommand(){this.setState({commandDialog:void 0})}applySessionStatus(t){this.applyStatus(t)}async archiveSession(t=this.getState().selectedSession){if(t){if(Ce(t)){await this.deleteCachedNewSession(t);return}try{await this.api.archive(t.id,g(this.getState()));const i=this.getState(),s=cp(i.sessions,t.id,new Date().toISOString()),o=dp(s,i.selectedSession?.id,t.id);this.setState({sessions:s}),o.type==="select"?await this.selectSession(o.session):o.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}}async archiveSessionWithDescendants(t=this.getState().selectedSession){if(!(!t||Ce(t)))try{const i=await this.api.archiveWithDescendants(t.id,g(this.getState())),s=i.sessionIds!==void 0&&i.sessionIds.length>0?i.sessionIds:[t.id],o=this.getState(),r=Sn(o.sessions,s,new Date().toISOString()),n=kn(r,o.selectedSession?.id,s);this.setState({sessions:r}),n.type==="select"?await this.selectSession(n.session):n.type==="clear"&&this.deselectSession({forgetRememberedSelection:!0})}catch(i){this.setState({error:String(i)})}}async deleteCachedNewSession(t=this.getState().selectedSession){if(!Ce(t))return;this.api.stop(t.id,g(this.getState())).catch(()=>{}),No(t.id,g(this.getState())),Fs(this.sessionCacheKey(t.id));const i=this.getState().sessions.filter(o=>o.id!==t.id);if(this.setState({sessions:i}),this.getState().selectedSession?.id!==t.id)return;const s=i.find(o=>o.archived!==!0)??i[0];s!==void 0?await this.selectSession(s):(this.clearActiveSession(),this.updateUrl())}async restoreSession(t=this.getState().selectedSession){if(t)try{await this.api.restore(t.id,g(this.getState()));const i={...t};delete i.archived,delete i.archivedAt,this.replaceSession(i),this.getState().selectedSession?.id===i.id&&await this.selectSession(i)}catch(i){this.setState({error:String(i)})}}async detachParent(t=this.getState().selectedSession){if(t?.parentSessionPath!==void 0)try{await this.api.detachParent(t.id,g(this.getState()));const i={...t};delete i.parentSessionPath,this.replaceSession(i)}catch(i){this.setState({error:String(i)})}}async listModels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.models(t.id,g(this.getState()))).models}catch(i){return this.setState({error:String(i)}),[]}}async setModel(t,i){const s=this.getState().selectedSession;if(!(!s||s.archived===!0))try{this.applyStatus(await this.api.setModel(s.id,t,i,g(this.getState())))}catch(o){this.setState({error:String(o)})}}async cycleModel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.cycleModel(i.id,t,g(this.getState())))}catch(s){this.setState({error:String(s)})}}async listThinkingLevels(){const t=this.getState().selectedSession;if(!t||t.archived===!0)return[];try{return(await this.api.thinkingLevels(t.id,g(this.getState()))).levels}catch(i){return this.setState({error:String(i)}),[]}}async setThinkingLevel(t){const i=this.getState().selectedSession;if(!(!i||i.archived===!0))try{this.applyStatus(await this.api.setThinkingLevel(i.id,t,g(this.getState())))}catch(s){this.setState({error:String(s)})}}async cycleThinkingLevel(){const t=this.getState().selectedSession;if(!(!t||t.archived===!0))try{this.applyStatus(await this.api.cycleThinkingLevel(t.id,g(this.getState())))}catch(i){this.setState({error:String(i)})}}async stopActiveWork(){const t=this.getState().selectedSession;if(t)try{await this.api.abort(t.id,g(this.getState()))}catch(i){this.setState({error:String(i)})}}async refreshSelectedSession(t=this.getState().selectedSession?.id){const i=this.getState().selectedSession;if(!(t===void 0||i?.id!==t||i.archived===!0))try{this.flushPendingTranscriptEvents();const[s,o]=await Promise.all([this.api.messages(t,{limit:ft},g(this.getState())),this.api.status(t,g(this.getState()))]);if(this.getState().selectedSession?.id!==t)return;const r=this.transcripts.mergeHistory(this.sessionCacheKey(t),s);this.setState({...r,status:o,activity:this.getState().sessionActivities[t],isReceivingPartialStream:o.isStreaming}),this.applyStatus(o)}catch(s){this.getState().selectedSession?.id===t&&this.setState({error:String(s)})}}sessionCacheKey(t){return hn(g(this.getState()),t)}workspaceSelectionKey(t){return`${g(this.getState())}:${t}`}replaceSession(t){const i=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s=>s.id===t.id?t:s),selectedSession:i?.id===t.id?t:i})}async recreateCachedNewSession(t,i){try{const s=g(this.getState()),o=await this.api.startSession(t.cwd,s);jo(o,s),bd(this.sessionCacheKey(t.id),this.sessionCacheKey(o.id)),No(t.id,s);const r=fs(o,s);this.setState({sessions:[r,...this.getState().sessions.filter(n=>n.id!==t.id)],error:""}),await this.selectSession(r,{updateUrl:!1}),this.updateUrl(i?.updateUrl===!1?{replace:!0}:void 0)}catch(s){this.setState({error:String(s)})}}markCachedNewSessionPersisted(t){if(!Ce(t))return;const i=this.getState().sessions.find(s=>s.id===t.id)??t;this.replaceSession(Kc(i))}applyCommandResult(t){if(t.type==="select"){this.setState({commandDialog:t});return}const i=(t.type==="unsupported",t.message);if(i!==void 0&&i!==""&&this.setState({messages:[...this.getState().messages,Ie(t.type==="unsupported"?"system":"tool",i)]}),t.type==="done"&&t.session){t.promptDraft!==void 0&&ci(this.sessionCacheKey(t.session.id),t.promptDraft);const s=this.getState().selectedSession,o=[t.session,...this.getState().sessions.filter(r=>r.id!==t.session?.id)];this.setState({sessions:o,selectedSession:s?.id===t.session.id?t.session:s}),s?.id!==t.session.id&&this.selectSession(t.session)}}applyActivity(t){this.setState({sessionActivities:{...this.getState().sessionActivities,[t.sessionId]:t},activity:this.getState().selectedSession?.id===t.sessionId?t:this.getState().activity})}applyStatus(t){const i=this.getState(),s=i.sessionActivities[t.sessionId]?.phase==="active"&&!Pi(t);this.setState({sessionStatuses:{...i.sessionStatuses,[t.sessionId]:t},...up(i,t.sessionId,t.messageCount),...s?{sessionActivities:hp(i.sessionActivities,t.sessionId)}:{},status:i.selectedSession?.id===t.sessionId?t:i.status,activity:i.selectedSession?.id===t.sessionId&&s?void 0:i.activity}),this.catchupStreamSessionId===t.sessionId&&!t.isStreaming&&this.finishStreamCatchup(t.sessionId)}applySessionName(t,i){const s=r=>{if(r.id!==t)return r;const n={...r};return i===void 0||i===""?delete n.name:n.name=i,n},o=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(s),selectedSession:o===void 0?void 0:s(o)})}applyEvent(t){const i=this.getState().selectedSession?.id;if(this.catchupStreamSessionId!==void 0&&this.catchupStreamSessionId===i){if(t.type==="message.end"||t.type==="agent.end"){this.finishStreamCatchup(this.catchupStreamSessionId);return}if(fp(t))return}if(gp(t)){this.queueTranscriptEvent(t);return}this.flushPendingTranscriptEvents();const s=this.transcripts.applyLiveEvent(this.getState().messages,t);s?this.setState({messages:s}):t.type==="status.update"?this.applyStatus(t.status):t.type==="activity.update"?this.applyActivity(t.activity):t.type==="session.name"&&this.applySessionName(t.sessionId,t.name)}queueTranscriptEvent(t){this.pendingTranscriptEvents.push(t),this.pendingTranscriptFrame===void 0&&(this.pendingTranscriptFrame=requestAnimationFrame(()=>{this.pendingTranscriptFrame=void 0,this.flushPendingTranscriptEvents()}))}flushPendingTranscriptEvents(){if(this.pendingTranscriptEvents.length===0)return;const t=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let i=this.getState().messages;for(const s of t)i=this.transcripts.applyLiveEvent(i,s)??i;i!==this.getState().messages&&this.setState({messages:i})}clearPendingTranscriptEvents(){this.pendingTranscriptEvents=[],this.pendingTranscriptFrame!==void 0&&(cancelAnimationFrame(this.pendingTranscriptFrame),this.pendingTranscriptFrame=void 0)}finishStreamCatchup(t){this.catchupStreamSessionId===t&&(this.catchupStreamSessionId=void 0,this.getState().selectedSession?.id===t&&this.setState({isReceivingPartialStream:!1}),this.refreshMessages(t))}async refreshMessages(t){try{const i=await this.api.messages(t,{limit:ft},g(this.getState()));if(this.getState().selectedSession?.id!==t)return;this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(t),i))}catch(i){this.getState().selectedSession?.id===t&&this.setState({error:String(i)})}}}function hp(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function up(e,t,i){if(i===void 0)return{};const o=e.sessions.some(n=>n.id===t&&n.messageCount!==i)?e.sessions.map(n=>n.id===t?{...n,messageCount:i}:n):void 0,r=e.selectedSession?.id===t&&e.selectedSession.messageCount!==i?{...e.selectedSession,messageCount:i}:e.selectedSession;return{...o===void 0?{}:{sessions:o},...r!==e.selectedSession?{selectedSession:r}:{}}}function fp(e){return["message.append","assistant.delta","assistant.thinking.delta","tool.start","tool.update","tool.end","shell.start","shell.chunk","shell.end","command.output","session.error"].includes(e.type)}function gp(e){return e.type==="assistant.delta"||e.type==="assistant.thinking.delta"||e.type==="shell.chunk"}function mp(e){return e instanceof Error&&e.message.toLowerCase().includes("session not found")}class vp{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}const bp="pi-web:workspace-selection:v1";class wp{constructor(t=Et()){this.workspaceIdsByProject=new Ii(bp,Us,t)}latestWorkspaceId(t){return this.workspaceIdsByProject.get(t)}rememberWorkspace(t){this.workspaceIdsByProject.set(t.projectId,t.id)}forgetProject(t){this.workspaceIdsByProject.delete(t)}}function yp(e,t){const i=t?.targetWorkspaceId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestWorkspaceId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e[0]:e[0]}class xp{constructor(t,i,s,o,r=new vp,n={}){this.getState=t,this.setState=i,this.updateUrl=s,this.sessions=o,this.workspaceSelection=r,this.api=n.api??B}clearSelection(t){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...Zt()}),t?.updateUrl!==!1&&this.updateUrl()}forgetProject(t){this.workspaceSelection.forgetProject(zi(g(this.getState()),t));const i=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([s])=>s!==t));this.setState({workspacesByProjectId:i})}async selectProject(t,i){const s=g(this.getState());this.sessions.clearActiveSession(),this.setState({selectedProject:t,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...Zt()});try{const o=await this.api.workspaces(t.id,s);if(g(this.getState())!==s||this.getState().selectedProject?.id!==t.id)return;this.setState({workspaces:o,workspacesByProjectId:{...this.getState().workspacesByProjectId,[t.id]:o},isLoadingWorkspaces:!1});const r=yp(o,{targetWorkspaceId:i?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(zi(s,t.id))});r?await this.selectWorkspace(r,{sessionId:i?.sessionId,updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedProject?.id===t.id&&this.setState({error:String(o),isLoadingWorkspaces:!1})}}async selectWorkspace(t,i){const s=g(this.getState());this.workspaceSelection.rememberWorkspace({...t,projectId:zi(s,t.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:t,isLoadingWorkspaces:!1,...Zt()});try{const o=qc(t.path,await this.api.sessions(t.path,s),s);if(g(this.getState())!==s||this.getState().selectedWorkspace?.id!==t.id||this.getState().selectedProject?.id!==t.projectId)return;this.setState({sessions:o});const r=this.sessions.preferredSession(t.path,o,i?.sessionId);r?await this.sessions.selectSession(r,{updateUrl:i?.updateUrl}):i?.updateUrl!==!1&&this.updateUrl()}catch(o){g(this.getState())===s&&this.getState().selectedWorkspace?.id===t.id&&this.setState({error:String(o)})}}async refreshProjectWorkspaces(t){const i=this.getState().projects.find(o=>o.id===t);if(i===void 0)throw new Error("Project not found");const s=await this.api.workspaces(i.id,g(this.getState()));return this.applyProjectWorkspaces(i.id,s),s}async refreshAfterWorkspaceDeleted(t,i){const s=await this.refreshProjectWorkspaces(t),o=this.getState();if(o.selectedProject?.id!==t||o.selectedWorkspace?.id!==i)return;const r=kp(s);r!==void 0?await this.selectWorkspace(r):this.clearSelection()}applyProjectWorkspaces(t,i){const s=this.getState(),o={...s.workspacesByProjectId,[t]:i};s.selectedProject?.id===t?this.setState({workspaces:i,workspacesByProjectId:o}):this.setState({workspacesByProjectId:o})}}function Sp(e){return e!==void 0&&e.isGitWorktree&&!e.isMain}function kp(e){return e.find(t=>t.isMain)??e[0]}const $p="pi-web:machine-navigation:v1";class Pp{constructor(t=Et()){this.snapshotsByMachine=new Ii($p,Ip,t)}latest(t){const i=this.snapshotsByMachine.get(t);return i?.machineId===t?Go(i):void 0}remember(t){this.snapshotsByMachine.set(t.machineId,Go(t))}forget(t){this.snapshotsByMachine.delete(t)}}function Cp(e){return{machineId:e,surface:{}}}function Ko(e){const t=e.selectedWorkspace!==void 0;return{machineId:e.selectedMachine?.id??pn,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 Vo(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 Go(e){return{...e,surface:{...e.surface}}}function Ip(e){if(!Pn(e))return;const t=Ee(e,"machineId");if(t===void 0)return;const i=$n(Ee(e,"tool")),s=Mp(Ee(e,"view"));return{machineId:t,projectId:Ee(e,"projectId"),workspaceId:Ee(e,"workspaceId"),sessionId:Ee(e,"sessionId"),...i===void 0?{}:{tool:i},...s===void 0?{}:{view:s},surface:Tp(e.surface)}}function Tp(e){return Pn(e)?{selectedFilePath:Ee(e,"selectedFilePath"),selectedDiffPath:Ee(e,"selectedDiffPath"),selectedTerminalId:Ee(e,"selectedTerminalId")}:{}}function Mp(e){return e==="navigation"||e==="chat"?e:$n(e)}function $n(e){return Rp(e)?e:void 0}function Rp(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Ee(e,t){const i=e[t];return typeof i=="string"&&i!==""?i:void 0}function Pn(e){return typeof e=="object"&&e!==null}const Ap="pi-web:terminal-selection:v1";class Ep{constructor(t=Et()){this.terminalIdsByCwd=new Ii(Ap,Us,t)}latestTerminalId(t){return this.terminalIdsByCwd.get(t)}rememberTerminal(t,i){this.terminalIdsByCwd.set(t,i)}forgetWorkspace(t){this.terminalIdsByCwd.delete(t)}forgetTerminal(t){for(const[i,s]of this.terminalIdsByCwd.entries())s===t&&this.terminalIdsByCwd.delete(i)}}function Mb(e,t){const i=t?.targetTerminalId;if(i!==void 0&&i!=="")return e.find(o=>o.id===i);const s=t?.latestTerminalId;return s!==void 0&&s!==""?e.find(o=>o.id===s)??e.find(o=>!o.exited)??e[0]:e.find(o=>!o.exited)??e[0]}function Rb(e){return e.find(t=>!t.exited)??e[0]}const Cn=1200,Dp=["mod","alt","shift"];class Wp{constructor(){this.pendingTokens=[]}handle(t,i,s={}){const o=Tn(t);if(o===void 0)return!1;const r=Hs(i,s.shortcuts,{enabledOnly:!0}).filter(n=>n.active).map(n=>({action:n.action,tokens:n.tokens}));if(this.pendingTokens.length>0){if(this.handleSequence([...this.pendingTokens,o],r))return!0;if(this.clearPending(),!It(o))return!1}else if(!It(o))return!1;return this.handleSequence([o],r)}reset(){this.clearPending()}handleSequence(t,i){const s=i.find(r=>Hp(r.tokens,t));return s!==void 0?(this.clearPending(),s.action.run(),!0):i.some(r=>qs(r.tokens,t))?(this.setPending(t),!0):!1}setPending(t){this.clearPending(),this.pendingTokens=t,this.pendingTimer=globalThis.setTimeout(()=>{this.pendingTokens=[],this.pendingTimer=void 0},Cn)}clearPending(){this.pendingTokens=[],this.pendingTimer!==void 0&&(globalThis.clearTimeout(this.pendingTimer),this.pendingTimer=void 0)}}function Hs(e,t,i={}){const s=e.flatMap((p,u)=>{if(i.enabledOnly===!0&&p.enabled===!1)return[];const h=Op(p,t,u);return h===void 0?[]:[h]}),o=new Map;for(const p of s)o.set(p.key,[...o.get(p.key)??[],p]);const r=new Map;for(const p of o.values()){const u=[...p].sort(vs)[0];u!==void 0&&r.set(u.key,u)}const n=[...r.values()].sort(jp),a=new Map,c=new Map;for(const p of s){const u=r.get(p.key);if(u===void 0)continue;const h=Np(u,n)??u;c.set(p,h),p!==h&&a.set(h,[...a.get(h)??[],p])}return s.map(p=>{const u=c.get(p),h=u===p,f=u===void 0||h?void 0:Jo(u),b=h?[...a.get(p)??[]].sort(vs).map(Jo):[];return{...p,active:h,shadows:b,...f===void 0?{}:{shadowedBy:f}}}).sort((p,u)=>p.order-u.order)}function qi(e){return Mn(e,{requireFirstChordActivator:!0})}function In(e){const t=Mn(e,{requireFirstChordActivator:!1});return t.ok?t.tokens:[]}function Xt(e){return In(e).map(t=>t.split("+").map(An).join("+")).join(" ")}function Tn(e){if(e.isComposing)return;const t=Bp(e.key);if(t===void 0)return;const i=[];return(e.metaKey||e.ctrlKey)&&i.push("mod"),e.altKey&&i.push("alt"),e.shiftKey&&i.push("shift"),i.push(t),i.join("+")}function It(e){return e.split("+").includes("mod")||e.split("+").includes("alt")}function Op(e,t,i){const s=_p(e.id,t);if(s===null)return;const o=s??e.shortcut;if(o===void 0||o==="")return;const r=In(o),n=r[0];if(!(n===void 0||!It(n)))return{action:e,shortcut:r.join(" "),source:s===void 0?"default":"custom",tokens:r,key:Lp(r),order:i}}function _p(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Lp(e){return e.join("\0")}function Jo(e){return{action:e.action,shortcut:e.shortcut,source:e.source}}function vs(e,t){return Zo(e.source)-Zo(t.source)||Qo(e.action.id,t.action.id)||Qo(e.action.title,t.action.title)||e.order-t.order}function jp(e,t){return e.tokens.length-t.tokens.length||vs(e,t)}function Np(e,t){return t.find(i=>i!==e&&i.tokens.length<e.tokens.length&&qs(e.tokens,i.tokens))}function Zo(e){switch(e){case"custom":return 0;case"default":return 1}}function Qo(e,t){return e<t?-1:e>t?1:0}function Mn(e,t){const i=e.trim().toLowerCase().replace(/\s*\+\s*/gu,"+");if(i==="")return{ok:!1,message:"Enter a shortcut, choose None, or reset to the default."};const s=[],o=i.split(/\s+/u).filter(r=>r!=="");for(const[r,n]of o.entries()){const a=Fp(n);if(!a.ok)return a;if(r===0&&t.requireFirstChordActivator&&!It(a.token))return{ok:!1,message:"Shortcuts must start with Ctrl/⌘ or Alt so normal typing is not captured."};s.push(a.token)}return{ok:!0,shortcut:s.join(" "),tokens:s}}function Fp(e){const t=e.split("+").filter(r=>r!=="");if(t.length===0)return{ok:!1,message:"Shortcut chords must include a key."};const i=new Set;let s;for(const r of t){const n=zp(r);if(n!==void 0){if(i.has(n))return{ok:!1,message:`Shortcut has duplicate ${An(n)} modifiers.`};i.add(n);continue}const a=Rn(r);if(a===void 0)return{ok:!1,message:`Unsupported shortcut key: ${r}`};if(s!==void 0)return{ok:!1,message:"Each shortcut chord can include only one non-modifier key."};s=a}return s===void 0?{ok:!1,message:"Shortcut chords must include a key."}:{ok:!0,token:[...Dp.filter(r=>i.has(r)),s].join("+")}}function zp(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 Rn(e){const t=Up(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 Bp(e){if(e===" ")return"space";const t=e.toLowerCase();return Rn(t)}function Up(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 An(e){return e==="mod"?Xo()?"⌘":"Ctrl":e==="shift"?"Shift":e==="alt"?Xo()?"⌥":"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 Hp(e,t){return e.length===t.length&&qs(e,t)}function qs(e,t){return t.every((i,s)=>e[s]===i)}function Xo(){return typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes("mac")}const Ks="themes:classic",qp="themes:pi-web-dark",Kp={themeId:qp,auto:!0},En="pi-web-app-theme",Vp=["--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"],Gp=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u;function Jp(){try{const e=window.localStorage.getItem(En);return e===null?void 0:eh(e)}catch{return}}function Zp(e){try{window.localStorage.setItem(En,JSON.stringify(e))}catch{}}function Qp(e){const t=document.documentElement;t.dataset.piWebTheme=e.id,t.style.colorScheme=e.colorScheme;for(const i of Vp){const s=e.tokens[i];typeof s=="string"&&s!==""?t.style.setProperty(i,s):t.style.removeProperty(i)}}function Xp(e){const t=Yp(e.themes,e.fallbackThemeId??Ks),i=e.themes.find(n=>n.id===e.preference.themeId)??t;if(i===void 0)return{selectedTheme:void 0,activeTheme:void 0,selectedThemePair:void 0,fallbackTheme:t};const s=Dn(e.themePairs,i.id);if(!e.preference.auto||s===void 0)return{selectedTheme:i,activeTheme:i,selectedThemePair:s,fallbackTheme:t};const o=e.prefersLight?s.light:s.dark,r=e.themes.find(n=>n.id===o)??i;return{selectedTheme:i,activeTheme:r,selectedThemePair:s,fallbackTheme:t}}function Yp(e,t=Ks){return e.find(i=>i.id===t)??e[0]}function Dn(e,t){return e.find(i=>i.light===t||i.dark===t)}function eh(e){const t=e.trim();if(t!=="")try{const i=JSON.parse(t);return th(i)?i:void 0}catch{return}}function th(e){if(!ih(e))return!1;const t=e.themeId,i=e.auto;return sh(t)&&typeof i=="boolean"}function ih(e){return typeof e=="object"&&e!==null}function sh(e){return typeof e=="string"&&Gp.test(e)}const oh="management";function rh(e){return nh(ah())===oh}function nh(e){if(e===void 0||e==="")return;const t=new URLSearchParams(e).get("embed")?.trim();return t===""?void 0:t}function ah(){return typeof window>"u"?void 0:window.location.search}const lh="workspace.delete",ch="pi.operation",dh="target.workspaceId";function ph(e){return{...e===void 0?{}:{projectId:e},metadata:{[ch]:lh}}}function hh(e){const t={};for(const i of e){const s=bs(i);if(s===void 0)continue;const o=t[s];(o===void 0||i.createdAt.localeCompare(o.createdAt)>=0)&&(t[s]=i)}return t}function uh(e){return Object.entries(e).filter(([,t])=>hi(t)).map(([t])=>t)}function Wn(e,t){if(t===void 0)return!1;const i=e.workspaceDeletionRuns[t.id];return i!==void 0&&hi(i)}function bs(e){return e.metadata[dh]}function hi(e){return e.status==="queued"||e.status==="running"}function Yo(){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:"针对已保存的 pi 凭据运行 /logout",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:gt,run:e=>{e.selectMainView("core:workspace.files")}},{id:"view.git",title:"转到 Git",shortcut:"mod+3",group:"导航",enabled:er,run:e=>{e.selectMainView("core:workspace.git")}},{id:"view.terminal",title:"转到终端",shortcut:"mod+4",group:"导航",enabled:gt,run:e=>{e.selectMainView("core:workspace.terminal")}},{id:"workspace.refresh-files",title:"刷新文件",shortcut:"mod+shift+f",group:"工作区",enabled:gt,run:e=>e.refreshFiles()},{id:"workspace.refresh-git",title:"刷新 Git",shortcut:"mod+shift+g",group:"工作区",enabled:er,run:e=>e.refreshGit()},{id:"workspace.refresh-current",title:"刷新当前面板",shortcut:"mod+shift+r",group:"工作区",enabled:gt,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:fh,run:e=>e.deleteWorkspace()},{id:"session.start",title:"启动会话",shortcut:"mod+enter",group:"会话",enabled:gt,run:e=>e.startSession()},{id:"session.archive",title:"归档会话",description:"归档所选会话",group:"会话",enabled:gh,run:e=>e.archiveSession()},{id:"session.delete",title:"删除新会话",description:"删除所选浏览器缓存的新会话",group:"会话",enabled:mh,run:e=>e.deleteCachedNewSession()},{id:"session.stop",title:"停止活动工作",shortcut:"mod+.",group:"会话",enabled:e=>e.state.selectedSession!==void 0&&Pi(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function gt(e){return e.state.selectedWorkspace!==void 0}function er(e){return e.state.selectedWorkspace?.isGitRepo===!0}function fh(e){const t=e.state.selectedWorkspace;return t!==void 0&&t.isGitWorktree&&!t.isMain&&!Wn(e.state,t)}function gh(e){const t=e.state.selectedSession;return t!==void 0&&t.archived!==!0&&!Ce(t)}function mh(e){return Ce(e.state.selectedSession)}const vh="modulepreload",bh=function(e){return"/"+e},tr={},On=function(t,i,s){let o=Promise.resolve();if(i&&i.length>0){let c=function(p){return Promise.all(p.map(u=>Promise.resolve(u).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const n=document.querySelector("meta[property=csp-nonce]"),a=n?.nonce||n?.getAttribute("nonce");o=c(i.map(p=>{if(p=bh(p),p in tr)return;tr[p]=!0;const u=p.endsWith(".css"),h=u?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${p}"]${h}`))return;const f=document.createElement("link");if(f.rel=u?"stylesheet":vh,u||(f.as="script"),f.crossOrigin="",f.href=p,a&&f.setAttribute("nonce",a),document.head.appendChild(f),u)return new Promise((b,P)=>{f.addEventListener("load",b),f.addEventListener("error",()=>P(new Error(`Unable to preload CSS for ${p}`)))})}))}function r(n){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=n,window.dispatchEvent(a),!a.defaultPrevented)throw n}return o.then(n=>{for(const a of n||[])a.status==="rejected"&&r(a.reason);return t().catch(r)})},wh=10*1024*1024,yh="10 MB";function xh(e){return typeof e!="string"?l`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`:Yt(e)}function Yt(e){switch(e){case"navigation":return st`
|
|
21
|
+
<svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
22
|
+
<circle cx="6" cy="7" r="1.5"></circle>
|
|
23
|
+
<path d="M10 7h8"></path>
|
|
24
|
+
<circle cx="6" cy="12" r="1.5"></circle>
|
|
25
|
+
<path d="M10 12h8"></path>
|
|
26
|
+
<circle cx="6" cy="17" r="1.5"></circle>
|
|
27
|
+
<path d="M10 17h8"></path>
|
|
28
|
+
</svg>
|
|
29
|
+
`;case"chat":return st`
|
|
30
|
+
<svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
31
|
+
<path d="M7 5h10a3 3 0 0 1 3 3v5a3 3 0 0 1-3 3h-6l-5 4v-4H7a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3Z"></path>
|
|
32
|
+
<path d="M8 9h8"></path>
|
|
33
|
+
<path d="M8 13h5"></path>
|
|
34
|
+
</svg>
|
|
35
|
+
`;case"files":return st`
|
|
36
|
+
<svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
37
|
+
<path d="M3 7a2 2 0 0 1 2-2h4l2 2.5h8a2 2 0 0 1 2 2V17a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"></path>
|
|
38
|
+
</svg>
|
|
39
|
+
`;case"git":return st`
|
|
40
|
+
<svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
41
|
+
<circle cx="6" cy="6" r="2"></circle>
|
|
42
|
+
<circle cx="18" cy="6" r="2"></circle>
|
|
43
|
+
<circle cx="12" cy="18" r="2"></circle>
|
|
44
|
+
<path d="M8 6h6"></path>
|
|
45
|
+
<path d="M6 8v2a6 6 0 0 0 6 6"></path>
|
|
46
|
+
<path d="M18 8v2a6 6 0 0 1-6 6"></path>
|
|
47
|
+
</svg>
|
|
48
|
+
`;case"terminal":return st`
|
|
49
|
+
<svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
50
|
+
<rect x="3" y="5" width="18" height="14" rx="2"></rect>
|
|
51
|
+
<path d="m7 10 3 3-3 3"></path>
|
|
52
|
+
<path d="M12 16h5"></path>
|
|
53
|
+
</svg>
|
|
54
|
+
`}}function ir(){return[{id:"workspace.files",title:"文件",icon:Yt("files"),order:10,render:Sh},{id:"workspace.git",title:"Git",icon:Yt("git"),order:20,visible:({workspace:e})=>e.isGitRepo,render:Dh},{id:"workspace.terminal",title:"终端",icon:Yt("terminal"),order:30,badge:e=>e.activeTerminalCount>0?e.activeTerminalCount:void 0,render:Eh}]}function Sh(e){return l`
|
|
55
|
+
<section class="toolbar">
|
|
56
|
+
<strong>文件</strong>
|
|
57
|
+
${e.fileTreeStale?l`<span class="stale">过期</span>`:null}
|
|
58
|
+
<div class="toolbar-actions">
|
|
59
|
+
<button @click=${e.onRefreshFiles}>刷新</button>
|
|
60
|
+
<button @click=${()=>{$h(e)}}>新建文件</button>
|
|
61
|
+
<button @click=${()=>{Ph(e)}}>新建目录</button>
|
|
62
|
+
${e.selectedFilePath===void 0?null:l`
|
|
63
|
+
${Dt(e)==="file"?l`<button @click=${()=>{e.onDownloadSelectedFile()}}>下载</button>`:null}
|
|
64
|
+
<button @click=${()=>{Ch(e)}}>移动</button>
|
|
65
|
+
<button class="danger" @click=${()=>{Ih(e)}}>删除</button>
|
|
66
|
+
`}
|
|
67
|
+
<label class="file-upload-button">
|
|
68
|
+
上传
|
|
69
|
+
<input type="file" multiple @change=${t=>{kh(e,t)}} />
|
|
70
|
+
</label>
|
|
71
|
+
</div>
|
|
72
|
+
</section>
|
|
73
|
+
<section class="split">
|
|
74
|
+
<div class="list tree">
|
|
75
|
+
${e.fileTree.length===0?l`<p class="muted">尚未加载文件。</p>`:e.fileTree.map(t=>_n(e,t,0))}
|
|
76
|
+
</div>
|
|
77
|
+
<div class="viewer">
|
|
78
|
+
${Rh(e)}
|
|
79
|
+
</div>
|
|
80
|
+
</section>
|
|
81
|
+
`}function kh(e,t){const i=t.currentTarget;!(i instanceof HTMLInputElement)||i.files===null||(e.onUploadFiles(Array.from(i.files)),i.value="")}function $h(e){const t=window.prompt("新建文件路径",Ln(e,"new-file.txt"));t===null||t.trim()===""||e.onCreateFile(t.trim())}function Ph(e){const t=window.prompt("新建目录路径",Ln(e,"new-folder"));t===null||t.trim()===""||e.onCreateDirectory(t.trim())}function Ch(e){const t=e.selectedFilePath;if(t===void 0||t==="")return;const i=window.prompt(Dt(e)==="directory"?"移动或重命名目录到":"移动或重命名文件到",t);i===null||i.trim()===""||i.trim()===t||e.onMoveSelectedPath(i.trim())}function Ih(e){const t=e.selectedFilePath;if(t===void 0||t==="")return;const i=Dt(e)==="directory"?"空目录":"文件";window.confirm(`删除${i} ${t}?`)&&e.onDeleteSelectedPath()}function _n(e,t,i){const s=e.expandedDirs[t.path],o=s!==void 0,r=e.selectedFilePath===t.path;return l`
|
|
82
|
+
<button class=${r?"row selected":"row"} style=${`--depth:${String(i)}`} @click=${()=>{Th(e,t)}}>
|
|
83
|
+
<span>${t.type==="directory"?o?"▾":"▸":"·"}</span>
|
|
84
|
+
<span>${t.name}</span>
|
|
85
|
+
</button>
|
|
86
|
+
${o?s.map(n=>_n(e,n,i+1)):null}
|
|
87
|
+
`}function Th(e,t){t.type==="directory"?(e.onSelectDirectory(t.path),e.onExpandDir(t.path)):e.onSelectFile(t.path)}function Dt(e){const t=e.selectedFilePath;return t===void 0?"file":Mh(e,t)?.type??"file"}function Ln(e,t){const i=e.selectedFilePath;if(i===void 0||i==="")return t;if(Dt(e)==="directory")return`${i}/${t}`;const s=i.lastIndexOf("/");return s===-1?t:`${i.slice(0,s)}/${t}`}function Mh(e,t){const i=e.fileTree.find(s=>s.path===t);if(i!==void 0)return i;for(const s of Object.values(e.expandedDirs)){const o=s.find(r=>r.path===t);if(o!==void 0)return o}}function Rh(e){const t=e.selectedFileContent;return e.selectedFilePath===void 0||e.selectedFilePath===""?l`<p class="muted">请选择文件。</p>`:Dt(e)==="directory"?l`<p class="muted">已选择目录 ${e.selectedFilePath}。</p>`:t===void 0?l`<p class="muted">正在加载 ${e.selectedFilePath}…</p>`:t.mediaType==="image"?Ah(e,t):t.binary?l`<p class="muted">二进制文件:${t.path} · ${ws(t.size)}</p>`:(jn(),l`
|
|
88
|
+
<div class="viewer-header"><strong>${t.path}</strong><small>${t.language??"文本"}${t.truncated?" · 已截断":""}</small></div>
|
|
89
|
+
<code-viewer .content=${t.content} .language=${t.language}></code-viewer>
|
|
90
|
+
`)}function Ah(e,t){const i=`${t.mimeType??"image"} · ${ws(t.size)}`;if(t.size>wh)return l`
|
|
91
|
+
<div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
|
|
92
|
+
<p class="muted">图片过大,无法预览:${ws(t.size)} · 限制 ${yh}</p>
|
|
93
|
+
`;const s=hc(e.workspace.projectId,e.workspace.id,t.path,{modifiedAt:t.modifiedAt,machineId:e.machine.id});return l`
|
|
94
|
+
<div class="viewer-header"><strong>${t.path}</strong><small>${i}</small></div>
|
|
95
|
+
<div class="image-preview">
|
|
96
|
+
<img src=${s} alt=${t.path} decoding="async" />
|
|
97
|
+
</div>
|
|
98
|
+
`}function Eh(e){return _h(),l`<terminal-panel .workspace=${e.workspace} .machineId=${e.machine.id} .selectedTerminalId=${e.selectedTerminalId} .autoStart=${e.terminalAutoStart} .onSelectTerminal=${e.onSelectTerminal}></terminal-panel>`}function Dh(e){const t=e.gitStatus;return l`
|
|
99
|
+
<section class="toolbar">
|
|
100
|
+
<strong>Git</strong>
|
|
101
|
+
${e.gitStale?l`<span class="stale">过期</span>`:null}
|
|
102
|
+
<button @click=${e.onRefreshGit}>刷新</button>
|
|
103
|
+
</section>
|
|
104
|
+
<section class="split">
|
|
105
|
+
<div class="list">
|
|
106
|
+
${t===void 0?l`<p class="muted">尚未加载状态。</p>`:t.isGitRepo?l`
|
|
107
|
+
<p class="summary">${Lh(t)}</p>
|
|
108
|
+
${t.files.length===0?l`<p class="muted">没有变更。</p>`:t.files.map(i=>l`
|
|
109
|
+
<button class="row ${e.selectedDiffPath===i.path?"selected":""}" @click=${()=>{e.onSelectDiff(i.path)}}>
|
|
110
|
+
<span>${jh(i.index,i.workingTree)}</span>
|
|
111
|
+
<span>${i.path}</span>
|
|
112
|
+
</button>
|
|
113
|
+
`)}
|
|
114
|
+
`:l`<p class="muted">不是 Git 仓库。</p>`}
|
|
115
|
+
</div>
|
|
116
|
+
<div class="viewer">
|
|
117
|
+
${Wh(e)}
|
|
118
|
+
</div>
|
|
119
|
+
</section>
|
|
120
|
+
`}function Wh(e){if(e.selectedDiffPath===void 0||e.selectedDiffPath==="")return l`<p class="muted">请选择一个已变更文件。</p>`;const t=e.selectedDiff,i=e.selectedStagedDiff;if(t===void 0||i===void 0)return l`<p class="muted">正在加载 diff…</p>`;const s=[i,t].filter(o=>o.diff!=="");return s.length===0?l`<p class="muted">没有 staged 或 unstaged diff。</p>`:l`
|
|
121
|
+
<div class=${s.length===1?"diffs single":"diffs"}>
|
|
122
|
+
${s.map(o=>Oh(o))}
|
|
123
|
+
</div>
|
|
124
|
+
`}function Oh(e){return jn(),l`
|
|
125
|
+
<section class="diff-section">
|
|
126
|
+
<div class="viewer-header"><strong>${e.path??"diff"}</strong><small>${e.staged?"已暂存":"未暂存"}${e.truncated?" · 已截断":""}</small></div>
|
|
127
|
+
<code-viewer .content=${e.diff} .language=${"diff"}></code-viewer>
|
|
128
|
+
</section>
|
|
129
|
+
`}function jn(){On(()=>import("./CodeViewer-8znVN61S.js"),__vite__mapDeps([0,1,2,3]))}function _h(){On(()=>import("./TerminalPanel-DrdWnF1y.js"),__vite__mapDeps([4,5,6,1,2]))}function Lh(e){const t=e.branch??"分离 HEAD",i=e.ahead??0,s=e.behind??0;return i===0&&s===0?t:`${t} · ↑${String(i)} ↓${String(s)}`}function jh(e,t){return(t!=="unmodified"?t:e).slice(0,1).toUpperCase()}function ws(e){if(!Number.isFinite(e)||e<0)return"0 B";if(e<1024)return`${String(e)} B`;const t=e/1024;if(t<1024)return`${Ki(t)} KB`;const i=t/1024;return i<1024?`${Ki(i)} MB`:`${Ki(i/1024)} GB`}function Ki(e){return e>=10?String(Math.round(e)):e.toFixed(1)}const Nh={apiVersion:1,name:"PI WEB 核心",activate:()=>{const e=!rh();return{contributions:{actions:e?Yo():Yo().filter(t=>t.id!=="view.terminal"),workspacePanels:e?ir():ir().filter(t=>t.id!=="workspace.terminal")}}}},Fh={"--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"},zh={"--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":"#3d4a78","--pi-selection-bg":"#151b31","--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"},Bh={"--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"},Uh={apiVersion:1,name:"PI WEB 主题",activate:()=>({contributions:{themes:[{id:"pi-web-dark",name:"PI WEB 深色",description:"PI WEB 深色配色。",order:10,colorScheme:"dark",tokens:zh},{id:"pi-web-light",name:"PI WEB 浅色",description:"PI WEB 浅色配色。",order:20,colorScheme:"light",tokens:Bh},{id:"classic",name:"PI WEB 经典",description:"原始 PI WEB 深色配色。",order:30,colorScheme:"dark",tokens:Fh}],themePairs:[{id:"pi-web",name:"PI WEB",description:"跟随系统浅色/深色偏好使用 PI WEB 主题。",order:10,light:"pi-web-light",dark:"pi-web-dark"}]}})},Hh=/^[a-z][a-z0-9.-]*$/u;function qh(e){return Hh.test(e)}const Kh="machine.";function Vh(e,t){if(e==="")throw new Error("Machine id is required");if(!qh(t))throw new Error(`Invalid PI WEB plugin id: ${t}`);return`${Kh}${Gh(e)}.${t}`}function Gh(e){return[...new TextEncoder().encode(e)].map(t=>t.toString(16).padStart(2,"0")).join("")}async function sr(e="/pi-web-plugins/manifest.json",t={}){const i=await Jh(e);if(i===void 0)return[];const s=[];for(const o of i.plugins)try{const r=new URL(o.module,new URL(e,window.location.href)).toString(),n=await import(r),a=Qh(n,r);s.push({id:t.machineId===void 0?o.id:Vh(t.machineId,o.id),plugin:a,...t.machineId===void 0?{}:{machineId:t.machineId,sourcePluginId:o.id}})}catch(r){console.warn(`Failed to load PI WEB plugin ${o.module}`,r)}return s}async function Jh(e){const t=await fetch(e,{cache:"no-store"});if(t.status!==404){if(!t.ok)throw new Error(`Failed to load plugin manifest: ${t.statusText}`);return Zh(await t.json())}}function Zh(e){if(!ui(e)||!Array.isArray(e.plugins))throw new Error("Invalid plugin manifest");return{plugins:e.plugins.map(t=>{if(!ui(t)||typeof t.id!="string"||t.id===""||typeof t.module!="string"||t.module==="")throw new Error("Invalid plugin manifest entry");return{id:t.id,module:t.module}})}}function Qh(e,t){if(!ui(e))throw new Error(`Plugin module ${t} did not export an object`);const i=e.default;if(!Xh(i))throw new Error(`Plugin module ${t} default export is not a PiWebPlugin`);return i}function Xh(e){return ui(e)&&e.apiVersion===1&&typeof e.name=="string"&&typeof e.activate=="function"}function ui(e){return typeof e=="object"&&e!==null}const Yh=/^[a-z][a-z0-9.-]*$/u,eu=/^[a-z][a-z0-9.-]*$/u,Nn=new WeakMap,Fn=new WeakMap;class tu{constructor(){this.actions=[],this.workspacePanels=[],this.workspaceLabels=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.gatewayPluginIds=new Set,this.contributionIds=new Set}register(t){const{id:i,plugin:s}=t;if(this.validatePluginId(i),this.pluginIds.has(i))throw new Error(`Duplicate plugin id: ${i}`);if(ru(t,this.gatewayPluginIds))return;this.pluginIds.add(i);const o=s.apiVersion;if(o!==1)throw new Error(`Unsupported plugin API version for ${i}: ${String(o)}`);const n=s.activate({apiVersion:1,pluginId:i,html:l,svg:st}).contributions;for(const a of n.actions??[])this.actions.push(this.qualifyAction(i,a,t.machineId,t.sourcePluginId));for(const a of n.workspacePanels??[])this.workspacePanels.push(this.qualifyWorkspacePanel(i,a,t.machineId,t.sourcePluginId));for(const a of n.workspaceLabels??[])this.workspaceLabels.push(this.qualifyWorkspaceLabelContribution(i,a,t.machineId,t.sourcePluginId));if(t.machineId===void 0){for(const a of n.themes??[])this.themes.push(this.qualifyTheme(i,a));for(const a of n.themePairs??[])this.themePairs.push(this.qualifyThemePair(i,a));this.gatewayPluginIds.add(i)}}getActions(t){return this.actions.filter(i=>mt(i.machineId,au(t),i.sourcePluginId,this.gatewayPluginIds)).map(i=>{const s=iu(t,i.pluginId),o=i.enabled?.(s),r={id:i.id,pluginId:i.pluginId,localId:i.localId,...i.machineId===void 0?{}:{machineId:i.machineId},title:i.title,run:()=>i.run(s)};return i.description!==void 0&&(r.description=i.description),i.shortcut!==void 0&&(r.shortcut=i.shortcut),i.group!==void 0&&(r.group=i.group),o!==void 0&&(r.enabled=o),r})}getWorkspacePanels(){return[...this.workspacePanels].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.title.localeCompare(i.title))}getThemes(){return[...this.themes].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getThemePairs(){return[...this.themePairs].sort((t,i)=>(t.order??1e3)-(i.order??1e3)||t.name.localeCompare(i.name))}getWorkspaceLabelItems(t){return[...this.workspaceLabels].sort((i,s)=>(i.order??1e3)-(s.order??1e3)||i.id.localeCompare(s.id)).flatMap(i=>i.visible?.(t)===!1?[]:i.items(t))}qualifyAction(t,i,s,o){const r=this.qualify(t,i.id);return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},...o===void 0?{}:{sourcePluginId:o}}}qualifyWorkspacePanel(t,i,s,o){const r=this.qualify(t,i.id),n=i.badge,a=i.visible;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>mt(s,c.machine.id,o,this.gatewayPluginIds)&&(a?.(Vi(c,t))??!0),...n===void 0?{}:{badge:c=>mt(s,c.machine.id,o,this.gatewayPluginIds)?n(Vi(c,t)):void 0},render:c=>i.render(Vi(c,t))}}qualifyWorkspaceLabelContribution(t,i,s,o){const r=this.qualify(t,i.id),n=i.visible,a=i.items;return{...i,id:r,pluginId:t,localId:i.id,...s===void 0?{}:{machineId:s},visible:c=>mt(s,c.machine.id,o,this.gatewayPluginIds)&&(n?.(c)??!0),items:c=>mt(s,c.machine.id,o,this.gatewayPluginIds)?a(c):[]}}qualifyTheme(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id}}qualifyThemePair(t,i){const s=this.qualify(t,i.id);return{...i,id:s,pluginId:t,localId:i.id,light:this.qualifyReference(t,i.light),dark:this.qualifyReference(t,i.dark)}}qualify(t,i){this.validateLocalId(i);const s=`${t}:${i}`;if(this.contributionIds.has(s))throw new Error(`Duplicate contribution id: ${s}`);return this.contributionIds.add(s),s}qualifyReference(t,i){return this.validateLocalId(i),`${t}:${i}`}validatePluginId(t){if(!Yh.test(t))throw new Error(`Invalid plugin id: ${t}`)}validateLocalId(t){if(!eu.test(t))throw new Error(`Invalid contribution id: ${t}`)}}function iu(e,t){return Nn.get(e)?.(t)??e}function Vi(e,t){return Fn.get(e)?.(t)??e}function su(e,t){return Nn.set(e,t),e}function ou(e,t){return Fn.set(e,t),e}function ru(e,t){return e.machineId!==void 0&&e.sourcePluginId!==void 0&&t.has(e.sourcePluginId)}function mt(e,t,i,s){return e===void 0||e===t&&!nu(i,s)}function nu(e,t){return e!==void 0&&t.has(e)}function au(e){return e.state.selectedMachine?.id??"local"}const lu=["(display-mode: standalone)","(display-mode: fullscreen)","(display-mode: minimal-ui)"];function cu(){return typeof window>"u"||!("matchMedia"in window)?[]:lu.map(e=>window.matchMedia(e))}function or(e,t=du()){return e.some(i=>i.matches)||pu(t)}function du(){return typeof navigator>"u"?void 0:navigator}function pu(e){return e!==void 0&&"standalone"in e&&e.standalone===!0}const hu=250;class uu{constructor(t=fu()){this.scheduler=t}repair(t){if(!t){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()},hu)}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);const t=this.scheduler.documentElement;t!==void 0&&(t.scrollTop=0);const i=this.scheduler.body;i!==void 0&&(i.scrollTop=0)}}function fu(){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}}}const gu="(max-width: 760px)";class mu{constructor(t,i={}){this.host=t,this.onMobileNavigationMediaChange=s=>{this.isMobileNavigationLayout!==s.matches&&(this.isMobileNavigationLayout=s.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{const s=or(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==s&&(this.isPwaDisplayMode=s,this.host.requestUpdate())},t.addController(this),this.mobileNavigationMedia=i.mobileNavigationMedia??vu(),this.pwaDisplayModeMedia=i.pwaDisplayModeMedia??cu(),this.viewportPositionRepairer=i.viewportPositionRepairer??new uu,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=or(this.pwaDisplayModeMedia)}hostConnected(){this.mobileNavigationMedia?.addEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.addEventListener("change",this.onPwaDisplayModeChange)}hostDisconnected(){this.mobileNavigationMedia?.removeEventListener("change",this.onMobileNavigationMediaChange);for(const t of this.pwaDisplayModeMedia)t.removeEventListener("change",this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.isMobileNavigationLayout?"navigation":"chat"}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}}function vu(){if(!(typeof window>"u"||!("matchMedia"in window)))return window.matchMedia(gu)}const fi=["machines","projects","workspaces","sessions"];function bu(e){return e.selectedProject===void 0?"projects":e.selectedWorkspace===void 0?"workspaces":"sessions"}function Vs(e,t){if(e!=="none")return e??bu(t)}function wu(e,t){return t.isMobileLayout?Vs(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function yu(e,t,i){return Vs(e,i.state)===t?"none":t}function xu(e,t,i){return i?t:e}function Su(e,t){const i=new Set(e);return i.has(t)?i.delete(t):i.add(t),Pu(i)}function ku(e){return fi[fi.indexOf(e)+1]}class $u{constructor(t,i,s){this.host=t,this.getState=i,this.isMobileLayout=s,this.collapsedSections=[],t.addController(this)}hostConnected(){}expandedSection(){return Vs(this.expanded,this.getState())}isCollapsed(t){return wu(t,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(t){if(this.isMobileLayout()){this.setExpanded(yu(this.expanded,t,{state:this.getState()}));return}this.setCollapsedSections(Su(this.collapsedSections,t))}expand(t){if(this.isMobileLayout()){this.setExpanded(xu(this.expanded,t,!0));return}this.setCollapsedSections(this.collapsedSections.filter(i=>i!==t))}advanceAfterSelection(t){if(!this.isMobileLayout())return;const i=ku(t);i!==void 0&&this.expand(i)}open(t,i){this.isMobileLayout()&&(this.expand(t),i())}setExpanded(t){this.expanded!==t&&(this.expanded=t,this.host.requestUpdate())}setCollapsedSections(t){Cu(this.collapsedSections,t)||(this.collapsedSections=t,this.host.requestUpdate())}}function Pu(e){const t=new Set(e);return fi.filter(i=>t.has(i))}function Cu(e,t){return e.length===t.length&&e.every((i,s)=>i===t[s])}class Iu{constructor(t){this.host=t,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,t.addController(this)}hostConnected(){}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(t){return["shell",zn(t),...this.navigationPanelCollapsed?["navigation-panel-collapsed"]:[],...this.workspacePanelCollapsed?["workspace-panel-collapsed"]:[]].join(" ")}}function zn(e){return e==="navigation"?"navigation-view":e==="chat"?"chat-view":"workspace-view"}const ys="pi-web:panel-sizes:v1",Tu={navigation:{minWidth:180,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}};class Mu{constructor(t,i={}){this.host=t,t.addController(this),this.storage=i.storage??Gs(),this.panelSizes=Du(this.storage)}hostConnected(){}constraints(t){return Wt(t)}panelWidth(t,i){return de(t,i??this.storedPanelWidth(t)??this.constraints(t).defaultWidth)}resizePanel(t,i,s={}){const o=de(t,i);this.storedPanelWidth(t)!==o&&(this.panelSizes=_u(this.panelSizes,t,o),s.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(t,i={}){this.storedPanelWidth(t)!==void 0&&(this.panelSizes=Lu(this.panelSizes,t),i.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(t={}){this.panelSizes.navigationPanelWidth===void 0&&this.panelSizes.workspacePanelWidth===void 0||(this.panelSizes={},t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){Wu(this.panelSizes,this.storage)}shellStyle(t={}){const i=[];return this.panelSizes.navigationPanelWidth!==void 0&&i.push(`--navigation-panel-size: ${nr(de("navigation",this.panelSizes.navigationPanelWidth,t.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&i.push(`--workspace-panel-size: ${nr(de("workspace",this.panelSizes.workspacePanelWidth,t.workspace))};`),i.join(" ")}storedPanelWidth(t){return t==="navigation"?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}}function Wt(e){return Tu[e]}function Ru(e,t,i){return e==="navigation"?i-t:t-i}function Au(e,t,i,s,o=Wt(e)){return de(e,t+Ru(e,i,s),o)}function Eu(e,t,i,s={}){const o=s.constraints??Wt(e);if(i==="Home")return o.minWidth;if(i==="End")return o.maxWidth;const r=s.largeStep===!0?o.largeKeyboardStep:o.keyboardStep,n=ju(e,i,r);if(n!==void 0)return de(e,t+n,o)}function de(e,t,i=Wt(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,i.minWidth),i.maxWidth)):i.defaultWidth}function Du(e=Gs()){try{const t=e?.getItem(ys);if(t==null||t==="")return{};const i=JSON.parse(t);return Ou(i)}catch{return{}}}function Wu(e,t=Gs()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(ys);return}const i={version:1};e.navigationPanelWidth!==void 0&&(i.navigationPanelWidth=de("navigation",e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(i.workspacePanelWidth=de("workspace",e.workspacePanelWidth)),t.setItem(ys,JSON.stringify(i))}catch{}}function Ou(e){if(!Nu(e)||e.version!==1)return{};const t={},i=rr(e.navigationPanelWidth),s=rr(e.workspacePanelWidth);return i!==void 0&&(t.navigationPanelWidth=de("navigation",i)),s!==void 0&&(t.workspacePanelWidth=de("workspace",s)),t}function rr(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function _u(e,t,i){return t==="navigation"?{...e,navigationPanelWidth:i}:{...e,workspacePanelWidth:i}}function Lu(e,t){return t==="navigation"?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function ju(e,t,i){if(e==="navigation")return t==="ArrowRight"?i:t==="ArrowLeft"?-i:void 0;if(t==="ArrowLeft")return i;if(t==="ArrowRight")return-i}function nr(e){return`${String(Math.round(e))}px`}function Gs(){try{return typeof window>"u"?void 0:window.localStorage}catch{return}}function Nu(e){return typeof e=="object"&&e!==null}function ar(){const 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:Fu(e.get("tool")),view:zu(e.get("view"))}}function Gi(e,t){const i=new URL(window.location.href);i.searchParams.delete("machine"),i.searchParams.delete("project"),i.searchParams.delete("workspace"),i.searchParams.delete("session"),i.searchParams.delete("tool"),i.searchParams.delete("view"),e.machineId!==void 0&&e.machineId!==""&&e.machineId!=="local"&&i.searchParams.set("machine",e.machineId),e.projectId!==void 0&&e.projectId!==""&&i.searchParams.set("project",e.projectId),e.workspaceId!==void 0&&e.workspaceId!==""&&i.searchParams.set("workspace",e.workspaceId),e.sessionId!==void 0&&e.sessionId!==""&&i.searchParams.set("session",e.sessionId),e.tool!==void 0&&i.searchParams.set("tool",e.tool),e.view!==void 0&&i.searchParams.set("view",e.view);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&(t?.replace===!0?window.history.replaceState({},"",i):window.history.pushState({},"",i))}function Fu(e){return e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Bn(e)?e:void 0}function zu(e){return e==="chat"?"chat":e==="files"?"core:workspace.files":e==="git"?"core:workspace.git":Bn(e)?e:void 0}function Bn(e){return e!==null&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function lr(){return Bu(new URLSearchParams(window.location.search).get("settings"))}function Ji(e,t){const i=new URL(window.location.href);e===void 0?i.searchParams.delete("settings"):i.searchParams.set("settings",e);const s=`${i.pathname}${i.search}${i.hash}`,o=`${window.location.pathname}${window.location.search}${window.location.hash}`;s!==o&&window.history.pushState({},"",i)}function Bu(e){if(e==="general")return"general";if(e==="plugins")return"plugins";if(e==="shortcuts"||e==="keyboard"||e==="keyboard-shortcuts")return"shortcuts"}function Uu(e,t){return t===void 0?e:e.map(i=>qu(i,t))}function Hu(e,t){const i=new Set(Hs(e,t,{enabledOnly:!0}).filter(s=>s.active).map(s=>s.action.id));return Uu(e,t).map(s=>s.shortcut!==void 0&&!i.has(s.id)?Un(s):s)}function qu(e,t){if(!Object.hasOwn(t,e.id))return e;const i=t[e.id];return i===void 0?e:i===null?Un(e):{...e,shortcut:i}}function Un(e){const t={...e};return delete t.shortcut,t}function Ku(e,t){const i=t.api??ot,s=t.pollIntervalMs??1e3,o=t.setTimeout??Gu(),r=t.clearTimeout??Ju();return{async runCommand(n){const a=await i.runTerminalCommand(e,n);return n.open===!0&&t.openTerminal(n.workspace,{terminalId:a.terminalId}),{run:a,completed:Vu(a,i,s,o,r)}},listCommandRuns:n=>i.listCommandRuns(n),getCommandRun:n=>i.getCommandRun(n),open:n=>{t.openTerminal(void 0,n)}}}function Vu(e,t,i,s,o){return cr(e)?Promise.resolve(e):new Promise((r,n)=>{let a,c=!1;const p=f=>{c||(c=!0,a!==void 0&&o(a),r(f))},u=f=>{c||(c=!0,a!==void 0&&o(a),n(f instanceof Error?f:new Error(String(f))))},h=()=>{t.getCommandRun(e.id).then(f=>{if(f!==void 0&&cr(f)){p(f);return}a=s(h,i)}).catch(u)};a=s(h,i)})}function cr(e){return e.status==="succeeded"||e.status==="failed"}function Gu(){return(e,t)=>globalThis.setTimeout(e,t)}function Ju(){return e=>{globalThis.clearTimeout(e)}}function Zu(e,t){return t[e.path]}function Qu(e){if(e?.hasSessionActivity===!0)return"session";if(e?.hasTerminalActivity===!0)return"terminal"}function Xu(e,t,i){return qn(Yu(e,t,i))}function Hn(e){return qn(Object.values(e??{}))}function qn(e){if(e.some(t=>t.hasSessionActivity))return"session";if(e.some(t=>t.hasTerminalActivity))return"terminal"}function Yu(e,t,i){const s=new Set(t.filter(r=>r.projectId===e.id).map(r=>r.path)),o=new Map;for(const r of s){const n=i[r];n!==void 0&&o.set(n.cwd,n)}for(const r of Object.values(i))(r.cwd===e.path||r.cwd.startsWith(`${e.path}/`))&&o.set(r.cwd,r);return[...o.values()]}const Bt=0,ef=120;function Ot(e,t={}){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const i=e.getBoundingClientRect(),s=t.constrainTo==="viewport"?Kn():tf(e),o=window.innerWidth,r=window.innerHeight,n=Math.max(0,s.left),a=Math.min(o,s.right),c=Math.max(0,s.top),p=Math.min(r,s.bottom),u=Math.min(i.right,a),h=p-i.bottom-Bt,f=i.top-c-Bt;return[...h<ef&&f>h?[`bottom: ${tt(r-i.top+Bt)};`,`max-height: ${tt(Math.max(0,f))};`]:[`top: ${tt(i.bottom+Bt)};`,`max-height: ${tt(Math.max(0,h))};`],`right: ${tt(Math.max(0,o-u))};`,`max-width: ${tt(Math.max(0,u-n))};`].join(" ")}function tf(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&t.host instanceof HTMLElement?t.host.getBoundingClientRect():Kn()}function Kn(){return{top:0,right:window.innerWidth,bottom:window.innerHeight,left:0}}function tt(e){return`${String(Math.round(e))}px`}function Vn(e,t="活跃"){if(e!==void 0)return l`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`}function Ti(e,t="Active"){const i=Vn(e,t);if(i!==void 0)return l`<span class="action-activity">${i}</span>`}const sf=["a[href]","button","input","select","textarea","summary","[role='button']","[role='link']","[contenteditable='true']"].join(",");function Gn(e){return e.composedPath().some(t=>of(t,sf))}function of(e,t){if(typeof Element<"u"&&e instanceof Element)return e.matches(t);if(!("matches"in e))return!1;const{matches:i}=e;return typeof i=="function"&&i.call(e,t)===!0}function Mi(e,t){Gn(e)||t()}function Ri(e,t){return Gn(e)?!1:e.key==="Enter"||e.key===" "?(e.preventDefault(),t.activate(),!0):e.key==="ArrowUp"?ze(e,()=>{dr(e.currentTarget,-1)}):e.key==="ArrowDown"?ze(e,()=>{dr(e.currentTarget,1)}):e.key==="Home"?ze(e,()=>{pr(e.currentTarget,0)}):e.key==="End"?ze(e,()=>{pr(e.currentTarget,-1)}):e.key==="ArrowLeft"&&t.previousSection!==void 0?ze(e,t.previousSection):e.key==="ArrowRight"&&t.nextSection!==void 0?ze(e,t.nextSection):e.key==="Escape"&&t.cancel!==void 0?ze(e,t.cancel):!1}function Ai(e,t={}){const i=e.querySelector(".action-row.selected")??e.querySelector(".action-row")??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return i==null?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}function ze(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function dr(e,t){const i=Zn(e),s=Qn(e);if(s===void 0||i.length===0)return;const o=i.indexOf(s);o<0||Jn(i,o+t)}function pr(e,t){const i=Zn(e);i.length!==0&&Jn(i,t<0?i.length-1:t)}function Jn(e,t){const i=e[Math.min(Math.max(t,0),e.length-1)];i?.focus(),i?.scrollIntoView({block:"nearest"})}function Zn(e){const t=Qn(e)?.getRootNode();return t===void 0||!rf(t)?[]:Array.from(t.querySelectorAll(".action-row"))}function rf(e){return typeof Document<"u"&&e instanceof Document||typeof DocumentFragment<"u"&&e instanceof DocumentFragment}function Qn(e){if(!(typeof HTMLElement>"u"||!(e instanceof HTMLElement)))return e.closest(".action-row")??void 0}const nf=A`
|
|
130
|
+
/* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
|
|
131
|
+
: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; }
|
|
132
|
+
:host([pwa-display-mode]) { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
|
|
133
|
+
@media (display-mode: standalone), (display-mode: fullscreen), (display-mode: minimal-ui) {
|
|
134
|
+
:host { --pi-app-safe-area-bottom: env(safe-area-inset-bottom); }
|
|
135
|
+
}
|
|
136
|
+
.shell { --navigation-panel-size: 340px; --workspace-panel-size: minmax(360px, 42vw); --navigation-panel-width: var(--navigation-panel-size); --workspace-panel-width: var(--workspace-panel-size); display: grid; grid-template-columns: var(--navigation-panel-width) 1px minmax(320px, 1fr) 1px var(--workspace-panel-width); height: 100%; min-height: 0; }
|
|
137
|
+
aside { grid-column: 1; display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
|
|
138
|
+
aside app-navigation-panel { flex: 1 1 auto; min-height: 0; }
|
|
139
|
+
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); }
|
|
140
|
+
.header-actions { display: flex; align-items: center; gap: 8px; }
|
|
141
|
+
project-list, workspace-list { flex: 0 0 auto; max-height: 26%; min-height: 0; overflow: hidden; border-bottom: 1px solid var(--pi-border-muted); }
|
|
142
|
+
session-list { flex: 1 1 auto; min-height: 0; overflow: hidden; }
|
|
143
|
+
main { grid-column: 3; display: flex; flex-direction: column; min-width: 0; min-height: 0; }
|
|
144
|
+
.context-bar { position: relative; flex: 0 0 auto; min-width: 0; display: none; align-items: center; gap: 0; padding: 6px 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
|
|
145
|
+
.context-bar::before, .context-bar::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 20px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
|
|
146
|
+
.context-bar::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
|
|
147
|
+
.context-bar::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
|
|
148
|
+
.context-bar.can-scroll-left::before, .context-bar.can-scroll-right::after { opacity: 1; }
|
|
149
|
+
.context-bar-label { display: none; }
|
|
150
|
+
.context-items { flex: 1 1 auto; min-width: 0; display: flex; align-items: stretch; gap: 5px; margin: 0; padding: 0 8px; list-style: none; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scroll-padding-inline: 8px; scrollbar-width: thin; }
|
|
151
|
+
.context-bar.has-context-actions .context-items { padding-right: 52px; scroll-padding-inline: 8px 52px; }
|
|
152
|
+
.context-item { flex: 0 0 auto; min-width: 0; display: flex; }
|
|
153
|
+
.context-actions { position: absolute; top: 6px; right: 0; bottom: 6px; z-index: 3; display: flex; align-items: center; padding: 0 8px 0 0; pointer-events: none; }
|
|
154
|
+
.context-actions::after { content: ""; position: absolute; top: 0; right: 0; bottom: 0; z-index: 0; width: 26px; background: var(--pi-bg); pointer-events: none; }
|
|
155
|
+
.context-chip { flex: 0 0 auto; min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 4px 8px; font: inherit; text-align: left; }
|
|
156
|
+
.context-chip:hover { background: var(--pi-surface-hover); }
|
|
157
|
+
.context-chip:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; }
|
|
158
|
+
.context-chip.empty { border-style: dashed; color: var(--pi-muted); }
|
|
159
|
+
.context-kind { display: none; }
|
|
160
|
+
.context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
|
|
161
|
+
app-mobile-main-tabs { display: none; }
|
|
162
|
+
.mobile-tabs-frame { position: relative; display: none; flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); background: var(--pi-bg); }
|
|
163
|
+
.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; }
|
|
164
|
+
.mobile-tabs-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
|
|
165
|
+
.mobile-tabs-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
|
|
166
|
+
.mobile-tabs-frame.can-scroll-left::before, .mobile-tabs-frame.can-scroll-right::after { opacity: 1; }
|
|
167
|
+
.mobile-tabs { flex: 1 1 auto; min-width: 0; display: flex; align-items: center; gap: 6px; padding: 8px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; }
|
|
168
|
+
.mobile-tabs button { flex: 0 0 auto; white-space: nowrap; }
|
|
169
|
+
.mobile-navigation-tab, .mobile-navigation-panel { display: none; }
|
|
170
|
+
.mobile-tabs button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
|
|
171
|
+
.tab-badge { display: inline-block; min-width: 14px; margin-left: 4px; border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
|
|
172
|
+
.navigation-panel-edge, .workspace-panel-edge { min-width: 0; min-height: 0; display: flex; align-items: center; justify-content: center; overflow: visible; background: var(--pi-border-muted); z-index: 2; }
|
|
173
|
+
.navigation-panel-edge { grid-column: 2; }
|
|
174
|
+
.workspace-panel-edge { grid-column: 4; }
|
|
175
|
+
.navigation-panel-edge-button, .workspace-panel-edge-button { position: relative; z-index: 1; box-sizing: border-box; display: grid; place-items: center; width: 18px; height: 48px; padding: 0; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-bg); color: var(--pi-muted); opacity: .75; cursor: pointer; }
|
|
176
|
+
.navigation-panel-edge-button:hover, .navigation-panel-edge-button:focus-visible, .workspace-panel-edge-button:hover, .workspace-panel-edge-button:focus-visible { color: var(--pi-text); background: var(--pi-surface-hover); opacity: 1; }
|
|
177
|
+
.shell.navigation-panel-collapsed .navigation-panel-edge-button { transform: translateX(calc(50% - .5px)); }
|
|
178
|
+
.shell.workspace-panel-collapsed .workspace-panel-edge-button { transform: translateX(calc(-50% + .5px)); }
|
|
179
|
+
.navigation-panel-edge-icon, .workspace-panel-edge-icon { width: 12px; height: 12px; fill: none; stroke: currentColor; stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
180
|
+
workspace-panel { grid-column: 5; min-width: 0; min-height: 0; overflow: hidden; }
|
|
181
|
+
@media (min-width: 1181px) {
|
|
182
|
+
.shell.navigation-panel-collapsed { --navigation-panel-width: 0px; }
|
|
183
|
+
.shell.navigation-panel-collapsed > aside { display: none; }
|
|
184
|
+
.shell.workspace-panel-collapsed { --workspace-panel-width: 0px; }
|
|
185
|
+
.shell.workspace-panel-collapsed > workspace-panel { display: none; }
|
|
186
|
+
}
|
|
187
|
+
@media (max-width: 1180px) {
|
|
188
|
+
.shell { grid-template-columns: var(--navigation-panel-width) 1px minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); }
|
|
189
|
+
.shell.navigation-panel-collapsed { --navigation-panel-width: 0px; }
|
|
190
|
+
.shell.navigation-panel-collapsed > aside { display: none; }
|
|
191
|
+
aside { grid-row: 1 / 3; }
|
|
192
|
+
.navigation-panel-edge { grid-row: 1 / 3; }
|
|
193
|
+
main { grid-column: 3; grid-row: 1 / 3; }
|
|
194
|
+
app-mobile-main-tabs { display: block; flex: 0 0 auto; min-width: 0; }
|
|
195
|
+
.mobile-tabs-frame { display: flex; }
|
|
196
|
+
.shell.workspace-view main { grid-row: 1; min-height: auto; }
|
|
197
|
+
.shell.workspace-view > workspace-panel { grid-column: 3; grid-row: 2; display: flex; border-left: 0; }
|
|
198
|
+
.shell:not(.workspace-view) > workspace-panel { display: none; }
|
|
199
|
+
.workspace-panel-edge { display: none; }
|
|
200
|
+
main.workspace-view chat-view, main.workspace-view prompt-editor, main.workspace-view status-bar,
|
|
201
|
+
main.workspace-view .empty { display: none; }
|
|
202
|
+
main.workspace-view { overflow: hidden; }
|
|
203
|
+
}
|
|
204
|
+
@media (max-width: 760px) {
|
|
205
|
+
.shell { grid-template-columns: minmax(0, 1fr); }
|
|
206
|
+
aside, .navigation-panel-edge { display: none; }
|
|
207
|
+
main, .shell.workspace-view > workspace-panel { grid-column: 1; }
|
|
208
|
+
.context-bar { display: flex; }
|
|
209
|
+
.mobile-navigation-tab { display: block; }
|
|
210
|
+
main.navigation-view chat-view, main.navigation-view prompt-editor, main.navigation-view status-bar,
|
|
211
|
+
main.navigation-view .empty { display: none; }
|
|
212
|
+
main.navigation-view .mobile-navigation-panel { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
|
|
213
|
+
main.navigation-view .mobile-navigation-panel app-navigation-panel { flex: 1 1 auto; min-height: 0; }
|
|
214
|
+
main.navigation-view .mobile-navigation-panel project-list,
|
|
215
|
+
main.navigation-view .mobile-navigation-panel workspace-list,
|
|
216
|
+
main.navigation-view .mobile-navigation-panel session-list { flex: 1 1 auto; max-height: none; min-height: 0; overflow: hidden; }
|
|
217
|
+
main.navigation-view .mobile-navigation-panel project-list[collapsed],
|
|
218
|
+
main.navigation-view .mobile-navigation-panel workspace-list[collapsed],
|
|
219
|
+
main.navigation-view .mobile-navigation-panel session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
220
|
+
}
|
|
221
|
+
status-bar { flex: 0 0 auto; }
|
|
222
|
+
chat-view { flex: 1 1 auto; min-height: 0; overflow: hidden; }
|
|
223
|
+
prompt-editor, chat-composer { flex: 0 0 auto; }
|
|
224
|
+
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
225
|
+
.empty { margin: auto; color: var(--pi-muted); }
|
|
226
|
+
.error { padding: 10px 16px; border-bottom: 1px solid var(--pi-border); color: var(--pi-danger); }
|
|
227
|
+
`,af=A`
|
|
228
|
+
: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; }
|
|
229
|
+
header { flex: 0 0 auto; min-width: 0; border-bottom: 1px solid var(--pi-border); }
|
|
230
|
+
.workspace-header-scroll-frame { position: relative; min-width: 0; background: var(--pi-bg); }
|
|
231
|
+
.workspace-header-scroll-frame::before, .workspace-header-scroll-frame::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 18px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
|
|
232
|
+
.workspace-header-scroll-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
|
|
233
|
+
.workspace-header-scroll-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
|
|
234
|
+
.workspace-header-scroll-frame.can-scroll-left::before, .workspace-header-scroll-frame.can-scroll-right::after { opacity: 1; }
|
|
235
|
+
.workspace-header-strip { display: flex; justify-content: space-between; align-items: center; gap: 8px; min-width: 0; padding: 8px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; }
|
|
236
|
+
.tabs { flex: 0 0 auto; display: flex; gap: 6px; align-items: center; }
|
|
237
|
+
.tabs button { flex: 0 0 auto; white-space: nowrap; }
|
|
238
|
+
.tabs button.icon-tab { min-width: 34px; }
|
|
239
|
+
button { display: inline-flex; align-items: center; gap: 5px; border: 1px solid var(--pi-border); border-radius: 7px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 7px; cursor: pointer; }
|
|
240
|
+
button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
|
|
241
|
+
.tab-icon { flex: 0 0 auto; width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
242
|
+
.tab-custom-icon { flex: 0 0 auto; width: 16px; height: 16px; display: inline-grid; place-items: center; color: currentColor; pointer-events: none; }
|
|
243
|
+
.tab-custom-icon svg { width: 16px; height: 16px; pointer-events: none; }
|
|
244
|
+
.tab-label { min-width: 0; }
|
|
245
|
+
.tab-badge { flex: 0 0 auto; display: inline-block; min-width: 14px; border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
|
|
246
|
+
@container (max-width: 430px) {
|
|
247
|
+
.tabs button.icon-tab { justify-content: center; padding-inline: 7px; }
|
|
248
|
+
.tabs button.icon-tab .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; }
|
|
249
|
+
}
|
|
250
|
+
.panel-content { flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; overflow: auto; }
|
|
251
|
+
.empty-state { box-sizing: border-box; width: min(100%, 380px); margin: auto; padding: 24px; display: grid; gap: 8px; color: var(--pi-muted); text-align: center; }
|
|
252
|
+
.empty-state h2 { margin: 0; color: var(--pi-text); font-size: 15px; line-height: 1.3; }
|
|
253
|
+
.empty-state p { margin: 0; line-height: 1.45; }
|
|
254
|
+
small, .muted { color: var(--pi-muted); }
|
|
255
|
+
@media (max-width: 1180px) { header { display: none; } }
|
|
256
|
+
.workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
|
|
257
|
+
.workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
258
|
+
.workspace-label-item, .workspace-label-render, .workspace-label-separator { color: var(--pi-muted); }
|
|
259
|
+
.workspace-label-link { color: var(--pi-accent); text-decoration: none; }
|
|
260
|
+
.workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
|
|
261
|
+
.toolbar { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; padding: 8px; border-bottom: 1px solid var(--pi-border-muted); }
|
|
262
|
+
.toolbar-actions { margin-left: auto; display: flex; align-items: center; justify-content: flex-end; gap: 6px; min-width: 0; flex-wrap: wrap; }
|
|
263
|
+
.toolbar button.danger { color: var(--pi-danger); }
|
|
264
|
+
.file-upload-button { display: inline-flex; align-items: center; gap: 5px; border: 1px solid var(--pi-border); border-radius: 7px; background: var(--pi-surface); color: var(--pi-text); padding: 5px 7px; cursor: pointer; }
|
|
265
|
+
.file-upload-button input { display: none; }
|
|
266
|
+
.stale { border: 1px solid var(--pi-warning-border); border-radius: 999px; color: var(--pi-warning); padding: 1px 6px; font-size: 12px; }
|
|
267
|
+
.split { flex: 1 1 auto; min-height: 0; display: grid; grid-template-rows: minmax(160px, 34%) minmax(0, 1fr); }
|
|
268
|
+
.list { min-height: 0; overflow: auto; border-bottom: 1px solid var(--pi-border); padding: 6px; }
|
|
269
|
+
.row { display: grid; grid-template-columns: 18px minmax(0, 1fr); gap: 4px; width: 100%; border: 0; border-radius: 5px; background: transparent; text-align: left; padding: 4px 6px 4px calc(6px + var(--depth, 0) * 14px); }
|
|
270
|
+
.row:hover, .row.selected { background: var(--pi-selection-bg); }
|
|
271
|
+
.row span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
272
|
+
.summary { margin: 4px 6px 8px; color: var(--pi-muted); }
|
|
273
|
+
.viewer { min-height: 0; overflow: auto; display: flex; flex-direction: column; }
|
|
274
|
+
.diffs { flex: 1 1 auto; min-height: 0; overflow: auto; display: grid; grid-template-rows: minmax(120px, 1fr) minmax(120px, 1fr); }
|
|
275
|
+
.diffs.single { grid-template-rows: minmax(0, 1fr); }
|
|
276
|
+
.diff-section { min-height: 0; display: flex; flex-direction: column; border-bottom: 1px solid var(--pi-border); }
|
|
277
|
+
.diff-section:last-child { border-bottom: 0; }
|
|
278
|
+
.viewer-header { position: sticky; top: 0; display: flex; justify-content: space-between; gap: 8px; padding: 8px; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
|
|
279
|
+
.viewer-header strong { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
280
|
+
code-viewer { flex: 1 1 auto; min-height: 0; }
|
|
281
|
+
.image-preview { flex: 1 1 auto; min-height: 0; box-sizing: border-box; display: flex; align-items: center; justify-content: center; overflow: auto; padding: 16px; }
|
|
282
|
+
.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); }
|
|
283
|
+
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; }
|
|
284
|
+
p { margin: 10px; }
|
|
285
|
+
`,Ei=A`
|
|
286
|
+
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
287
|
+
:host([collapsed]) { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
288
|
+
section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 10px; }
|
|
289
|
+
h2 { flex: 0 0 auto; display: flex; justify-content: space-between; align-items: center; gap: 8px; margin: 0 0 8px; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
|
|
290
|
+
.list-body { flex: 1 1 auto; min-height: 0; overflow: auto; }
|
|
291
|
+
.empty-list { box-sizing: border-box; display: grid; gap: 4px; margin: 6px 0; border: 1px dashed var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-muted); padding: 10px; line-height: 1.35; }
|
|
292
|
+
.empty-list strong { color: var(--pi-text); font-size: 13px; }
|
|
293
|
+
.empty-list small { white-space: normal; overflow: visible; text-overflow: clip; }
|
|
294
|
+
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
295
|
+
section > button { display: block; width: 100%; text-align: left; margin: 6px 0; }
|
|
296
|
+
.subheading { margin-top: 14px; }
|
|
297
|
+
.section-toggle { display: flex; flex: 1 1 auto; min-width: 0; align-items: center; justify-content: space-between; gap: 8px; width: 100%; border: 0; background: transparent; color: inherit; padding: 0; font: inherit; text-align: left; text-transform: inherit; }
|
|
298
|
+
.section-toggle span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
299
|
+
.section-title { display: grid; gap: 2px; min-width: 0; }
|
|
300
|
+
.section-toggle .section-selected { display: block; color: var(--pi-text); font-size: 12px; font-weight: 600; line-height: 1.25; text-transform: none; }
|
|
301
|
+
.section-toggle .section-count { flex: 0 0 auto; display: inline; color: var(--pi-muted); font-size: inherit; }
|
|
302
|
+
.section-toggle small { display: inline; color: inherit; font-size: inherit; }
|
|
303
|
+
.action-row { position: relative; display: grid; grid-template-columns: minmax(0, 1fr) auto; margin: 6px 0; cursor: pointer; }
|
|
304
|
+
.action-row:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; border-radius: 8px; }
|
|
305
|
+
.action-row.selected .action-main, .action-row.selected .action-menu-toggle { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
|
|
306
|
+
.action-row.archived .action-main { color: var(--pi-muted); }
|
|
307
|
+
.action-main { position: relative; box-sizing: border-box; min-width: 0; width: 100%; border: 1px solid var(--pi-border); border-top-right-radius: 0; border-bottom-right-radius: 0; border-top-left-radius: 8px; border-bottom-left-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 22px 7px calc(9px + var(--depth, 0) * 16px); text-align: left; }
|
|
308
|
+
.action-name { display: -webkit-box; max-height: 2.5em; overflow: hidden; overflow-wrap: anywhere; line-height: 1.25; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
|
|
309
|
+
.action-row:not(.selected):hover .action-main { background: var(--pi-surface-hover); }
|
|
310
|
+
.workspace-row .action-main { border-radius: 8px 0 0 8px; }
|
|
311
|
+
.workspace-primary { min-width: 0; display: flex; align-items: baseline; gap: 6px; }
|
|
312
|
+
.workspace-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
313
|
+
.workspace-status { flex: 0 0 auto; color: var(--pi-warning); font-size: 12px; }
|
|
314
|
+
.workspace-secondary { margin-top: 3px; }
|
|
315
|
+
.workspace-menu-panel { width: max-content; min-width: min(120px, calc(100vw - 16px)); padding: 8px; }
|
|
316
|
+
.workspace-menu-actions { margin: 0 0 8px; padding-bottom: 8px; border-bottom: 1px solid var(--pi-border-muted); }
|
|
317
|
+
.workspace-menu-actions button.danger { color: var(--pi-danger); }
|
|
318
|
+
.workspace-menu-actions button.danger:hover, .workspace-menu-actions button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
|
|
319
|
+
.workspace-menu-details { display: grid; gap: 6px; margin: 0; }
|
|
320
|
+
.workspace-detail-row { display: grid; grid-template-columns: minmax(58px, max-content) minmax(0, 1fr); gap: 8px; align-items: baseline; }
|
|
321
|
+
.workspace-detail-row dt { color: var(--pi-muted); font-size: 12px; white-space: normal; }
|
|
322
|
+
.workspace-detail-row dd { min-width: 0; margin: 0; overflow-wrap: anywhere; white-space: normal; }
|
|
323
|
+
.tree-marker { color: var(--pi-dim); margin-right: 5px; }
|
|
324
|
+
.badge { display: inline-block; margin-left: 5px; border: 1px solid var(--pi-border); border-radius: 999px; color: var(--pi-muted); padding: 0 5px; font-size: 11px; font-weight: 400; }
|
|
325
|
+
.action-activity { position: absolute; top: 5px; right: 6px; z-index: 1; display: grid; place-items: center; width: 10px; height: 10px; }
|
|
326
|
+
.action-activity .activity-indicator { margin: 0; vertical-align: 0; }
|
|
327
|
+
.activity-indicator { display: inline-block; width: 7px; height: 7px; margin-right: 6px; background: var(--pi-success); animation: pulse 1s ease-in-out infinite; vertical-align: 1px; }
|
|
328
|
+
.activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
|
|
329
|
+
.activity-indicator.terminal { border-radius: 2px; background: var(--pi-accent); }
|
|
330
|
+
.action-menu { position: relative; align-self: stretch; }
|
|
331
|
+
.action-menu-toggle { display: grid; place-items: center; height: 100%; min-width: 32px; padding: 0; color: var(--pi-muted); border-left: 0; border-top-left-radius: 0; border-bottom-left-radius: 0; }
|
|
332
|
+
.action-menu-toggle:hover { color: var(--pi-text); background: var(--pi-surface-hover); }
|
|
333
|
+
.action-menu-panel { position: fixed; z-index: 50; box-sizing: border-box; min-width: min(120px, calc(100vw - 16px)); overflow: auto; padding: 4px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 8px 24px var(--pi-shadow); overflow-wrap: anywhere; }
|
|
334
|
+
.action-menu-panel button { display: block; width: 100%; text-align: left; white-space: normal; overflow-wrap: anywhere; border: 0; background: transparent; color: var(--pi-text); }
|
|
335
|
+
.action-menu-panel button:hover { background: var(--pi-selection-bg); }
|
|
336
|
+
button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
|
|
337
|
+
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
338
|
+
small { display: block; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
339
|
+
.workspace-label { min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; max-width: 100%; overflow: hidden; white-space: nowrap; }
|
|
340
|
+
.workspace-label-base, .workspace-label-item, .workspace-label-render { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
341
|
+
.workspace-label-item, .workspace-label-render, .workspace-label-separator { color: var(--pi-muted); }
|
|
342
|
+
.workspace-label-link { color: var(--pi-accent); text-decoration: none; }
|
|
343
|
+
.workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
|
|
344
|
+
.workspace-detail-row .workspace-label { overflow: visible; white-space: normal; flex-wrap: wrap; }
|
|
345
|
+
.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; }
|
|
346
|
+
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
347
|
+
`,lf=A`
|
|
348
|
+
: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; }
|
|
349
|
+
.chat-wrap { position: relative; flex: 1 1 auto; min-height: 0; overflow: hidden; }
|
|
350
|
+
.chat { height: 100%; min-height: 0; overflow: auto; overflow-anchor: none; padding: 26px 16px 64px; box-sizing: border-box; }
|
|
351
|
+
.scroll-marker { display: block; height: 0; overflow: hidden; pointer-events: none; }
|
|
352
|
+
.activity-dock { position: absolute; left: 16px; right: 16px; bottom: 12px; z-index: 20; display: flex; align-items: center; gap: 8px; min-width: 0; box-sizing: border-box; border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-bg-overlay); color: var(--pi-muted); padding: 8px 12px; font-size: 13px; pointer-events: none; box-shadow: 0 8px 28px var(--pi-shadow); backdrop-filter: blur(6px); }
|
|
353
|
+
.activity-dock.active { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-bg-overlay); }
|
|
354
|
+
.activity-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
355
|
+
.dot { width: 8px; height: 8px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
|
|
356
|
+
.activity-dock.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
|
|
357
|
+
.msg { max-width: 100%; min-width: 0; box-sizing: border-box; margin: 0 0 14px; padding: 12px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); overflow: visible; }
|
|
358
|
+
.msg.user { border-color: var(--pi-accent-border); background: var(--pi-selection-bg); }
|
|
359
|
+
.msg.tool { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); color: var(--pi-warning); }
|
|
360
|
+
.msg.tool-execution-shell { padding: 0; border: 0; background: transparent; color: var(--pi-text); }
|
|
361
|
+
.msg.system { color: var(--pi-danger); }
|
|
362
|
+
.msg.bash { border-color: var(--pi-success); background: var(--pi-success-bg); }
|
|
363
|
+
.msg.skill { border-color: var(--pi-purple-border); background: var(--pi-purple-surface); }
|
|
364
|
+
.msg.event-group { padding: 0; border-color: var(--pi-border); background: var(--pi-bg); color: var(--pi-muted); }
|
|
365
|
+
.msg.event-group.live { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
|
|
366
|
+
.msg.event-group > summary { position: sticky; top: -26px; z-index: 5; display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-radius: 9px 9px 0 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); color: var(--pi-muted); }
|
|
367
|
+
.msg.event-group.live > summary { border-bottom-color: var(--pi-success-border); background: var(--pi-success-bg); color: var(--pi-success); }
|
|
368
|
+
.msg.event-group > summary .label { margin: 0; }
|
|
369
|
+
.group-body { padding: 0 12px 12px; }
|
|
370
|
+
.group-msg { max-width: 100%; min-width: 0; box-sizing: border-box; padding: 10px 0; border-top: 1px solid var(--pi-border-muted); color: var(--pi-text); overflow: visible; }
|
|
371
|
+
.group-msg.tool { color: var(--pi-warning); }
|
|
372
|
+
.group-msg.tool-execution-shell { color: var(--pi-text); }
|
|
373
|
+
.group-msg.system { color: var(--pi-danger); }
|
|
374
|
+
.group-msg.bash { color: var(--pi-success); }
|
|
375
|
+
.history-boundary { position: relative; z-index: 5; display: grid; gap: 3px; justify-items: center; margin: 0 0 14px; color: var(--pi-muted); font-size: 12px; text-align: center; }
|
|
376
|
+
.history-load-button { border: 1px solid var(--pi-border); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text-secondary); padding: 5px 12px; font: 12px system-ui, sans-serif; cursor: pointer; }
|
|
377
|
+
.history-load-button:hover, .history-load-button:focus { border-color: var(--pi-accent); color: var(--pi-text-bright); }
|
|
378
|
+
.history-load-button:disabled { cursor: default; opacity: .55; }
|
|
379
|
+
.queued-messages { max-width: 100%; min-width: 0; box-sizing: border-box; display: grid; gap: 8px; margin: 0 0 14px; padding: 12px; border: 1px solid var(--pi-warning-border); border-radius: 10px; background: var(--pi-warning-surface); color: var(--pi-text); overflow: hidden; }
|
|
380
|
+
.queued-header { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; }
|
|
381
|
+
.queued-header strong { color: var(--pi-warning); }
|
|
382
|
+
.queued-header small { color: var(--pi-muted); }
|
|
383
|
+
.queued-message { display: grid; gap: 4px; padding-top: 8px; border-top: 1px solid var(--pi-border); }
|
|
384
|
+
.queued-message:first-of-type { padding-top: 0; border-top: 0; }
|
|
385
|
+
.queued-kind { color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
|
|
386
|
+
.session-activity { max-width: 100%; min-width: 0; box-sizing: border-box; display: grid; gap: 4px; margin: 0 0 14px; padding: 12px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); color: var(--pi-text); overflow: hidden; }
|
|
387
|
+
.session-activity.compacting { border-color: var(--pi-purple-border); background: var(--pi-purple-surface); }
|
|
388
|
+
.session-activity.receiving { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
|
|
389
|
+
.session-activity strong { color: var(--pi-purple); }
|
|
390
|
+
.session-activity.receiving strong { color: var(--pi-success); }
|
|
391
|
+
.session-activity span, .session-activity small { color: var(--pi-muted); }
|
|
392
|
+
.history-boundary small { color: var(--pi-dim); }
|
|
393
|
+
.msg-header { display: flex; align-items: center; justify-content: space-between; gap: 10px; min-height: 22px; margin-bottom: 8px; }
|
|
394
|
+
.msg > .msg-header { position: sticky; top: -26px; z-index: 4; margin: -12px -12px 8px; padding: 7px 10px 6px; border-radius: 9px 9px 0 0; border-bottom: 1px solid color-mix(in srgb, var(--pi-border-muted) 35%, transparent); background: var(--pi-surface); box-shadow: 0 8px 18px var(--pi-shadow-soft); }
|
|
395
|
+
.msg.user > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-accent-border) 35%, transparent); background: var(--pi-selection-bg); }
|
|
396
|
+
.msg.tool > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-warning-border) 35%, transparent); background: var(--pi-warning-surface); }
|
|
397
|
+
.msg.bash > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-success) 35%, transparent); background: var(--pi-success-bg); }
|
|
398
|
+
.msg.skill > .msg-header { border-bottom-color: color-mix(in srgb, var(--pi-purple-border) 35%, transparent); background: var(--pi-purple-surface); }
|
|
399
|
+
.group-msg > .msg-header { position: sticky; top: -26px; z-index: 4; margin: -10px 0 8px; padding: 7px 0 6px; border-bottom: 1px solid color-mix(in srgb, var(--pi-border-muted) 35%, transparent); background: var(--pi-bg); }
|
|
400
|
+
.msg-header-trailing { min-width: 0; display: inline-flex; align-items: baseline; justify-content: flex-end; gap: 8px; }
|
|
401
|
+
.msg-actions { display: inline-flex; gap: 6px; opacity: 0; transition: opacity .12s ease; }
|
|
402
|
+
.msg-action { display: inline-grid; place-items: center; width: 24px; height: 24px; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 0; font: 14px system-ui, sans-serif; line-height: 1; cursor: pointer; }
|
|
403
|
+
.msg-action:hover, .msg-action:focus { color: var(--pi-text); border-color: var(--pi-accent); }
|
|
404
|
+
.msg:hover > .msg-header .msg-actions, .msg:focus-within > .msg-header .msg-actions, .group-msg:hover > .msg-header .msg-actions, .group-msg:focus-within > .msg-header .msg-actions { opacity: 1; }
|
|
405
|
+
.label { display: block; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
|
|
406
|
+
.msg-header .label { margin: 0; }
|
|
407
|
+
.msg-meta { min-width: 0; opacity: .28; border: 0; background: transparent; color: var(--pi-dim); padding: 0; font: 11px system-ui, sans-serif; text-align: right; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; transition: opacity .12s ease, max-width .12s ease; cursor: pointer; user-select: text; -webkit-user-select: text; }
|
|
408
|
+
.msg:hover > .msg-header .msg-meta, .msg:focus-within > .msg-header .msg-meta, .group-msg:hover > .msg-header .msg-meta, .group-msg:focus-within > .msg-header .msg-meta, .msg-meta:focus, .msg-meta.expanded { opacity: 1; }
|
|
409
|
+
.msg-meta:focus { outline: 1px solid var(--pi-border); outline-offset: 3px; border-radius: 4px; }
|
|
410
|
+
@media (hover: none) {
|
|
411
|
+
.msg-actions { opacity: 1; }
|
|
412
|
+
.msg-meta { opacity: .75; max-width: 26px; }
|
|
413
|
+
.msg-meta::before { content: "ⓘ"; font-size: 13px; }
|
|
414
|
+
.msg-meta:focus, .msg-meta.expanded { opacity: 1; max-width: 75%; }
|
|
415
|
+
.msg-meta:focus::before, .msg-meta.expanded::before { content: ""; }
|
|
416
|
+
}
|
|
417
|
+
formatted-text.part { display: block; }
|
|
418
|
+
.part { max-width: 100%; min-width: 0; box-sizing: border-box; overflow: visible; }
|
|
419
|
+
.part + .part { margin-top: 10px; }
|
|
420
|
+
.tool-line { color: var(--pi-warning); }
|
|
421
|
+
.summary { color: var(--pi-muted); margin-left: 6px; }
|
|
422
|
+
.part:is(details) { border-top: 1px solid var(--pi-border); padding-top: 8px; }
|
|
423
|
+
.part > formatted-text { display: block; max-width: 100%; min-width: 0; overflow: visible; }
|
|
424
|
+
.skill-invocation, .skill-read { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); padding: 8px 10px; }
|
|
425
|
+
.skill-invocation > summary, .skill-read > strong { color: var(--pi-purple); }
|
|
426
|
+
.skill-invocation > small, .skill-read > small { display: block; margin: 6px 0 0; color: var(--pi-muted); }
|
|
427
|
+
summary { cursor: pointer; color: var(--pi-muted); }
|
|
428
|
+
pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; }
|
|
429
|
+
.shell-output { color: var(--pi-text); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
|
|
430
|
+
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
431
|
+
`,cf=A`
|
|
432
|
+
:host { display: block; }
|
|
433
|
+
.formatted { white-space: normal; overflow-wrap: anywhere; line-height: 1.45; }
|
|
434
|
+
p, ul, ol, pre, blockquote, table, .code-block-wrapper { margin: 0 0 10px; }
|
|
435
|
+
:is(p, ul, ol, pre, blockquote, table, .code-block-wrapper):last-child { margin-bottom: 0; }
|
|
436
|
+
ul, ol { padding-left: 22px; }
|
|
437
|
+
li + li { margin-top: 3px; }
|
|
438
|
+
code { border: 1px solid var(--pi-border); border-radius: 4px; background: var(--pi-bg); padding: 1px 4px; font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
|
|
439
|
+
.code-block-wrapper { position: relative; }
|
|
440
|
+
.code-block-wrapper pre { margin: 0; padding-right: 40px; }
|
|
441
|
+
pre { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); padding: 10px; overflow-x: auto; overflow-y: hidden; }
|
|
442
|
+
pre code { border: 0; padding: 0; background: transparent; }
|
|
443
|
+
.code-copy-button { position: absolute; top: 6px; right: 6px; z-index: 1; display: inline-grid; place-items: center; width: 24px; height: 24px; border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-muted); padding: 0; font: 14px system-ui, sans-serif; line-height: 1; cursor: pointer; }
|
|
444
|
+
.code-copy-button:hover, .code-copy-button:focus { color: var(--pi-text); border-color: var(--pi-accent); }
|
|
445
|
+
blockquote { border-left: 3px solid var(--pi-border); padding-left: 10px; color: var(--pi-muted); }
|
|
446
|
+
a { color: var(--pi-accent); }
|
|
447
|
+
h1, h2, h3, h4 { margin: 14px 0 8px; line-height: 1.2; }
|
|
448
|
+
h1:first-child, h2:first-child, h3:first-child, h4:first-child { margin-top: 0; }
|
|
449
|
+
h1 { font-size: 20px; }
|
|
450
|
+
h2 { font-size: 17px; }
|
|
451
|
+
h3 { font-size: 15px; }
|
|
452
|
+
h4 { font-size: 14px; }
|
|
453
|
+
table { border-collapse: collapse; display: block; overflow-x: auto; overflow-y: hidden; }
|
|
454
|
+
th, td { border: 1px solid var(--pi-border); padding: 4px 8px; }
|
|
455
|
+
th { background: var(--pi-surface); }
|
|
456
|
+
`,df=A`
|
|
457
|
+
:host { display: block; color: var(--pi-muted); font: 12px system-ui, sans-serif; }
|
|
458
|
+
.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; }
|
|
459
|
+
span { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
460
|
+
.activity { display: inline-flex; align-items: center; gap: 6px; color: var(--pi-muted); }
|
|
461
|
+
.activity.active { color: var(--pi-success); }
|
|
462
|
+
.dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; opacity: .45; flex: 0 0 auto; }
|
|
463
|
+
.activity.active .dot { animation: pulse 1s ease-in-out infinite; opacity: 1; }
|
|
464
|
+
.muted { color: var(--pi-dim); }
|
|
465
|
+
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
466
|
+
`,pf=A`
|
|
467
|
+
:host { display: block; }
|
|
468
|
+
.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); }
|
|
469
|
+
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; }
|
|
470
|
+
button:last-child { border-bottom: 0; }
|
|
471
|
+
button.selected, button:hover { background: var(--pi-selection-bg); }
|
|
472
|
+
span { color: var(--pi-muted); font-size: 12px; }
|
|
473
|
+
small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
474
|
+
`,Xn=A`
|
|
475
|
+
:host { position: fixed; inset: 0; z-index: 10; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
476
|
+
.backdrop { display: grid; place-items: center; width: 100%; height: 100%; background: var(--pi-overlay); }
|
|
477
|
+
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; }
|
|
478
|
+
header { display: flex; align-items: center; justify-content: space-between; padding: 12px; border-bottom: 1px solid var(--pi-border); }
|
|
479
|
+
.options { min-height: 0; overflow: auto; outline: none; }
|
|
480
|
+
button { border: 0; background: transparent; color: var(--pi-text); cursor: pointer; }
|
|
481
|
+
header button { font-size: 20px; color: var(--pi-muted); }
|
|
482
|
+
input { margin: 10px 12px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); font: 14px system-ui, sans-serif; padding: 8px 10px; outline: none; }
|
|
483
|
+
input:focus { border-color: var(--pi-accent); }
|
|
484
|
+
.options button { display: block; width: 100%; padding: 10px 12px; border-bottom: 1px solid var(--pi-border-muted); text-align: left; }
|
|
485
|
+
.options button.selected, .options button:hover { background: var(--pi-selection-bg); }
|
|
486
|
+
small { display: block; margin-top: 4px; color: var(--pi-muted); }
|
|
487
|
+
.empty { padding: 24px; color: var(--pi-muted); text-align: center; }
|
|
488
|
+
`,hf=A`
|
|
489
|
+
:host { position: fixed; inset: 0; z-index: 20; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
490
|
+
.backdrop { --palette-top: min(12dvh, 90px); --palette-bottom: max(20px, env(safe-area-inset-bottom)); display: grid; align-items: start; justify-items: center; width: 100%; height: 100dvh; background: var(--pi-overlay); padding: var(--palette-top) 20px var(--palette-bottom); box-sizing: border-box; overflow: hidden; }
|
|
491
|
+
section { width: min(720px, 100%); max-height: min(640px, calc(100dvh - var(--palette-top) - var(--palette-bottom))); display: flex; flex-direction: column; border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
|
|
492
|
+
header { display: grid; grid-template-columns: 1fr auto; gap: 8px; padding: 10px; border-bottom: 1px solid var(--pi-border); }
|
|
493
|
+
input { min-width: 0; border: 0; outline: none; background: transparent; color: var(--pi-text); font: 16px system-ui, sans-serif; padding: 8px; }
|
|
494
|
+
input::placeholder { color: var(--pi-dim); }
|
|
495
|
+
button { border: 0; background: transparent; color: var(--pi-text); cursor: pointer; }
|
|
496
|
+
header button { color: var(--pi-muted); font-size: 22px; padding: 2px 8px; }
|
|
497
|
+
.options { flex: 1 1 auto; min-height: 0; overflow: auto; }
|
|
498
|
+
.options button { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 3px 12px; width: 100%; padding: 10px 12px; border-bottom: 1px solid var(--pi-border-muted); text-align: left; }
|
|
499
|
+
.options button.selected, .options button:hover { background: var(--pi-selection-bg); }
|
|
500
|
+
.main { min-width: 0; }
|
|
501
|
+
strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
502
|
+
small { display: block; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
503
|
+
.group { grid-column: 1 / -1; font-size: 12px; }
|
|
504
|
+
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; }
|
|
505
|
+
.empty { padding: 24px; color: var(--pi-muted); text-align: center; }
|
|
506
|
+
`,uf=A`
|
|
507
|
+
:host { position: relative; z-index: 5; display: block; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
508
|
+
footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 8px; padding: 12px; border-top: 1px solid var(--pi-border); }
|
|
509
|
+
footer.shell-mode { border-top-color: var(--pi-success); background: var(--pi-success-bg); }
|
|
510
|
+
.editor-wrap { position: relative; min-width: 0; }
|
|
511
|
+
.actions { display: flex; gap: 8px; align-items: center; justify-content: flex-end; flex-wrap: nowrap; white-space: nowrap; }
|
|
512
|
+
.compact-status { display: flex; min-width: 0; align-items: center; gap: 6px; color: var(--pi-muted); font-size: 12px; flex: 1 1 0; }
|
|
513
|
+
.compact-status > button { flex: 0 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
514
|
+
.select-model { max-width: min(42vw, 320px); }
|
|
515
|
+
.select-thinking { max-width: 110px; }
|
|
516
|
+
textarea, .markdown-editor .cm-editor { box-sizing: border-box; width: 100%; min-height: 54px; max-height: 220px; resize: none; overflow: hidden; border-radius: 8px; border: 1px solid var(--pi-border); background: var(--pi-bg); color: var(--pi-text); font: 16px/1.4 system-ui, sans-serif; }
|
|
517
|
+
textarea { overflow-y: auto; padding: 8px; }
|
|
518
|
+
.markdown-editor .cm-scroller { max-height: 220px; overflow-y: auto; font-family: system-ui, sans-serif; line-height: 1.4; }
|
|
519
|
+
.markdown-editor .cm-content { min-height: 38px; padding: 8px; caret-color: var(--pi-text); }
|
|
520
|
+
.markdown-editor .cm-line { padding: 0; }
|
|
521
|
+
.markdown-editor .cm-placeholder { color: var(--pi-dim); }
|
|
522
|
+
.markdown-editor .cm-focused { outline: none; }
|
|
523
|
+
.shell-mode textarea, .shell-mode .markdown-editor .cm-editor { border-color: var(--pi-success); box-shadow: 0 0 0 1px var(--pi-success-ring); }
|
|
524
|
+
.mode-hint { position: absolute; right: 8px; bottom: 8px; max-width: calc(100% - 16px); border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 2px 8px; font-size: 12px; pointer-events: none; }
|
|
525
|
+
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
526
|
+
button:disabled, textarea:disabled, .markdown-editor-disabled .cm-editor { opacity: .5; cursor: not-allowed; }
|
|
527
|
+
@media (max-width: 640px) {
|
|
528
|
+
footer { gap: 8px; padding: 8px; }
|
|
529
|
+
.actions { gap: 6px; }
|
|
530
|
+
.compact-status { flex: 1 1 220px; gap: 4px; }
|
|
531
|
+
.select-model { max-width: min(58vw, 260px); }
|
|
532
|
+
button { padding: 6px 8px; }
|
|
533
|
+
}
|
|
534
|
+
@media (max-width: 430px) {
|
|
535
|
+
.compact-status { flex-basis: 170px; font-size: 11px; }
|
|
536
|
+
.select-model { max-width: 48vw; }
|
|
537
|
+
.select-thinking { max-width: 70px; }
|
|
538
|
+
button { padding: 5px 7px; }
|
|
539
|
+
}
|
|
540
|
+
`;var ff=Object.defineProperty,gf=Object.getOwnPropertyDescriptor,oe=(e,t,i,s)=>{for(var o=s>1?void 0:s?gf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&ff(t,i,o),o};let J=class extends T{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.openMenuMachineId!==void 0&&!this.machines.some(t=>t.id===this.openMenuMachineId)&&(this.openMenuMachineId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuMachineId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Ai(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
|
|
541
|
+
<section>
|
|
542
|
+
<h2>${this.renderHeading()}</h2>
|
|
543
|
+
${this.collapsed?null:l`
|
|
544
|
+
<div class="list-body">
|
|
545
|
+
${this.machines.map(e=>this.renderMachine(e))}
|
|
546
|
+
</div>
|
|
547
|
+
`}
|
|
548
|
+
</section>
|
|
549
|
+
`}renderMachine(e){const t=this.statuses[e.id]?.status??e.status??"unknown",i=t==="online"?"在线":t==="offline"?"离线":t==="error"?"错误":"未知",s=Yn(e)&&this.onRemove!==void 0;return l`
|
|
550
|
+
<div
|
|
551
|
+
class=${`action-row machine-row ${this.selected?.id===e.id?"selected":""} ${s?"":"no-actions"}`}
|
|
552
|
+
tabindex="0"
|
|
553
|
+
title=${e.baseUrl??e.name}
|
|
554
|
+
@click=${o=>{Mi(o,()=>this.onSelect?.(e))}}
|
|
555
|
+
@keydown=${o=>{this.handleMachineKeydown(o,e)}}
|
|
556
|
+
>
|
|
557
|
+
<div class="action-main">
|
|
558
|
+
<span class="action-name machine-primary">${this.renderActivity(e)}<span class="machine-primary-label">${e.name}</span></span><small>${e.kind==="local"?"本机 Pi Web":e.baseUrl??"远程 Pi Web"} · ${i}</small>
|
|
559
|
+
</div>
|
|
560
|
+
${s?this.renderMachineMenu(e):null}
|
|
561
|
+
</div>
|
|
562
|
+
`}renderActivity(e){const t=this.statuses[e.id]?.status??e.status;if(t==="offline"||t==="error")return;const i=Hn(this.activities[e.id]);return Ti(i,i==="terminal"?"机器终端活跃":"机器活跃")}renderMachineMenu(e){const t=this.openMenuMachineId===e.id,i=mf(e.id);return l`
|
|
563
|
+
<div class="action-menu">
|
|
564
|
+
<button
|
|
565
|
+
class="action-menu-toggle"
|
|
566
|
+
title="机器操作"
|
|
567
|
+
aria-label=${`${e.name} 的操作`}
|
|
568
|
+
aria-expanded=${String(t)}
|
|
569
|
+
aria-controls=${i}
|
|
570
|
+
@click=${s=>{s.stopPropagation(),this.toggleMenu(e.id,s.currentTarget)}}
|
|
571
|
+
>⋯</button>
|
|
572
|
+
${t?l`
|
|
573
|
+
<div class="action-menu-panel machine-menu-panel" id=${i} style=${this.menuStyle} @click=${s=>{s.stopPropagation()}}>
|
|
574
|
+
<button class="danger" title=${`移除 ${e.name}`} @click=${()=>{this.removeMachine(e)}}>移除</button>
|
|
575
|
+
</div>
|
|
576
|
+
`:null}
|
|
577
|
+
</div>
|
|
578
|
+
`}renderHeading(){if(!this.collapsible)return"机器";const e=this.selected?.name??"未选择机器",t=this.selected?.baseUrl??e;return l`<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?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}toggleMenu(e,t){if(this.openMenuMachineId===e){this.openMenuMachineId=void 0;return}this.menuStyle=Ot(t),this.openMenuMachineId=e}removeMachine(e){this.openMenuMachineId=void 0,this.onRemove?.(e)}handleMachineKeydown(e,t){if(e.key==="Escape"&&this.openMenuMachineId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuMachineId=void 0;return}Ri(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}};J.styles=[Ei,A`
|
|
579
|
+
.machine-row.no-actions .action-main { border-radius: 8px; }
|
|
580
|
+
.machine-primary { display: flex; align-items: baseline; gap: 6px; }
|
|
581
|
+
.machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
582
|
+
.machine-menu-panel button.danger { color: var(--pi-danger); }
|
|
583
|
+
.machine-menu-panel button.danger:hover, .machine-menu-panel button.danger:focus { background: color-mix(in srgb, var(--pi-danger) 14%, transparent); }
|
|
584
|
+
`];oe([d({attribute:!1})],J.prototype,"machines",2);oe([d({attribute:!1})],J.prototype,"selected",2);oe([d({attribute:!1})],J.prototype,"statuses",2);oe([d({attribute:!1})],J.prototype,"activities",2);oe([d({type:Boolean,reflect:!0})],J.prototype,"collapsible",2);oe([d({type:Boolean,reflect:!0})],J.prototype,"collapsed",2);oe([d({attribute:!1})],J.prototype,"onSelect",2);oe([d({attribute:!1})],J.prototype,"onRemove",2);oe([d({attribute:!1})],J.prototype,"onToggleCollapsed",2);oe([d({attribute:!1})],J.prototype,"onFocusNextSection",2);oe([d({attribute:!1})],J.prototype,"onCancelKeyboardNavigation",2);oe([w()],J.prototype,"openMenuMachineId",2);oe([w()],J.prototype,"menuStyle",2);J=oe([R("machine-list")],J);function Yn(e){return e.kind==="remote"}function mf(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var vf=Object.defineProperty,bf=Object.getOwnPropertyDescriptor,Y=(e,t,i,s)=>{for(var o=s>1?void 0:s?bf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&vf(t,i,o),o};let K=class extends T{constructor(){super(...arguments),this.projects=[],this.activities={},this.workspacesByProjectId={},this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuProjectId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("projects")&&this.openMenuProjectId!==void 0&&!this.projects.some(t=>t.id===this.openMenuProjectId)&&(this.openMenuProjectId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuProjectId=void 0)}async focusSelectedOrFirst(){return await this.updateComplete,Ai(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
|
|
585
|
+
<section>
|
|
586
|
+
<h2>${this.renderHeading()}</h2>
|
|
587
|
+
${this.collapsed?null:l`
|
|
588
|
+
<div class="list-body">
|
|
589
|
+
${this.projects.length===0?l`
|
|
590
|
+
<div class="empty-list" role="status">
|
|
591
|
+
<strong>暂无可访问项目</strong>
|
|
592
|
+
<small>请先在 AI 平台手动创建项目,然后刷新此页面。</small>
|
|
593
|
+
</div>
|
|
594
|
+
`:this.projects.map(e=>l`
|
|
595
|
+
<div
|
|
596
|
+
class=${`action-row ${this.selected?.id===e.id?"selected":""}`}
|
|
597
|
+
tabindex="0"
|
|
598
|
+
title=${e.path}
|
|
599
|
+
@click=${t=>{Mi(t,()=>this.onSelect?.(e))}}
|
|
600
|
+
@keydown=${t=>{this.handleProjectKeydown(t,e)}}
|
|
601
|
+
>
|
|
602
|
+
<div class="action-main">
|
|
603
|
+
<span class="action-name">${e.name}</span><small>${e.path}</small>
|
|
604
|
+
${this.renderActivity(e)}
|
|
605
|
+
</div>
|
|
606
|
+
<div class="action-menu">
|
|
607
|
+
<button class="action-menu-toggle" title="项目操作" aria-label=${`${e.name} 的操作`} @click=${t=>{t.stopPropagation(),this.toggleMenu(e.id,t.currentTarget)}}>⋯</button>
|
|
608
|
+
${this.openMenuProjectId===e.id?l`
|
|
609
|
+
<div class="action-menu-panel" style=${this.menuStyle}>
|
|
610
|
+
<button title="关闭项目" @click=${()=>{this.close(e)}}>关闭</button>
|
|
611
|
+
</div>
|
|
612
|
+
`:null}
|
|
613
|
+
</div>
|
|
614
|
+
</div>
|
|
615
|
+
`)}
|
|
616
|
+
</div>
|
|
617
|
+
`}
|
|
618
|
+
</section>
|
|
619
|
+
`}handleProjectKeydown(e,t){Ri(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"项目";const e=this.selected?.name??"未选择项目",t=this.selected?.path??e;return l`<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?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){const t=Xu(e,this.workspacesByProjectId[e.id]??[],this.activities);return Ti(t,t==="terminal"?"项目终端活跃":"项目活跃")}toggleMenu(e,t){if(this.openMenuProjectId===e){this.openMenuProjectId=void 0;return}this.menuStyle=Ot(t),this.openMenuProjectId=e}close(e){this.openMenuProjectId=void 0,confirm(`关闭 ${e.name}?
|
|
620
|
+
|
|
621
|
+
这只会从 PI WEB 中移除它,不会修改项目文件夹。`)&&this.onClose?.(e)}};K.styles=Ei;Y([d({attribute:!1})],K.prototype,"projects",2);Y([d({attribute:!1})],K.prototype,"selected",2);Y([d({attribute:!1})],K.prototype,"activities",2);Y([d({attribute:!1})],K.prototype,"workspacesByProjectId",2);Y([d({type:Boolean,reflect:!0})],K.prototype,"collapsible",2);Y([d({type:Boolean,reflect:!0})],K.prototype,"collapsed",2);Y([d({attribute:!1})],K.prototype,"onSelect",2);Y([d({attribute:!1})],K.prototype,"onClose",2);Y([d({attribute:!1})],K.prototype,"onToggleCollapsed",2);Y([d({attribute:!1})],K.prototype,"onFocusPreviousSection",2);Y([d({attribute:!1})],K.prototype,"onFocusNextSection",2);Y([d({attribute:!1})],K.prototype,"onCancelKeyboardNavigation",2);Y([w()],K.prototype,"openMenuProjectId",2);Y([w()],K.prototype,"menuStyle",2);K=Y([R("project-list")],K);function hr(e=[]){return e.map((t,i)=>l`${i===0?null:l`<span class="workspace-label-separator">·</span>`}${wf(t)}`)}function wf(e){if(e.type==="render")return l`<span class="workspace-label-render">${e.render()}</span>`;if(e.type==="link"&&yf(e.href)){const t=e.target??"_blank",i=t==="_blank"?"noopener noreferrer":void 0;return l`<a class="workspace-label-item workspace-label-link" href=${e.href} title=${e.title??e.text} target=${t} rel=${i??void 0}>${e.text}</a>`}return l`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function yf(e){const t=e.trim().toLowerCase();return t!==""&&!t.startsWith("javascript:")&&!t.startsWith("data:")}var xf=Object.defineProperty,Sf=Object.getOwnPropertyDescriptor,Z=(e,t,i,s)=>{for(var o=s>1?void 0:s?Sf(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&xf(t,i,o),o};let H=class extends T{constructor(){super(...arguments),this.workspaces=[],this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],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(t=>t.id===this.openMenuWorkspaceId)&&(this.openMenuWorkspaceId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuWorkspaceId=void 0),(e.has("selected")||e.has("workspaces")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,Ai(this.renderRoot,{fallbackSelector:".section-toggle"})}render(){return l`
|
|
622
|
+
<section>
|
|
623
|
+
<h2>${this.renderHeading()}</h2>
|
|
624
|
+
${this.collapsed?null:l`
|
|
625
|
+
<div class="list-body">
|
|
626
|
+
${this.workspaces.map(e=>{const t=kf(e),i=this.workspaceLabelItems(e);return l`
|
|
627
|
+
<div
|
|
628
|
+
class=${`action-row workspace-row ${this.selected?.id===e.id?"selected":""}`}
|
|
629
|
+
tabindex="0"
|
|
630
|
+
title=${t}
|
|
631
|
+
@click=${s=>{Mi(s,()=>this.onSelect?.(e))}}
|
|
632
|
+
@keydown=${s=>{this.handleWorkspaceKeydown(s,e)}}
|
|
633
|
+
>
|
|
634
|
+
<div class="action-main">
|
|
635
|
+
${this.renderWorkspaceMain(t,i,e)}
|
|
636
|
+
</div>
|
|
637
|
+
${this.renderWorkspaceMenu(t,i,e)}
|
|
638
|
+
</div>
|
|
639
|
+
`})}
|
|
640
|
+
</div>
|
|
641
|
+
`}
|
|
642
|
+
</section>
|
|
643
|
+
`}renderHeading(){if(!this.collapsible)return"工作区";const e=this.selected===void 0?"未选择工作区":`${this.selected.label}${this.selected.isMain?" · 主工作区":""} · ${this.selected.path}`,t=this.selected?.path??e;return l`<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?l`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){const t=Qu(Zu(e,this.activities));return Ti(t,t==="terminal"?"工作区终端活跃":"工作区活跃")}renderWorkspaceMain(e,t,i){return l`
|
|
644
|
+
<span class="workspace-primary">
|
|
645
|
+
<span class="workspace-primary-label">${e}</span>
|
|
646
|
+
${this.isDeleting(i)?l`<span class="workspace-status">正在删除…</span>`:null}
|
|
647
|
+
</span>
|
|
648
|
+
${t.length===0?null:l`
|
|
649
|
+
<small class="workspace-secondary">
|
|
650
|
+
<span class="workspace-label">${hr(t)}</span>
|
|
651
|
+
</small>
|
|
652
|
+
`}
|
|
653
|
+
${this.renderActivity(i)}
|
|
654
|
+
`}renderWorkspaceMenu(e,t,i){const s=this.openMenuWorkspaceId===i.id,o=Pf(i.id);return l`
|
|
655
|
+
<div class="action-menu">
|
|
656
|
+
<button
|
|
657
|
+
class="action-menu-toggle"
|
|
658
|
+
title="工作区操作和详情"
|
|
659
|
+
aria-label=${`${e} 的操作和详情`}
|
|
660
|
+
aria-expanded=${String(s)}
|
|
661
|
+
aria-controls=${o}
|
|
662
|
+
@click=${r=>{r.stopPropagation(),this.toggleMenu(i.id,r.currentTarget)}}
|
|
663
|
+
>⋯</button>
|
|
664
|
+
${s?l`
|
|
665
|
+
<div class="action-menu-panel workspace-menu-panel" id=${o} style=${this.menuStyle} @click=${r=>{r.stopPropagation()}}>
|
|
666
|
+
${this.renderWorkspaceActions(i)}
|
|
667
|
+
${this.renderWorkspaceDetails(e,t,i)}
|
|
668
|
+
</div>
|
|
669
|
+
`:null}
|
|
670
|
+
</div>
|
|
671
|
+
`}renderWorkspaceActions(e){if(!$f(e))return;const t=this.isDeleting(e);return l`
|
|
672
|
+
<div class="workspace-menu-actions">
|
|
673
|
+
<button class="danger" title=${t?"正在删除工作区":"删除工作区"} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?"正在删除…":"删除工作区"}</button>
|
|
674
|
+
</div>
|
|
675
|
+
`}renderWorkspaceDetails(e,t,i){return l`
|
|
676
|
+
<dl class="workspace-menu-details">
|
|
677
|
+
<div class="workspace-detail-row">
|
|
678
|
+
<dt>${i.branch===void 0?"工作区":"分支"}</dt>
|
|
679
|
+
<dd>${e}</dd>
|
|
680
|
+
</div>
|
|
681
|
+
<div class="workspace-detail-row">
|
|
682
|
+
<dt>路径</dt>
|
|
683
|
+
<dd title=${i.path}>${i.path}</dd>
|
|
684
|
+
</div>
|
|
685
|
+
${t.length===0?null:l`
|
|
686
|
+
<div class="workspace-detail-row">
|
|
687
|
+
<dt>详情</dt>
|
|
688
|
+
<dd><span class="workspace-label">${hr(t)}</span></dd>
|
|
689
|
+
</div>
|
|
690
|
+
`}
|
|
691
|
+
</dl>
|
|
692
|
+
`}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=Ot(t),this.openMenuWorkspaceId=e}handleWorkspaceKeydown(e,t){if(e.key==="Escape"&&this.openMenuWorkspaceId===t.id){e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0;return}Ri(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"})}};H.styles=Ei;Z([d({attribute:!1})],H.prototype,"workspaces",2);Z([d({attribute:!1})],H.prototype,"selected",2);Z([d({type:Boolean,reflect:!0})],H.prototype,"collapsible",2);Z([d({type:Boolean,reflect:!0})],H.prototype,"collapsed",2);Z([d({attribute:!1})],H.prototype,"workspaceLabelItems",2);Z([d({attribute:!1})],H.prototype,"activities",2);Z([d({attribute:!1})],H.prototype,"deletingWorkspaceIds",2);Z([d({attribute:!1})],H.prototype,"onSelect",2);Z([d({attribute:!1})],H.prototype,"onDelete",2);Z([d({attribute:!1})],H.prototype,"onToggleCollapsed",2);Z([d({attribute:!1})],H.prototype,"onFocusPreviousSection",2);Z([d({attribute:!1})],H.prototype,"onFocusNextSection",2);Z([d({attribute:!1})],H.prototype,"onCancelKeyboardNavigation",2);Z([w()],H.prototype,"openMenuWorkspaceId",2);Z([w()],H.prototype,"menuStyle",2);H=Z([R("workspace-list")],H);function kf(e){return`${e.branch??e.label}${e.isMain?" · 主工作区":""}`}function $f(e){return e.isGitWorktree&&!e.isMain}function Pf(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,"-")}`}var Cf=Object.defineProperty,If=Object.getOwnPropertyDescriptor,O=(e,t,i,s)=>{for(var o=s>1?void 0:s?If(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Cf(t,i,o),o};function Zi(e){return e.name!==void 0&&e.name!==""?e.name:e.firstMessage!==""?e.firstMessage:e.id.slice(0,8)}let D=class extends T{constructor(){super(...arguments),this.sessions=[],this.statuses={},this.activities={},this.canStart=!1,this.collapsible=!1,this.collapsed=!1,this.menuStyle="",this.archivedExpanded=!1,this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.openMenuSessionId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("sessions")&&this.openMenuSessionId!==void 0&&!this.sessions.some(i=>i.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),e.has("collapsed")&&this.collapsed&&(this.openMenuSessionId=void 0),e.has("sessions")&&!this.sessions.some(i=>i.archived===!0)&&(this.archivedExpanded=!1);const t=e.get("selected");if(e.has("selected")&&this.selected?.archived===!0&&(t?.id!==this.selected.id||t.archived!==!0)&&!this.archivedExpanded){this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()});return}(e.has("selected")||e.has("sessions")||e.has("collapsed"))&&!this.collapsed&&this.scrollSelectedIntoView()}async focusSelectedOrFirst(){return await this.updateComplete,Ai(this.renderRoot,{fallbackSelector:".section-toggle, h2 button:not([disabled])"})}render(){const e=Mf(this.sessions),t=new Set(e.map(o=>o.session.id)),i=ea(this.sessions.filter(o=>o.archived===!0&&!t.has(o.id))),s=Tf(this.sessions);return l`
|
|
693
|
+
<section>
|
|
694
|
+
${this.renderHeading(e.length+i.length)}
|
|
695
|
+
${this.collapsed?null:l`
|
|
696
|
+
<div class="list-body">
|
|
697
|
+
${e.map(o=>this.renderSession(o,s.get(o.session.id)??0))}
|
|
698
|
+
${i.length>0?l`
|
|
699
|
+
<h2 class="subheading"><button class="section-toggle" aria-expanded=${String(this.archivedExpanded)} @click=${()=>{this.toggleArchived()}}><span>${this.archivedExpanded?"▾":"▸"} 已归档</span><small>${i.length}</small></button></h2>
|
|
700
|
+
${this.archivedExpanded?i.map(o=>this.renderSession(o,s.get(o.session.id)??0)):null}
|
|
701
|
+
`:null}
|
|
702
|
+
</div>
|
|
703
|
+
`}
|
|
704
|
+
</section>
|
|
705
|
+
`}renderHeading(e){if(!this.collapsible)return l`<h2>会话 <button ?disabled=${!this.canStart} @click=${()=>this.onStart?.()}>+</button></h2>`;const t=this.selected===void 0?"未选择会话":Zi(this.selected),i=this.selected?.path??t;return l`
|
|
706
|
+
<h2>
|
|
707
|
+
<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?l`<small class="section-selected" title=${i}>${t}</small>`:null}</span><small class="section-count">${e}</small></button>
|
|
708
|
+
<button ?disabled=${!this.canStart} @click=${s=>{s.stopPropagation(),this.onStart?.()}}>+</button>
|
|
709
|
+
</h2>
|
|
710
|
+
`}renderSession(e,t){const{session:i}=e,s=Math.min(e.depth,2);return l`
|
|
711
|
+
<div
|
|
712
|
+
class="action-row ${this.selected?.id===i.id?"selected":""} ${i.archived===!0?"archived":""}"
|
|
713
|
+
style=${`--depth:${String(s)}`}
|
|
714
|
+
tabindex="0"
|
|
715
|
+
title=${i.path}
|
|
716
|
+
@click=${o=>{Mi(o,()=>this.onSelect?.(i))}}
|
|
717
|
+
@keydown=${o=>{this.handleSessionKeydown(o,i)}}
|
|
718
|
+
>
|
|
719
|
+
<div class="action-main">
|
|
720
|
+
<span class="action-name">${e.depth>0?l`<span class="tree-marker">↳</span>`:null}${Zi(i)}${e.depth>2?l` <span class="badge">深度 ${e.depth}</span>`:null}${e.hasMissingParent?l` <span class="badge">父会话不可用</span>`:null}</span><small>${this.renderSessionMetaPrefix(i)}${String(i.messageCount)} 条消息</small>
|
|
721
|
+
${this.renderActivity(i)}
|
|
722
|
+
</div>
|
|
723
|
+
<div class="action-menu">
|
|
724
|
+
<button class="action-menu-toggle" title="会话操作" @click=${o=>{o.stopPropagation(),this.toggleMenu(i.id,o.currentTarget)}}>⋯</button>
|
|
725
|
+
${this.openMenuSessionId===i.id?l`
|
|
726
|
+
<div class="action-menu-panel" style=${this.menuStyle}>
|
|
727
|
+
${i.parentSessionPath!==void 0?l`<button title="从父会话分离" @click=${()=>{this.openMenuSessionId=void 0,this.onDetachParent?.(i)}}>从父会话分离</button>`:null}
|
|
728
|
+
${Ce(i)?l`<button title="删除浏览器缓存的新会话" @click=${()=>{this.openMenuSessionId=void 0,this.onDelete?.(i)}}>删除</button>`:i.archived===!0?l`<button title="恢复会话" @click=${()=>{this.openMenuSessionId=void 0,this.onRestore?.(i)}}>恢复</button>`:l`
|
|
729
|
+
<button title="归档会话" @click=${()=>{this.openMenuSessionId=void 0,this.onArchive?.(i)}}>归档</button>
|
|
730
|
+
${t>0?l`<button title="归档此会话及其子会话" @click=${()=>{this.openMenuSessionId=void 0,this.confirmArchiveWithDescendants(i,t)}}>连同子会话归档(${t})</button>`:null}
|
|
731
|
+
`}
|
|
732
|
+
</div>
|
|
733
|
+
`:null}
|
|
734
|
+
</div>
|
|
735
|
+
</div>
|
|
736
|
+
`}handleSessionKeydown(e,t){Ri(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?.()}})}confirmArchiveWithDescendants(e,t){confirm(`归档“${Zi(e)}”及 ${String(t)} 个子会话?`)&&this.onArchiveWithDescendants?.(e)}toggleMenu(e,t){if(this.openMenuSessionId===e){this.openMenuSessionId=void 0;return}this.menuStyle=Ot(t),this.openMenuSessionId=e}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.onArchivedCollapsed?.())}scrollSelectedIntoView(){this.renderRoot.querySelector(".action-row.selected")?.scrollIntoView({block:"nearest"})}renderSessionMetaPrefix(e){return Ce(e)?"新建 · ":e.archived===!0?"只读 · ":""}renderActivity(e){if(!(Ce(e)||e.archived===!0))return Ti(Pi(this.statuses[e.id],this.activities[e.id])?"session":void 0,"会话活跃")}};D.styles=Ei;O([d({attribute:!1})],D.prototype,"sessions",2);O([d({attribute:!1})],D.prototype,"statuses",2);O([d({attribute:!1})],D.prototype,"activities",2);O([d({attribute:!1})],D.prototype,"selected",2);O([d({type:Boolean})],D.prototype,"canStart",2);O([d({type:Boolean,reflect:!0})],D.prototype,"collapsible",2);O([d({type:Boolean,reflect:!0})],D.prototype,"collapsed",2);O([d({attribute:!1})],D.prototype,"onSelect",2);O([d({attribute:!1})],D.prototype,"onStart",2);O([d({attribute:!1})],D.prototype,"onToggleCollapsed",2);O([d({attribute:!1})],D.prototype,"onArchivedCollapsed",2);O([d({attribute:!1})],D.prototype,"onFocusPreviousSection",2);O([d({attribute:!1})],D.prototype,"onFocusNextSection",2);O([d({attribute:!1})],D.prototype,"onCancelKeyboardNavigation",2);O([w()],D.prototype,"openMenuSessionId",2);O([w()],D.prototype,"menuStyle",2);O([w()],D.prototype,"archivedExpanded",2);O([d({attribute:!1})],D.prototype,"onArchive",2);O([d({attribute:!1})],D.prototype,"onArchiveWithDescendants",2);O([d({attribute:!1})],D.prototype,"onRestore",2);O([d({attribute:!1})],D.prototype,"onDelete",2);O([d({attribute:!1})],D.prototype,"onDetachParent",2);D=O([R("session-list")],D);function Tf(e){const t=new Map;for(const s of e){if(s.parentSessionPath===void 0)continue;const o=t.get(s.parentSessionPath)??[];o.push(s),t.set(s.parentSessionPath,o)}const i=(s,o)=>{if(o.has(s.path))return 0;const r=new Set(o);r.add(s.path);let n=0;for(const a of t.get(s.path)??[])r.has(a.path)||(a.archived!==!0&&(n+=1),n+=i(a,r));return n};return new Map(e.map(s=>[s.id,i(s,new Set)]))}function Mf(e){const t=new Map(e.map(s=>[s.path,s])),i=new Set;for(const s of e){if(s.archived===!0)continue;i.add(s.id);let o=s.parentSessionPath;const r=new Set([s.path]);for(;o!==void 0&&!r.has(o);){r.add(o);const n=t.get(o);if(n===void 0)break;i.add(n.id),o=n.parentSessionPath}}return ea(e.filter(s=>i.has(s.id)))}function ea(e){const t=new Map(e.map(n=>[n.path,n])),i=new Map,s=[];for(const n of e){const a=n.parentSessionPath,c=a===void 0?void 0:t.get(a);if(c===void 0){s.push(n);continue}const p=i.get(c.path)??[];p.push(n),i.set(c.path,p)}const o=[],r=(n,a,c)=>{if(c.has(n.path))return;const p=n.parentSessionPath;o.push({session:n,depth:a,hasMissingParent:p!==void 0&&!t.has(p)});const u=new Set(c);u.add(n.path);for(const h of i.get(n.path)??[])r(h,a+1,u)};for(const n of s)r(n,0,new Set);return o}const Js={CHILD:2,ELEMENT:6},Zs=e=>(...t)=>({_$litDirective$:e,values:t});let Qs=class{constructor(t){}get _$AU(){return this._$AM._$AU}_$AT(t,i,s){this._$Ct=t,this._$AM=i,this._$Ci=s}_$AS(t,i){return this.update(t,i)}update(t,i){return this.render(...i)}};const{I:Rf}=el,ur=e=>e,fr=()=>document.createComment(""),vt=(e,t,i)=>{const s=e._$AA.parentNode,o=t===void 0?e._$AB:t._$AA;if(i===void 0){const r=s.insertBefore(fr(),o),n=s.insertBefore(fr(),o);i=new Rf(r,n,e,e.options)}else{const r=i._$AB.nextSibling,n=i._$AM,a=n!==e;if(a){let c;i._$AQ?.(e),i._$AM=e,i._$AP!==void 0&&(c=e._$AU)!==n._$AU&&i._$AP(c)}if(r!==o||a){let c=i._$AA;for(;c!==r;){const p=ur(c).nextSibling;ur(s).insertBefore(c,o),c=p}}}return i},Be=(e,t,i=e)=>(e._$AI(t,i),e),Af={},Ef=(e,t=Af)=>e._$AH=t,Df=e=>e._$AH,Qi=e=>{e._$AR(),e._$AA.remove()};const gr=(e,t,i)=>{const s=new Map;for(let o=t;o<=i;o++)s.set(e[o],o);return s},Wf=Zs(class extends Qs{constructor(e){if(super(e),e.type!==Js.CHILD)throw Error("repeat() can only be used in text expressions")}dt(e,t,i){let s;i===void 0?i=t:t!==void 0&&(s=t);const o=[],r=[];let n=0;for(const a of e)o[n]=s?s(a,n):n,r[n]=i(a,n),n++;return{values:r,keys:o}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,s]){const o=Df(e),{values:r,keys:n}=this.dt(t,i,s);if(!Array.isArray(o))return this.ut=n,r;const a=this.ut??=[],c=[];let p,u,h=0,f=o.length-1,b=0,P=r.length-1;for(;h<=f&&b<=P;)if(o[h]===null)h++;else if(o[f]===null)f--;else if(a[h]===n[b])c[b]=Be(o[h],r[b]),h++,b++;else if(a[f]===n[P])c[P]=Be(o[f],r[P]),f--,P--;else if(a[h]===n[P])c[P]=Be(o[h],r[P]),vt(e,c[P+1],o[h]),h++,P--;else if(a[f]===n[b])c[b]=Be(o[f],r[b]),vt(e,o[h],o[f]),f--,b++;else if(p===void 0&&(p=gr(n,b,P),u=gr(a,h,f)),p.has(a[h]))if(p.has(a[f])){const z=u.get(n[b]),Xe=z!==void 0?o[z]:null;if(Xe===null){const dt=vt(e,o[h]);Be(dt,r[b]),c[b]=dt}else c[b]=Be(Xe,r[b]),vt(e,o[h],Xe),o[z]=null;b++}else Qi(o[f]),f--;else Qi(o[h]),h++;for(;b<=P;){const z=vt(e,c[P+1]);Be(z,r[b]),c[b++]=z}for(;h<=f;){const z=o[h++];z!==null&&Qi(z)}return this.ut=n,Ef(e,c),Ne}}),Of="pi-web:chat-groups:",_f={read(e){try{if(typeof localStorage>"u")return;const t=localStorage.getItem(mr(e));return t===null||t===""?void 0:jf(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>"u")return;localStorage.setItem(mr(e),JSON.stringify(t))}catch{}}};class Lf{constructor(t=_f){this.storage=t,this.sessionId="",this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(t){if(this.sessionId===t)return;this.sessionId=t;const i=t===""?void 0:this.storage.read(t);this.openGroupKeys=new Set(i?.open??[]),this.closedDefaultOpenGroupKeys=new Set(i?.closedDefaultOpen??[])}isOpen(t,i){return i?!this.closedDefaultOpenGroupKeys.has(t):this.openGroupKeys.has(t)}applyToggle(t,i,s){const o=this.isOpen(t,s),r=new Set(this.openGroupKeys),n=new Set(this.closedDefaultOpenGroupKeys);return s?(r.delete(t),i?n.delete(t):n.add(t)):(n.delete(t),i?r.add(t):r.delete(t)),(s?!n.has(t):r.has(t))===o&&vr(r,this.openGroupKeys)&&vr(n,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=r,this.closedDefaultOpenGroupKeys=n,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==""&&this.storage.write(this.sessionId,this.snapshot())}}function mr(e){return`${Of}${e}`}function jf(e){if(Array.isArray(e))return{open:Xi(e),closedDefaultOpen:[]};if(Nf(e))return{open:Array.isArray(e.open)?Xi(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Xi(e.closedDefaultOpen):[]}}function Xi(e){return e.filter(t=>typeof t=="string")}function vr(e,t){if(e.size!==t.size)return!1;for(const i of e)if(!t.has(i))return!1;return!0}function Nf(e){return typeof e=="object"&&e!==null}function Ff(e,t=0){const i=[];let s=[],o=0;const r=(a,c)=>{s.length||(o=c),s.push(a)},n=()=>{s.length&&(i.push({kind:"group",messages:s,startIndex:o,endIndex:o+s.length-1}),s=[])};return e.forEach((a,c)=>{const p=a.parts.filter(b=>br(a,b)),u=a.parts.filter(b=>!br(a,b)),h=t+c,f={...a.source===void 0?{}:{source:a.source},...a.meta===void 0?{}:{meta:a.meta}};if(u.length&&r({role:a.role,parts:u,...f},h),p.length){n();const b=p.every(P=>P.type==="skillRead")?"skill":a.role;i.push({kind:"message",message:{role:b,parts:p,...f},index:h})}}),n(),i}function zf(e){if(e.every(s=>s.source==="compaction"))return`${String(e.length)} 条历史压缩摘要`;if(e.every(s=>s.source==="branch_summary"))return`${String(e.length)} 条分支摘要`;const t=e.reduce((s,o)=>(s[o.role]=(s[o.role]??0)+1,s),{}),i=Object.entries(t).map(([s,o])=>`${String(o)} ${Bf(s)}`).join(" · ");return`${String(e.length)} 个事件${i!==""?` · ${i}`:""}`}function Bf(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function br(e,t){return e.source==="compaction"||e.source==="branch_summary"?!1:t.type==="skillInvocation"||t.type==="skillRead"?!0:t.type==="text"&&(e.role==="user"||e.role==="assistant"||e.role==="system"||e.role==="bash")}const Uf=30;function Hf(e,t){const i=Kf(Jf(e,t)),s={distanceFromBottom:e.scrollHeight-e.scrollTop};return i===void 0?s:{...s,markerId:i.id,markerOffset:i.offset}}function qf(e,t,i){if(i!==void 0&&t.markerOffset!==void 0){const s=i.getBoundingClientRect().top-e.getBoundingClientRect().top;e.scrollTop+=Vf(s,t.markerOffset);return}e.scrollTop=Gf(e.scrollHeight,t.distanceFromBottom)}function Kf(e){let t,i=Number.NEGATIVE_INFINITY,s,o=Number.POSITIVE_INFINITY;for(const r of e)r.offset<=0&&r.offset>=i?(t=r,i=r.offset):r.offset>0&&r.offset<o&&(s=r,o=r.offset);return t??s}function Vf(e,t){return e-t}function Gf(e,t){return Math.max(0,e-t)}function Jf(e,t){const i=e.getBoundingClientRect().top;return t.flatMap(s=>{const o=s.dataset.markerId;return o===void 0?[]:[{id:o,offset:s.getBoundingClientRect().top-i}]})}const Zf=600,Qf=1;function Xf(e){return!e.hasMore||e.loadingMore||!e.canRequest||e.clientHeight<=0?!1:Yf(e)||eg(e)}function Yf(e){return e.scrollTop<(e.topThreshold??Math.max(Zf,e.clientHeight))}function eg(e){return e.scrollHeight<=e.clientHeight+Qf}const tg="pi-web:chat-scroll:",ig=180,sg=48,og=2,rg={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)}},ng={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}};class ag{constructor(t=rg,i=ng){this.storage=t,this.scheduler=i}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(t,i,s=ig){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,i(t)},s)}savePosition(t,i,s,o=og){if(t===""||i===void 0||!es(i))return"skipped";try{if(ia(i,o)){const a={mode:"bottom"};return this.storage.setItem(Yi(t),JSON.stringify(a)),"saved"}const r=dg(i,s);if(r===void 0)return"skipped";const n=cg(i,r);return this.storage.setItem(Yi(t),JSON.stringify(n)),"saved"}catch{return"skipped"}}restorePosition(t,i,s,o){const r=this.readPosition(t);return r===void 0?this.scrollToBottom(i):this.restoreExplicitPosition(r,i,s,o)}restoreExplicitPosition(t,i,s,o){if(t.mode==="bottom")return this.scrollToBottom(i);if(i===void 0||!es(i))return{status:"skipped"};const r=pg(s,t.anchorId);if(r===void 0)return o?.fallbackToBottom===!1?{status:"missing",position:t}:this.scrollToBottom(i);const n=i.getBoundingClientRect().top,a=r.getBoundingClientRect().top-n;return i.scrollTop+=a-t.offset,{status:"restored"}}readPosition(t){if(t!=="")try{const i=this.storage.getItem(Yi(t));if(i===null||i==="")return;const s=JSON.parse(i);return lg(s)?s:void 0}catch{return}}scrollToBottom(t){return t===void 0||!es(t)?{status:"skipped"}:(t.scrollTop=t.scrollHeight,{status:"bottom"})}}function Yi(e){return`${tg}${e}`}function lg(e){return typeof e!="object"||e===null||!("mode"in e)?!1:e.mode==="bottom"?!0:e.mode==="anchor"&&"anchorId"in e&&typeof e.anchorId=="string"&&e.anchorId!==""&&"offset"in e&&typeof e.offset=="number"}function es(e){return e.clientHeight>0&&e.scrollHeight>0}function ta(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function ia(e,t=sg){return ta(e)<t}function cg(e,t){const i=e.getBoundingClientRect().top;return{mode:"anchor",anchorId:Xs(t)??"",offset:t.getBoundingClientRect().top-i}}function dg(e,t){const i=e.getBoundingClientRect();let s,o=Number.NEGATIVE_INFINITY,r,n=Number.POSITIVE_INFINITY;for(const a of t){if(Xs(a)===void 0)continue;const c=a.getBoundingClientRect();if(c.bottom<=c.top||c.bottom<i.top||c.top>i.bottom)continue;const p=c.top-i.top;p<=0&&p>=o?(s=a,o=p):p>0&&p<n&&(r=a,n=p)}return s??r}function wr(e,t){const i=e.getBoundingClientRect();return t.find(s=>{const o=s.getBoundingClientRect();return o.bottom>=i.top&&o.top<=i.bottom})}function pg(e,t){return e.find(i=>Xs(i)===t)}function Xs(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==""?e.dataset.scrollAnchorId:void 0}var hg=Object.defineProperty,ug=Object.getOwnPropertyDescriptor,Ys=(e,t,i,s)=>{for(var o=s>1?void 0:s?ug(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&hg(t,i,o),o};let Tt=class extends T{constructor(){super(...arguments),this.positionPercent=0,this.loadedPercent=100}render(){const e=yr(this.positionPercent),t=yr(this.loadedPercent),i=`消息位置:约在会话 ${String(Math.round(e))}% 处。已加载 ${String(Math.round(t))}% 的消息。`;return l`
|
|
737
|
+
<div
|
|
738
|
+
class="meter"
|
|
739
|
+
style=${`--position:${e.toFixed(2)}%;`}
|
|
740
|
+
role="meter"
|
|
741
|
+
aria-label=${i}
|
|
742
|
+
aria-valuemin="0"
|
|
743
|
+
aria-valuemax="100"
|
|
744
|
+
aria-valuenow=${String(Math.round(e))}
|
|
745
|
+
title=${i}
|
|
746
|
+
>
|
|
747
|
+
<div class="track" aria-hidden="true">
|
|
748
|
+
<div class="progress"></div>
|
|
749
|
+
<div class="marker"></div>
|
|
750
|
+
</div>
|
|
751
|
+
</div>
|
|
752
|
+
`}};Tt.styles=A`
|
|
753
|
+
:host { position: absolute; top: -4px; left: 16px; right: 16px; z-index: 6; display: block; height: 12px; opacity: .58; transition: opacity .15s ease; }
|
|
754
|
+
:host(:hover), :host(:focus-within) { opacity: .92; }
|
|
755
|
+
.meter { height: 100%; }
|
|
756
|
+
.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); }
|
|
757
|
+
.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)); }
|
|
758
|
+
.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%); }
|
|
759
|
+
`;Ys([d({type:Number})],Tt.prototype,"positionPercent",2);Ys([d({type:Number})],Tt.prototype,"loadedPercent",2);Tt=Ys([R("conversation-meter")],Tt);function yr(e){return Number.isFinite(e)?Math.min(100,Math.max(0,e)):0}class xs extends Qs{constructor(t){if(super(t),this.it=_,t.type!==Js.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(t){if(t===_||t==null)return this._t=void 0,this.it=t;if(t===Ne)return t;if(typeof t!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(t===this.it)return this._t;this.it=t;const i=[t];return i.raw=i,this._t={_$litType$:this.constructor.resultType,strings:i,values:[]}}}xs.directiveName="unsafeHTML",xs.resultType=1;const fg=Zs(xs);function eo(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Je=eo();function sa(e){Je=e}var Ue={exec:()=>null};function I(e,t=""){let i=typeof e=="string"?e:e.source,s={replace:(o,r)=>{let n=typeof r=="string"?r:r.source;return n=n.replace(G.caret,"$1"),i=i.replace(o,n),s},getRegex:()=>new RegExp(i,t)};return s}var gg=((e="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+e)}catch{return!1}})(),G={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=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i"),blockquoteBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}>`)},mg=/^(?:[ \t]*(?:\n|$))+/,vg=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,bg=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,_t=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,wg=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,to=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,oa=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,ra=I(oa).replace(/bull/g,to).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(),yg=I(oa).replace(/bull/g,to).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(),io=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,xg=/^[^\n]+/,so=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Sg=I(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",so).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),kg=I(/^(bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,to).getRegex(),Di="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",oo=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,$g=I("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\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",oo).replace("tag",Di).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),na=I(io).replace("hr",_t).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"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",Di).getRegex(),Pg=I(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",na).getRegex(),ro={blockquote:Pg,code:vg,def:Sg,fences:bg,heading:wg,hr:_t,html:$g,lheading:ra,list:kg,newline:mg,paragraph:na,table:Ue,text:xg},xr=I("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",_t).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",Di).getRegex(),Cg={...ro,lheading:yg,table:xr,paragraph:I(io).replace("hr",_t).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",xr).replace("blockquote"," {0,3}>").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",Di).getRegex()},Ig={...ro,html:I(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",oo).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:Ue,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:I(io).replace("hr",_t).replace("heading",` *#{1,6} *[^
|
|
760
|
+
]`).replace("lheading",ra).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Tg=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Mg=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,aa=/^( {2,}|\\)\n(?!\s*$)/,Rg=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,ct=/[\p{P}\p{S}]/u,Wi=/[\s\p{P}\p{S}]/u,no=/[^\s\p{P}\p{S}]/u,Ag=I(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Wi).getRegex(),la=/(?!~)[\p{P}\p{S}]/u,Eg=/(?!~)[\s\p{P}\p{S}]/u,Dg=/(?:[^\s\p{P}\p{S}]|~)/u,Wg=I(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",gg?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),ca=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Og=I(ca,"u").replace(/punct/g,ct).getRegex(),_g=I(ca,"u").replace(/punct/g,la).getRegex(),da="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",Lg=I(da,"gu").replace(/notPunctSpace/g,no).replace(/punctSpace/g,Wi).replace(/punct/g,ct).getRegex(),jg=I(da,"gu").replace(/notPunctSpace/g,Dg).replace(/punctSpace/g,Eg).replace(/punct/g,la).getRegex(),Ng=I("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,no).replace(/punctSpace/g,Wi).replace(/punct/g,ct).getRegex(),Fg=I(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,ct).getRegex(),zg="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Bg=I(zg,"gu").replace(/notPunctSpace/g,no).replace(/punctSpace/g,Wi).replace(/punct/g,ct).getRegex(),Ug=I(/\\(punct)/,"gu").replace(/punct/g,ct).getRegex(),Hg=I(/^<(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(),qg=I(oo).replace("(?:-->|$)","-->").getRegex(),Kg=I("^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",qg).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),gi=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,Vg=I(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace("label",gi).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),pa=I(/^!?\[(label)\]\[(ref)\]/).replace("label",gi).replace("ref",so).getRegex(),ha=I(/^!?\[(ref)\](?:\[\])?/).replace("ref",so).getRegex(),Gg=I("reflink|nolink(?!\\()","g").replace("reflink",pa).replace("nolink",ha).getRegex(),Sr=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,ao={_backpedal:Ue,anyPunctuation:Ug,autolink:Hg,blockSkip:Wg,br:aa,code:Mg,del:Ue,delLDelim:Ue,delRDelim:Ue,emStrongLDelim:Og,emStrongRDelimAst:Lg,emStrongRDelimUnd:Ng,escape:Tg,link:Vg,nolink:ha,punctuation:Ag,reflink:pa,reflinkSearch:Gg,tag:Kg,text:Rg,url:Ue},Jg={...ao,link:I(/^!?\[(label)\]\((.*?)\)/).replace("label",gi).getRegex(),reflink:I(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",gi).getRegex()},Ss={...ao,emStrongRDelimAst:jg,emStrongLDelim:_g,delLDelim:Fg,delRDelim:Bg,url:I(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",Sr).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:I(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace("protocol",Sr).getRegex()},Zg={...Ss,br:I(aa).replace("{2,}","*").getRegex(),text:I(Ss.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},Ut={normal:ro,gfm:Cg,pedantic:Ig},bt={normal:ao,gfm:Ss,breaks:Zg,pedantic:Jg},Qg={"&":"&","<":"<",">":">",'"':""","'":"'"},kr=e=>Qg[e];function Pe(e,t){if(t){if(G.escapeTest.test(e))return e.replace(G.escapeReplace,kr)}else if(G.escapeTestNoEncode.test(e))return e.replace(G.escapeReplaceNoEncode,kr);return e}function $r(e){try{e=encodeURI(e).replace(G.percentDecode,"%")}catch{return null}return e}function Pr(e,t){let i=e.replace(G.findPipe,(r,n,a)=>{let c=!1,p=n;for(;--p>=0&&a[p]==="\\";)c=!c;return c?"|":" |"}),s=i.split(G.splitPipe),o=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length<t;)s.push("");for(;o<s.length;o++)s[o]=s[o].trim().replace(G.slashPipe,"|");return s}function Le(e,t,i){let s=e.length;if(s===0)return"";let o=0;for(;o<s&&e.charAt(s-o-1)===t;)o++;return e.slice(0,s-o)}function Cr(e){let t=e.split(`
|
|
761
|
+
`),i=t.length-1;for(;i>=0&&G.blankLine.test(t[i]);)i--;return t.length-i<=2?e:t.slice(0,i+1).join(`
|
|
762
|
+
`)}function Xg(e,t){if(e.indexOf(t[1])===-1)return-1;let i=0;for(let s=0;s<e.length;s++)if(e[s]==="\\")s++;else if(e[s]===t[0])i++;else if(e[s]===t[1]&&(i--,i<0))return s;return i>0?-2:-1}function Yg(e,t=0){let i=t,s="";for(let o of e)if(o===" "){let r=4-i%4;s+=" ".repeat(r),i+=r}else s+=o,i++;return s}function Ir(e,t,i,s,o){let r=t.href,n=t.title||null,a=e[1].replace(o.other.outputLinkReplace,"$1");s.state.inLink=!0;let c={type:e[0].charAt(0)==="!"?"image":"link",raw:i,href:r,title:n,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,c}function em(e,t,i){let s=e.match(i.other.indentCodeCompensation);if(s===null)return t;let o=s[1];return t.split(`
|
|
763
|
+
`).map(r=>{let n=r.match(i.other.beginningSpace);if(n===null)return r;let[a]=n;return a.length>=o.length?r.slice(o.length):r}).join(`
|
|
764
|
+
`)}var mi=class{options;rules;lexer;constructor(e){this.options=e||Je}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 i=this.options.pedantic?t[0]:Cr(t[0]),s=i.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:i,codeBlockStyle:"indented",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let i=t[0],s=em(i,t[3]||"",this.rules);return{type:"code",raw:i,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let i=t[2].trim();if(this.rules.other.endingHash.test(i)){let s=Le(i,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(i=s.trim())}return{type:"heading",raw:Le(t[0],`
|
|
765
|
+
`),depth:t[1].length,text:i,tokens:this.lexer.inline(i)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:Le(t[0],`
|
|
766
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let i=Le(t[0],`
|
|
767
|
+
`).split(`
|
|
768
|
+
`),s="",o="",r=[];for(;i.length>0;){let n=!1,a=[],c;for(c=0;c<i.length;c++)if(this.rules.other.blockquoteStart.test(i[c]))a.push(i[c]),n=!0;else if(!n)a.push(i[c]);else break;i=i.slice(c);let p=a.join(`
|
|
769
|
+
`),u=p.replace(this.rules.other.blockquoteSetextReplace,`
|
|
770
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
|
|
771
|
+
${p}`:p,o=o?`${o}
|
|
772
|
+
${u}`:u;let h=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,r,!0),this.lexer.state.top=h,i.length===0)break;let f=r.at(-1);if(f?.type==="code")break;if(f?.type==="blockquote"){let b=f,P=b.raw+`
|
|
773
|
+
`+i.join(`
|
|
774
|
+
`),z=this.blockquote(P);r[r.length-1]=z,s=s.substring(0,s.length-b.raw.length)+z.raw,o=o.substring(0,o.length-b.text.length)+z.text;break}else if(f?.type==="list"){let b=f,P=b.raw+`
|
|
775
|
+
`+i.join(`
|
|
776
|
+
`),z=this.list(P);r[r.length-1]=z,s=s.substring(0,s.length-f.raw.length)+z.raw,o=o.substring(0,o.length-b.raw.length)+z.raw,i=P.substring(r.at(-1).raw.length).split(`
|
|
777
|
+
`);continue}}return{type:"blockquote",raw:s,tokens:r,text:o}}}list(e){let t=this.rules.block.list.exec(e);if(t){let i=t[1].trim(),s=i.length>1,o={type:"list",raw:"",ordered:s,start:s?+i.slice(0,-1):"",loose:!1,items:[]};i=s?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=s?i:"[*+-]");let r=this.rules.other.listItemRegex(i),n=!1;for(;e;){let c=!1,p="",u="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;p=t[0],e=e.substring(p.length);let h=Yg(t[2].split(`
|
|
778
|
+
`,1)[0],t[1].length),f=e.split(`
|
|
779
|
+
`,1)[0],b=!h.trim(),P=0;if(this.options.pedantic?(P=2,u=h.trimStart()):b?P=t[1].length+1:(P=h.search(this.rules.other.nonSpaceChar),P=P>4?1:P,u=h.slice(P),P+=t[1].length),b&&this.rules.other.blankLine.test(f)&&(p+=f+`
|
|
780
|
+
`,e=e.substring(f.length+1),c=!0),!c){let z=this.rules.other.nextBulletRegex(P),Xe=this.rules.other.hrRegex(P),dt=this.rules.other.fencesBeginRegex(P),po=this.rules.other.headingBeginRegex(P),xa=this.rules.other.htmlBeginRegex(P),Sa=this.rules.other.blockquoteBeginRegex(P);for(;e;){let _i=e.split(`
|
|
781
|
+
`,1)[0],pt;if(f=_i,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),pt=f):pt=f.replace(this.rules.other.tabCharGlobal," "),dt.test(f)||po.test(f)||xa.test(f)||Sa.test(f)||z.test(f)||Xe.test(f))break;if(pt.search(this.rules.other.nonSpaceChar)>=P||!f.trim())u+=`
|
|
782
|
+
`+pt.slice(P);else{if(b||h.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||dt.test(h)||po.test(h)||Xe.test(h))break;u+=`
|
|
783
|
+
`+f}b=!f.trim(),p+=_i+`
|
|
784
|
+
`,e=e.substring(_i.length+1),h=pt.slice(P)}}o.loose||(n?o.loose=!0:this.rules.other.doubleBlankLine.test(p)&&(n=!0)),o.items.push({type:"list_item",raw:p,task:!!this.options.gfm&&this.rules.other.listIsTask.test(u),loose:!1,text:u,tokens:[]}),o.raw+=p}let a=o.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;o.raw=o.raw.trimEnd();for(let c of o.items){this.lexer.state.top=!1,c.tokens=this.lexer.blockTokens(c.text,[]);let p=c.tokens[0];if(c.task&&(p?.type==="text"||p?.type==="paragraph")){c.text=c.text.replace(this.rules.other.listReplaceTask,""),p.raw=p.raw.replace(this.rules.other.listReplaceTask,""),p.text=p.text.replace(this.rules.other.listReplaceTask,"");for(let h=this.lexer.inlineQueue.length-1;h>=0;h--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[h].src)){this.lexer.inlineQueue[h].src=this.lexer.inlineQueue[h].src.replace(this.rules.other.listReplaceTask,"");break}let u=this.rules.other.listTaskCheckbox.exec(c.raw);if(u){let h={type:"checkbox",raw:u[0]+" ",checked:u[0]!=="[ ]"};c.checked=h.checked,o.loose?c.tokens[0]&&["paragraph","text"].includes(c.tokens[0].type)&&"tokens"in c.tokens[0]&&c.tokens[0].tokens?(c.tokens[0].raw=h.raw+c.tokens[0].raw,c.tokens[0].text=h.raw+c.tokens[0].text,c.tokens[0].tokens.unshift(h)):c.tokens.unshift({type:"paragraph",raw:h.raw,text:h.raw,tokens:[h]}):c.tokens.unshift(h)}}else c.task&&(c.task=!1);if(!o.loose){let u=c.tokens.filter(f=>f.type==="space"),h=u.length>0&&u.some(f=>this.rules.other.anyLine.test(f.raw));o.loose=h}}if(o.loose)for(let c of o.items){c.loose=!0;for(let p of c.tokens)p.type==="text"&&(p.type="paragraph")}return o}}html(e){let t=this.rules.block.html.exec(e);if(t){let i=Cr(t[0]);return{type:"html",block:!0,raw:i,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:i}}}def(e){let t=this.rules.block.def.exec(e);if(t){let i=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",o=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:i,raw:Le(t[0],`
|
|
785
|
+
`),href:s,title:o}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let i=Pr(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),o=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
|
|
786
|
+
`):[],r={type:"table",raw:Le(t[0],`
|
|
787
|
+
`),header:[],align:[],rows:[]};if(i.length===s.length){for(let n of s)this.rules.other.tableAlignRight.test(n)?r.align.push("right"):this.rules.other.tableAlignCenter.test(n)?r.align.push("center"):this.rules.other.tableAlignLeft.test(n)?r.align.push("left"):r.align.push(null);for(let n=0;n<i.length;n++)r.header.push({text:i[n],tokens:this.lexer.inline(i[n]),header:!0,align:r.align[n]});for(let n of o)r.rows.push(Pr(n,r.header.length).map((a,c)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:r.align[c]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let i=t[1].trim();return{type:"heading",raw:Le(t[0],`
|
|
788
|
+
`),depth:t[2].charAt(0)==="="?1:2,text:i,tokens:this.lexer.inline(i)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let i=t[1].charAt(t[1].length-1)===`
|
|
789
|
+
`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:i,tokens:this.lexer.inline(i)}}}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 i=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(i)){if(!this.rules.other.endAngleBracket.test(i))return;let r=Le(i.slice(0,-1),"\\");if((i.length-r.length)%2===0)return}else{let r=Xg(t[2],"()");if(r===-2)return;if(r>-1){let n=(t[0].indexOf("!")===0?5:4)+t[1].length+r;t[2]=t[2].substring(0,r),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let s=t[2],o="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(s);r&&(s=r[1],o=r[3])}else o=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(i)?s=s.slice(1):s=s.slice(1,-1)),Ir(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let i;if((i=this.rules.inline.reflink.exec(e))||(i=this.rules.inline.nolink.exec(e))){let s=(i[2]||i[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=t[s.toLowerCase()];if(!o){let r=i[0].charAt(0);return{type:"text",raw:r,text:r}}return Ir(i,o,i[0],this.lexer,this.rules)}}emStrong(e,t,i=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&i.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[3])||!i||this.rules.inline.punctuation.exec(i))){let o=[...s[0]].length-1,r,n,a=o,c=0,p=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+o);(s=p.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(n=[...r].length,s[3]||s[4]){a+=n;continue}else if((s[5]||s[6])&&o%3&&!((o+n)%3)){c+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a+c);let u=[...s[0]][0].length,h=e.slice(0,o+s.index+u+n);if(Math.min(o,n)%2){let b=h.slice(1,-1);return{type:"em",raw:h,text:b,tokens:this.lexer.inlineTokens(b)}}let f=h.slice(2,-2);return{type:"strong",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let i=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(i),o=this.rules.other.startingSpaceChar.test(i)&&this.rules.other.endingSpaceChar.test(i);return s&&o&&(i=i.substring(1,i.length-1)),{type:"codespan",raw:t[0],text:i}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,i=""){let s=this.rules.inline.delLDelim.exec(e);if(s&&(!s[1]||!i||this.rules.inline.punctuation.exec(i))){let o=[...s[0]].length-1,r,n,a=o,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+o);(s=c.exec(t))!==null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r||(n=[...r].length,n!==o))continue;if(s[3]||s[4]){a+=n;continue}if(a-=n,a>0)continue;n=Math.min(n,n+a);let p=[...s[0]][0].length,u=e.slice(0,o+s.index+p+n),h=u.slice(o,-o);return{type:"del",raw:u,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let i,s;return t[2]==="@"?(i=t[1],s="mailto:"+i):(i=t[1],s=i),{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let i,s;if(t[2]==="@")i=t[0],s="mailto:"+i;else{let o;do o=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(o!==t[0]);i=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:i,href:s,tokens:[{type:"text",raw:i,text:i}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let i=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:i}}}},we=class ks{tokens;options;state;inlineQueue;tokenizer;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Je,this.options.tokenizer=this.options.tokenizer||new mi,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 i={other:G,block:Ut.normal,inline:bt.normal};this.options.pedantic?(i.block=Ut.pedantic,i.inline=bt.pedantic):this.options.gfm&&(i.block=Ut.gfm,this.options.breaks?i.inline=bt.breaks:i.inline=bt.gfm),this.tokenizer.rules=i}static get rules(){return{block:Ut,inline:bt}}static lex(t,i){return new ks(i).lex(t)}static lexInline(t,i){return new ks(i).inlineTokens(t)}lex(t){t=t.replace(G.carriageReturn,`
|
|
790
|
+
`),this.blockTokens(t,this.tokens);for(let i=0;i<this.inlineQueue.length;i++){let s=this.inlineQueue[i];this.inlineTokens(s.src,s.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(t,i=[],s=!1){this.tokenizer.lexer=this,this.options.pedantic&&(t=t.replace(G.tabCharGlobal," ").replace(G.spaceLine,""));let o=1/0;for(;t;){if(t.length<o)o=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}let r;if(this.options.extensions?.block?.some(a=>(r=a.call({lexer:this},t,i))?(t=t.substring(r.raw.length),i.push(r),!0):!1))continue;if(r=this.tokenizer.space(t)){t=t.substring(r.raw.length);let a=i.at(-1);r.raw.length===1&&a!==void 0?a.raw+=`
|
|
791
|
+
`:i.push(r);continue}if(r=this.tokenizer.code(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
792
|
+
`)?"":`
|
|
793
|
+
`)+r.raw,a.text+=`
|
|
794
|
+
`+r.text,this.inlineQueue.at(-1).src=a.text):i.push(r);continue}if(r=this.tokenizer.fences(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.heading(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.hr(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.blockquote(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.list(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.html(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.def(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
795
|
+
`)?"":`
|
|
796
|
+
`)+r.raw,a.text+=`
|
|
797
|
+
`+r.raw,this.inlineQueue.at(-1).src=a.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},i.push(r));continue}if(r=this.tokenizer.table(t)){t=t.substring(r.raw.length),i.push(r);continue}if(r=this.tokenizer.lheading(t)){t=t.substring(r.raw.length),i.push(r);continue}let n=t;if(this.options.extensions?.startBlock){let a=1/0,c=t.slice(1),p;this.options.extensions.startBlock.forEach(u=>{p=u.call({lexer:this},c),typeof p=="number"&&p>=0&&(a=Math.min(a,p))}),a<1/0&&a>=0&&(n=t.substring(0,a+1))}if(this.state.top&&(r=this.tokenizer.paragraph(n))){let a=i.at(-1);s&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
|
|
798
|
+
`)?"":`
|
|
799
|
+
`)+r.raw,a.text+=`
|
|
800
|
+
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r),s=n.length!==t.length,t=t.substring(r.raw.length);continue}if(r=this.tokenizer.text(t)){t=t.substring(r.raw.length);let a=i.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
|
|
801
|
+
`)?"":`
|
|
802
|
+
`)+r.raw,a.text+=`
|
|
803
|
+
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):i.push(r);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return this.state.top=!0,i}inline(t,i=[]){return this.inlineQueue.push({src:t,tokens:i}),i}inlineTokens(t,i=[]){this.tokenizer.lexer=this;let s=t,o=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(o=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(o[0].slice(o[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,o.index)+"["+"a".repeat(o[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(o=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,o.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let r;for(;(o=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)r=o[2]?o[2].length:0,s=s.slice(0,o.index+r)+"["+"a".repeat(o[0].length-r-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let n=!1,a="",c=1/0;for(;t;){if(t.length<c)c=t.length;else{this.infiniteLoopError(t.charCodeAt(0));break}n||(a=""),n=!1;let p;if(this.options.extensions?.inline?.some(h=>(p=h.call({lexer:this},t,i))?(t=t.substring(p.raw.length),i.push(p),!0):!1))continue;if(p=this.tokenizer.escape(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.tag(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.link(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(p.raw.length);let h=i.at(-1);p.type==="text"&&h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(p=this.tokenizer.emStrong(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.codespan(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.br(t)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.del(t,s,a)){t=t.substring(p.raw.length),i.push(p);continue}if(p=this.tokenizer.autolink(t)){t=t.substring(p.raw.length),i.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(t))){t=t.substring(p.raw.length),i.push(p);continue}let u=t;if(this.options.extensions?.startInline){let h=1/0,f=t.slice(1),b;this.options.extensions.startInline.forEach(P=>{b=P.call({lexer:this},f),typeof b=="number"&&b>=0&&(h=Math.min(h,b))}),h<1/0&&h>=0&&(u=t.substring(0,h+1))}if(p=this.tokenizer.inlineText(u)){t=t.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(a=p.raw.slice(-1)),n=!0;let h=i.at(-1);h?.type==="text"?(h.raw+=p.raw,h.text+=p.text):i.push(p);continue}if(t){this.infiniteLoopError(t.charCodeAt(0));break}}return i}infiniteLoopError(t){let i="Infinite loop on byte: "+t;if(this.options.silent)console.error(i);else throw new Error(i)}},vi=class{options;parser;constructor(e){this.options=e||Je}space(e){return""}code({text:e,lang:t,escaped:i}){let s=(t||"").match(G.notSpaceStart)?.[0],o=e.replace(G.endingNewline,"")+`
|
|
804
|
+
`;return s?'<pre><code class="language-'+Pe(s)+'">'+(i?o:Pe(o,!0))+`</code></pre>
|
|
805
|
+
`:"<pre><code>"+(i?o:Pe(o,!0))+`</code></pre>
|
|
806
|
+
`}blockquote({tokens:e}){return`<blockquote>
|
|
807
|
+
${this.parser.parse(e)}</blockquote>
|
|
808
|
+
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
809
|
+
`}hr(e){return`<hr>
|
|
810
|
+
`}list(e){let t=e.ordered,i=e.start,s="";for(let n=0;n<e.items.length;n++){let a=e.items[n];s+=this.listitem(a)}let o=t?"ol":"ul",r=t&&i!==1?' start="'+i+'"':"";return"<"+o+r+`>
|
|
811
|
+
`+s+"</"+o+`>
|
|
812
|
+
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
813
|
+
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
814
|
+
`}table(e){let t="",i="";for(let o=0;o<e.header.length;o++)i+=this.tablecell(e.header[o]);t+=this.tablerow({text:i});let s="";for(let o=0;o<e.rows.length;o++){let r=e.rows[o];i="";for(let n=0;n<r.length;n++)i+=this.tablecell(r[n]);s+=this.tablerow({text:i})}return s&&(s=`<tbody>${s}</tbody>`),`<table>
|
|
815
|
+
<thead>
|
|
816
|
+
`+t+`</thead>
|
|
817
|
+
`+s+`</table>
|
|
818
|
+
`}tablerow({text:e}){return`<tr>
|
|
819
|
+
${e}</tr>
|
|
820
|
+
`}tablecell(e){let t=this.parser.parseInline(e.tokens),i=e.header?"th":"td";return(e.align?`<${i} align="${e.align}">`:`<${i}>`)+t+`</${i}>
|
|
821
|
+
`}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>${Pe(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:i}){let s=this.parser.parseInline(i),o=$r(e);if(o===null)return s;e=o;let r='<a href="'+e+'"';return t&&(r+=' title="'+Pe(t)+'"'),r+=">"+s+"</a>",r}image({href:e,title:t,text:i,tokens:s}){s&&(i=this.parser.parseInline(s,this.parser.textRenderer));let o=$r(e);if(o===null)return Pe(i);e=o;let r=`<img src="${e}" alt="${Pe(i)}"`;return t&&(r+=` title="${Pe(t)}"`),r+=">",r}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:Pe(e.text)}},lo=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}},ye=class $s{options;renderer;textRenderer;constructor(t){this.options=t||Je,this.options.renderer=this.options.renderer||new vi,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new lo}static parse(t,i){return new $s(i).parse(t)}static parseInline(t,i){return new $s(i).parseInline(t)}parse(t){this.renderer.parser=this;let i="";for(let s=0;s<t.length;s++){let o=t[s];if(this.options.extensions?.renderers?.[o.type]){let n=o,a=this.options.extensions.renderers[n.type].call({parser:this},n);if(a!==!1||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(n.type)){i+=a||"";continue}}let r=o;switch(r.type){case"space":{i+=this.renderer.space(r);break}case"hr":{i+=this.renderer.hr(r);break}case"heading":{i+=this.renderer.heading(r);break}case"code":{i+=this.renderer.code(r);break}case"table":{i+=this.renderer.table(r);break}case"blockquote":{i+=this.renderer.blockquote(r);break}case"list":{i+=this.renderer.list(r);break}case"checkbox":{i+=this.renderer.checkbox(r);break}case"html":{i+=this.renderer.html(r);break}case"def":{i+=this.renderer.def(r);break}case"paragraph":{i+=this.renderer.paragraph(r);break}case"text":{i+=this.renderer.text(r);break}default:{let n='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(n),"";throw new Error(n)}}}return i}parseInline(t,i=this.renderer){this.renderer.parser=this;let s="";for(let o=0;o<t.length;o++){let r=t[o];if(this.options.extensions?.renderers?.[r.type]){let a=this.options.extensions.renderers[r.type].call({parser:this},r);if(a!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){s+=a||"";continue}}let n=r;switch(n.type){case"escape":{s+=i.text(n);break}case"html":{s+=i.html(n);break}case"link":{s+=i.link(n);break}case"image":{s+=i.image(n);break}case"checkbox":{s+=i.checkbox(n);break}case"strong":{s+=i.strong(n);break}case"em":{s+=i.em(n);break}case"codespan":{s+=i.codespan(n);break}case"br":{s+=i.br(n);break}case"del":{s+=i.del(n);break}case"text":{s+=i.text(n);break}default:{let a='Token with "'+n.type+'" type was not found.';if(this.options.silent)return console.error(a),"";throw new Error(a)}}}return s}},yt=class{options;block;constructor(e){this.options=e||Je}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?we.lex:we.lexInline}provideParser(e=this.block){return e?ye.parse:ye.parseInline}},tm=class{defaults=eo();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=ye;Renderer=vi;TextRenderer=lo;Lexer=we;Tokenizer=mi;Hooks=yt;constructor(...e){this.use(...e)}walkTokens(e,t){let i=[];for(let s of e)switch(i=i.concat(t.call(this,s)),s.type){case"table":{let o=s;for(let r of o.header)i=i.concat(this.walkTokens(r.tokens,t));for(let r of o.rows)for(let n of r)i=i.concat(this.walkTokens(n.tokens,t));break}case"list":{let o=s;i=i.concat(this.walkTokens(o.items,t));break}default:{let o=s;this.defaults.extensions?.childTokens?.[o.type]?this.defaults.extensions.childTokens[o.type].forEach(r=>{let n=o[r].flat(1/0);i=i.concat(this.walkTokens(n,t))}):o.tokens&&(i=i.concat(this.walkTokens(o.tokens,t)))}}return i}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(i=>{let s={...i};if(s.async=this.defaults.async||s.async||!1,i.extensions&&(i.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if("renderer"in o){let r=t.renderers[o.name];r?t.renderers[o.name]=function(...n){let a=o.renderer.apply(this,n);return a===!1&&(a=r.apply(this,n)),a}:t.renderers[o.name]=o.renderer}if("tokenizer"in o){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=t[o.level];r?r.unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}"childTokens"in o&&o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),s.extensions=t),i.renderer){let o=this.defaults.renderer||new vi(this.defaults);for(let r in i.renderer){if(!(r in o))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let n=r,a=i.renderer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u||""}}s.renderer=o}if(i.tokenizer){let o=this.defaults.tokenizer||new mi(this.defaults);for(let r in i.tokenizer){if(!(r in o))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let n=r,a=i.tokenizer[n],c=o[n];o[n]=(...p)=>{let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.tokenizer=o}if(i.hooks){let o=this.defaults.hooks||new yt;for(let r in i.hooks){if(!(r in o))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let n=r,a=i.hooks[n],c=o[n];yt.passThroughHooks.has(r)?o[n]=p=>{if(this.defaults.async&&yt.passThroughHooksRespectAsync.has(r))return(async()=>{let h=await a.call(o,p);return c.call(o,h)})();let u=a.call(o,p);return c.call(o,u)}:o[n]=(...p)=>{if(this.defaults.async)return(async()=>{let h=await a.apply(o,p);return h===!1&&(h=await c.apply(o,p)),h})();let u=a.apply(o,p);return u===!1&&(u=c.apply(o,p)),u}}s.hooks=o}if(i.walkTokens){let o=this.defaults.walkTokens,r=i.walkTokens;s.walkTokens=function(n){let a=[];return a.push(r.call(this,n)),o&&(a=a.concat(o.call(this,n))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return we.lex(e,t??this.defaults)}parser(e,t){return ye.parse(e,t??this.defaults)}parseMarkdown(e){return(t,i)=>{let s={...i},o={...this.defaults,...s},r=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&s.async===!1)return r(new 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 r(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let n=o.hooks?await o.hooks.preprocess(t):t,a=await(o.hooks?await o.hooks.provideLexer(e):e?we.lex:we.lexInline)(n,o),c=o.hooks?await o.hooks.processAllTokens(a):a;o.walkTokens&&await Promise.all(this.walkTokens(c,o.walkTokens));let p=await(o.hooks?await o.hooks.provideParser(e):e?ye.parse:ye.parseInline)(c,o);return o.hooks?await o.hooks.postprocess(p):p})().catch(r);try{o.hooks&&(t=o.hooks.preprocess(t));let n=(o.hooks?o.hooks.provideLexer(e):e?we.lex:we.lexInline)(t,o);o.hooks&&(n=o.hooks.processAllTokens(n)),o.walkTokens&&this.walkTokens(n,o.walkTokens);let a=(o.hooks?o.hooks.provideParser(e):e?ye.parse:ye.parseInline)(n,o);return o.hooks&&(a=o.hooks.postprocess(a)),a}catch(n){return r(n)}}}onError(e,t){return i=>{if(i.message+=`
|
|
822
|
+
Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+Pe(i.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(i);throw i}}},Ve=new tm;function M(e,t){return Ve.parse(e,t)}M.options=M.setOptions=function(e){return Ve.setOptions(e),M.defaults=Ve.defaults,sa(M.defaults),M};M.getDefaults=eo;M.defaults=Je;M.use=function(...e){return Ve.use(...e),M.defaults=Ve.defaults,sa(M.defaults),M};M.walkTokens=function(e,t){return Ve.walkTokens(e,t)};M.parseInline=Ve.parseInline;M.Parser=ye;M.parser=ye.parse;M.Renderer=vi;M.TextRenderer=lo;M.Lexer=we;M.lexer=we.lex;M.Tokenizer=mi;M.Hooks=yt;M.parse=M;M.options;M.setOptions;M.use;M.walkTokens;M.parseInline;ye.parse;we.lex;const ua=new M.Renderer;ua.html=({text:e})=>om(e);const im=300,wt=new Map;function sm(e){const t=wt.get(e);if(t!==void 0)return t;const i=M.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:ua}),s=rm(i);if(wt.set(e,s),wt.size>im){const o=wt.keys().next().value;o!==void 0&&wt.delete(o)}return s}function om(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">")}function rm(e){const t=document.createElement("template");return t.innerHTML=e,t.content.querySelectorAll("script, style, iframe, object, embed").forEach(i=>{i.remove()}),t.content.querySelectorAll("*").forEach(i=>{for(const s of[...i.attributes]){const o=s.name.toLowerCase();o.startsWith("on")&&i.removeAttribute(s.name),(o==="href"||o==="src")&&!nm(s.value)&&i.removeAttribute(s.name)}i.tagName==="A"&&(i.setAttribute("target","_blank"),i.setAttribute("rel","noreferrer noopener"))}),t.innerHTML}function nm(e){if(e.startsWith("#")||e.startsWith("/"))return!0;try{return["http:","https:","mailto:"].includes(new URL(e).protocol)}catch{return!1}}var am=Object.defineProperty,lm=Object.getOwnPropertyDescriptor,fa=(e,t,i,s)=>{for(var o=s>1?void 0:s?lm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&am(t,i,o),o};let bi=class extends T{constructor(){super(...arguments),this.text="",this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;const t=e.target.closest(".code-copy-button");if(!(t instanceof HTMLButtonElement))return;const i=t.closest(".code-block-wrapper");if(!(i instanceof HTMLElement))return;const s=i.querySelector("pre code");s instanceof HTMLElement&&this.copyCode(s.textContent,t)},this.onFormattedCopy=e=>{e.clipboardData===null||!pm(cm(this))||(e.clipboardData.setData("text/plain",this.text),e.preventDefault(),e.stopPropagation())}}render(){return l`<div class="formatted" @click=${this.onFormattedClick} @copy=${this.onFormattedCopy}>${fg(sm(this.text))}</div>`}updated(){this.enhanceCodeBlocks()}enhanceCodeBlocks(){this.renderRoot.querySelectorAll("pre").forEach(e=>{if(!(e instanceof HTMLPreElement)||e.parentElement?.classList.contains("code-block-wrapper")===!0||!(e.querySelector("code")instanceof HTMLElement))return;const i=document.createElement("div");i.className="code-block-wrapper";const s=document.createElement("button");s.type="button",s.className="code-copy-button",s.title="复制代码块",s.setAttribute("aria-label","复制代码块");const o=document.createElement("span");o.setAttribute("aria-hidden","true"),o.textContent="⧉",s.append(o),e.before(i),i.append(e,s)})}async copyCode(e,t){const i=await hm(e);this.setCopyButtonState(t,i?"copied":"failed"),window.setTimeout(()=>{this.setCopyButtonState(t,"idle")},1200)}setCopyButtonState(e,t){const i=e.querySelector("span");i!==null&&(i.textContent=t==="copied"?"✓":"⧉");const s=t==="copied"?"已复制代码块":t==="failed"?"复制代码块失败":"复制代码块";e.title=s,e.setAttribute("aria-label",s)}};bi.styles=cf;fa([d()],bi.prototype,"text",2);bi=fa([R("formatted-text")],bi);function cm(e){const t=e.getRootNode();return typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&dm(t)?t.getSelection():e.ownerDocument.getSelection()}function dm(e){return"getSelection"in e&&typeof e.getSelection=="function"}function pm(e){return e!==null&&!e.isCollapsed&&e.toString()!==""}async function hm(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}var um=Object.defineProperty,fm=Object.getOwnPropertyDescriptor,Lt=(e,t,i,s)=>{for(var o=s>1?void 0:s?fm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&um(t,i,o),o};const Tr=180;let Ge=class extends T{constructor(){super(...arguments),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0}render(){const e=this.execution;if(e===void 0)return null;const t=e.toolName==="edit",i=gm(e.args),s=mm(e.details),o=e.preview,r=s??o?.diff,n=r===void 0?void 0:vm(r),a=s!==void 0&&o?.diff!==void 0&&s!==o.diff,c=e.status==="error"?e.resultText:o?.error,p=r===void 0?e.resultText:void 0;return l`
|
|
823
|
+
<section class=${`tool-card ${e.status}`}>
|
|
824
|
+
<div class="tool-header">
|
|
825
|
+
<div class="tool-title">
|
|
826
|
+
<span class="status-icon" aria-hidden="true">${wm(e.status)}</span>
|
|
827
|
+
<strong>${e.toolName}</strong>
|
|
828
|
+
${i===void 0?l`<span class="summary">${e.summary}</span>`:l`<span class="path">${i}</span>`}
|
|
829
|
+
</div>
|
|
830
|
+
<div class="tool-meta">
|
|
831
|
+
${Mr(e)===void 0?null:l`<span>${Mr(e)}</span>`}
|
|
832
|
+
${n===void 0?null:l`<span class="diff-stats"><b class="added">+${n.added}</b><span>/</span><b class="removed">-${n.removed}</b></span>`}
|
|
833
|
+
<span class="status-label">${ym(e.status)}</span>
|
|
834
|
+
</div>
|
|
835
|
+
</div>
|
|
836
|
+
|
|
837
|
+
${a?l`<p class="notice">实际应用的 diff 与预览不同。</p>`:null}
|
|
838
|
+
${c===void 0||c===""?null:l`<pre class="error-text">${c}</pre>`}
|
|
839
|
+
${r===void 0?this.renderTextBody(p,e.status==="error"):this.renderDiffBody(r,s===void 0?"预览 diff":"已应用 diff")}
|
|
840
|
+
${!t&&r===void 0&&(p===void 0||p==="")?l`<p class="muted">${e.summary}</p>`:null}
|
|
841
|
+
</section>
|
|
842
|
+
`}renderTextBody(e,t){return e===void 0||e===""?null:l`
|
|
843
|
+
<details class="text-body" ?open=${t}>
|
|
844
|
+
<summary>结果</summary>
|
|
845
|
+
<pre>${e}</pre>
|
|
846
|
+
</details>
|
|
847
|
+
`}renderDiffBody(e,t){const i=e.split(`
|
|
848
|
+
`),s=!this.showFullDiff&&i.length>Tr,o=s?i.slice(0,Tr):i;return l`
|
|
849
|
+
<details class="diff-details" ?open=${this.diffOpen} @toggle=${r=>{this.onDiffToggle(r)}}>
|
|
850
|
+
<summary>
|
|
851
|
+
<span>${t}</span>
|
|
852
|
+
<small>${String(i.length)} 行</small>
|
|
853
|
+
</summary>
|
|
854
|
+
<div class="diff-toolbar">
|
|
855
|
+
<span>${s?`显示 ${String(o.length)} / ${String(i.length)} 行`:"完整 diff"}</span>
|
|
856
|
+
<button type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?"已复制":"复制 diff"}</button>
|
|
857
|
+
</div>
|
|
858
|
+
<pre class="diff" aria-label=${t}><code class="diff-content">${o.map(r=>l`<span class=${bm(r)}>${r}</span>`)}</code></pre>
|
|
859
|
+
${s?l`
|
|
860
|
+
<button class="show-more" type="button" @click=${()=>{this.showFullDiff=!0}}>
|
|
861
|
+
显示全部 ${String(i.length)} 行 diff
|
|
862
|
+
</button>
|
|
863
|
+
`:null}
|
|
864
|
+
</details>
|
|
865
|
+
`}onDiffToggle(e){const t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){try{await navigator.clipboard.writeText(e),this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)}catch{this.copied=!1}}};Ge.styles=A`
|
|
866
|
+
:host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
|
|
867
|
+
.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); }
|
|
868
|
+
.tool-card.running, .tool-card.pending { border-color: var(--pi-warning-border); background: var(--pi-warning-surface); }
|
|
869
|
+
.tool-card.success { border-color: var(--pi-success-border); background: var(--pi-success-bg); }
|
|
870
|
+
.tool-card.error { border-color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-bg)); }
|
|
871
|
+
.tool-header { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; min-width: 0; }
|
|
872
|
+
.tool-title { display: inline-flex; align-items: baseline; gap: 7px; min-width: 0; }
|
|
873
|
+
.status-icon { flex: 0 0 auto; color: var(--pi-muted); }
|
|
874
|
+
strong { color: var(--pi-text); }
|
|
875
|
+
.path, .summary { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--pi-accent); font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
|
|
876
|
+
.summary { color: var(--pi-muted); font-family: inherit; }
|
|
877
|
+
.tool-meta { flex: 0 0 auto; display: inline-flex; align-items: baseline; gap: 8px; color: var(--pi-muted); font-size: 12px; }
|
|
878
|
+
.diff-stats { display: inline-flex; gap: 3px; }
|
|
879
|
+
.added, .diff .added { color: var(--pi-success); }
|
|
880
|
+
.removed, .diff .removed { color: var(--pi-danger); }
|
|
881
|
+
.status-label { text-transform: uppercase; letter-spacing: .04em; color: var(--pi-muted); }
|
|
882
|
+
.notice { margin: 0; color: var(--pi-warning); }
|
|
883
|
+
.muted { margin: 0; color: var(--pi-muted); }
|
|
884
|
+
.error-text { margin: 0; border: 1px solid var(--pi-danger); border-radius: 7px; background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-bg)); color: var(--pi-danger); padding: 8px; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
|
|
885
|
+
.text-body { border-top: 1px solid var(--pi-border-muted); padding-top: 6px; }
|
|
886
|
+
.text-body pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: var(--pi-text); }
|
|
887
|
+
.diff-details { min-width: 0; max-width: 100%; border-top: 1px solid var(--pi-border-muted); padding-top: 6px; }
|
|
888
|
+
.diff-details > summary { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; min-width: 0; color: var(--pi-muted); cursor: pointer; }
|
|
889
|
+
.diff-details > summary span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
890
|
+
.diff-details > summary small { flex: 0 0 auto; color: var(--pi-dim); }
|
|
891
|
+
.diff-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 8px; min-width: 0; margin-top: 8px; color: var(--pi-muted); font-size: 12px; }
|
|
892
|
+
.diff-toolbar span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
893
|
+
button { border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-surface); color: var(--pi-text); padding: 3px 7px; font: 12px system-ui, sans-serif; cursor: pointer; }
|
|
894
|
+
button:hover, button:focus { border-color: var(--pi-accent); }
|
|
895
|
+
.diff { box-sizing: border-box; width: 100%; max-width: 100%; min-width: 0; margin: 0; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; border: 1px solid var(--pi-border-muted); border-radius: 7px; background: var(--pi-bg); padding: 8px 0; color: var(--pi-muted); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; line-height: 1.45; }
|
|
896
|
+
.diff-content { display: block; width: max-content; min-width: 100%; }
|
|
897
|
+
.diff span { display: block; min-height: 1.45em; padding: 0 8px; white-space: pre; }
|
|
898
|
+
.diff .context { color: var(--pi-muted); }
|
|
899
|
+
.diff .hunk { color: var(--pi-accent); }
|
|
900
|
+
.diff .file { color: var(--pi-dim); }
|
|
901
|
+
.diff .meta { color: var(--pi-dim); }
|
|
902
|
+
.diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
|
|
903
|
+
.diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
|
|
904
|
+
.show-more { justify-self: start; }
|
|
905
|
+
`;Lt([d({attribute:!1})],Ge.prototype,"execution",2);Lt([w()],Ge.prototype,"showFullDiff",2);Lt([w()],Ge.prototype,"copied",2);Lt([w()],Ge.prototype,"diffOpen",2);Ge=Lt([R("tool-execution-view")],Ge);function gm(e){return Ps(e,"path")??Ps(e,"file_path")}function Mr(e){if(e.toolName!=="edit")return;const t=ei(e.args,"edits");if(Array.isArray(t))return`${String(t.length)} 处编辑`;if(typeof ei(e.args,"oldText")=="string"&&typeof ei(e.args,"newText")=="string")return"1 处编辑"}function mm(e){return Ps(e,"diff")}function vm(e){let t=0,i=0;for(const s of e.split(`
|
|
906
|
+
`))ga(s)?t++:ma(s)&&i++;return{added:t,removed:i}}function bm(e){return ga(e)?"added":ma(e)?"removed":e.startsWith("@@")?"hunk":e.startsWith("+++")||e.startsWith("---")?"file":e.startsWith("diff ")||e.startsWith("index ")?"meta":"context"}function ga(e){return e.startsWith("+")&&!e.startsWith("+++")}function ma(e){return e.startsWith("-")&&!e.startsWith("---")}function wm(e){return e==="success"?"✓":e==="error"?"✖":e==="running"?"●":"○"}function ym(e){return e==="success"?"完成":e==="error"?"失败":e==="running"?"运行中":"等待中"}function xm(e){return typeof e=="object"&&e!==null}function ei(e,t){return xm(e)?e[t]:void 0}function Ps(e,t){const i=ei(e,t);return typeof i=="string"?i:void 0}var Sm=Object.defineProperty,km=Object.getOwnPropertyDescriptor,F=(e,t,i,s)=>{for(var o=s>1?void 0:s?km(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Sm(t,i,o),o};const $m=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}),Pm=new Intl.DateTimeFormat(void 0,{dateStyle:"medium",timeStyle:"medium"}),ts=["你打开此会话时助手已经在回复。完整答案很快会显示。","当前标签页接入得稍晚,完整回复准备好后会显示。","助手已先开始回复,完整答案到达后会显示。","正在等待完整回复,避免显示不完整内容。","回复仍在生成中,完整答案即将显示。","正在同步这次回复,稍后会显示完整版本。"];function Rr(){return ts[Math.floor(Math.random()*ts.length)]??ts[0]}function Ar(e){return ti(e,0,100)}function ti(e,t,i){return Number.isFinite(e)?Math.min(i,Math.max(t,e)):t}let L=class extends T{constructor(){super(...arguments),this.messages=[],this.sessionId="",this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.loadingMore=!1,this.isReceivingPartialStream=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.pinnedToBottom=!0,this.disclosures=new Lf,this.scrollController=new ag,this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageMetaCache=new WeakMap,this.messageCopyTextCache=new WeakMap,this.lastScrollTop=0,this.lastClientHeight=0,this.prependRestoreToken=0,this.loadMoreRequested=!1,this.onViewportResize=()=>{this.pinnedToBottom?this.scrollToBottom():this.lastClientHeight=this.chat?.clientHeight??0},this.onPageHide=()=>{this.saveScrollPosition()}}connectedCallback(){super.connectedCallback(),window.addEventListener("resize",this.onViewportResize),window.addEventListener("pagehide",this.onPageHide),window.visualViewport?.addEventListener("resize",this.onViewportResize)}firstUpdated(){this.lastClientHeight=this.chat?.clientHeight??0}disconnectedCallback(){this.saveScrollPosition(),this.scrollController.dispose(),this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.loadMoreCheckFrame!==void 0&&cancelAnimationFrame(this.loadMoreCheckFrame),this.scrollToBottomFrame!==void 0&&cancelAnimationFrame(this.scrollToBottomFrame),this.conversationRailFrame!==void 0&&cancelAnimationFrame(this.conversationRailFrame),window.removeEventListener("resize",this.onViewportResize),window.removeEventListener("pagehide",this.onPageHide),window.visualViewport?.removeEventListener("resize",this.onViewportResize),super.disconnectedCallback()}savePreviousSessionScrollPosition(e){typeof e!="string"||e===""||e===this.sessionId||this.saveScrollPosition(e)}prepareSessionUiState(){this.disclosures.syncSession(this.sessionId),this.scrollController.clearScheduledSave(),this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1,this.pendingScrollRestoreSessionId=void 0,this.pendingScrollRestorePosition=void 0,this.prependRestoreToken+=1,this.restoreScrollFrame!==void 0&&(cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=void 0)}willUpdate(e){e.has("sessionId")&&(this.savePreviousSessionScrollPosition(e.get("sessionId")),this.prepareSessionUiState()),(e.has("isReceivingPartialStream")||e.has("sessionId")&&this.isReceivingPartialStream)&&this.syncPartialStreamNoticeBody(),e.has("messages")&&(this.pinnedToBottom=this.pinnedToBottom&&(this.didChatHeightChange()||this.isNearBottom()))}update(e){const t=this.isPrependingMessages(e)?this.capturePrependScrollAnchor():void 0;super.update(e),t!==void 0&&this.restorePrependScrollAnchor(t)}updated(e){e.has("loadingMore")&&!this.loadingMore&&(this.loadMoreRequested=!1),e.has("hasMore")&&!this.hasMore&&(this.loadMoreRequested=!1),e.has("sessionId")&&this.restoreScrollPosition(),!e.has("sessionId")&&e.has("messages")&&this.pinnedToBottom&&this.scrollToBottom(),(e.has("messages")||e.has("messageStart")||e.has("messageTotal")||e.has("hasMore")||e.has("loadingMore"))&&this.scheduleConversationRailUpdate(),(e.has("messages")||e.has("messageStart")||e.has("hasMore")||e.has("loadingMore"))&&this.continuePendingScrollRestore(),(e.has("messages")||e.has("hasMore")||e.has("loadingMore"))&&this.requestLoadMoreIfNeeded()}render(){const e=this.groupedMessages();return l`
|
|
907
|
+
<div class="chat-wrap">
|
|
908
|
+
${this.renderConversationRail()}
|
|
909
|
+
<div class="chat" @scroll=${()=>{this.onScroll()}} @wheel=${t=>{this.onWheel(t)}} @touchstart=${t=>{this.onTouchStart(t)}} @touchmove=${t=>{this.onTouchMove(t)}}>
|
|
910
|
+
${this.renderHistoryBoundary()}
|
|
911
|
+
${Wf(e,t=>t.kind==="message"?this.messageAnchorKey(t.index):this.groupRenderKey(t.startIndex),(t,i)=>t.kind==="message"?this.renderMessage(t.message,t.index):this.renderMessageGroup(t.messages,t.startIndex,t.endIndex,this.isLiveTailGroup(e,i)))}
|
|
912
|
+
${this.renderQueuedMessages()}
|
|
913
|
+
${this.renderSessionActivity()}
|
|
914
|
+
</div>
|
|
915
|
+
${this.renderActivityDock()}
|
|
916
|
+
</div>
|
|
917
|
+
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart?this.groupedMessagesCache:(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=Ff(this.messages,this.messageStart),this.groupedMessagesCache)}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase==="active"}renderActivityDock(){const e=this.activityState();if(e===void 0)return null;const t=e!=="idle"||this.activity?.phase==="active";return l`
|
|
918
|
+
<div class=${t?"activity-dock active":"activity-dock"} aria-live="polite">
|
|
919
|
+
<span class="dot"></span>
|
|
920
|
+
<span class="activity-text">${this.activityText(e)}</span>
|
|
921
|
+
</div>
|
|
922
|
+
`}renderQueuedMessages(){const e=this.status?.queuedMessages??[];return e.length===0?null:l`
|
|
923
|
+
<aside class="queued-messages" aria-live="polite">
|
|
924
|
+
<div class="queued-header">
|
|
925
|
+
<strong>排队消息</strong>
|
|
926
|
+
<small>${e.length} 条待处理 · 停止会清空队列</small>
|
|
927
|
+
</div>
|
|
928
|
+
${e.map((t,i)=>l`
|
|
929
|
+
<div class="queued-message">
|
|
930
|
+
<span class="queued-kind">${t.kind==="steer"?"引导":"跟进"} ${String(i+1)}</span>
|
|
931
|
+
<formatted-text .text=${t.text}></formatted-text>
|
|
932
|
+
</div>
|
|
933
|
+
`)}
|
|
934
|
+
</aside>
|
|
935
|
+
`}renderSessionActivity(){return this.isReceivingPartialStream?l`
|
|
936
|
+
<aside class="session-activity receiving" aria-live="polite">
|
|
937
|
+
<strong>正在同步…</strong>
|
|
938
|
+
<span>${this.currentPartialStreamNoticeBody()}</span>
|
|
939
|
+
</aside>
|
|
940
|
+
`:this.isCompacting?l`
|
|
941
|
+
<aside class="session-activity compacting" aria-live="polite">
|
|
942
|
+
<strong>正在压缩历史…</strong>
|
|
943
|
+
<span>助手正在总结早前上下文。压缩完成前,新提示会排队等待。</span>
|
|
944
|
+
${this.pendingMessageCount>0?l`<small>${this.pendingMessageCount} 条消息已排队</small>`:null}
|
|
945
|
+
</aside>
|
|
946
|
+
`:null}syncPartialStreamNoticeBody(){this.partialStreamNoticeBody=this.isReceivingPartialStream?Rr():void 0}currentPartialStreamNoticeBody(){return this.partialStreamNoticeBody??=Rr(),this.partialStreamNoticeBody}activityState(){const 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){const t=this.activity;return t===void 0?e:e!=="idle"&&t.phase==="idle"?Cm(e):t.detail!==void 0&&t.detail!==""?`${t.label}: ${t.detail}`:t.label}renderConversationRail(){if(!this.messages.length||this.messageTotal<=0)return null;const e=this.conversationDisplayTotal(),t=this.conversationPositionPercent(e),i=this.hasMore?Ar(this.messages.length/e*100):100;return l`<conversation-meter .positionPercent=${t} .loadedPercent=${i}></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;const t=this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,i=ti(this.currentConversationIndex??t,0,e-1);return Ar(i/(e-1)*100)}renderHistoryBoundary(){const e=this.historyRangeLabel();return this.loadingMore?l`<div class="history-boundary"><span>正在加载更早的消息…</span>${e}</div>`:this.hasMore?l`
|
|
947
|
+
<div class="history-boundary">
|
|
948
|
+
<button type="button" class="history-load-button" ?disabled=${this.loadMoreRequested} @click=${()=>{this.requestLoadMore()}}>加载更早的消息</button>
|
|
949
|
+
<span>向上滚动加载更早的消息</span>
|
|
950
|
+
${e}
|
|
951
|
+
</div>
|
|
952
|
+
`:this.messages.length?l`<div class="history-boundary"><span>会话开始</span>${e}</div>`:null}historyRangeLabel(){if(!this.messages.length||this.messageTotal<=0)return null;const e=this.messageStart+1,t=this.loadedRawMessageEnd(),i=Math.max(this.messageTotal,t);return l`<small>显示消息 ${e}–${t} / ${i}</small>`}loadedRawMessageEnd(){return Math.max(this.messageEnd,this.messageStart+this.messages.length)}renderMessage(e,t){const i=this.isToolExecutionOnlyMessage(e);return l`
|
|
953
|
+
${this.renderScrollMarker(this.messageScrollMarkerId(t))}
|
|
954
|
+
<article class=${i?"msg tool-execution-shell":`msg ${e.role}`} data-index=${t} data-scroll-anchor-id=${this.messageAnchorKey(t)}>
|
|
955
|
+
${i?null:this.renderMessageHeader(e,String(t))}
|
|
956
|
+
${e.parts.map(s=>this.renderPart(s,e))}
|
|
957
|
+
</article>
|
|
958
|
+
`}isToolExecutionOnlyMessage(e){return e.role==="tool"&&e.parts.length>0&&e.parts.every(t=>t.type==="toolExecution")}renderMessageGroup(e,t,i,s){const o=this.groupDisclosureKey(t,i,s),r=this.disclosures.isOpen(o,s);return l`
|
|
959
|
+
${this.renderScrollMarker(this.groupScrollMarkerId(i))}
|
|
960
|
+
<details class=${s?"msg event-group live":"msg event-group"} data-index=${t} data-scroll-anchor-id=${this.groupAnchorKey(t)} ?open=${r} @toggle=${n=>{this.onGroupToggle(o,n,s)}}>
|
|
961
|
+
<summary>
|
|
962
|
+
<b class="label">${s?"实时事件":"事件"}</b>
|
|
963
|
+
<span>${zf(e)}</span>
|
|
964
|
+
</summary>
|
|
965
|
+
<div class="group-body">
|
|
966
|
+
${e.map((n,a)=>{const c=this.isToolExecutionOnlyMessage(n);return l`
|
|
967
|
+
<section class=${c?"group-msg tool-execution-shell":`group-msg ${n.role}`} data-index=${t+a} data-scroll-anchor-id=${this.eventAnchorKey(t+a)}>
|
|
968
|
+
${c?null:this.renderMessageHeader(n,`${String(t)}:${String(a)}`)}
|
|
969
|
+
${n.parts.map(p=>this.renderPart(p,n))}
|
|
970
|
+
</section>
|
|
971
|
+
`})}
|
|
972
|
+
</div>
|
|
973
|
+
</details>
|
|
974
|
+
`}renderScrollMarker(e){return l`<span class="scroll-marker" data-marker-id=${e} aria-hidden="true"></span>`}renderMessageHeader(e,t){const i=this.messageMetaLabel(e),s=this.expandedMetaKey===t;return l`
|
|
975
|
+
<div class="msg-header">
|
|
976
|
+
<b class="label">${Er(e.role)}</b>
|
|
977
|
+
<div class="msg-header-trailing">
|
|
978
|
+
${this.renderMessageActions(e,t)}
|
|
979
|
+
<span class=${s?"msg-meta expanded":"msg-meta"} role="button" tabindex="0" title=${i.full} aria-label=${i.full} aria-expanded=${String(s)} @click=${()=>{this.expandedMetaKey=s?void 0:t}} @keydown=${o=>{this.onMetaKeydown(o,t,s)}}>${i.short}</span>
|
|
980
|
+
</div>
|
|
981
|
+
</div>
|
|
982
|
+
`}renderMessageActions(e,t){if(!this.isCopyableMessage(e))return null;const i=this.copiedMessageKey===t;return l`
|
|
983
|
+
<div class="msg-actions" aria-label="消息操作">
|
|
984
|
+
<button type="button" class="msg-action" title=${i?"已复制":"复制消息"} aria-label=${`${i?"已复制":"复制"}${Er(e.role)}消息`} @click=${s=>{this.copyMessage(e,t,s)}}>
|
|
985
|
+
<span aria-hidden="true">${i?"✓":"⧉"}</span>
|
|
986
|
+
</button>
|
|
987
|
+
</div>
|
|
988
|
+
`}onMetaKeydown(e,t,i){e.key!=="Enter"&&e.key!==" "||(e.preventDefault(),this.expandedMetaKey=i?void 0:t)}isCopyableMessage(e){return(e.role==="user"||e.role==="assistant")&&this.messageCopyText(e)!==""}messageCopyText(e){const t=this.messageCopyTextCache.get(e);if(t!==void 0)return t;const i=e.parts.filter(s=>s.type==="text").map(s=>s.text.trim()).filter(s=>s!=="").join(`
|
|
989
|
+
|
|
990
|
+
`);return this.messageCopyTextCache.set(e,i),i}async copyMessage(e,t,i){i.stopPropagation(),await this.writeClipboard(this.messageCopyText(e))&&(this.copiedMessageKey=t,window.setTimeout(()=>{this.copiedMessageKey===t&&(this.copiedMessageKey=void 0)},1200))}async writeClipboard(e){try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}messageMetaLabel(e){const t=this.messageMetaCache.get(e);if(t!==void 0)return t;const i=e.meta?.timestamp,s=this.modelLabel(e);if(i===void 0&&s===void 0){const c={short:"无信息",full:"没有可用的 Pi 消息元数据"};return this.messageMetaCache.set(e,c),c}const o=i===void 0?void 0:this.formatTimestamp(i),r=[o?.short,s].filter(c=>c!==void 0&&c!==""),n=[o?.full,s===void 0?void 0:`模型:${s}`].filter(c=>c!==void 0&&c!==""),a={short:r.join(" · "),full:n.join(" · ")};return this.messageMetaCache.set(e,a),a}formatTimestamp(e){const t=new Date(e);if(Number.isFinite(t.getTime()))return{short:$m.format(t),full:Pm.format(t)}}modelLabel(e){const t=e.meta?.model;if(t===void 0)return;const i=t.responseId??t.id;return i===void 0||i===""?t.provider:t.provider!==void 0&&t.provider!==""?`${t.provider}/${i}`:i}renderPart(e,t){return e.type==="text"&&t?.role==="bash"?l`<pre class="part shell-output">${e.text}</pre>`:e.type==="text"?l`<formatted-text class="part" .text=${e.text}></formatted-text>`:e.type==="thinking"?l`<details class="part"><summary>思考</summary><formatted-text .text=${e.text}></formatted-text></details>`:e.type==="skillInvocation"?l`
|
|
991
|
+
<details class="part skill-invocation">
|
|
992
|
+
<summary><b>[技能]</b> ${e.name}</summary>
|
|
993
|
+
<small>${e.location}</small>
|
|
994
|
+
<formatted-text .text=${e.content}></formatted-text>
|
|
995
|
+
</details>
|
|
996
|
+
`:e.type==="skillRead"?l`
|
|
997
|
+
<div class="part skill-read">
|
|
998
|
+
<strong>已加载 ${e.name}</strong>
|
|
999
|
+
<small>读取 ${e.path}</small>
|
|
1000
|
+
</div>
|
|
1001
|
+
`:e.type==="toolCall"?l`<div class="part tool-line">▶ ${e.toolName}<span class="summary">${e.summary}</span></div>`:e.type==="toolExecution"?l`<tool-execution-view class="part" .execution=${e}></tool-execution-view>`:e.type==="toolResult"?l`
|
|
1002
|
+
<details class="part" ?open=${e.isError}>
|
|
1003
|
+
<summary>${e.isError?"✖":"✓"} ${e.toolName} 结果</summary>
|
|
1004
|
+
<formatted-text .text=${e.text}></formatted-text>
|
|
1005
|
+
</details>
|
|
1006
|
+
`:null}onGroupToggle(e,t,i){const s=t.currentTarget;s instanceof HTMLDetailsElement&&this.disclosures.applyToggle(e,s.open,i)&&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){const t=e.touches[0]?.clientY;this.touchStartY!==void 0&&t!==void 0&&t>this.touchStartY&&this.canScrollUp()&&(this.pinnedToBottom=!1)}updatePinnedToBottomFromScroll(){const e=this.chat;if(!e)return;const t=this.didChatHeightChange(),i=this.pinnedToBottom,s=e.scrollTop<this.lastScrollTop;if(t&&i){this.lastClientHeight=e.clientHeight,this.scrollToBottom();return}this.isAtBottom()?this.pinnedToBottom=!0:s?this.pinnedToBottom=!1:this.pinnedToBottom=this.isNearBottom(),this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight}didChatHeightChange(){const e=this.chat;return e!==void 0&&this.lastClientHeight!==0&&e.clientHeight!==this.lastClientHeight}isPrependingMessages(e){const 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;const e=this.chat;e&&Xf({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(){const e=this.chat;return e?ia(e):!0}isAtBottom(){const e=this.chat;return e?ta(e)<2:!0}canScrollUp(){const e=this.chat;return e!==void 0&&e.scrollTop>0}scrollToBottom(){this.scrollToBottomFrame===void 0&&(this.scrollToBottomFrame=requestAnimationFrame(()=>{this.scrollToBottomFrame=void 0;const e=this.chat;e&&this.withSuppressedScrollSave(()=>{e.scrollTop=e.scrollHeight,this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight})}))}restoreScrollPosition(){const e=this.sessionId;this.restoreScrollFrame!==void 0&&cancelAnimationFrame(this.restoreScrollFrame),this.restoreScrollFrame=requestAnimationFrame(()=>{this.restoreScrollFrame=void 0,this.sessionId===e&&this.withSuppressedScrollSave(()=>{const t=this.scrollController.restorePosition(e,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,t)})})}continuePendingScrollRestore(){const 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(()=>{const i=this.scrollController.restoreExplicitPosition(t,this.chat,this.scrollAnchorElements(),{fallbackToBottom:this.shouldFallbackToBottomForMissingAnchor()});this.handleScrollRestoreResult(e,i)})}))}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;const i=this.chat;i===void 0||!this.hasMore||this.loadingMore||(i.scrollTop=0,this.syncScrollMetrics(),this.requestLoadMore())}shouldFallbackToBottomForMissingAnchor(){return!this.hasMore&&!this.isReceivingPartialStream}updatePinnedToBottomAfterRestore(e){e==="bottom"?this.pinnedToBottom=!0:e==="restored"&&(this.pinnedToBottom=this.isNearBottom())}syncScrollMetrics(){const e=this.chat;e!==void 0&&(this.lastScrollTop=e.scrollTop,this.lastClientHeight=e.clientHeight)}cancelPrependRestore(){this.prependRestoreToken+=1,this.suppressLoadMoreRequests=!1}capturePrependScrollAnchor(){const e=this.chat;if(e)return Hf(e,this.scrollMarkers())}restorePrependScrollAnchor(e){if(!this.chat||!e)return;this.suppressLoadMoreRequests=!0,this.suppressScrollSave=!0;const t=this.prependRestoreToken+1;this.prependRestoreToken=t;let i=0;const s=()=>{const o=this.chat;if(!(!o||t!==this.prependRestoreToken)){if(qf(o,e,e.markerId===void 0?void 0:this.scrollMarkerAt(e.markerId)),this.lastScrollTop=o.scrollTop,i+=1,i<Uf){requestAnimationFrame(s);return}requestAnimationFrame(()=>{t===this.prependRestoreToken&&(this.suppressScrollSave=!1,this.suppressLoadMoreRequests=!1)})}};s()}saveScrollPosition(e=this.sessionId){e&&this.scrollController.savePosition(e,this.chat,this.scrollAnchorElements())}scheduleScrollPositionSave(){const e=this.sessionId;this.scrollController.scheduleSave(e,t=>{this.sessionId===t&&this.saveScrollPosition(t)})}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}const e=this.conversationDisplayTotal(),t=this.firstVisibleArticle(),i=Number(t?.dataset.index);if(Number.isFinite(i)){this.currentConversationIndex=ti(i,0,Math.max(0,e-1));return}this.currentConversationIndex=ti(this.pinnedToBottom?this.messageStart+this.messages.length-1:this.messageStart,0,Math.max(0,e-1))}scrollMarkers(){return Array.from(this.renderRoot.querySelectorAll(".scroll-marker"))}scrollMarkerAt(e){return this.scrollMarkers().find(t=>t.dataset.markerId===e)}firstVisibleArticle(){const e=this.chat;if(e===void 0)return;const t=Array.from(this.renderRoot.querySelectorAll("article.msg"));return wr(e,t)??wr(e,this.articles())}articles(){return Array.from(this.renderRoot.querySelectorAll("article.msg, details.msg"))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll("[data-scroll-anchor-id]"))}withSuppressedScrollSave(e){this.suppressScrollSave=!0,e(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.suppressScrollSave=!1})})}groupDisclosureKey(e,t,i){return i?`${this.sessionId}:live:${String(e)}`:`${this.sessionId}:${String(t)}`}messageAnchorKey(e){return`m:${String(e)}`}groupRenderKey(e){return`g:${String(e)}`}groupAnchorKey(e){return`g:${String(e)}`}eventAnchorKey(e){return`e:${String(e)}`}messageScrollMarkerId(e){return`m:${String(e)}`}groupScrollMarkerId(e){return`g:${String(e)}`}};L.styles=lf;F([d({attribute:!1})],L.prototype,"messages",2);F([d()],L.prototype,"sessionId",2);F([d({type:Number})],L.prototype,"messageStart",2);F([d({type:Number})],L.prototype,"messageEnd",2);F([d({type:Number})],L.prototype,"messageTotal",2);F([d({type:Boolean})],L.prototype,"hasMore",2);F([d({type:Boolean})],L.prototype,"loadingMore",2);F([d({type:Boolean})],L.prototype,"isReceivingPartialStream",2);F([d({type:Boolean})],L.prototype,"isCompacting",2);F([d({type:Number})],L.prototype,"pendingMessageCount",2);F([d({attribute:!1})],L.prototype,"status",2);F([d({attribute:!1})],L.prototype,"activity",2);F([d({attribute:!1})],L.prototype,"onLoadMore",2);F([N(".chat")],L.prototype,"chat",2);F([w()],L.prototype,"pinnedToBottom",2);F([w()],L.prototype,"expandedMetaKey",2);F([w()],L.prototype,"copiedMessageKey",2);F([w()],L.prototype,"currentConversationIndex",2);F([w()],L.prototype,"loadMoreRequested",2);L=F([R("chat-view")],L);function Er(e){return e==="user"?"用户":e==="assistant"?"助手":e==="system"?"系统":e==="tool"?"工具":e==="toolResult"?"工具结果":e==="bash"?"Shell":e==="skill"?"技能":e}function Cm(e){return e==="compacting"?"正在压缩":e==="bash"?"Shell 运行中":e==="running"?"运行中":e==="queued"?"已排队":e==="idle"?"空闲":e}class Im extends Qs{constructor(t){super(t),this.wasSelected=!1,this.isElementPart=t.type===Js.ELEMENT}update(t,[i,s]){if(!this.isElementPart)throw new Error("scrollWhenSelected must be used on an element");if(i&&(!this.wasSelected||s!==this.previousKey)){const o="element"in t?t.element:void 0;requestAnimationFrame(()=>{o instanceof HTMLElement&&o.scrollIntoView({block:"nearest"})})}this.wasSelected=i,this.previousKey=s}render(t,i){}}const co=Zs(Im);var Tm=Object.defineProperty,Mm=Object.getOwnPropertyDescriptor,Oi=(e,t,i,s)=>{for(var o=s>1?void 0:s?Mm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Tm(t,i,o),o};let nt=class extends T{constructor(){super(...arguments),this.items=[],this.selectedIndex=0}render(){return this.items.length?l`
|
|
1007
|
+
<div class="menu">
|
|
1008
|
+
${this.items.map((e,t)=>l`
|
|
1009
|
+
<button class=${t===this.selectedIndex?"selected":""} ${co(t===this.selectedIndex,e)} @mousedown=${i=>{i.preventDefault(),this.onPick?.(e)}}>
|
|
1010
|
+
<strong>${e.insertText}</strong>
|
|
1011
|
+
<span>${e.detail}</span>
|
|
1012
|
+
${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
|
|
1013
|
+
</button>
|
|
1014
|
+
`)}
|
|
1015
|
+
</div>
|
|
1016
|
+
`:null}};nt.styles=pf;Oi([d({attribute:!1})],nt.prototype,"items",2);Oi([d({type:Number})],nt.prototype,"selectedIndex",2);Oi([d({attribute:!1})],nt.prototype,"onPick",2);nt=Oi([R("autocomplete-menu")],nt);var Rm=Object.defineProperty,Am=Object.getOwnPropertyDescriptor,V=(e,t,i,s)=>{for(var o=s>1?void 0:s?Am(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Rm(t,i,o),o};let U=class extends T{constructor(){super(...arguments),this.disabled=!1,this.machineId="local",this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.draft="",this.completions=[],this.selectedIndex=0,this.requestVersion=0,this.editableCompartment=new ho,this.readOnlyCompartment=new ho}willUpdate(e){if(!e.has("sessionId")&&!e.has("machineId"))return;const t=e.has("sessionId")?e.get("sessionId"):this.sessionId,i=e.has("machineId")?e.get("machineId"):this.machineId,s=Ht(i,t);s!==void 0&&ci(s,this.draft);const o=Ht(this.machineId,this.sessionId);this.draft=o!==void 0?fn(o):"",this.completions=[],this.selectedIndex=0}firstUpdated(){this.createEditor()}updated(e){e.has("disabled")&&this.updateEditorDisabledState(),(e.has("draft")||e.has("sessionId")||e.has("machineId"))&&this.syncEditorDoc()}disconnectedCallback(){this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){const e=zs(this.draft),t=e.kind==="shell",i=this.canSteer||this.isCompacting;return l`
|
|
1017
|
+
<footer class=${t?"shell-mode":""}>
|
|
1018
|
+
<div class="editor-wrap">
|
|
1019
|
+
<div class=${`markdown-editor${this.disabled?" markdown-editor-disabled":""}`} aria-label="给 pi 发送消息" aria-disabled=${this.disabled?"true":"false"}></div>
|
|
1020
|
+
${t?l`<div class="mode-hint">Shell 命令${e.excludeFromContext?" · 不加入上下文":""}</div>`:null}
|
|
1021
|
+
${this.isCompacting&&!t?l`<div class="mode-hint">正在压缩历史 · 消息将排队发送</div>`:null}
|
|
1022
|
+
<autocomplete-menu .items=${this.completions} .selectedIndex=${this.selectedIndex} .onPick=${s=>{this.pick(s)}}></autocomplete-menu>
|
|
1023
|
+
</div>
|
|
1024
|
+
<div class="actions">
|
|
1025
|
+
${this.renderCompactStatus()}
|
|
1026
|
+
<button ?disabled=${this.disabled} title=${i?"当前活动结束后排队发送":"发送消息"} @click=${()=>{this.send("followUp")}}>${i?"排队":"发送"}</button>
|
|
1027
|
+
${this.canSteer&&!this.isCompacting?l`<button ?disabled=${this.disabled} title="在下一次模型调用前引导当前回复" @click=${()=>{this.send("steer")}}>引导</button>`:null}
|
|
1028
|
+
<button ?disabled=${this.disabled||!this.canStop} title=${this.canStop?"停止当前工作并清空排队消息":"当前没有运行任务"} @click=${()=>this.onStop?.()}>停止</button>
|
|
1029
|
+
</div>
|
|
1030
|
+
</footer>
|
|
1031
|
+
`}focusInput(){this.editor?.focus()}renderCompactStatus(){const e=this.status;if(e===void 0)return null;const t=e.model?.id??"未选择模型",i=e.model?.provider!==void 0&&e.model.provider!==""?`${e.model.provider}/`:"";return l`
|
|
1032
|
+
<div class="compact-status" aria-label="会话状态">
|
|
1033
|
+
<button class="select-model" title="选择模型" @click=${()=>this.onSelectModel?.()}>${i}${t}</button>
|
|
1034
|
+
<button class="select-thinking" title="选择思考级别" @click=${()=>this.onSelectThinking?.()}>思考 ${Om(e.thinkingLevel)}</button>
|
|
1035
|
+
</div>
|
|
1036
|
+
`}createEditor(){!this.editorHost||this.editor!==void 0||(this.editor=new Ye({parent:this.editorHost,state:Li.create({doc:this.draft,extensions:[ka(),Da(),$a(),Pa.of(" "),Ca(Ea,{fallback:!0}),Ye.lineWrapping,Ye.contentAttributes.of(e=>jm(e.state.sliceDoc(0,e.state.selection.main.head))),Ia("给 pi 发送消息... 使用 / 输入命令,使用 @ 引用跟踪文件,使用 @ 空格查看全部文件"),this.editableCompartment.of(Ye.editable.of(!this.disabled)),this.readOnlyCompartment.of(Li.readOnly.of(this.disabled)),Ye.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),Ta.of([{key:"ArrowDown",run:()=>this.moveCompletion(1)},{key:"ArrowUp",run:()=>this.moveCompletion(-1)},{key:"Escape",run:()=>this.closeCompletions()},{key:"Enter",run:()=>this.handleEditorEnter()},{key:"Shift-Enter",run:e=>Wa(e)||Aa(e)},{key:"Tab",run:e=>this.handleEditorTab(e)},{key:"Shift-Tab",run:e=>uo.shift?.(e)??!1},{key:"Backspace",run:e=>Oa(e)},...Ma,...Ra])]})}))}syncEditorDoc(){const e=this.editor;if(!e)return;const t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:fo.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(Ye.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(Li.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;const t=Ht(this.machineId,this.sessionId);t!==void 0&&ci(t,this.draft),this.refreshCompletions()}async refreshCompletions(){const 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!==""){const i=await B.commands(this.sessionId,this.machineId).catch(Dm);if(t!==this.requestVersion)return;this.completions=i.filter(s=>s.name.toLowerCase().includes(e.query.toLowerCase())).slice(0,12).map(s=>({kind:"command",replaceFrom:e.from,replaceTo:e.to,insertText:`/${s.name}`,detail:s.source,...s.description===void 0?{}:{description:s.description}}))}else if(e.kind==="file"&&this.cwd!==void 0&&this.cwd!==""){const i=await B.files(this.cwd,e.query,{scope:e.fileScope,machineId:this.machineId}).catch(Wm);if(t!==this.requestVersion)return;this.completions=i.slice(0,12).map(s=>{const o=Em(s.path,e.quoted===!0,s.path.endsWith("/")?e.allPrefix:void 0);return{kind:"file",replaceFrom:e.from,replaceTo:e.to,insertText:o,detail:s.kind,...s.path.endsWith("/")&&o.endsWith('"')?{cursorOffset:o.length-1}:{}}})}}currentTrigger(){const e=this.editor?.state.selection.main.head??this.draft.length,t=this.draft.slice(0,e),i=this.currentQuotedTrigger(t,e);if(i!==void 0)return i;const s=Math.max(t.lastIndexOf(" "),t.lastIndexOf(`
|
|
1037
|
+
`))+1,o=t.slice(s);if(t.slice(0,s).endsWith("@ "))return{kind:"file",query:o,from:s-2,to:e,fileScope:"all",allPrefix:"@ "};if(o.startsWith("/")&&s===0)return{kind:"command",query:o.slice(1),from:s,to:e};if(o.startsWith("!@"))return{kind:"file",query:o.slice(2),from:s,to:e,fileScope:"all",allPrefix:"!@"};if(o.startsWith("@"))return{kind:"file",query:o.slice(1),from:s,to:e,fileScope:"tracked"}}currentQuotedTrigger(e,t){const i=e.lastIndexOf('"');if(i===-1)return;const s=e.slice(0,i);if(s.endsWith("!@"))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"!@",quoted:!0};if(s.endsWith("@"))return{kind:"file",query:e.slice(i+1),from:s.length-1,to:t,fileScope:"tracked",quoted:!0};if(s.endsWith("@ "))return{kind:"file",query:e.slice(i+1),from:s.length-2,to:t,fileScope:"all",allPrefix:"@ ",quoted:!0}}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}handleEditorEnter(){if(this.completions.length){const e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.send(this.canSteer||this.isCompacting?"followUp":void 0),!0}handleEditorTab(e){if(this.completions.length){const i=this.completions[this.selectedIndex];return i!==void 0&&this.pick(i),!0}return this.currentTrigger()?.kind==="file"?(this.refreshCompletions(),!0):uo.run?.(e)??!1}pick(e){const t=this.editor;if(!t)return;const i=e.kind==="file"&&(e.insertText.endsWith("/")||e.cursorOffset!==void 0)?"":" ",s=e.replaceFrom+(e.cursorOffset??e.insertText.length)+i.length,o=e.insertText.endsWith('"')&&this.draft.slice(e.replaceTo).startsWith('"')?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:o,insert:`${e.insertText}${i}`},selection:fo.cursor(s),scrollIntoView:!0}),this.completions=[]}send(e){const t=this.draft.trim();if(t===""||this.disabled)return;this.draft="";const i=Ht(this.machineId,this.sessionId);i!==void 0&&Fs(i),this.completions=[],this.onSend?.(t,this.canSteer||this.isCompacting?e:void 0)}};U.styles=uf;V([d({type:Boolean})],U.prototype,"disabled",2);V([d()],U.prototype,"sessionId",2);V([d()],U.prototype,"cwd",2);V([d()],U.prototype,"machineId",2);V([d({type:Boolean})],U.prototype,"canSteer",2);V([d({type:Boolean})],U.prototype,"isCompacting",2);V([d({type:Boolean})],U.prototype,"canStop",2);V([d({attribute:!1})],U.prototype,"status",2);V([d({attribute:!1})],U.prototype,"onSend",2);V([d({attribute:!1})],U.prototype,"onStop",2);V([d({attribute:!1})],U.prototype,"onSelectModel",2);V([d({attribute:!1})],U.prototype,"onSelectThinking",2);V([N(".markdown-editor")],U.prototype,"editorHost",2);V([w()],U.prototype,"draft",2);V([w()],U.prototype,"completions",2);V([w()],U.prototype,"selectedIndex",2);U=V([R("prompt-editor")],U);function Ht(e,t){if(!(typeof e!="string"||e==="")&&!(typeof t!="string"||t===""))return hn(e,t)}function Em(e,t,i){const s=i??"@";return!t&&!e.includes(" ")?`${s}${e}`:`${s}"${e}"`}function Dm(){return[]}function Wm(){return[]}function Om(e){return e===void 0||e==="off"?"关闭":e==="minimal"?"极简":e==="low"?"低":e==="medium"?"中":e==="high"?"高":e==="xhigh"?"超高":e}const _m={spellcheck:"true",autocorrect:"on",autocapitalize:"sentences",writingsuggestions:"true"},Lm={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false"};function jm(e){return zs(e).kind==="normal"?_m:Lm}function qt(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 Nm(e){return!Number.isFinite(e)||e===0?"$0":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}var Fm=Object.defineProperty,zm=Object.getOwnPropertyDescriptor,va=(e,t,i,s)=>{for(var o=s>1?void 0:s?zm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Fm(t,i,o),o};let wi=class extends T{render(){const e=this.status;if(e===void 0)return l`<div class="bar muted">暂无会话状态</div>`;const t=e.contextUsage,i=t?t.percent==null?`上下文 ${qt(t.contextWindow)}`:`${t.percent.toFixed(1)}%/${qt(t.contextWindow)}`:"上下文未知",s=e.tokens;return l`
|
|
1038
|
+
<div class="bar">
|
|
1039
|
+
<span>↑${qt(s.input)}</span>
|
|
1040
|
+
<span>↓${qt(s.output)}</span>
|
|
1041
|
+
<span class="context">${i}</span>
|
|
1042
|
+
<span>${Nm(e.cost)}</span>
|
|
1043
|
+
${e.pendingMessageCount>0?l`<span>${String(e.pendingMessageCount)} 条排队</span>`:null}
|
|
1044
|
+
</div>
|
|
1045
|
+
`}};wi.styles=df;va([d({attribute:!1})],wi.prototype,"status",2);wi=va([R("status-bar")],wi);var Bm=Object.defineProperty,Um=Object.getOwnPropertyDescriptor,Oe=(e,t,i,s)=>{for(var o=s>1?void 0:s?Um(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Bm(t,i,o),o};let xe=class extends T{constructor(){super(...arguments),this.title="选择",this.searchable=!1,this.options=[],this.selectedIndex=0,this.query=""}render(){const e=this.filteredOptions();return l`
|
|
1046
|
+
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
1047
|
+
<section @mousedown=${t=>{t.stopPropagation()}}>
|
|
1048
|
+
<header>
|
|
1049
|
+
<strong>${this.title}</strong>
|
|
1050
|
+
<button @click=${()=>this.onCancel?.()}>×</button>
|
|
1051
|
+
</header>
|
|
1052
|
+
${this.searchable?l`<input placeholder="搜索" .value=${this.query} @input=${t=>{this.handleSearchInput(t)}} @keydown=${t=>{this.handleKeyDown(t)}}>`:null}
|
|
1053
|
+
<div class="options" @keydown=${t=>{this.handleKeyDown(t)}} tabindex="0">
|
|
1054
|
+
${e.map((t,i)=>l`
|
|
1055
|
+
<button class=${i===this.selectedIndex?"selected":""} ${co(i===this.selectedIndex,t.value)} @click=${()=>this.onPick?.(t.value)}>
|
|
1056
|
+
<span>${t.label}</span>
|
|
1057
|
+
${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
|
|
1058
|
+
</button>
|
|
1059
|
+
`)}
|
|
1060
|
+
${e.length===0?l`<div class="empty">没有匹配选项</div>`:null}
|
|
1061
|
+
</div>
|
|
1062
|
+
</section>
|
|
1063
|
+
</div>
|
|
1064
|
+
`}firstUpdated(){this.selectInitialValue(),this.renderRoot.querySelector(this.searchable?"input":".options")?.focus()}selectInitialValue(){if(this.selectedValue===void 0)return;const e=this.filteredOptions().findIndex(t=>t.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){const e=this.query.trim().toLowerCase();return e===""?this.options:this.options.filter(t=>`${t.label} ${t.description??""} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredOptions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i&&this.onPick?.(i.value)}}};xe.styles=Xn;Oe([d()],xe.prototype,"title",2);Oe([d({type:Boolean})],xe.prototype,"searchable",2);Oe([d({attribute:!1})],xe.prototype,"options",2);Oe([d({attribute:!1})],xe.prototype,"selectedValue",2);Oe([d({attribute:!1})],xe.prototype,"onPick",2);Oe([d({attribute:!1})],xe.prototype,"onCancel",2);Oe([w()],xe.prototype,"selectedIndex",2);Oe([w()],xe.prototype,"query",2);xe=Oe([R("command-picker")],xe);var Hm=Object.defineProperty,qm=Object.getOwnPropertyDescriptor,Ze=(e,t,i,s)=>{for(var o=s>1?void 0:s?qm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Hm(t,i,o),o};let De=class extends T{constructor(){super(...arguments),this.actions=[],this.queryText="",this.selectedIndex=0}render(){const e=this.filteredActions();return l`
|
|
1065
|
+
<div class="backdrop" @mousedown=${()=>this.onCancel?.()}>
|
|
1066
|
+
<section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
|
|
1067
|
+
<header>
|
|
1068
|
+
<input
|
|
1069
|
+
.value=${this.queryText}
|
|
1070
|
+
placeholder="搜索操作..."
|
|
1071
|
+
@input=${t=>{t.target instanceof HTMLInputElement&&(this.queryText=t.target.value,this.selectedIndex=0)}}
|
|
1072
|
+
>
|
|
1073
|
+
<button title="关闭" @click=${()=>this.onCancel?.()}>×</button>
|
|
1074
|
+
</header>
|
|
1075
|
+
<div class="options">
|
|
1076
|
+
${e.length===0?l`<div class="empty">未找到操作。</div>`:e.map((t,i)=>l`
|
|
1077
|
+
<button class=${i===this.selectedIndex?"selected":""} ${co(i===this.selectedIndex,t.id)} @click=${()=>{this.run(t)}}>
|
|
1078
|
+
<span class="main">
|
|
1079
|
+
<strong>${t.title}</strong>
|
|
1080
|
+
${t.description!==void 0&&t.description!==""?l`<small>${t.description}</small>`:null}
|
|
1081
|
+
</span>
|
|
1082
|
+
${t.shortcut!==void 0?l`<kbd>${Xt(t.shortcut)}</kbd>`:null}
|
|
1083
|
+
${t.group!==void 0&&t.group!==""?l`<small class="group">${t.group}</small>`:null}
|
|
1084
|
+
</button>
|
|
1085
|
+
`)}
|
|
1086
|
+
</div>
|
|
1087
|
+
</section>
|
|
1088
|
+
</div>
|
|
1089
|
+
`}firstUpdated(){this.input?.focus()}updated(e){if(!e.has("actions")&&!e.has("queryText"))return;const t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){const e=this.queryText.trim().toLowerCase();return this.actions.filter(t=>t.enabled!==!1).filter(t=>e===""?!0:[t.title,t.description??"",t.group??"",t.shortcut??""].join(" ").toLowerCase().includes(e))}handleKeyDown(e){const t=this.filteredActions();if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="ArrowDown")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key==="ArrowUp")e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key==="Enter"){e.preventDefault();const i=t[this.selectedIndex];i!==void 0&&this.run(i)}}run(e){this.onRun?.(e)}};De.styles=hf;Ze([d({attribute:!1})],De.prototype,"actions",2);Ze([d({attribute:!1})],De.prototype,"onRun",2);Ze([d({attribute:!1})],De.prototype,"onCancel",2);Ze([N("input")],De.prototype,"input",2);Ze([w()],De.prototype,"queryText",2);Ze([w()],De.prototype,"selectedIndex",2);De=Ze([R("action-palette")],De);var Km=Object.defineProperty,Vm=Object.getOwnPropertyDescriptor,ge=(e,t,i,s)=>{for(var o=s>1?void 0:s?Vm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Km(t,i,o),o};let ee=class extends T{render(){const e=this.state;return e===void 0?null:l`
|
|
1090
|
+
<div class="backdrop" @mousedown=${()=>{this.cancel()}}>
|
|
1091
|
+
<section @mousedown=${t=>{t.stopPropagation()}} @keydown=${t=>{this.handleKeyDown(t)}}>
|
|
1092
|
+
<header>
|
|
1093
|
+
<strong>${this.dialogTitle(e)}</strong>
|
|
1094
|
+
<button title="关闭" @click=${()=>{this.cancel()}}>×</button>
|
|
1095
|
+
</header>
|
|
1096
|
+
${this.renderBody(e)}
|
|
1097
|
+
</section>
|
|
1098
|
+
</div>
|
|
1099
|
+
`}updated(){this.focusInputIfNeeded()}dialogTitle(e){switch(e.step){case"method":return"配置提供商认证";case"providers":return e.authType===void 0?"选择提供商认证":e.authType==="oauth"?"选择订阅提供商":"选择 API key 提供商";case"apiKey":return`${e.provider.name} 的 API key`;case"oauth":return`登录 ${e.flow.providerName}`;case"logout":return"移除已保存的提供商认证"}}renderBody(e){switch(e.step){case"method":return l`
|
|
1100
|
+
<div class="options">
|
|
1101
|
+
<button @click=${()=>{this.onChooseMethod?.("oauth")}}><span>使用订阅</span><small>ChatGPT Plus/Pro、Claude Pro/Max 或 GitHub Copilot</small></button>
|
|
1102
|
+
<button @click=${()=>{this.onChooseMethod?.("api_key")}}><span>使用 API key</span><small>将 API key 存入 pi auth.json</small></button>
|
|
1103
|
+
</div>
|
|
1104
|
+
`;case"providers":return l`<div class="options">${e.providers.length===0?l`<div class="empty">没有可用提供商。</div>`:e.providers.map(t=>this.renderProviderButton(t))}</div>`;case"apiKey":return l`
|
|
1105
|
+
<div class="form">
|
|
1106
|
+
<p>输入 <strong>${e.provider.name}</strong> 的 API key。它会由 pi 存入 <code>auth.json</code>。</p>
|
|
1107
|
+
<input type="password" autocomplete="off" placeholder="API key" .value=${e.value} @input=${t=>{t.target instanceof HTMLInputElement&&this.onApiKeyInput?.(t.target.value)}}>
|
|
1108
|
+
${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
|
|
1109
|
+
<div class="actions"><button @click=${()=>{this.cancel()}}>取消</button><button class="primary" ?disabled=${e.saving===!0} @click=${()=>{this.onSaveApiKey?.()}}>${e.saving===!0?"正在保存…":"保存 API key"}</button></div>
|
|
1110
|
+
</div>
|
|
1111
|
+
`;case"oauth":return this.renderOAuth(e);case"logout":return l`<div class="options">${e.providers.length===0?l`<div class="empty">没有已保存的凭据。环境变量和 models.json 设置不会变化。</div>`:e.providers.map(t=>l`
|
|
1112
|
+
<button @click=${()=>{this.onLogoutProvider?.(t.id)}}><span>${t.name}</span><small>${t.id} · ${Dr(t.authType)}</small></button>
|
|
1113
|
+
`)}</div>`}}renderProviderButton(e){return l`
|
|
1114
|
+
<button @click=${()=>{this.onSelectProvider?.(e.id,e.authType)}}>
|
|
1115
|
+
<span>${e.name}${e.status.source!==void 0?l` <em>${Jm(e)}</em>`:null}</span>
|
|
1116
|
+
<small>${e.id} · ${Dr(e.authType)}</small>
|
|
1117
|
+
</button>
|
|
1118
|
+
`}renderOAuth(e){const t=e.flow,i=t.prompt,s=t.select;return l`
|
|
1119
|
+
<div class="form">
|
|
1120
|
+
${t.auth!==void 0?l`
|
|
1121
|
+
<p>打开此授权链接:</p>
|
|
1122
|
+
<p><a href=${t.auth.url} target="_blank" rel="noreferrer">${t.auth.url}</a></p>
|
|
1123
|
+
${t.auth.instructions!==void 0?l`<p class="warning">${t.auth.instructions}</p>`:null}
|
|
1124
|
+
`:l`<p>正在启动登录流程…</p>`}
|
|
1125
|
+
${t.progress.length>0?l`<ul class="progress">${t.progress.map(o=>l`<li>${o}</li>`)}</ul>`:null}
|
|
1126
|
+
${i!==void 0?l`
|
|
1127
|
+
<label>${i.message}</label>
|
|
1128
|
+
<input .value=${e.inputValue??""} placeholder=${i.placeholder??""} @input=${o=>{o.target instanceof HTMLInputElement&&this.onOAuthInput?.(o.target.value)}}>
|
|
1129
|
+
<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>取消</button><button class="primary" ?disabled=${e.responding===!0} @click=${()=>{this.onOAuthRespond?.()}}>提交</button></div>
|
|
1130
|
+
`:null}
|
|
1131
|
+
${s!==void 0?l`
|
|
1132
|
+
<p>${s.message}</p>
|
|
1133
|
+
<div class="inline-options">${s.options.map(o=>l`<button @click=${()=>{this.onOAuthRespond?.(o.value)}}>${o.label}</button>`)}</div>
|
|
1134
|
+
`:null}
|
|
1135
|
+
${e.error!==void 0&&e.error!==""?l`<div class="error-text">${e.error}</div>`:null}
|
|
1136
|
+
${t.status==="error"||t.status==="cancelled"?l`<div class="error-text">${t.error??Zm(t.status)}</div><div class="actions"><button @click=${()=>{this.cancel()}}>关闭</button></div>`:null}
|
|
1137
|
+
${i===void 0&&s===void 0&&t.status==="running"?l`<div class="actions"><button @click=${()=>{this.onOAuthCancel?.()}}>取消</button></div>`:null}
|
|
1138
|
+
</div>
|
|
1139
|
+
`}focusInputIfNeeded(){const e=Gm(this.state);if(e===void 0){this.lastFocusedInputKey=void 0;return}e!==this.lastFocusedInputKey&&(this.lastFocusedInputKey=e,this.input?.focus())}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.cancel();return}if(e.key!=="Enter")return;const t=this.state;t?.step==="apiKey"?(e.preventDefault(),this.onSaveApiKey?.()):t?.step==="oauth"&&t.flow.prompt!==void 0&&(e.preventDefault(),this.onOAuthRespond?.())}cancel(){this.state?.step==="oauth"?this.onOAuthCancel?.():this.onCancel?.()}};ee.styles=[Xn,A`
|
|
1140
|
+
.form { display: grid; gap: 12px; padding: 14px; overflow: auto; }
|
|
1141
|
+
.form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
|
|
1142
|
+
.form a { color: var(--pi-accent); overflow-wrap: anywhere; }
|
|
1143
|
+
.form code { border: 1px solid var(--pi-border); border-radius: 4px; background: var(--pi-surface); padding: 1px 4px; }
|
|
1144
|
+
label { color: var(--pi-muted); }
|
|
1145
|
+
.actions { display: flex; justify-content: flex-end; gap: 8px; }
|
|
1146
|
+
.actions button, .inline-options button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; }
|
|
1147
|
+
.actions button.primary { border-color: var(--pi-success-border); background: var(--pi-success-surface); color: var(--pi-success); }
|
|
1148
|
+
.actions button:disabled { opacity: .6; cursor: wait; }
|
|
1149
|
+
.warning { color: var(--pi-warning); }
|
|
1150
|
+
.error-text { color: var(--pi-danger); }
|
|
1151
|
+
.progress { margin: 0; padding-left: 18px; color: var(--pi-muted); }
|
|
1152
|
+
.inline-options { display: grid; gap: 8px; }
|
|
1153
|
+
em { color: var(--pi-success); font-style: normal; font-size: 12px; }
|
|
1154
|
+
`];ge([d({attribute:!1})],ee.prototype,"state",2);ge([d({attribute:!1})],ee.prototype,"onChooseMethod",2);ge([d({attribute:!1})],ee.prototype,"onSelectProvider",2);ge([d({attribute:!1})],ee.prototype,"onApiKeyInput",2);ge([d({attribute:!1})],ee.prototype,"onSaveApiKey",2);ge([d({attribute:!1})],ee.prototype,"onLogoutProvider",2);ge([d({attribute:!1})],ee.prototype,"onOAuthInput",2);ge([d({attribute:!1})],ee.prototype,"onOAuthRespond",2);ge([d({attribute:!1})],ee.prototype,"onOAuthCancel",2);ge([d({attribute:!1})],ee.prototype,"onCancel",2);ge([N("input")],ee.prototype,"input",2);ee=ge([R("auth-dialog")],ee);function Dr(e){return e==="oauth"?"订阅":"API key"}function Gm(e){if(e?.step==="apiKey")return`api-key:${e.provider.authType}:${e.provider.id}`;if(e?.step==="oauth"&&e.flow.prompt!==void 0)return`oauth:${e.flow.flowId}:${e.flow.prompt.requestId}`}function Jm(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 Zm(e){return e==="cancelled"?"已取消":e==="error"?"错误":e}var Qm=Object.defineProperty,Xm=Object.getOwnPropertyDescriptor,Me=(e,t,i,s)=>{for(var o=s>1?void 0:s?Xm(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Qm(t,i,o),o};let he=class extends T{constructor(){super(...arguments),this.machineId="local",this.path="",this.createMissing=!0,this.suggestions=[],this.selected=0,this.loading=!1,this.requestId=0}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}firstUpdated(){this.pathInput?.focus()}async loadSuggestions(){const e=++this.requestId;this.loading=!0;try{const t=await B.projectDirectories(this.path,this.machineId);if(e!==this.requestId)return;this.suggestions=t,this.selected=Math.min(this.selected,Math.max(0,t.length-1))}catch{e===this.requestId&&(this.suggestions=[])}finally{e===this.requestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.loadSuggestions()}pick(e){this.setPath(e.path)}submit(){this.path.trim()!==""&&this.onSubmit?.(this.path,this.createMissing)}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}onKeyDown(e){if(e.key==="Escape")e.preventDefault(),this.onCancel?.();else if(e.key==="Enter")e.preventDefault(),this.submit();else if(e.key==="ArrowDown")e.preventDefault(),this.selected=Math.min(this.selected+1,Math.max(0,this.suggestions.length-1));else if(e.key==="ArrowUp")e.preventDefault(),this.selected=Math.max(0,this.selected-1);else if(e.key==="Tab"){const t=this.suggestions[this.selected];if(t===void 0)return;e.preventDefault(),this.pick(t)}}render(){return l`
|
|
1155
|
+
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
1156
|
+
<section @click=${e=>{e.stopPropagation()}}>
|
|
1157
|
+
<header>
|
|
1158
|
+
<strong>添加项目</strong>
|
|
1159
|
+
<button @click=${()=>{this.onCancel?.()}} aria-label="关闭">×</button>
|
|
1160
|
+
</header>
|
|
1161
|
+
<div class="body">
|
|
1162
|
+
<label>
|
|
1163
|
+
项目文件夹
|
|
1164
|
+
<input .value=${this.path} @input=${e=>{this.onPathInput(e)}} @keydown=${e=>{this.onKeyDown(e)}} placeholder="/path/to/project or ~/code/project" autofocus />
|
|
1165
|
+
</label>
|
|
1166
|
+
<div class="suggestions">
|
|
1167
|
+
${this.loading?l`<div class="hint">正在加载文件夹…</div>`:null}
|
|
1168
|
+
${this.suggestions.map((e,t)=>l`
|
|
1169
|
+
<button class=${t===this.selected?"selected":""} @click=${()=>{this.pick(e)}}>
|
|
1170
|
+
${e.path}
|
|
1171
|
+
</button>
|
|
1172
|
+
`)}
|
|
1173
|
+
${!this.loading&&this.suggestions.length===0?l`<div class="hint">没有匹配的文件夹。输入新路径即可创建。</div>`:null}
|
|
1174
|
+
</div>
|
|
1175
|
+
<label class="check">
|
|
1176
|
+
<input type="checkbox" .checked=${this.createMissing} @change=${e=>{this.onCreateMissingChange(e)}} />
|
|
1177
|
+
如果文件夹不存在则创建
|
|
1178
|
+
</label>
|
|
1179
|
+
</div>
|
|
1180
|
+
<footer>
|
|
1181
|
+
<button @click=${()=>{this.onCancel?.()}}>取消</button>
|
|
1182
|
+
<button class="primary" ?disabled=${this.path.trim()===""} @click=${()=>{this.submit()}}>添加项目</button>
|
|
1183
|
+
</footer>
|
|
1184
|
+
</section>
|
|
1185
|
+
</div>
|
|
1186
|
+
`}};he.styles=A`
|
|
1187
|
+
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
1188
|
+
.backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
|
|
1189
|
+
section { width: min(720px, calc(100vw - 40px)); max-height: min(700px, 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; }
|
|
1190
|
+
header, footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
|
|
1191
|
+
footer { border-top: 1px solid var(--pi-border); border-bottom: 0; justify-content: end; }
|
|
1192
|
+
.body { display: grid; gap: 12px; padding: 12px; min-height: 0; }
|
|
1193
|
+
label { display: grid; gap: 6px; color: var(--pi-muted); }
|
|
1194
|
+
input[type="text"], input:not([type]) { box-sizing: border-box; width: 100%; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px; font: 14px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
|
|
1195
|
+
.check { display: flex; grid-template-columns: auto 1fr; align-items: center; color: var(--pi-text); }
|
|
1196
|
+
.suggestions { min-height: 90px; max-height: 320px; overflow: auto; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); }
|
|
1197
|
+
.suggestions button { display: block; width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; border: 0; border-bottom: 1px solid var(--pi-border); border-radius: 0; background: transparent; color: var(--pi-text); padding: 8px 10px; text-align: left; font: 13px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
|
|
1198
|
+
.suggestions button.selected, .suggestions button:hover { background: var(--pi-selection-bg); }
|
|
1199
|
+
.hint { padding: 12px; color: var(--pi-muted); }
|
|
1200
|
+
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
1201
|
+
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
1202
|
+
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
1203
|
+
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
1204
|
+
`;Me([d({attribute:!1})],he.prototype,"onSubmit",2);Me([d({attribute:!1})],he.prototype,"onCancel",2);Me([d()],he.prototype,"machineId",2);Me([w()],he.prototype,"path",2);Me([w()],he.prototype,"createMissing",2);Me([w()],he.prototype,"suggestions",2);Me([w()],he.prototype,"selected",2);Me([w()],he.prototype,"loading",2);Me([N("input")],he.prototype,"pathInput",2);he=Me([R("project-dialog")],he);var Ym=Object.defineProperty,ev=Object.getOwnPropertyDescriptor,Re=(e,t,i,s)=>{for(var o=s>1?void 0:s?ev(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Ym(t,i,o),o};let ue=class extends T{constructor(){super(...arguments),this.error="",this.url="",this.name="",this.token="",this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=""}firstUpdated(){this.urlInput?.focus()}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;const t=e.target.value,i=tv(t);(!this.nameEdited||this.name.trim()===""||this.name===this.previousSuggestedName)&&(this.name=i),this.previousSuggestedName=i,this.url=t}handleNameInput(e){e.target instanceof HTMLInputElement&&(this.nameEdited=!0,this.name=e.target.value)}handleTokenInput(e){e.target instanceof HTMLInputElement&&(this.token=e.target.value)}handleKeyDown(e){if(e.key==="Escape"){e.preventDefault(),this.onCancel?.();return}e.key==="Enter"&&e.target instanceof HTMLInputElement&&e.target.name==="baseUrl"&&is(this.url)===void 0&&(e.preventDefault(),this.updateComplete.then(()=>{this.nameInput?.focus(),this.nameInput?.select()}))}handleSubmit(e){e.preventDefault(),this.submit()}async submit(){const e=this.validInput();if(!(e===void 0||this.submitting)){this.submitting=!0;try{await this.onSubmit?.(e)}finally{this.isConnected&&(this.submitting=!1)}}}validInput(){const e=this.url.trim(),t=this.name.trim();if(e===""||t===""||is(e)!==void 0)return;const i=this.token.trim();return{name:t,baseUrl:e,...i===""?{}:{token:i}}}render(){const e=this.url.trim()!=="",t=e?is(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return l`
|
|
1205
|
+
<div class="backdrop" @click=${()=>this.onCancel?.()}>
|
|
1206
|
+
<section @click=${s=>{s.stopPropagation()}}>
|
|
1207
|
+
<form @submit=${s=>{this.handleSubmit(s)}} @keydown=${s=>{this.handleKeyDown(s)}}>
|
|
1208
|
+
<header>
|
|
1209
|
+
<strong>添加机器</strong>
|
|
1210
|
+
<button type="button" @click=${()=>{this.onCancel?.()}} aria-label="关闭">×</button>
|
|
1211
|
+
</header>
|
|
1212
|
+
<div class="body">
|
|
1213
|
+
${this.error===""?null:l`<div class="dialog-error" role="alert">${this.error}</div>`}
|
|
1214
|
+
<label>
|
|
1215
|
+
远程 PI WEB URL
|
|
1216
|
+
<input name="baseUrl" type="url" .value=${this.url} @input=${s=>{this.handleUrlInput(s)}} placeholder="http://dev-box.local:8504" autocomplete="url" inputmode="url" autofocus />
|
|
1217
|
+
</label>
|
|
1218
|
+
<small class=${t===void 0?"hint":"field-error"}>${t??"先输入可访问的基础 URL,包含 http:// 或 https://。"}</small>
|
|
1219
|
+
${e?l`
|
|
1220
|
+
<label>
|
|
1221
|
+
机器名称
|
|
1222
|
+
<input name="name" type="text" .value=${this.name} @input=${s=>{this.handleNameInput(s)}} placeholder=${this.previousSuggestedName||"开发机"} autocomplete="off" />
|
|
1223
|
+
</label>
|
|
1224
|
+
<small class="hint">根据 URL 自动建议。可以改成更友好的侧栏名称。</small>
|
|
1225
|
+
<label>
|
|
1226
|
+
Bearer token <span class="optional">可选</span>
|
|
1227
|
+
<input name="token" type="password" .value=${this.token} @input=${s=>{this.handleTokenInput(s)}} placeholder="如果远程机器不需要 token,可留空" autocomplete="off" />
|
|
1228
|
+
</label>
|
|
1229
|
+
<small class="hint">只粘贴 token 值;PI WEB 会通过 Authorization: Bearer 请求头发送。</small>
|
|
1230
|
+
`:l`<p class="hint intro">输入 URL 后,PI WEB 会建议机器名称,并允许添加可选的 bearer token。</p>`}
|
|
1231
|
+
</div>
|
|
1232
|
+
<footer>
|
|
1233
|
+
<button type="button" @click=${()=>{this.onCancel?.()}}>取消</button>
|
|
1234
|
+
<button class="primary" type="submit" ?disabled=${!i}>${this.submitting?"正在添加…":"添加机器"}</button>
|
|
1235
|
+
</footer>
|
|
1236
|
+
</form>
|
|
1237
|
+
</section>
|
|
1238
|
+
</div>
|
|
1239
|
+
`}};ue.styles=A`
|
|
1240
|
+
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
1241
|
+
.backdrop { display: grid; place-items: start center; width: 100%; height: 100%; padding-top: min(12vh, 90px); box-sizing: border-box; background: var(--pi-overlay); }
|
|
1242
|
+
section { width: min(560px, calc(100vw - 40px)); max-height: min(640px, calc(100vh - 40px)); border: 1px solid var(--pi-border); border-radius: 12px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
|
|
1243
|
+
form { display: flex; flex-direction: column; max-height: inherit; min-height: 0; }
|
|
1244
|
+
header, footer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 12px; border-bottom: 1px solid var(--pi-border); }
|
|
1245
|
+
footer { border-top: 1px solid var(--pi-border); border-bottom: 0; justify-content: end; }
|
|
1246
|
+
.body { display: grid; gap: 8px; padding: 12px; min-height: 0; overflow: auto; }
|
|
1247
|
+
label { display: grid; gap: 6px; color: var(--pi-muted); }
|
|
1248
|
+
input { box-sizing: border-box; width: 100%; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px; font: 14px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
|
|
1249
|
+
input:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 1px; }
|
|
1250
|
+
.hint { color: var(--pi-muted); }
|
|
1251
|
+
.intro { margin: 4px 0 0; line-height: 1.4; }
|
|
1252
|
+
.optional { color: var(--pi-muted); font-weight: 400; }
|
|
1253
|
+
.field-error { color: var(--pi-danger); }
|
|
1254
|
+
.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; }
|
|
1255
|
+
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
1256
|
+
header button { border: 0; background: transparent; color: var(--pi-muted); font-size: 22px; padding: 0 8px; }
|
|
1257
|
+
.primary { border-color: var(--pi-success-border); background: var(--pi-success-border); }
|
|
1258
|
+
button:disabled { opacity: .5; cursor: not-allowed; }
|
|
1259
|
+
`;Re([d({attribute:!1})],ue.prototype,"onSubmit",2);Re([d({attribute:!1})],ue.prototype,"onCancel",2);Re([d()],ue.prototype,"error",2);Re([w()],ue.prototype,"url",2);Re([w()],ue.prototype,"name",2);Re([w()],ue.prototype,"token",2);Re([w()],ue.prototype,"submitting",2);Re([N("input[name='baseUrl']")],ue.prototype,"urlInput",2);Re([N("input[name='name']")],ue.prototype,"nameInput",2);ue=Re([R("machine-dialog")],ue);function tv(e){const t=e.trim();if(t==="")return"";const i=Wr(t)??Wr(`http://${t.replace(/^\/+/u,"")}`);return i!==void 0&&i.hostname!==""?i.hostname.replace(/^\[(.*)\]$/u,"$1"):iv(t)}function is(e){const t=e.trim();if(t==="")return"必须填写远程 PI WEB URL。";let i;try{i=new URL(t)}catch{return"请输入包含 http:// 或 https:// 的有效 URL。"}if(i.protocol!=="http:"&&i.protocol!=="https:")return"请使用 http:// 或 https:// URL。";if(i.username!==""||i.password!=="")return"机器 URL 中不要包含凭据。";if(i.search!==""||i.hash!=="")return"不要包含查询字符串或片段。"}function Wr(e){try{const t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"?t:void 0}catch{return}}function iv(e){const t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,""),s=t.slice(t.lastIndexOf("@")+1).split(/[/?#]/u)[0]??"";return s.startsWith("[")&&s.includes("]")?s.slice(1,s.indexOf("]")):s.replace(/:\d+$/u,"")}function sv(){return{host:"",port:"",allowedHostsMode:"list",allowedHostsText:""}}function ov(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(`
|
|
1260
|
+
`):""}}function rv(e,t={}){const i={...t.shortcuts===void 0?{}:{shortcuts:t.shortcuts},...t.plugins===void 0?{}:{plugins:t.plugins}},s=e.host.trim(),o=e.port.trim();if(s!==""&&(i.host=s),o!==""){const r=Number(o);if(!Number.isInteger(r)||r<1||r>65535)throw new Error("端口必须是 1 到 65535 之间的整数。");i.port=r}return i.allowedHosts=e.allowedHostsMode==="all"?!0:nv(e.allowedHostsText),i}function nv(e){return e.split(/[\n,]/u).map(t=>t.trim()).filter(t=>t!=="")}var av=Object.defineProperty,lv=Object.getOwnPropertyDescriptor,Ae=(e,t,i,s)=>{for(var o=s>1?void 0:s?lv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&av(t,i,o),o};let fe=class extends T{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.draft=sv(),this.localError=""}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.draft=ov(this.configResponse.config),this.localError="")}render(){const e=this.configResponse;return l`
|
|
1261
|
+
<div class="section-heading">
|
|
1262
|
+
<div>
|
|
1263
|
+
<h2>通用配置</h2>
|
|
1264
|
+
<p>更新 PI WEB 正在使用的 JSON 配置文件。Host 和端口会立即保存,但需要重启 Web 服务后,运行中的服务器才会绑定到新地址。</p>
|
|
1265
|
+
</div>
|
|
1266
|
+
<button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>重新加载</button>
|
|
1267
|
+
</div>
|
|
1268
|
+
${this.renderMessages()}
|
|
1269
|
+
${e===void 0&&this.loading?l`<div class="loading-card">正在加载配置…</div>`:l`
|
|
1270
|
+
<div class="config-path-card">
|
|
1271
|
+
<span>配置文件</span>
|
|
1272
|
+
<code>${e?.path??"未知"}</code>
|
|
1273
|
+
<small>${e?.exists===!0?"已有文件":"保存时会创建此文件"}</small>
|
|
1274
|
+
</div>
|
|
1275
|
+
<form class="config-form" @submit=${t=>{this.saveConfig(t)}}>
|
|
1276
|
+
<label class="field">
|
|
1277
|
+
<span class="field-heading">
|
|
1278
|
+
<span>Host</span>
|
|
1279
|
+
${this.renderOverrideBadge("host")}
|
|
1280
|
+
</span>
|
|
1281
|
+
<input .value=${this.draft.host} placeholder="127.0.0.1" autocomplete="off" spellcheck="false" @input=${t=>{this.updateDraft({host:Or(t)})}}>
|
|
1282
|
+
<small>Web 服务器应绑定的地址。留空则使用 PI WEB 默认值。</small>
|
|
1283
|
+
</label>
|
|
1284
|
+
|
|
1285
|
+
<label class="field">
|
|
1286
|
+
<span class="field-heading">
|
|
1287
|
+
<span>Port</span>
|
|
1288
|
+
${this.renderOverrideBadge("port")}
|
|
1289
|
+
</span>
|
|
1290
|
+
<input .value=${this.draft.port} inputmode="numeric" pattern="[0-9]*" placeholder="8504" autocomplete="off" @input=${t=>{this.updateDraft({port:Or(t)})}}>
|
|
1291
|
+
<small>TCP 端口,范围 1 到 65535。留空则使用 PI WEB 默认值。</small>
|
|
1292
|
+
</label>
|
|
1293
|
+
|
|
1294
|
+
<div class="field">
|
|
1295
|
+
<span class="field-heading">
|
|
1296
|
+
<span>允许的 hosts</span>
|
|
1297
|
+
${this.renderOverrideBadge("allowedHosts")}
|
|
1298
|
+
</span>
|
|
1299
|
+
<select .value=${this.draft.allowedHostsMode} @change=${t=>{this.updateDraft({allowedHostsMode:dv(t)==="all"?"all":"list"})}}>
|
|
1300
|
+
<option value="list">仅允许列出的 hosts</option>
|
|
1301
|
+
<option value="all">允许所有 host</option>
|
|
1302
|
+
</select>
|
|
1303
|
+
<textarea .value=${this.draft.allowedHostsText} ?disabled=${this.draft.allowedHostsMode==="all"} rows="4" placeholder="example.local 192.168.1.20" spellcheck="false" @input=${t=>{this.updateDraft({allowedHostsText:pv(t)})}}></textarea>
|
|
1304
|
+
<small>每行输入一个 host,或选择“允许所有 host”写入 <code>true</code>。</small>
|
|
1305
|
+
</div>
|
|
1306
|
+
|
|
1307
|
+
${this.renderEffectiveConfig()}
|
|
1308
|
+
|
|
1309
|
+
<footer class="form-actions">
|
|
1310
|
+
<button class="primary" ?disabled=${this.loading||this.saving}>${this.saving?"正在保存…":"保存配置"}</button>
|
|
1311
|
+
</footer>
|
|
1312
|
+
</form>
|
|
1313
|
+
`}
|
|
1314
|
+
`}renderMessages(){const e=this.localError||this.error;return e!==""?l`<div class="message error-message">${e}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage}</div>`:null}renderOverrideBadge(e){return this.configResponse?.envOverrides[e]!==!0?null:l`<span class="override-badge">环境变量覆盖</span>`}renderEffectiveConfig(){const e=this.configResponse?.effectiveConfig??{};return l`
|
|
1315
|
+
<section class="effective-card" aria-label="最终生效配置摘要">
|
|
1316
|
+
<h3>环境变量覆盖后的生效配置</h3>
|
|
1317
|
+
<dl>
|
|
1318
|
+
<div><dt>Host</dt><dd>${e.host??l`<span class="muted">默认 127.0.0.1</span>`}</dd></div>
|
|
1319
|
+
<div><dt>端口</dt><dd>${e.port??l`<span class="muted">默认 8504</span>`}</dd></div>
|
|
1320
|
+
<div><dt>允许的 hosts</dt><dd>${cv(e.allowedHosts)}</dd></div>
|
|
1321
|
+
</dl>
|
|
1322
|
+
</section>
|
|
1323
|
+
`}async saveConfig(e){e.preventDefault(),this.localError="";try{await this.onSave?.(rv(this.draft,this.configResponse?.config??{}))}catch(t){this.localError=hv(t)}}updateDraft(e){this.draft={...this.draft,...e},this.localError=""}};fe.styles=A`
|
|
1324
|
+
:host { display: block; }
|
|
1325
|
+
.section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
1326
|
+
.section-heading > div { display: grid; gap: 6px; min-width: 0; }
|
|
1327
|
+
h2, h3, p { margin: 0; }
|
|
1328
|
+
h2 { font-size: 17px; line-height: 1.25; }
|
|
1329
|
+
h3 { font-size: 13px; line-height: 1.3; }
|
|
1330
|
+
p { color: var(--pi-muted); line-height: 1.45; }
|
|
1331
|
+
button, input, select, textarea { font: inherit; }
|
|
1332
|
+
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
1333
|
+
button:disabled { opacity: .55; cursor: not-allowed; }
|
|
1334
|
+
.secondary { flex: 0 0 auto; }
|
|
1335
|
+
.message, .loading-card, .config-path-card, .effective-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
|
|
1336
|
+
.message { margin-bottom: 12px; }
|
|
1337
|
+
.error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
|
|
1338
|
+
.success-message { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
|
|
1339
|
+
.loading-card { color: var(--pi-muted); }
|
|
1340
|
+
.config-path-card { display: grid; gap: 5px; margin-bottom: 14px; }
|
|
1341
|
+
.config-path-card span, .field-heading, dt { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
|
|
1342
|
+
code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
|
|
1343
|
+
.config-path-card small, .field small { color: var(--pi-muted); }
|
|
1344
|
+
.config-form { display: grid; gap: 14px; }
|
|
1345
|
+
.field { display: grid; gap: 7px; }
|
|
1346
|
+
.field-heading { display: flex; align-items: center; gap: 8px; }
|
|
1347
|
+
input, select, textarea { box-sizing: border-box; width: 100%; min-width: 0; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 9px 10px; outline: none; }
|
|
1348
|
+
input:focus, select:focus, textarea:focus { border-color: var(--pi-accent); box-shadow: 0 0 0 1px var(--pi-accent-border); }
|
|
1349
|
+
textarea { resize: vertical; min-height: 94px; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
|
|
1350
|
+
textarea:disabled { opacity: .55; }
|
|
1351
|
+
.override-badge { border: 1px solid var(--pi-warning-border); border-radius: 999px; color: var(--pi-warning); background: var(--pi-warning-surface); padding: 2px 7px; font-size: 11px; font-weight: 600; text-transform: none; }
|
|
1352
|
+
.effective-card { display: grid; gap: 10px; }
|
|
1353
|
+
.effective-card dl { display: grid; gap: 8px; margin: 0; }
|
|
1354
|
+
.effective-card dl > div { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 12px; align-items: baseline; }
|
|
1355
|
+
dd { margin: 0; min-width: 0; overflow-wrap: anywhere; }
|
|
1356
|
+
.muted { color: var(--pi-muted); }
|
|
1357
|
+
.form-actions { display: flex; justify-content: flex-end; gap: 8px; padding-top: 2px; }
|
|
1358
|
+
.primary { border-color: var(--pi-accent); background: var(--pi-selection-bg); color: var(--pi-text-bright); }
|
|
1359
|
+
|
|
1360
|
+
@media (max-width: 760px) {
|
|
1361
|
+
.section-heading { display: grid; gap: 12px; }
|
|
1362
|
+
.section-heading .secondary { justify-self: start; }
|
|
1363
|
+
.effective-card dl > div { grid-template-columns: minmax(0, 1fr); gap: 3px; }
|
|
1364
|
+
}
|
|
1365
|
+
`;Ae([d({attribute:!1})],fe.prototype,"configResponse",2);Ae([d({type:Boolean})],fe.prototype,"loading",2);Ae([d({type:Boolean})],fe.prototype,"saving",2);Ae([d()],fe.prototype,"error",2);Ae([d()],fe.prototype,"savedMessage",2);Ae([d({attribute:!1})],fe.prototype,"onReload",2);Ae([d({attribute:!1})],fe.prototype,"onSave",2);Ae([w()],fe.prototype,"draft",2);Ae([w()],fe.prototype,"localError",2);fe=Ae([R("settings-general-panel")],fe);function cv(e){return e===!0?"任意 host":Array.isArray(e)?e.length===0?l`<span class="muted">未列出</span>`:e.join(", "):l`<span class="muted">未设置</span>`}function Or(e){return e.target instanceof HTMLInputElement?e.target.value:""}function dv(e){return e.target instanceof HTMLSelectElement?e.target.value:""}function pv(e){return e.target instanceof HTMLTextAreaElement?e.target.value:""}function hv(e){return e instanceof Error?e.message:String(e)}var uv=Object.defineProperty,fv=Object.getOwnPropertyDescriptor,_e=(e,t,i,s)=>{for(var o=s>1?void 0:s?fv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&uv(t,i,o),o};let Se=class extends T{constructor(){super(...arguments),this.loading=!1,this.saving=!1,this.error="",this.savedMessage=""}render(){const e=this.pluginsResponse?.plugins??[];return l`
|
|
1366
|
+
<div class="section-heading">
|
|
1367
|
+
<div>
|
|
1368
|
+
<h2>插件</h2>
|
|
1369
|
+
<p>启用或禁用已发现的 PI WEB 插件。更改会在重新加载浏览器标签页后生效;当前页面已加载的插件代码不会被卸载。</p>
|
|
1370
|
+
</div>
|
|
1371
|
+
<button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>重新加载</button>
|
|
1372
|
+
</div>
|
|
1373
|
+
${this.renderMessages()}
|
|
1374
|
+
<div class="plugin-note">配置键:<code>plugins</code>。除非条目将 <code>enabled</code> 设置为 <code>false</code>,插件默认启用。</div>
|
|
1375
|
+
${this.loading&&e.length===0?l`<div class="loading-card">正在加载插件…</div>`:e.length===0?l`<div class="loading-card">未发现外部或内置插件。</div>`:l`
|
|
1376
|
+
<div class="plugin-list">
|
|
1377
|
+
${e.map(t=>this.renderPlugin(t))}
|
|
1378
|
+
</div>
|
|
1379
|
+
`}
|
|
1380
|
+
`}renderMessages(){return this.error!==""?l`<div class="message error-message">${this.error}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage} 重新加载浏览器标签页以应用插件更改。</div>`:null}renderPlugin(e){const t=this.configResponse?.config.plugins?.[e.id],i=t?.enabled===!1?"配置已禁用":t?.enabled===!0?"配置已启用":"默认启用";return l`
|
|
1381
|
+
<article class=${`plugin-card${e.enabled?"":" disabled"}`}>
|
|
1382
|
+
<div class="plugin-main">
|
|
1383
|
+
<strong>${e.id}</strong>
|
|
1384
|
+
<small>${e.source} · ${e.scope}</small>
|
|
1385
|
+
<small>${i}</small>
|
|
1386
|
+
</div>
|
|
1387
|
+
<label class="toggle">
|
|
1388
|
+
<input type="checkbox" .checked=${e.enabled} ?disabled=${this.saving} @change=${s=>{this.togglePlugin(e,s)}}>
|
|
1389
|
+
<span>${e.enabled?"已启用":"已禁用"}</span>
|
|
1390
|
+
</label>
|
|
1391
|
+
</article>
|
|
1392
|
+
`}async togglePlugin(e,t){const i=t.target instanceof HTMLInputElement?t.target.checked:e.enabled;await this.onTogglePlugin?.(e.id,i)}};Se.styles=A`
|
|
1393
|
+
:host { display: block; }
|
|
1394
|
+
.section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
1395
|
+
.section-heading > div { display: grid; gap: 6px; min-width: 0; }
|
|
1396
|
+
h2, p { margin: 0; }
|
|
1397
|
+
h2 { font-size: 17px; line-height: 1.25; }
|
|
1398
|
+
p { color: var(--pi-muted); line-height: 1.45; }
|
|
1399
|
+
button, input { font: inherit; }
|
|
1400
|
+
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
1401
|
+
button:disabled, input:disabled { opacity: .55; cursor: not-allowed; }
|
|
1402
|
+
.secondary { flex: 0 0 auto; }
|
|
1403
|
+
.message, .loading-card, .plugin-note, .plugin-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
|
|
1404
|
+
.message { margin-bottom: 12px; }
|
|
1405
|
+
.error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
|
|
1406
|
+
.success-message { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
|
|
1407
|
+
.loading-card, .plugin-note { color: var(--pi-muted); }
|
|
1408
|
+
.plugin-note { margin-bottom: 14px; }
|
|
1409
|
+
code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
|
|
1410
|
+
.plugin-list { display: grid; gap: 10px; }
|
|
1411
|
+
.plugin-card { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 12px; align-items: center; }
|
|
1412
|
+
.plugin-card.disabled { opacity: .75; }
|
|
1413
|
+
.plugin-main { min-width: 0; display: grid; gap: 3px; }
|
|
1414
|
+
.plugin-main strong, .plugin-main small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1415
|
+
.plugin-main small { color: var(--pi-muted); }
|
|
1416
|
+
.toggle { display: inline-flex; align-items: center; gap: 7px; white-space: nowrap; }
|
|
1417
|
+
.toggle input { width: 18px; height: 18px; accent-color: var(--pi-accent); }
|
|
1418
|
+
|
|
1419
|
+
@media (max-width: 760px) {
|
|
1420
|
+
.section-heading { display: grid; gap: 12px; }
|
|
1421
|
+
.section-heading .secondary { justify-self: start; }
|
|
1422
|
+
.plugin-card { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
1423
|
+
.toggle { justify-self: start; }
|
|
1424
|
+
}
|
|
1425
|
+
`;_e([d({attribute:!1})],Se.prototype,"pluginsResponse",2);_e([d({attribute:!1})],Se.prototype,"configResponse",2);_e([d({type:Boolean})],Se.prototype,"loading",2);_e([d({type:Boolean})],Se.prototype,"saving",2);_e([d()],Se.prototype,"error",2);_e([d()],Se.prototype,"savedMessage",2);_e([d({attribute:!1})],Se.prototype,"onReload",2);_e([d({attribute:!1})],Se.prototype,"onTogglePlugin",2);Se=_e([R("settings-plugins-panel")],Se);var gv=Object.defineProperty,mv=Object.getOwnPropertyDescriptor,me=(e,t,i,s)=>{for(var o=s>1?void 0:s?mv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&gv(t,i,o),o};const _r={capture:!0};let te=class extends T{constructor(){super(...arguments),this.actions=[],this.loading=!1,this.saving=!1,this.error="",this.savedMessage="",this.drafts={},this.localError="",this.recordingListenerActive=!1,this.onRecordKeyDown=e=>{const t=this.recording;if(t===void 0)return;if(e.preventDefault(),e.stopPropagation(),e.key==="Escape"){this.stopRecording();return}const i=Tn(e);if(i===void 0){this.localError="Press a letter, number, punctuation, function, or navigation key. Press Esc to cancel recording.";return}if(t.tokens.length===0&&!It(i)){this.localError="Start shortcuts with Ctrl/⌘ or Alt so normal typing is not captured.";return}const s=[...t.tokens,i];this.localError="",this.drafts={[t.actionId]:s.join(" ")},this.recording={actionId:t.actionId,tokens:s},this.armRecordingTimer()}}willUpdate(e){e.has("configResponse")&&this.configResponse!==void 0&&(this.drafts={},this.localError="",this.stopRecording())}disconnectedCallback(){this.stopRecording(),super.disconnectedCallback()}render(){const e=yv(this.actions),t=this.shortcutResolutions();return l`
|
|
1426
|
+
<div class="section-heading">
|
|
1427
|
+
<div>
|
|
1428
|
+
<h2>键盘快捷键</h2>
|
|
1429
|
+
<p>按操作编辑应用快捷键。输入 <code>mod+k</code> 或 <code>mod+g p</code> 这类快捷键,也可以从键盘录制、设为无或恢复默认。快捷键冲突时,自定义快捷键优先于默认值;同级按 action id 排序,较短快捷键会遮蔽相同前缀的较长序列。</p>
|
|
1430
|
+
</div>
|
|
1431
|
+
<button class="secondary" ?disabled=${this.loading} @click=${()=>{this.onReload?.()}}>Reload</button>
|
|
1432
|
+
</div>
|
|
1433
|
+
${this.renderMessages()}
|
|
1434
|
+
${this.configResponse===void 0&&this.loading?l`<div class="loading-card">正在加载快捷键…</div>`:l`
|
|
1435
|
+
<div class="config-path-card">
|
|
1436
|
+
<span>配置文件</span>
|
|
1437
|
+
<code>${this.configResponse?.path??"未知"}</code>
|
|
1438
|
+
<small>快捷键覆盖项保存在 <code>shortcuts</code> 下。值为 <code>null</code> 时会禁用该操作快捷键。</small>
|
|
1439
|
+
</div>
|
|
1440
|
+
${e.length===0?l`<div class="loading-card">没有已注册操作。</div>`:e.map(i=>l`
|
|
1441
|
+
<section class="shortcut-group">
|
|
1442
|
+
<h3>${i.name}</h3>
|
|
1443
|
+
<div class="shortcut-list">
|
|
1444
|
+
${i.actions.map(s=>this.renderShortcutRow(s,t.get(s.id)))}
|
|
1445
|
+
</div>
|
|
1446
|
+
</section>
|
|
1447
|
+
`)}
|
|
1448
|
+
`}
|
|
1449
|
+
`}renderMessages(){const e=this.localError||this.error;return e!==""?l`<div class="message error-message">${e}</div>`:this.savedMessage!==""?l`<div class="message success-message">${this.savedMessage}</div>`:null}renderShortcutRow(e,t){const i=this.configResponse?.config.shortcuts,s=yi(e.id,i),o=$v(e,i),r=this.shortcutInputText(e),n=r.trim()===""?void 0:qi(r),a=n?.ok===!0?n.shortcut:kv(e,i),c=s!==void 0,p=this.drafts[e.id]!==void 0,u=p&&r.trim()!==""?"custom":o,h=this.recordingHint(e.id),f=wv(t);return l`
|
|
1450
|
+
<article class=${vv(t)}>
|
|
1451
|
+
<div class="shortcut-main">
|
|
1452
|
+
<strong>${e.title}</strong>
|
|
1453
|
+
${e.description!==void 0&&e.description!==""?l`<small>${e.description}</small>`:null}
|
|
1454
|
+
<small class="shortcut-id">${e.id}</small>
|
|
1455
|
+
<small>${e.shortcut!==void 0&&e.shortcut!==""?l`Default: <kbd>${Xt(e.shortcut)}</kbd>`:"No default shortcut"}</small>
|
|
1456
|
+
</div>
|
|
1457
|
+
<div class="shortcut-editor">
|
|
1458
|
+
<div class="shortcut-status">
|
|
1459
|
+
${a!==void 0&&a!==""?l`<kbd>${Xt(a)}</kbd>`:l`<span class="unassigned">${o==="disabled"?"已禁用":"未分配"}</span>`}
|
|
1460
|
+
<small class=${u}>${Pv(u)}${p?" · 未保存":""}</small>
|
|
1461
|
+
${f===void 0?null:l`<small class=${bv(t)}>${f}</small>`}
|
|
1462
|
+
</div>
|
|
1463
|
+
<label class="shortcut-input-label">
|
|
1464
|
+
<span>快捷键</span>
|
|
1465
|
+
<input
|
|
1466
|
+
class="shortcut-input"
|
|
1467
|
+
data-action-id=${e.id}
|
|
1468
|
+
.value=${r}
|
|
1469
|
+
placeholder=${e.shortcut??"mod+k"}
|
|
1470
|
+
autocomplete="off"
|
|
1471
|
+
autocapitalize="off"
|
|
1472
|
+
spellcheck="false"
|
|
1473
|
+
?disabled=${this.saving}
|
|
1474
|
+
@input=${b=>{this.updateDraft(e.id,Cv(b))}}
|
|
1475
|
+
>
|
|
1476
|
+
</label>
|
|
1477
|
+
${h!==""?l`<small class="recording-hint">${h}</small>`:null}
|
|
1478
|
+
<div class="shortcut-actions">
|
|
1479
|
+
<button class="primary" ?disabled=${this.loading||this.saving||!p||r.trim()===""} @click=${()=>{this.saveShortcut(e)}}>保存</button>
|
|
1480
|
+
<button ?disabled=${this.loading||this.saving} @click=${()=>{this.toggleRecording(e.id)}}>${this.recording?.actionId===e.id?"取消录制":"录制"}</button>
|
|
1481
|
+
<button ?disabled=${this.loading||this.saving||s===null} @click=${()=>{this.setShortcutNone(e.id)}}>无</button>
|
|
1482
|
+
<button ?disabled=${this.loading||this.saving||!c} @click=${()=>{this.resetShortcut(e.id)}}>重置</button>
|
|
1483
|
+
</div>
|
|
1484
|
+
</div>
|
|
1485
|
+
</article>
|
|
1486
|
+
`}shortcutInputText(e){const t=this.drafts[e.id];if(t!==void 0)return t;const i=yi(e.id,this.configResponse?.config.shortcuts);return i===null?"":i??e.shortcut??""}recordingHint(e){const t=this.recording;return t?.actionId!==e?"":t.tokens.length===0?"Recording: press Ctrl/⌘ or Alt with a key. Press Esc to cancel.":`Recording: ${Xt(t.tokens.join(" "))}. Press another key to add a sequence, or wait to finish.`}updateDraft(e,t){this.drafts={[e]:t},this.localError=""}async saveShortcut(e){this.stopRecording();const t=this.shortcutInputText(e).trim(),i=qi(t);if(!i.ok){this.localError=i.message;return}this.localError="",await this.saveShortcutPreference(e.id,i.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){const i={...this.configResponse?.config??{}},s=i.shortcuts??{},o=t===void 0?Sv(s,e):{...s,[e]:t};Object.keys(o).length===0?delete i.shortcuts:i.shortcuts=o,await this.onSave?.(i)}shortcutResolutions(){return new Map(Hs(this.actions,this.previewShortcutConfig(),{enabledOnly:!0}).map(e=>[e.action.id,e]))}previewShortcutConfig(){const e={...this.configResponse?.config.shortcuts??{}};for(const[t,i]of Object.entries(this.drafts)){const s=i.trim();if(s==="")continue;const o=qi(s);o.ok&&(e[t]=o.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(const 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()},Cn)}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,_r),this.recordingListenerActive=!0)}removeRecordingListener(){this.recordingListenerActive&&(window.removeEventListener("keydown",this.onRecordKeyDown,_r),this.recordingListenerActive=!1)}};te.styles=A`
|
|
1487
|
+
:host { display: block; }
|
|
1488
|
+
.section-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 16px; margin-bottom: 14px; }
|
|
1489
|
+
.section-heading > div { display: grid; gap: 6px; min-width: 0; }
|
|
1490
|
+
h2, h3, p { margin: 0; }
|
|
1491
|
+
h2 { font-size: 17px; line-height: 1.25; }
|
|
1492
|
+
h3 { font-size: 13px; line-height: 1.3; }
|
|
1493
|
+
p { color: var(--pi-muted); line-height: 1.45; }
|
|
1494
|
+
button, input { font: inherit; }
|
|
1495
|
+
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
1496
|
+
button:disabled, input:disabled { opacity: .55; cursor: not-allowed; }
|
|
1497
|
+
.primary { border-color: var(--pi-accent); background: var(--pi-selection-bg); color: var(--pi-text-bright); }
|
|
1498
|
+
.secondary { flex: 0 0 auto; }
|
|
1499
|
+
.message, .loading-card, .config-path-card { border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); padding: 12px; }
|
|
1500
|
+
.message { margin-bottom: 12px; }
|
|
1501
|
+
.error-message { border-color: var(--pi-danger); color: var(--pi-danger); background: color-mix(in srgb, var(--pi-danger) 10%, var(--pi-surface)); }
|
|
1502
|
+
.success-message { border-color: var(--pi-success-border); color: var(--pi-success); background: var(--pi-success-surface); }
|
|
1503
|
+
.loading-card, .config-path-card { color: var(--pi-muted); }
|
|
1504
|
+
.config-path-card { display: grid; gap: 5px; margin-bottom: 14px; }
|
|
1505
|
+
.config-path-card span { color: var(--pi-muted); font-size: 12px; font-weight: 700; text-transform: uppercase; }
|
|
1506
|
+
code { border: 1px solid var(--pi-border-muted); border-radius: 5px; background: var(--pi-bg); padding: 1px 4px; color: var(--pi-text); font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; overflow-wrap: anywhere; }
|
|
1507
|
+
.shortcut-group { margin: 0 0 16px; }
|
|
1508
|
+
.shortcut-group h3 { margin: 0 0 8px; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
|
|
1509
|
+
.shortcut-list { border: 1px solid var(--pi-border); border-radius: 10px; overflow: hidden; }
|
|
1510
|
+
.shortcut-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(360px, 48%); gap: 14px; align-items: start; padding: 12px; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-surface); }
|
|
1511
|
+
.shortcut-row.shadowed { background: color-mix(in srgb, var(--pi-warning) 5%, var(--pi-surface)); }
|
|
1512
|
+
.shortcut-row.shadowing { background: color-mix(in srgb, var(--pi-accent) 5%, var(--pi-surface)); }
|
|
1513
|
+
.shortcut-row:last-child { border-bottom: 0; }
|
|
1514
|
+
.shortcut-main { min-width: 0; display: grid; gap: 4px; }
|
|
1515
|
+
.shortcut-main strong, .shortcut-main small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1516
|
+
.shortcut-main small { color: var(--pi-muted); }
|
|
1517
|
+
.shortcut-id { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
|
|
1518
|
+
.shortcut-editor { min-width: 0; display: grid; gap: 8px; }
|
|
1519
|
+
.shortcut-status { display: flex; align-items: center; justify-content: flex-end; gap: 8px; flex-wrap: wrap; }
|
|
1520
|
+
.shortcut-status small { color: var(--pi-muted); font-size: 11px; }
|
|
1521
|
+
.shortcut-status small.custom { color: var(--pi-accent); }
|
|
1522
|
+
.shortcut-status small.disabled { color: var(--pi-warning); }
|
|
1523
|
+
.shortcut-status small.conflict { border: 1px solid currentColor; border-radius: 999px; padding: 2px 7px; }
|
|
1524
|
+
.shortcut-status small.conflict.shadowing { color: var(--pi-accent); }
|
|
1525
|
+
.shortcut-status small.conflict.shadowed { color: var(--pi-warning); }
|
|
1526
|
+
.shortcut-input-label { min-width: 0; display: grid; gap: 5px; }
|
|
1527
|
+
.shortcut-input-label span { color: var(--pi-muted); font-size: 11px; font-weight: 700; text-transform: uppercase; }
|
|
1528
|
+
input { box-sizing: border-box; width: 100%; min-width: 0; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-bg); color: var(--pi-text); padding: 8px 9px; outline: none; font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
|
|
1529
|
+
input:focus { border-color: var(--pi-accent); box-shadow: 0 0 0 1px var(--pi-accent-border); }
|
|
1530
|
+
.shortcut-actions { display: flex; justify-content: flex-end; gap: 7px; flex-wrap: wrap; }
|
|
1531
|
+
kbd { border: 1px solid var(--pi-border); border-radius: 6px; background: var(--pi-bg); color: var(--pi-text-secondary); padding: 3px 7px; font: 12px ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; white-space: nowrap; }
|
|
1532
|
+
.unassigned { color: var(--pi-muted); font-size: 12px; }
|
|
1533
|
+
.recording-hint { color: var(--pi-accent); font-size: 12px; }
|
|
1534
|
+
|
|
1535
|
+
@media (max-width: 760px) {
|
|
1536
|
+
.section-heading { display: grid; gap: 12px; }
|
|
1537
|
+
.section-heading .secondary { justify-self: start; }
|
|
1538
|
+
.shortcut-row { grid-template-columns: minmax(0, 1fr); align-items: start; }
|
|
1539
|
+
.shortcut-status, .shortcut-actions { justify-content: flex-start; }
|
|
1540
|
+
}
|
|
1541
|
+
`;me([d({attribute:!1})],te.prototype,"actions",2);me([d({attribute:!1})],te.prototype,"configResponse",2);me([d({type:Boolean})],te.prototype,"loading",2);me([d({type:Boolean})],te.prototype,"saving",2);me([d()],te.prototype,"error",2);me([d()],te.prototype,"savedMessage",2);me([d({attribute:!1})],te.prototype,"onReload",2);me([d({attribute:!1})],te.prototype,"onSave",2);me([w()],te.prototype,"drafts",2);me([w()],te.prototype,"localError",2);me([w()],te.prototype,"recording",2);te=me([R("settings-shortcuts-panel")],te);function vv(e){return e?.active===!1?"shortcut-row shadowed":e?.active===!0&&e.shadows.length>0?"shortcut-row shadowing":"shortcut-row"}function bv(e){return e?.active===!1?"conflict shadowed":"conflict shadowing"}function wv(e){if(e===void 0)return;if(!e.active)return`Shadowed by ${e.shadowedBy?.action.title??"another action"}`;const t=e.shadows.length;if(t===0)return;const i=e.shadows.slice(0,2).map(o=>o.action.title).join(", "),s=t>2?`, +${String(t-2)} more`:"";return`Shadows ${String(t)} ${t===1?"action":"actions"}: ${i}${s}`}function yv(e){const t=new Map;for(const i of[...e].sort(xv)){const s=i.group??"其他";t.set(s,[...t.get(s)??[],i])}return[...t.entries()].map(([i,s])=>({name:i,actions:s}))}function xv(e,t){return(e.group??"其他").localeCompare(t.group??"其他")||e.title.localeCompare(t.title)}function yi(e,t){if(!(t===void 0||!Object.hasOwn(t,e)))return t[e]}function Sv(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function kv(e,t){const i=yi(e.id,t);if(i!==null)return i??e.shortcut}function $v(e,t){const i=yi(e.id,t);return i===null?"disabled":i!==void 0?"custom":e.shortcut===void 0||e.shortcut===""?"unassigned":"default"}function Pv(e){switch(e){case"default":return"默认";case"custom":return"配置覆盖";case"disabled":return"配置禁用";case"unassigned":return"无默认值"}}function Cv(e){return e.target instanceof HTMLInputElement?e.target.value:""}var Iv=Object.defineProperty,Tv=Object.getOwnPropertyDescriptor,ve=(e,t,i,s)=>{for(var o=s>1?void 0:s?Tv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Iv(t,i,o),o};let ie=class extends T{constructor(){super(...arguments),this.section="general",this.actions=[],this.loading=!0,this.saving=!1,this.error="",this.savedMessage=""}connectedCallback(){super.connectedCallback(),this.loadConfig()}disconnectedCallback(){this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=void 0,super.disconnectedCallback()}render(){return l`
|
|
1542
|
+
<div class="backdrop" @mousedown=${()=>this.onClose?.()}>
|
|
1543
|
+
<section class="settings-shell" role="dialog" aria-modal="true" aria-label="PI WEB 设置" @mousedown=${e=>{e.stopPropagation()}} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
1544
|
+
<header class="settings-header">
|
|
1545
|
+
<div>
|
|
1546
|
+
<span class="eyebrow">设置</span>
|
|
1547
|
+
<h1>PI WEB</h1>
|
|
1548
|
+
</div>
|
|
1549
|
+
<button class="close-button" title="关闭设置" aria-label="关闭设置" @click=${()=>this.onClose?.()}>×</button>
|
|
1550
|
+
</header>
|
|
1551
|
+
<div class="settings-body">
|
|
1552
|
+
<nav class="settings-nav" aria-label="设置分区">
|
|
1553
|
+
${this.renderNavButton("general","通用","服务器配置")}
|
|
1554
|
+
${this.renderNavButton("plugins","插件","启用和禁用")}
|
|
1555
|
+
${this.renderNavButton("shortcuts","键盘","快捷键")}
|
|
1556
|
+
</nav>
|
|
1557
|
+
<main class="settings-content">
|
|
1558
|
+
${this.renderActiveSection()}
|
|
1559
|
+
</main>
|
|
1560
|
+
</div>
|
|
1561
|
+
</section>
|
|
1562
|
+
</div>
|
|
1563
|
+
`}renderActiveSection(){return this.section==="shortcuts"?l`
|
|
1564
|
+
<settings-shortcuts-panel
|
|
1565
|
+
.actions=${this.actions}
|
|
1566
|
+
.configResponse=${this.configResponse}
|
|
1567
|
+
.loading=${this.loading}
|
|
1568
|
+
.saving=${this.saving}
|
|
1569
|
+
.error=${this.error}
|
|
1570
|
+
.savedMessage=${this.savedMessage}
|
|
1571
|
+
.onReload=${()=>this.loadConfig()}
|
|
1572
|
+
.onSave=${e=>this.saveConfig(e)}
|
|
1573
|
+
></settings-shortcuts-panel>
|
|
1574
|
+
`:this.section==="plugins"?l`
|
|
1575
|
+
<settings-plugins-panel
|
|
1576
|
+
.configResponse=${this.configResponse}
|
|
1577
|
+
.pluginsResponse=${this.pluginsResponse}
|
|
1578
|
+
.loading=${this.loading}
|
|
1579
|
+
.saving=${this.saving}
|
|
1580
|
+
.error=${this.error}
|
|
1581
|
+
.savedMessage=${this.savedMessage}
|
|
1582
|
+
.onReload=${()=>this.loadConfig()}
|
|
1583
|
+
.onTogglePlugin=${(e,t)=>this.togglePlugin(e,t)}
|
|
1584
|
+
></settings-plugins-panel>
|
|
1585
|
+
`:l`
|
|
1586
|
+
<settings-general-panel
|
|
1587
|
+
.configResponse=${this.configResponse}
|
|
1588
|
+
.loading=${this.loading}
|
|
1589
|
+
.saving=${this.saving}
|
|
1590
|
+
.error=${this.error}
|
|
1591
|
+
.savedMessage=${this.savedMessage}
|
|
1592
|
+
.onReload=${()=>this.loadConfig()}
|
|
1593
|
+
.onSave=${e=>this.saveConfig(e)}
|
|
1594
|
+
></settings-general-panel>
|
|
1595
|
+
`}renderNavButton(e,t,i){const s=this.section===e;return l`
|
|
1596
|
+
<button class=${s?"selected":""} aria-current=${s?"page":"false"} @click=${()=>{this.navigate(e)}}>
|
|
1597
|
+
<strong>${t}</strong>
|
|
1598
|
+
<small>${i}</small>
|
|
1599
|
+
</button>
|
|
1600
|
+
`}navigate(e){this.onNavigate?.(e)}async loadConfig(){this.loading=!0,this.error="";try{const[e,t]=await Promise.all([ri.config(),ps.plugins()]);this.configResponse=e,this.pluginsResponse=t}catch(e){this.error=`加载设置失败:${ss(e)}`}finally{this.loading=!1}}async togglePlugin(e,t){const i=this.configResponse?.config??{},s=i.plugins??{},o=s[e]??{};await this.saveConfig({...i,plugins:{...s,[e]:{...o,enabled:t}}}),await this.refreshPlugins()}async saveConfig(e){if(!this.saving){this.saving=!0,this.error="",this.savedMessage="";try{const t=await ri.saveConfig(e);this.configResponse=t,this.onConfigSaved?.(t.config),this.showSavedMessage()}catch(t){this.error=`保存配置失败:${ss(t)}`}finally{this.saving=!1}}}async refreshPlugins(){try{this.pluginsResponse=await ps.plugins()}catch(e){this.error=`刷新插件失败:${ss(e)}`}}showSavedMessage(){this.savedMessage="配置已保存。",this.savedMessageTimer!==void 0&&window.clearTimeout(this.savedMessageTimer),this.savedMessageTimer=window.setTimeout(()=>{this.savedMessage==="配置已保存。"&&(this.savedMessage=""),this.savedMessageTimer=void 0},3e3)}handleKeyDown(e){e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.onClose?.())}};ie.styles=A`
|
|
1601
|
+
:host { position: fixed; inset: 0; z-index: 30; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
1602
|
+
.backdrop { box-sizing: border-box; width: 100%; height: 100dvh; display: grid; place-items: center; padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); background: var(--pi-overlay); overflow: hidden; }
|
|
1603
|
+
.settings-shell { width: min(980px, 100%); max-height: min(760px, 100%); min-height: min(620px, 100%); display: grid; grid-template-rows: auto minmax(0, 1fr); border: 1px solid var(--pi-border); border-radius: 14px; background: var(--pi-bg); box-shadow: 0 20px 60px var(--pi-shadow-strong); overflow: hidden; }
|
|
1604
|
+
.settings-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 14px 16px; border-bottom: 1px solid var(--pi-border); }
|
|
1605
|
+
.eyebrow { display: block; color: var(--pi-muted); font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
|
|
1606
|
+
h1 { margin: 0; font-size: 20px; line-height: 1.2; }
|
|
1607
|
+
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; font: inherit; cursor: pointer; }
|
|
1608
|
+
.close-button { width: 34px; height: 34px; display: grid; place-items: center; border: 0; background: transparent; color: var(--pi-muted); padding: 0; font-size: 24px; }
|
|
1609
|
+
.close-button:hover, .close-button:focus { color: var(--pi-text); background: var(--pi-surface-hover); }
|
|
1610
|
+
.settings-body { min-height: 0; display: grid; grid-template-columns: 220px minmax(0, 1fr); }
|
|
1611
|
+
.settings-nav { min-height: 0; padding: 10px; border-right: 1px solid var(--pi-border); background: var(--pi-surface); overflow: auto; }
|
|
1612
|
+
.settings-nav button { display: grid; gap: 2px; width: 100%; margin: 0 0 6px; text-align: left; border-color: transparent; background: transparent; }
|
|
1613
|
+
.settings-nav button:hover, .settings-nav button:focus { background: var(--pi-surface-hover); }
|
|
1614
|
+
.settings-nav button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
|
|
1615
|
+
.settings-nav small { color: var(--pi-muted); }
|
|
1616
|
+
.settings-content { min-width: 0; min-height: 0; overflow: auto; padding: 18px; }
|
|
1617
|
+
|
|
1618
|
+
@media (max-width: 760px) {
|
|
1619
|
+
.backdrop { padding: 0; place-items: stretch; }
|
|
1620
|
+
.settings-shell { width: 100%; height: 100dvh; max-height: none; min-height: 0; border: 0; border-radius: 0; }
|
|
1621
|
+
.settings-header { padding: max(12px, env(safe-area-inset-top)) 12px 12px; }
|
|
1622
|
+
.settings-body { grid-template-columns: minmax(0, 1fr); grid-template-rows: auto minmax(0, 1fr); }
|
|
1623
|
+
.settings-nav { display: flex; gap: 8px; padding: 8px; border-right: 0; border-bottom: 1px solid var(--pi-border); overflow-x: auto; overflow-y: hidden; }
|
|
1624
|
+
.settings-nav button { flex: 0 0 auto; width: auto; min-width: 128px; margin: 0; }
|
|
1625
|
+
.settings-content { padding: 14px 12px calc(18px + env(safe-area-inset-bottom)); }
|
|
1626
|
+
}
|
|
1627
|
+
`;ve([d({attribute:!1})],ie.prototype,"section",2);ve([d({attribute:!1})],ie.prototype,"actions",2);ve([d({attribute:!1})],ie.prototype,"onNavigate",2);ve([d({attribute:!1})],ie.prototype,"onClose",2);ve([d({attribute:!1})],ie.prototype,"onConfigSaved",2);ve([w()],ie.prototype,"configResponse",2);ve([w()],ie.prototype,"pluginsResponse",2);ve([w()],ie.prototype,"loading",2);ve([w()],ie.prototype,"saving",2);ve([w()],ie.prototype,"error",2);ve([w()],ie.prototype,"savedMessage",2);ie=ve([R("settings-dialog")],ie);function ss(e){return e instanceof Error?e.message:String(e)}var Mv=Object.defineProperty,Rv=Object.getOwnPropertyDescriptor,ke=(e,t,i,s)=>{for(var o=s>1?void 0:s?Rv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Mv(t,i,o),o};let ae=class extends T{constructor(){super(...arguments),this.tool="core:workspace.files",this.panels=[],this.hideToolTabs=!1,this.onSelectTool=()=>{},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 或终端。"});const t=this.panelContext;if(t===void 0)return this.renderEmptyState({title:"工作区工具不可用",body:"请尝试重新选择工作区。"});const i=this.panels,s=i.find(o=>o.id===this.tool)??i[0];return l`
|
|
1628
|
+
${this.hideToolTabs?null:l`
|
|
1629
|
+
<header>
|
|
1630
|
+
<div class=${this.workspaceHeaderFrameClass()}>
|
|
1631
|
+
<div class="workspace-header-strip" @scroll=${this.onWorkspaceHeaderScroll}>
|
|
1632
|
+
<div class="tabs">
|
|
1633
|
+
${i.map(o=>{const r=s?.id===o.id,n=o.badge?.(t),a=this.panelTabAriaLabel(o,n);return l`
|
|
1634
|
+
<button class=${this.panelTabClass(o,r)} title=${a} aria-label=${a} aria-pressed=${String(r)} @click=${()=>{this.onSelectTool(o.id)}}>
|
|
1635
|
+
${this.renderPanelTabContent(o,n)}
|
|
1636
|
+
</button>
|
|
1637
|
+
`})}
|
|
1638
|
+
</div>
|
|
1639
|
+
</div>
|
|
1640
|
+
</div>
|
|
1641
|
+
</header>
|
|
1642
|
+
`}
|
|
1643
|
+
${s===void 0?this.renderEmptyState({title:"没有可用的工作区工具",body:"此工作区没有可用工具。"}):l`
|
|
1644
|
+
<div class="panel-content">
|
|
1645
|
+
${s.render(t)}
|
|
1646
|
+
</div>
|
|
1647
|
+
`}
|
|
1648
|
+
`}panelTabClass(e,t){return[...e.icon===void 0?[]:["icon-tab"],...t?["selected"]:[]].join(" ")}panelTabAriaLabel(e,t){if(typeof t!="string"&&typeof t!="number")return e.title;const i=String(t).trim();return i===""?e.title:`${e.title}, ${i}`}renderPanelTabContent(e,t){return l`
|
|
1649
|
+
${e.icon===void 0?null:l`<span class="tab-custom-icon" aria-hidden="true">${e.icon}</span>`}
|
|
1650
|
+
<span class="tab-label">${e.title}</span>
|
|
1651
|
+
${this.isEmptyBadge(t)?null:l`<span class="tab-badge">${t}</span>`}
|
|
1652
|
+
`}isEmptyBadge(e){return e===void 0||e===""}renderEmptyState(e){return l`
|
|
1653
|
+
<section class="empty-state" role="status">
|
|
1654
|
+
<h2>${e.title}</h2>
|
|
1655
|
+
${e.body===void 0?null:l`<p>${e.body}</p>`}
|
|
1656
|
+
</section>
|
|
1657
|
+
`}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?" can-scroll-left":""}${this.workspaceHeaderCanScrollRight?" can-scroll-right":""}`}observeWorkspaceHeaderStrip(){const 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(){const e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==i&&(this.workspaceHeaderCanScrollLeft=i),this.workspaceHeaderCanScrollRight!==s&&(this.workspaceHeaderCanScrollRight=s)}workspaceHeaderStripElement(){const e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}};ae.styles=af;ke([d({attribute:!1})],ae.prototype,"workspace",2);ke([d({attribute:!1})],ae.prototype,"panelContext",2);ke([d({attribute:!1})],ae.prototype,"emptyState",2);ke([d()],ae.prototype,"tool",2);ke([d({attribute:!1})],ae.prototype,"panels",2);ke([d({type:Boolean})],ae.prototype,"hideToolTabs",2);ke([d({attribute:!1})],ae.prototype,"onSelectTool",2);ke([N(".workspace-header-strip")],ae.prototype,"workspaceHeaderStrip",2);ke([w()],ae.prototype,"workspaceHeaderCanScrollLeft",2);ke([w()],ae.prototype,"workspaceHeaderCanScrollRight",2);ae=ke([R("workspace-panel")],ae);var Av=Object.defineProperty,Ev=Object.getOwnPropertyDescriptor,be=(e,t,i,s)=>{for(var o=s>1?void 0:s?Ev(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Av(t,i,o),o};let se=class extends T{constructor(){super(...arguments),this.machines=[],this.canScrollLeft=!1,this.canScrollRight=!1,this.onContextScroll=()=>{this.updateScrollState()}}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){const e=Dv(this.machines),t=Wv(this.machine),i=_v(this.project),s=jv(this.workspace),o=Fv(this.session);return l`
|
|
1658
|
+
<nav class=${this.contextBarClass()} aria-label="当前位置">
|
|
1659
|
+
<span class="context-bar-label">位置</span>
|
|
1660
|
+
<ol class="context-items" @scroll=${this.onContextScroll}>
|
|
1661
|
+
${e?l`
|
|
1662
|
+
<li class="context-item">
|
|
1663
|
+
<button type="button" class=${this.machine===void 0?"context-chip empty":"context-chip"} title=${Ov(this.machine)} aria-label=${`机器:${t}。打开机器选择。`} @click=${()=>{this.onOpenSection?.("machines")}}>
|
|
1664
|
+
<span class="context-kind">机器</span>
|
|
1665
|
+
<span class="context-value">${t}</span>
|
|
1666
|
+
</button>
|
|
1667
|
+
</li>
|
|
1668
|
+
`:null}
|
|
1669
|
+
<li class="context-item">
|
|
1670
|
+
<button type="button" class=${this.project===void 0?"context-chip empty":"context-chip"} title=${Lv(this.project)} aria-label=${`项目:${i}。打开项目选择。`} @click=${()=>{this.onOpenSection?.("projects")}}>
|
|
1671
|
+
<span class="context-kind">项目</span>
|
|
1672
|
+
<span class="context-value">${i}</span>
|
|
1673
|
+
</button>
|
|
1674
|
+
</li>
|
|
1675
|
+
<li class="context-item">
|
|
1676
|
+
<button type="button" class=${this.workspace===void 0?"context-chip empty":"context-chip"} title=${Nv(this.workspace)} aria-label=${`工作区:${s}。打开工作区选择。`} @click=${()=>{this.onOpenSection?.("workspaces")}}>
|
|
1677
|
+
<span class="context-kind">工作区</span>
|
|
1678
|
+
<span class="context-value">${s}</span>
|
|
1679
|
+
</button>
|
|
1680
|
+
</li>
|
|
1681
|
+
<li class="context-item">
|
|
1682
|
+
<button type="button" class=${this.session===void 0?"context-chip empty":"context-chip"} title=${zv(this.session)} aria-label=${`会话:${o}。打开会话选择。`} @click=${()=>{this.onOpenSection?.("sessions")}}>
|
|
1683
|
+
<span class="context-kind">会话</span>
|
|
1684
|
+
<span class="context-value">${o}</span>
|
|
1685
|
+
</button>
|
|
1686
|
+
</li>
|
|
1687
|
+
</ol>
|
|
1688
|
+
${this.hasContextActions()?l`<div class="context-actions">${this.renderActionsButton()}${this.refreshControl}</div>`:null}
|
|
1689
|
+
</nav>
|
|
1690
|
+
`}renderActionsButton(){return this.onShowActions===void 0?null:l`
|
|
1691
|
+
<button type="button" class="context-action-button" title="显示操作" aria-label="显示操作" @click=${e=>{e.stopPropagation(),this.onShowActions?.()}}>
|
|
1692
|
+
<svg class="context-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1693
|
+
<path d="M13 2 4 14h7l-1 8 10-13h-7V2Z"></path>
|
|
1694
|
+
</svg>
|
|
1695
|
+
</button>
|
|
1696
|
+
`}contextBarClass(){const e=["context-bar"];return this.hasContextActions()&&e.push("has-context-actions"),this.refreshControl!==void 0&&this.onShowActions!==void 0&&e.push("has-context-actions-double"),this.canScrollLeft&&e.push("can-scroll-left"),this.canScrollRight&&e.push("can-scroll-right"),e.join(" ")}hasContextActions(){return this.refreshControl!==void 0||this.onShowActions!==void 0}observeContextItems(){const e=this.contextItemsElement();this.observedContextItems!==e&&(this.contextItemsResizeObserver?.disconnect(),this.observedContextItems=e,this.contextItemsResizeObserver=void 0,!(e===void 0||typeof ResizeObserver>"u")&&(this.contextItemsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.contextItemsResizeObserver.observe(e)))}updateScrollState(){const e=this.contextItemsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}contextItemsElement(){const e=this.contextItems;return e instanceof HTMLElement?e:void 0}};se.styles=A`
|
|
1697
|
+
/* Keep the refresh menu in this shadow tree above the following mobile tab strip. */
|
|
1698
|
+
:host { position: relative; z-index: 20; flex: 0 0 auto; min-width: 0; }
|
|
1699
|
+
.context-bar { position: relative; flex: 0 0 auto; min-width: 0; display: flex; align-items: center; gap: 0; padding: 6px 0; border-bottom: 1px solid var(--pi-border-muted); background: var(--pi-bg); }
|
|
1700
|
+
.context-bar::before, .context-bar::after { content: ""; position: absolute; top: 0; bottom: 0; z-index: 2; width: 20px; opacity: 0; pointer-events: none; transition: opacity .15s ease; }
|
|
1701
|
+
.context-bar::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
|
|
1702
|
+
.context-bar::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
|
|
1703
|
+
.context-bar.can-scroll-left::before, .context-bar.can-scroll-right::after { opacity: 1; }
|
|
1704
|
+
.context-bar-label { display: none; }
|
|
1705
|
+
.context-items { flex: 1 1 auto; min-width: 0; display: flex; align-items: stretch; gap: 5px; margin: 0; padding: 0 8px; list-style: none; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scroll-padding-inline: 8px; scrollbar-width: thin; }
|
|
1706
|
+
.context-bar.has-context-actions .context-items { padding-right: 58px; scroll-padding-inline: 8px 58px; }
|
|
1707
|
+
.context-bar.has-context-actions-double .context-items { padding-right: 102px; scroll-padding-inline: 8px 102px; }
|
|
1708
|
+
.context-item { flex: 0 0 auto; min-width: 0; display: flex; }
|
|
1709
|
+
.context-actions { position: absolute; top: 6px; right: 0; bottom: 6px; z-index: 3; display: flex; align-items: center; gap: 6px; padding: 0 8px; background: var(--pi-bg); pointer-events: none; }
|
|
1710
|
+
.context-actions::before { content: ""; position: absolute; top: 0; bottom: 0; left: -24px; z-index: 0; width: 24px; background: linear-gradient(90deg, transparent, var(--pi-bg)); pointer-events: none; }
|
|
1711
|
+
app-refresh-control, .context-action-button { position: relative; z-index: 1; pointer-events: auto; }
|
|
1712
|
+
.context-action-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; }
|
|
1713
|
+
.context-action-button:hover, .context-action-button:focus-visible { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
|
|
1714
|
+
.context-action-icon { width: 18px; height: 18px; fill: currentColor; pointer-events: none; }
|
|
1715
|
+
.context-chip { flex: 0 0 auto; min-width: 0; display: inline-flex; align-items: baseline; gap: 5px; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-surface); color: var(--pi-text); padding: 4px 8px; font: inherit; text-align: left; }
|
|
1716
|
+
.context-chip:hover { background: var(--pi-surface-hover); }
|
|
1717
|
+
.context-chip:focus-visible { outline: 2px solid var(--pi-accent); outline-offset: 2px; }
|
|
1718
|
+
.context-chip.empty { border-style: dashed; color: var(--pi-muted); }
|
|
1719
|
+
.context-kind { display: none; }
|
|
1720
|
+
.context-value { min-width: 0; overflow: visible; text-overflow: clip; white-space: nowrap; }
|
|
1721
|
+
button { cursor: pointer; }
|
|
1722
|
+
`;be([d({attribute:!1})],se.prototype,"machines",2);be([d({attribute:!1})],se.prototype,"machine",2);be([d({attribute:!1})],se.prototype,"project",2);be([d({attribute:!1})],se.prototype,"workspace",2);be([d({attribute:!1})],se.prototype,"session",2);be([d({attribute:!1})],se.prototype,"refreshControl",2);be([d({attribute:!1})],se.prototype,"onOpenSection",2);be([d({attribute:!1})],se.prototype,"onShowActions",2);be([N(".context-items")],se.prototype,"contextItems",2);be([w()],se.prototype,"canScrollLeft",2);be([w()],se.prototype,"canScrollRight",2);se=be([R("app-context-bar")],se);function Dv(e){return e.length>1}function Wv(e){return e===void 0?"未选择机器":`${e.name}${e.kind==="remote"?" · 远程":""}`}function Ov(e){return e===void 0?"未选择机器":e.baseUrl??e.name}function _v(e){return e?.name??"未选择项目"}function Lv(e){return e===void 0?"未选择项目":`${e.name} — ${e.path}`}function jv(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} · ${e.path}`}function Nv(e){return e===void 0?"未选择工作区":`${e.label}${e.isMain?" · 主工作区":""} — ${e.path}`}function Fv(e){const t=e?.name?.trim(),i=e?.firstMessage.trim();return t!==void 0&&t!==""?t:i!==void 0&&i!==""?i:e?.id.slice(0,8)??"未选择会话"}function zv(e){return e===void 0?"未选择会话":e.path}var Bv=Object.defineProperty,Uv=Object.getOwnPropertyDescriptor,Qe=(e,t,i,s)=>{for(var o=s>1?void 0:s?Uv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Bv(t,i,o),o};let We=class extends T{constructor(){super(...arguments),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(){const e=this.fallbackLabels();return l`
|
|
1723
|
+
<div class=${this.frameClass()}>
|
|
1724
|
+
<div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
|
|
1725
|
+
${this.tabs.map(t=>{const i=this.selectedView===t.id;return l`
|
|
1726
|
+
<button class=${this.tabClass(t)} title=${t.label} aria-label=${this.tabAriaLabel(t)} aria-pressed=${String(i)} @click=${()=>{this.onSelect?.(t.id)}}>
|
|
1727
|
+
${this.renderTabMark(t,e)}
|
|
1728
|
+
<span class="tab-label">${t.label}</span>
|
|
1729
|
+
${this.isEmptyBadge(t.badge)?null:l`<span class="tab-badge">${t.badge}</span>`}
|
|
1730
|
+
</button>
|
|
1731
|
+
`})}
|
|
1732
|
+
</div>
|
|
1733
|
+
</div>
|
|
1734
|
+
`}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){if(typeof e.badge!="string"&&typeof e.badge!="number")return e.label;const t=String(e.badge).trim();return t===""?e.label:`${e.label}, ${t}`}isEmptyBadge(e){return e===void 0||e===""}renderTabMark(e,t){return e.icon===void 0?l`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:xh(e.icon)}fallbackLabels(){const e=this.tabs.filter(s=>s.icon===void 0),t=new Map;for(const s of e){const o=this.initialsLabel(s.label);t.set(o,(t.get(o)??0)+1)}const i=new Map;for(const s of e){const o=this.initialsLabel(s.label);i.set(s.id,(t.get(o)??0)>1?this.fullFallbackLabel(s.label):o)}return i}initialsLabel(e){const i=(e.match(/[\p{L}\p{N}]+/gu)??[]).map(s=>Array.from(s)[0]??"").join("").toLocaleUpperCase();return i===""?"?":i}fullFallbackLabel(e){const t=e.trim();return t===""?"?":t}observeMobileTabs(){const 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(){const e=this.mobileTabsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),i=e!==void 0&&e.scrollLeft>1,s=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==i&&(this.canScrollLeft=i),this.canScrollRight!==s&&(this.canScrollRight=s)}mobileTabsElement(){const e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}};We.styles=A`
|
|
1735
|
+
:host { flex: 0 0 auto; min-width: 0; }
|
|
1736
|
+
.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); }
|
|
1737
|
+
.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; }
|
|
1738
|
+
.mobile-tabs-frame::before { left: 0; background: linear-gradient(90deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
|
|
1739
|
+
.mobile-tabs-frame::after { right: 0; background: linear-gradient(270deg, color-mix(in srgb, var(--pi-shadow-strong) 55%, transparent) 0%, transparent 100%); }
|
|
1740
|
+
.mobile-tabs-frame.can-scroll-left::before, .mobile-tabs-frame.can-scroll-right::after { opacity: 1; }
|
|
1741
|
+
.mobile-tabs { flex: 1 1 auto; min-width: 0; display: flex; align-items: center; gap: 6px; padding: 8px; overflow-x: auto; overflow-y: hidden; overscroll-behavior-x: contain; scrollbar-width: thin; }
|
|
1742
|
+
.mobile-tabs button { flex: 0 0 auto; display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
|
|
1743
|
+
.mobile-tabs .navigation-tab { display: none; }
|
|
1744
|
+
.mobile-tabs button.selected { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
|
|
1745
|
+
.tab-icon { flex: 0 0 auto; width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
1746
|
+
.tab-custom-icon { flex: 0 0 auto; width: 18px; height: 18px; display: inline-grid; place-items: center; color: currentColor; pointer-events: none; }
|
|
1747
|
+
.tab-custom-icon svg { width: 18px; height: 18px; pointer-events: none; }
|
|
1748
|
+
.tab-fallback { display: none; font-weight: 650; letter-spacing: .01em; pointer-events: none; }
|
|
1749
|
+
.tab-label { min-width: 0; }
|
|
1750
|
+
.tab-badge { flex: 0 0 auto; display: inline-block; min-width: 14px; margin-left: 0; border: 1px solid var(--pi-success-border); border-radius: 999px; background: var(--pi-success-surface); color: var(--pi-success); padding: 0 5px; font-size: 11px; line-height: 16px; text-align: center; }
|
|
1751
|
+
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
1752
|
+
@media (max-width: 760px) {
|
|
1753
|
+
.mobile-tabs { gap: 4px; padding: 6px 8px; }
|
|
1754
|
+
.mobile-tabs button { min-width: 40px; height: 36px; justify-content: center; gap: 4px; padding: 0 8px; }
|
|
1755
|
+
.mobile-tabs .navigation-tab { display: inline-flex; }
|
|
1756
|
+
.tab-fallback { display: inline-block; }
|
|
1757
|
+
.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; }
|
|
1758
|
+
.tab-badge { min-width: 13px; padding: 0 4px; font-size: 10px; line-height: 13px; }
|
|
1759
|
+
}
|
|
1760
|
+
`;Qe([d({attribute:!1})],We.prototype,"tabs",2);Qe([d({attribute:!1})],We.prototype,"selectedView",2);Qe([d({attribute:!1})],We.prototype,"onSelect",2);Qe([N(".mobile-tabs")],We.prototype,"mobileTabs",2);Qe([w()],We.prototype,"canScrollLeft",2);Qe([w()],We.prototype,"canScrollRight",2);We=Qe([R("app-mobile-main-tabs")],We);var Hv=Object.defineProperty,qv=Object.getOwnPropertyDescriptor,ce=(e,t,i,s)=>{for(var o=s>1?void 0:s?qv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Hv(t,i,o),o};let X=class extends T{constructor(){super(...arguments),this.machines=[],this.statuses={},this.activities={},this.open=!1,this.menuStyle="",this.actionMenuStyle="",this.onDocumentClick=e=>{e.composedPath().includes(this)||(this.open=!1,this.openActionsMachineId=void 0)}}connectedCallback(){super.connectedCallback(),document.addEventListener("click",this.onDocumentClick)}disconnectedCallback(){document.removeEventListener("click",this.onDocumentClick),super.disconnectedCallback()}updated(e){e.has("machines")&&this.open&&this.selectedMachine()===void 0&&(this.open=!1),e.has("machines")&&this.openActionsMachineId!==void 0&&!this.machines.some(t=>t.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){const e=this.switcherButton();return e===null?!1:await this.openMenuAndFocusOption(e)}render(){const e=this.selectedMachine();if(e===void 0)return null;const t=os(e,this.statuses),i=e.name;return l`
|
|
1761
|
+
<div class="machine-switcher">
|
|
1762
|
+
<button
|
|
1763
|
+
type="button"
|
|
1764
|
+
class="machine-switcher-button"
|
|
1765
|
+
title=${jr(e)}
|
|
1766
|
+
aria-label=${`Machine: ${i}. Switch machine.`}
|
|
1767
|
+
aria-expanded=${String(this.open)}
|
|
1768
|
+
@click=${s=>{this.toggleMenu(s.currentTarget)}}
|
|
1769
|
+
@keydown=${s=>{this.handleSwitcherButtonKeydown(s)}}
|
|
1770
|
+
>
|
|
1771
|
+
${this.renderActivity(e)}
|
|
1772
|
+
<span class="machine-switcher-text">
|
|
1773
|
+
<span class="machine-switcher-kicker">Machine</span>
|
|
1774
|
+
<span class="machine-switcher-label">${i}</span>
|
|
1775
|
+
</span>
|
|
1776
|
+
<span class=${`machine-status ${t}`}>${Lr(t)}</span>
|
|
1777
|
+
<span class="machine-chevron" aria-hidden="true">▾</span>
|
|
1778
|
+
</button>
|
|
1779
|
+
${this.open?l`
|
|
1780
|
+
<div class="machine-switcher-menu" style=${this.menuStyle} @click=${s=>{s.stopPropagation()}}>
|
|
1781
|
+
${this.machines.map(s=>this.renderMachineOption(s))}
|
|
1782
|
+
</div>
|
|
1783
|
+
`:null}
|
|
1784
|
+
</div>
|
|
1785
|
+
`}renderMachineOption(e){const t=this.selected?.id===e.id,i=os(e,this.statuses),s=Yn(e)&&this.onRemove!==void 0,o=this.openActionsMachineId===e.id;return l`
|
|
1786
|
+
<div class=${`machine-option ${t?"selected":""} ${s?"":"no-actions"}`}>
|
|
1787
|
+
<button
|
|
1788
|
+
type="button"
|
|
1789
|
+
class="machine-option-main"
|
|
1790
|
+
title=${jr(e)}
|
|
1791
|
+
data-machine-id=${e.id}
|
|
1792
|
+
@click=${()=>{this.select(e)}}
|
|
1793
|
+
@keydown=${r=>{this.handleMachineOptionKeydown(r)}}
|
|
1794
|
+
>
|
|
1795
|
+
<span class="machine-option-name">${this.renderActivity(e)}<span>${e.name}</span></span>
|
|
1796
|
+
<small>${e.kind==="local"?"Local Pi Web":e.baseUrl??"Remote Pi Web"} · ${Lr(i)}</small>
|
|
1797
|
+
</button>
|
|
1798
|
+
${s?l`
|
|
1799
|
+
<div class="machine-option-actions">
|
|
1800
|
+
<button
|
|
1801
|
+
type="button"
|
|
1802
|
+
class="machine-option-actions-toggle"
|
|
1803
|
+
title="Machine actions"
|
|
1804
|
+
aria-label=${`Actions for ${e.name}`}
|
|
1805
|
+
aria-expanded=${String(o)}
|
|
1806
|
+
@click=${r=>{r.stopPropagation(),this.toggleActionsMenu(e.id,r.currentTarget)}}
|
|
1807
|
+
>⋯</button>
|
|
1808
|
+
${o?l`
|
|
1809
|
+
<div class="machine-option-actions-panel" style=${this.actionMenuStyle} @click=${r=>{r.stopPropagation()}}>
|
|
1810
|
+
<button class="danger" title=${`Remove ${e.name}`} @click=${()=>{this.removeMachine(e)}}>Remove</button>
|
|
1811
|
+
</div>
|
|
1812
|
+
`:null}
|
|
1813
|
+
</div>
|
|
1814
|
+
`:null}
|
|
1815
|
+
</div>
|
|
1816
|
+
`}renderActivity(e){const t=os(e,this.statuses);if(t==="offline"||t==="error")return;const i=Hn(this.activities[e.id]);return Vn(i,i==="terminal"?"Machine terminal active":"Machine active")}selectedMachine(){return this.selected??this.machines.find(e=>e.id==="local")??this.machines[0]}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=Nr(e),this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){const e=this.switcherButton();return e===null?!1:(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuStyle=Nr(e),this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){const e=this.renderRoot.querySelector(".machine-option.selected .machine-option-main"),t=this.machineOptionButtons()[0],i=e??t;return i===void 0?!1:(i.focus(),i.scrollIntoView({block:"nearest"}),!0)}focusRelativeMachineOption(e,t,i){i.preventDefault(),i.stopPropagation();const s=this.machineOptionButtons();if(s.length===0||!(e instanceof HTMLElement))return;const o=s.indexOf(e);o<0||this.focusMachineOptionAt(o+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){const t=this.machineOptionButtons(),i=t[Math.min(Math.max(e,0),t.length-1)];i?.focus(),i?.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=Ot(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)}};X.styles=A`
|
|
1817
|
+
:host { min-width: 0; display: block; }
|
|
1818
|
+
.machine-switcher { min-width: 0; }
|
|
1819
|
+
.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; }
|
|
1820
|
+
.machine-switcher-button:hover, .machine-switcher-button:focus-visible { border-color: var(--pi-accent); background: var(--pi-selection-bg); }
|
|
1821
|
+
.machine-switcher-text { flex: 1 1 auto; min-width: 0; display: grid; gap: 1px; }
|
|
1822
|
+
.machine-switcher-kicker { color: var(--pi-muted); font-size: 10px; line-height: 1; text-transform: uppercase; letter-spacing: .02em; }
|
|
1823
|
+
.machine-switcher-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; font-weight: 600; line-height: 1.2; }
|
|
1824
|
+
.machine-status { flex: 0 0 auto; color: var(--pi-muted); font-size: 11px; }
|
|
1825
|
+
.machine-status.online { color: var(--pi-success); }
|
|
1826
|
+
.machine-status.offline, .machine-status.error { color: var(--pi-danger); }
|
|
1827
|
+
.machine-chevron { flex: 0 0 auto; color: var(--pi-muted); font-size: 11px; }
|
|
1828
|
+
.activity-indicator { flex: 0 0 auto; display: inline-block; width: 7px; height: 7px; background: var(--pi-success); animation: pulse 1s ease-in-out infinite; }
|
|
1829
|
+
.activity-indicator.session { border-radius: 50%; background: var(--pi-success); }
|
|
1830
|
+
.activity-indicator.terminal { border-radius: 2px; background: var(--pi-accent); }
|
|
1831
|
+
.machine-switcher-menu { position: fixed; z-index: 10000; box-sizing: border-box; min-width: min(280px, calc(100vw - 16px)); overflow: auto; padding: 4px; border: 1px solid var(--pi-border); border-radius: 10px; background: var(--pi-surface); box-shadow: 0 8px 24px var(--pi-shadow); }
|
|
1832
|
+
.machine-option { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px; align-items: stretch; margin: 2px 0; }
|
|
1833
|
+
.machine-option.no-actions { grid-template-columns: minmax(0, 1fr); }
|
|
1834
|
+
.machine-option-main, .machine-option-actions-toggle, .machine-option-actions-panel button { border: 0; border-radius: 7px; background: transparent; color: var(--pi-text); cursor: pointer; }
|
|
1835
|
+
.machine-option-main { min-width: 0; display: grid; gap: 2px; padding: 7px 8px; text-align: left; }
|
|
1836
|
+
.machine-option-name { min-width: 0; display: flex; align-items: baseline; gap: 6px; }
|
|
1837
|
+
.machine-option-name span:last-child { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1838
|
+
.machine-option-main small { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--pi-muted); }
|
|
1839
|
+
.machine-option-actions { position: relative; align-self: stretch; }
|
|
1840
|
+
.machine-option-actions-toggle { display: grid; place-items: center; height: 100%; min-width: 32px; padding: 0; color: var(--pi-muted); }
|
|
1841
|
+
.machine-option-actions-panel { position: fixed; z-index: 10001; box-sizing: border-box; min-width: min(120px, calc(100vw - 16px)); overflow: auto; padding: 4px; border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 8px 24px var(--pi-shadow); }
|
|
1842
|
+
.machine-option-actions-panel button { display: block; width: 100%; padding: 7px 9px; text-align: left; white-space: nowrap; }
|
|
1843
|
+
.machine-option-actions-panel button.danger { color: var(--pi-danger); }
|
|
1844
|
+
.machine-option-main:hover, .machine-option-main:focus-visible, .machine-option-actions-toggle:hover, .machine-option-actions-toggle:focus-visible, .machine-option.selected .machine-option-main { background: var(--pi-selection-bg); }
|
|
1845
|
+
.machine-option-actions-panel button:hover, .machine-option-actions-panel button:focus-visible { background: var(--pi-selection-bg); }
|
|
1846
|
+
.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); }
|
|
1847
|
+
@keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
|
|
1848
|
+
`;ce([d({attribute:!1})],X.prototype,"machines",2);ce([d({attribute:!1})],X.prototype,"selected",2);ce([d({attribute:!1})],X.prototype,"statuses",2);ce([d({attribute:!1})],X.prototype,"activities",2);ce([d({attribute:!1})],X.prototype,"onSelect",2);ce([d({attribute:!1})],X.prototype,"onRemove",2);ce([d({attribute:!1})],X.prototype,"onFocusNextSection",2);ce([d({attribute:!1})],X.prototype,"onCancelKeyboardNavigation",2);ce([w()],X.prototype,"open",2);ce([w()],X.prototype,"menuStyle",2);ce([w()],X.prototype,"openActionsMachineId",2);ce([w()],X.prototype,"actionMenuStyle",2);X=ce([R("machine-switcher")],X);function os(e,t){return t[e.id]?.status??e.status??"unknown"}function Lr(e){return e==="online"?"online":e==="offline"?"offline":e==="error"?"error":"unknown"}function jr(e){return e.baseUrl??e.name}function Nr(e){if(typeof HTMLElement>"u"||typeof window>"u"||!(e instanceof HTMLElement))return"";const t=e.getBoundingClientRect(),i=8,s=Math.min(280,Math.max(0,window.innerWidth-i*2)),o=Math.min(Math.max(i,t.left),Math.max(i,window.innerWidth-i-s)),r=Math.max(0,window.innerHeight-t.bottom-i);return[`top: ${Kt(t.bottom)};`,`left: ${Kt(o)};`,`width: ${Kt(s)};`,`max-height: ${Kt(r)};`].join(" ")}function Kt(e){return`${String(Math.round(e))}px`}var Kv=Object.defineProperty,Vv=Object.getOwnPropertyDescriptor,$=(e,t,i,s)=>{for(var o=s>1?void 0:s?Vv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Kv(t,i,o),o};let k=class extends T{constructor(){super(...arguments),this.machines=[],this.machineStatuses={},this.machineActivities={},this.projects=[],this.workspaces=[],this.sessions=[],this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.canStartSession=!1}async focusSection(e){switch(await this.updateComplete,e){case"machines":return await this.focusNavigableSection(this.compact?this.machineList:this.machineSwitcher);case"projects":return await this.focusNavigableSection(this.projectList);case"workspaces":return await this.focusNavigableSection(this.workspaceList);case"sessions":return await this.focusNavigableSection(this.sessionList)}}render(){return l`
|
|
1849
|
+
<header>
|
|
1850
|
+
<strong>PI WEB</strong>
|
|
1851
|
+
${xi(this.machines)?l`
|
|
1852
|
+
<machine-switcher
|
|
1853
|
+
.machines=${this.machines}
|
|
1854
|
+
.selected=${this.selectedMachine}
|
|
1855
|
+
.statuses=${this.machineStatuses}
|
|
1856
|
+
.activities=${this.machineActivities}
|
|
1857
|
+
.onSelect=${e=>this.onSelectMachine?.(e)}
|
|
1858
|
+
.onRemove=${e=>this.onRemoveMachine?.(e)}
|
|
1859
|
+
.onFocusNextSection=${()=>{this.focusNextFrom("machines")}}
|
|
1860
|
+
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
1861
|
+
></machine-switcher>
|
|
1862
|
+
`:null}
|
|
1863
|
+
<div class="header-actions">
|
|
1864
|
+
${this.refreshControl}
|
|
1865
|
+
<button title="显示操作" aria-label="显示操作" @click=${()=>{this.onShowActions?.()}}>操作</button>
|
|
1866
|
+
</div>
|
|
1867
|
+
</header>
|
|
1868
|
+
${this.compact&&xi(this.machines)?l`
|
|
1869
|
+
<machine-list
|
|
1870
|
+
.machines=${this.machines}
|
|
1871
|
+
.selected=${this.selectedMachine}
|
|
1872
|
+
.statuses=${this.machineStatuses}
|
|
1873
|
+
.activities=${this.machineActivities}
|
|
1874
|
+
.collapsible=${this.collapsible}
|
|
1875
|
+
.collapsed=${this.machinesCollapsed}
|
|
1876
|
+
.onToggleCollapsed=${()=>{this.onToggleMachines?.()}}
|
|
1877
|
+
.onSelect=${e=>this.onSelectMachine?.(e)}
|
|
1878
|
+
.onRemove=${e=>this.onRemoveMachine?.(e)}
|
|
1879
|
+
.onFocusNextSection=${()=>{this.focusNextFrom("machines")}}
|
|
1880
|
+
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
1881
|
+
></machine-list>
|
|
1882
|
+
`:null}
|
|
1883
|
+
<project-list
|
|
1884
|
+
.projects=${this.projects}
|
|
1885
|
+
.selected=${this.selectedProject}
|
|
1886
|
+
.activities=${this.workspaceActivities}
|
|
1887
|
+
.workspacesByProjectId=${this.workspacesByProjectId}
|
|
1888
|
+
.collapsible=${this.collapsible}
|
|
1889
|
+
.collapsed=${this.projectsCollapsed}
|
|
1890
|
+
.onToggleCollapsed=${()=>{this.onToggleProjects?.()}}
|
|
1891
|
+
.onSelect=${e=>this.onSelectProject?.(e)}
|
|
1892
|
+
.onClose=${e=>this.onCloseProject?.(e)}
|
|
1893
|
+
.onFocusPreviousSection=${()=>{this.focusPreviousFrom("projects")}}
|
|
1894
|
+
.onFocusNextSection=${()=>{this.focusNextFrom("projects")}}
|
|
1895
|
+
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
1896
|
+
></project-list>
|
|
1897
|
+
<workspace-list
|
|
1898
|
+
.workspaces=${this.workspaces}
|
|
1899
|
+
.selected=${this.selectedWorkspace}
|
|
1900
|
+
.activities=${this.workspaceActivities}
|
|
1901
|
+
.deletingWorkspaceIds=${this.deletingWorkspaceIds}
|
|
1902
|
+
.collapsible=${this.collapsible}
|
|
1903
|
+
.collapsed=${this.workspacesCollapsed}
|
|
1904
|
+
.workspaceLabelItems=${this.workspaceLabelItems}
|
|
1905
|
+
.onToggleCollapsed=${()=>{this.onToggleWorkspaces?.()}}
|
|
1906
|
+
.onSelect=${e=>this.onSelectWorkspace?.(e)}
|
|
1907
|
+
.onDelete=${e=>this.onDeleteWorkspace?.(e)}
|
|
1908
|
+
.onFocusPreviousSection=${()=>{this.focusPreviousFrom("workspaces")}}
|
|
1909
|
+
.onFocusNextSection=${()=>{this.focusNextFrom("workspaces")}}
|
|
1910
|
+
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
1911
|
+
></workspace-list>
|
|
1912
|
+
<session-list
|
|
1913
|
+
.sessions=${this.sessions}
|
|
1914
|
+
.statuses=${this.sessionStatuses}
|
|
1915
|
+
.activities=${this.sessionActivities}
|
|
1916
|
+
.selected=${this.selectedSession}
|
|
1917
|
+
.canStart=${this.canStartSession}
|
|
1918
|
+
.collapsible=${this.collapsible}
|
|
1919
|
+
.collapsed=${this.sessionsCollapsed}
|
|
1920
|
+
.onToggleCollapsed=${()=>{this.onToggleSessions?.()}}
|
|
1921
|
+
.onArchivedCollapsed=${()=>this.onArchivedCollapsed?.()}
|
|
1922
|
+
.onStart=${()=>this.onStartSession?.()}
|
|
1923
|
+
.onSelect=${e=>this.onSelectSession?.(e)}
|
|
1924
|
+
.onArchive=${e=>this.onArchiveSession?.(e)}
|
|
1925
|
+
.onArchiveWithDescendants=${e=>this.onArchiveSessionWithDescendants?.(e)}
|
|
1926
|
+
.onRestore=${e=>this.onRestoreSession?.(e)}
|
|
1927
|
+
.onDelete=${e=>this.onDeleteCachedNewSession?.(e)}
|
|
1928
|
+
.onDetachParent=${e=>this.onDetachParentSession?.(e)}
|
|
1929
|
+
.onFocusPreviousSection=${()=>{this.focusPreviousFrom("sessions")}}
|
|
1930
|
+
.onFocusNextSection=${()=>{this.focusNextFrom("sessions")}}
|
|
1931
|
+
.onCancelKeyboardNavigation=${()=>{this.cancelKeyboardNavigation()}}
|
|
1932
|
+
></session-list>
|
|
1933
|
+
`}async focusNavigableSection(e){return e===void 0?!1:await e.focusSelectedOrFirst()}focusPreviousFrom(e){const t=Gv(e,this.machines);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(Jv(e,this.machines))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}};k.styles=A`
|
|
1934
|
+
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
|
|
1935
|
+
:host([compact]) { flex: 1 1 auto; }
|
|
1936
|
+
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); }
|
|
1937
|
+
header strong { flex: 0 0 auto; }
|
|
1938
|
+
machine-switcher { flex: 1 1 auto; min-width: 0; }
|
|
1939
|
+
:host([compact]) header { display: none; }
|
|
1940
|
+
.header-actions { flex: 0 0 auto; display: flex; align-items: center; gap: 8px; }
|
|
1941
|
+
machine-list, project-list, workspace-list { flex: 0 0 auto; max-height: 26%; min-height: 0; overflow: hidden; border-bottom: 1px solid var(--pi-border-muted); }
|
|
1942
|
+
session-list { flex: 1 1 auto; min-height: 0; overflow: hidden; }
|
|
1943
|
+
machine-list[collapsed],
|
|
1944
|
+
project-list[collapsed],
|
|
1945
|
+
workspace-list[collapsed],
|
|
1946
|
+
session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
1947
|
+
:host([compact]) machine-list,
|
|
1948
|
+
:host([compact]) project-list,
|
|
1949
|
+
:host([compact]) workspace-list,
|
|
1950
|
+
:host([compact]) session-list { flex: 1 1 auto; max-height: none; min-height: 0; overflow: hidden; }
|
|
1951
|
+
:host([compact]) machine-list[collapsed],
|
|
1952
|
+
:host([compact]) project-list[collapsed],
|
|
1953
|
+
:host([compact]) workspace-list[collapsed],
|
|
1954
|
+
:host([compact]) session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; }
|
|
1955
|
+
button { border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); color: var(--pi-text); padding: 7px 9px; cursor: pointer; }
|
|
1956
|
+
`;$([d({attribute:!1})],k.prototype,"machines",2);$([d({attribute:!1})],k.prototype,"selectedMachine",2);$([d({attribute:!1})],k.prototype,"machineStatuses",2);$([d({attribute:!1})],k.prototype,"machineActivities",2);$([d({attribute:!1})],k.prototype,"projects",2);$([d({attribute:!1})],k.prototype,"selectedProject",2);$([d({attribute:!1})],k.prototype,"workspaces",2);$([d({attribute:!1})],k.prototype,"selectedWorkspace",2);$([d({attribute:!1})],k.prototype,"sessions",2);$([d({attribute:!1})],k.prototype,"selectedSession",2);$([d({attribute:!1})],k.prototype,"workspaceActivities",2);$([d({attribute:!1})],k.prototype,"sessionActivities",2);$([d({attribute:!1})],k.prototype,"sessionStatuses",2);$([d({attribute:!1})],k.prototype,"workspacesByProjectId",2);$([d({attribute:!1})],k.prototype,"deletingWorkspaceIds",2);$([d({attribute:!1})],k.prototype,"workspaceLabelItems",2);$([d({attribute:!1})],k.prototype,"refreshControl",2);$([d({type:Boolean,reflect:!0})],k.prototype,"collapsible",2);$([d({type:Boolean,reflect:!0})],k.prototype,"compact",2);$([d({type:Boolean})],k.prototype,"machinesCollapsed",2);$([d({type:Boolean})],k.prototype,"projectsCollapsed",2);$([d({type:Boolean})],k.prototype,"workspacesCollapsed",2);$([d({type:Boolean})],k.prototype,"sessionsCollapsed",2);$([d({type:Boolean})],k.prototype,"canStartSession",2);$([d({attribute:!1})],k.prototype,"onShowActions",2);$([d({attribute:!1})],k.prototype,"onToggleMachines",2);$([d({attribute:!1})],k.prototype,"onToggleProjects",2);$([d({attribute:!1})],k.prototype,"onToggleWorkspaces",2);$([d({attribute:!1})],k.prototype,"onToggleSessions",2);$([d({attribute:!1})],k.prototype,"onSelectProject",2);$([d({attribute:!1})],k.prototype,"onCloseProject",2);$([d({attribute:!1})],k.prototype,"onSelectWorkspace",2);$([d({attribute:!1})],k.prototype,"onDeleteWorkspace",2);$([d({attribute:!1})],k.prototype,"onStartSession",2);$([d({attribute:!1})],k.prototype,"onSelectSession",2);$([d({attribute:!1})],k.prototype,"onArchiveSession",2);$([d({attribute:!1})],k.prototype,"onArchiveSessionWithDescendants",2);$([d({attribute:!1})],k.prototype,"onRestoreSession",2);$([d({attribute:!1})],k.prototype,"onDeleteCachedNewSession",2);$([d({attribute:!1})],k.prototype,"onDetachParentSession",2);$([d({attribute:!1})],k.prototype,"onArchivedCollapsed",2);$([d({attribute:!1})],k.prototype,"onSelectMachine",2);$([d({attribute:!1})],k.prototype,"onRemoveMachine",2);$([d({attribute:!1})],k.prototype,"onFocusNavigationTarget",2);$([d({attribute:!1})],k.prototype,"onCancelKeyboardNavigation",2);$([N("machine-list")],k.prototype,"machineList",2);$([N("machine-switcher")],k.prototype,"machineSwitcher",2);$([N("project-list")],k.prototype,"projectList",2);$([N("workspace-list")],k.prototype,"workspaceList",2);$([N("session-list")],k.prototype,"sessionList",2);k=$([R("app-navigation-panel")],k);function xi(e){return e.length>1}function Gv(e,t){const i=ba(t);return i[i.indexOf(e)-1]}function Jv(e,t){const i=ba(t);return i[i.indexOf(e)+1]??"chat"}function ba(e){return fi.filter(t=>t!=="machines"||xi(e))}var Zv=Object.defineProperty,Qv=Object.getOwnPropertyDescriptor,Q=(e,t,i,s)=>{for(var o=s>1?void 0:s?Qv(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&Zv(t,i,o),o};const Xv=new Set(["ArrowLeft","ArrowRight","Home","End"]),Yv=420,eb=4;let q=class extends T{constructor(){super(...arguments),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(){const e=this.collapsed?this.expandLabel:this.collapseLabel;return l`
|
|
1957
|
+
${this.renderResizeHandle()}
|
|
1958
|
+
<button
|
|
1959
|
+
type="button"
|
|
1960
|
+
class="edge-button"
|
|
1961
|
+
title=${e}
|
|
1962
|
+
aria-label=${e}
|
|
1963
|
+
aria-controls=${this.controls}
|
|
1964
|
+
aria-expanded=${String(!this.collapsed)}
|
|
1965
|
+
@click=${()=>{this.onToggle?.()}}
|
|
1966
|
+
>${this.renderIcon()}</button>
|
|
1967
|
+
`}renderResizeHandle(){if(!this.resizable)return _;const e=this.resizeConstraints();return l`
|
|
1968
|
+
<div
|
|
1969
|
+
class="resize-handle"
|
|
1970
|
+
role="separator"
|
|
1971
|
+
tabindex="0"
|
|
1972
|
+
aria-label=${this.resizeLabel}
|
|
1973
|
+
title=${`${this.resizeLabel}。双击或双击轻触可重置。`}
|
|
1974
|
+
aria-controls=${this.controls}
|
|
1975
|
+
aria-orientation="vertical"
|
|
1976
|
+
aria-valuemin=${String(e.minWidth)}
|
|
1977
|
+
aria-valuemax=${String(e.maxWidth)}
|
|
1978
|
+
aria-valuenow=${this.resizeAriaValueNow()}
|
|
1979
|
+
@pointerdown=${t=>{this.onResizePointerDown(t)}}
|
|
1980
|
+
@pointermove=${t=>{this.onResizePointerMove(t)}}
|
|
1981
|
+
@pointerup=${t=>{this.onResizePointerUp(t)}}
|
|
1982
|
+
@pointercancel=${t=>{this.onResizePointerCancel(t)}}
|
|
1983
|
+
@dblclick=${t=>{this.onResizeDoubleClick(t)}}
|
|
1984
|
+
@keydown=${t=>{this.onResizeKeyDown(t)}}
|
|
1985
|
+
></div>
|
|
1986
|
+
`}resizeAriaValueNow(){return this.panelWidth===void 0?_:String(Math.round(this.panelWidth))}renderIcon(){const t=this.iconDirection()==="left"?"M15 18l-6-6 6-6":"M9 18l6-6-6-6";return l`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${t}/></svg>`}iconDirection(){return this.side==="navigation"?this.collapsed?"right":"left":this.collapsed?"left":"right"}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;const t=e.currentTarget;if(!(t instanceof HTMLElement))return;const i=this.resizeStartWidth();i!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:i,handle:t,moved:!1},this.toggleAttribute("resizing",!0))}onResizePointerMove(e){const t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=eb)&&(t.moved=!0,this.commitPanelWidth(Au(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){const 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||!Xv.has(e.key))return;const t=this.resizeStartWidth();if(t===void 0)return;const i=Eu(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});i!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(i),this.onResizeEnd?.())}registerTapForReset(){const e=Date.now();if(e-this.lastTapAt<=Yv){this.lastTapAt=0,this.resetPanelSize();return}this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){const e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return de(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(de(this.side,e,this.resizeConstraints()))}finishActiveResize(){const 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(){const e=Wt(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}};q.styles=A`
|
|
1987
|
+
: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; }
|
|
1988
|
+
:host([side="navigation"]) { grid-column: 2; }
|
|
1989
|
+
:host([side="workspace"]) { grid-column: 4; }
|
|
1990
|
+
.resize-handle { position: absolute; inset: 0 -6px; z-index: 0; cursor: col-resize; touch-action: none; outline: none; }
|
|
1991
|
+
.resize-handle::after { content: ""; position: absolute; top: 0; bottom: 0; left: 50%; width: 1px; transform: translateX(-50%); background: transparent; transition: width .12s ease, background .12s ease, opacity .12s ease; }
|
|
1992
|
+
.resize-handle:hover::after, .resize-handle:focus-visible::after, :host([resizing]) .resize-handle::after { width: 3px; background: var(--pi-accent); opacity: .72; }
|
|
1993
|
+
.edge-button { position: relative; z-index: 1; box-sizing: border-box; display: grid; place-items: center; width: 18px; height: 48px; padding: 0; border: 1px solid var(--pi-border-muted); border-radius: 999px; background: var(--pi-bg); color: var(--pi-muted); opacity: .75; cursor: pointer; }
|
|
1994
|
+
.edge-button:hover, .edge-button:focus-visible { color: var(--pi-text); background: var(--pi-surface-hover); opacity: 1; }
|
|
1995
|
+
:host([side="navigation"][collapsed]) .edge-button { transform: translateX(calc(50% - .5px)); }
|
|
1996
|
+
:host([side="workspace"][collapsed]) .edge-button { transform: translateX(calc(-50% + .5px)); }
|
|
1997
|
+
.edge-icon { width: 12px; height: 12px; fill: none; stroke: currentColor; stroke-width: 2.2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
1998
|
+
@media (max-width: 1180px) {
|
|
1999
|
+
:host([side="navigation"]) { grid-row: 1 / 3; }
|
|
2000
|
+
:host([side="workspace"]) { display: none; }
|
|
2001
|
+
}
|
|
2002
|
+
@media (max-width: 760px) {
|
|
2003
|
+
:host([side="navigation"]) { display: none; }
|
|
2004
|
+
}
|
|
2005
|
+
`;Q([d({reflect:!0})],q.prototype,"side",2);Q([d({type:Boolean,reflect:!0})],q.prototype,"collapsed",2);Q([d({type:Boolean})],q.prototype,"resizable",2);Q([d({type:Number})],q.prototype,"panelWidth",2);Q([d({type:Number})],q.prototype,"minWidth",2);Q([d({type:Number})],q.prototype,"maxWidth",2);Q([d()],q.prototype,"controls",2);Q([d()],q.prototype,"resizeLabel",2);Q([d()],q.prototype,"expandLabel",2);Q([d()],q.prototype,"collapseLabel",2);Q([d({attribute:!1})],q.prototype,"onToggle",2);Q([d({attribute:!1})],q.prototype,"onResizeStart",2);Q([d({attribute:!1})],q.prototype,"onResize",2);Q([d({attribute:!1})],q.prototype,"onResizeEnd",2);Q([d({attribute:!1})],q.prototype,"onReset",2);q=Q([R("app-panel-edge-control")],q);var tb=Object.defineProperty,ib=Object.getOwnPropertyDescriptor,wa=(e,t,i,s)=>{for(var o=s>1?void 0:s?ib(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&tb(t,i,o),o};let Si=class extends T{constructor(){super(...arguments),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()}}render(){const e="完整重载页面";return l`
|
|
2006
|
+
<button
|
|
2007
|
+
class="app-refresh-button"
|
|
2008
|
+
title=${e}
|
|
2009
|
+
aria-label=${e}
|
|
2010
|
+
@click=${this.onReloadClick}
|
|
2011
|
+
>${this.renderRefreshIcon()}</button>
|
|
2012
|
+
`}renderRefreshIcon(){return l`
|
|
2013
|
+
<svg class="app-refresh-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2014
|
+
<path d="M20 6v5h-5"></path>
|
|
2015
|
+
<path d="M4 18v-5h5"></path>
|
|
2016
|
+
<path d="M18.2 9A7 7 0 0 0 6.1 6.8L4 9"></path>
|
|
2017
|
+
<path d="M5.8 15a7 7 0 0 0 12.1 2.2L20 15"></path>
|
|
2018
|
+
</svg>
|
|
2019
|
+
`}};Si.styles=A`
|
|
2020
|
+
:host { position: relative; z-index: 1; display: flex; align-items: center; pointer-events: auto; -webkit-touch-callout: none; -webkit-user-select: none; user-select: none; }
|
|
2021
|
+
:host, :host * { -webkit-user-select: none; user-select: none; }
|
|
2022
|
+
.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; }
|
|
2023
|
+
.app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
2024
|
+
`;wa([d({attribute:!1})],Si.prototype,"onReload",2);Si=wa([R("app-refresh-control")],Si);var sb=Object.defineProperty,ob=Object.getOwnPropertyDescriptor,$e=(e,t,i,s)=>{for(var o=s>1?void 0:s?ob(t,i):t,r=e.length-1,n;r>=0;r--)(n=e[r])&&(o=(s?n(t,i,o):n(o))||o);return s&&o&&sb(t,i,o),o};const rb=900*1e3,Fr={capture:!0},rs="auto:on",zr="auto:off",Vt="theme:",ns=Mt("core:workspace.files"),as=Mt("core:workspace.git"),Gt=Mt("core:workspace.terminal"),nb=320,ab=2,lb="(min-width: 1181px)";let le=class extends T{constructor(){super(...arguments),this.state=Ic(),this.sessions=new pp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new rp),this.activity=new Tc(()=>this.state,e=>{this.setState(e)}),this.auth=new Ac(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)}),this.workspaces=new xp(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new wp),this.projects=new Uc(()=>this.state,e=>{this.setState(e)},this.workspaces),this.machines=new zc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects),this.files=new Oc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.git=new Fc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()}),this.keyboard=new Wp,this.realtime=new qo,this.machineActivitySockets=new Map,this.activeTerminalIds=new Set,this.machineNavigation=new Pp,this.terminalSelection=new Ep,this.appShell=new mu(this),this.panelCollapse=new Iu(this),this.panelResize=new Mu(this),this.navigationSections=new $u(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.routeRestoreSeq=0,this.routeRestoreDepth=0,this.plugins=cb(),this.loadedMachinePluginIds=new Set,this.machinePluginLoadPromises=new Map,this.themePreference=Jp()??Kp,this.activeThemeId=Ks,this.isRefreshingApp=!1,this.settingsSection=lr(),this.shortcutConfig={},this.onPopState=()=>{this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onPageShow=()=>{this.appShell.repairViewportPosition()},this.onFocus=()=>{this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.refreshPiWebStatus(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns()},this.onVisibilityChange=()=>{document.visibilityState==="visible"&&(this.appShell.repairViewportPosition(),this.sessions.refreshSelectedSession(),this.refreshPiWebStatus(),this.refreshMachineActivities(),this.refreshWorkspaceDeletionRuns())},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.settingsSection===void 0&&this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())}}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute("pwa-display-mode",this.appShell.isPwaDisplayMode)}connectedCallback(){super.connectedCallback(),window.addEventListener("popstate",this.onPopState),window.addEventListener("pageshow",this.onPageShow),window.addEventListener("focus",this.onFocus),document.addEventListener("visibilitychange",this.onVisibilityChange),window.addEventListener("keydown",this.onKeyDown,Fr),this.systemLightThemeMedia?.addEventListener("change",this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.connectRealtime(),this.piWebStatusTimer=window.setInterval(()=>{this.refreshPiWebStatus()},rb),this.refreshPiWebStatus(),this.refreshWorkspaceActivity(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute()}disconnectedCallback(){window.removeEventListener("popstate",this.onPopState),window.removeEventListener("pageshow",this.onPageShow),window.removeEventListener("focus",this.onFocus),document.removeEventListener("visibilitychange",this.onVisibilityChange),window.removeEventListener("keydown",this.onKeyDown,Fr),this.systemLightThemeMedia?.removeEventListener("change",this.onSystemLightThemeChange),this.keyboard.reset(),this.auth.dispose(),this.sessions.dispose(),this.realtime.close(),this.closeMachineActivitySockets(),this.git.dispose(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.workspaceDeletionPollTimer!==void 0&&window.clearInterval(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,super.disconnectedCallback()}setState(e){if(!hb(this.state,e))return;const t=this.state;this.state={...this.state,...e},this.handleActivityTransition(t,this.state),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),db(t,this.state)&&this.syncMachineActivitySubscriptions()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();const e=ar();await this.machines.loadMachines(e.machineId);const t=this.state.error,i=this.routeForSelectedMachine(e);i!==e&&this.replaceRouteAndClearWorkspaceQuery(i),await this.projects.loadProjects(),t!==""&&this.state.error===""&&this.setState({error:t}),await this.withChatScrollTransition(()=>this.restoreRouteFor(i,!1)),this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}async refreshPiWebStatus(){try{this.setState({piWebStatus:await an.piWebStatus()})}catch(e){console.warn("Failed to refresh PI WEB status",e)}}async refreshWorkspaceActivity(e=g(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){const e=this.state.machines.length===0?[g(this.state)]:this.state.machines.filter(t=>ya(t,this.state.machineStatuses[t.id])).map(t=>t.id);await Promise.all(e.map(t=>this.refreshWorkspaceActivity(t)))}async loadClientConfig(){try{this.applyClientConfig((await ri.config()).config)}catch(e){console.warn("Failed to load PI WEB config",e)}}applyClientConfig(e){this.shortcutConfig=e.shortcuts??{}}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Promise.all([this.sessions.refreshSelectedSession(),this.refreshPiWebStatus(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface()])}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){const e=this.state.selectedWorkspace,t=this.state.mainView!=="chat"&&this.state.mainView!=="navigation"?this.state.mainView:this.state.workspaceTool;t==="core:workspace.files"?await this.files.refreshFiles():t==="core:workspace.git"?await this.git.refreshGit():t==="core:workspace.terminal"&&e!==void 0&&await this.refreshActiveTerminals(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e){await this.restoreRouteFor(ar(),e),this.rememberCurrentMachineNavigation()}async restoreRouteFor(e,t,i=this.readWorkspaceRouteSurface(e),s){const o=e.projectId===void 0||e.projectId===""?Hr():i,r=++this.routeRestoreSeq;this.routeRestoreDepth+=1,this.restoringRouteTerminalId=o.selectedTerminalId;try{await this.restoreRouteMachine(e,!1);const n=this.loadPluginsForSelectedMachine();if(e.tool?.startsWith("machine.")===!0&&await n,!this.isCurrentRouteRestore(r))return;if(this.setState({workspaceTool:e.tool??this.state.workspaceTool,mainView:s??e.view??this.defaultRouteView(),selectedFilePath:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),e.projectId===void 0||e.projectId===""){t&&this.updateUrl();return}if(this.routeMatchesCurrentSelection(e)){o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl();return}const a=this.state.projects.find(c=>c.id===e.projectId);if(!a){this.setState({selectedFilePath:void 0,selectedDiffPath:void 0,selectedTerminalId:void 0}),t&&this.updateUrl();return}if(await this.workspaces.selectProject(a,{workspaceId:e.workspaceId,sessionId:e.sessionId,updateUrl:!1}),!this.isCurrentRouteRestore(r))return;this.setState({selectedFilePath:o.selectedFilePath,selectedDiffPath:o.selectedDiffPath,selectedTerminalId:o.selectedTerminalId}),o.selectedTerminalId!==void 0&&this.rememberSelectedTerminal(o.selectedTerminalId),await this.refreshRestoredWorkspaceTool(e.tool,o.selectedFilePath),this.git.updatePolling(),t&&this.updateUrl()}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),this.routeRestoreDepth===0&&(this.restoringRouteTerminalId=void 0)}}isCurrentRouteRestore(e){return e===this.routeRestoreSeq}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===""?Hr():{selectedFilePath:Bi(ns,"file"),selectedDiffPath:Bi(as,"diff"),selectedTerminalId:Bi(Gt,"terminal")}}routeForSelectedMachine(e){const 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){Gi(e,{replace:!0}),re(ns,"file",void 0,{replace:!0}),re(as,"diff",void 0,{replace:!0}),re(Gt,"terminal",void 0,{replace:!0})}async restoreRouteMachine(e,t){const i=e.machineId??"local";if(this.state.selectedMachine?.id===i)return;const s=this.state.machines.find(o=>o.id===i);s!==void 0&&await this.machines.selectMachine(s,{updateUrl:t})}routeMatchesCurrentSelection(e){return(e.machineId??"local")===(this.state.selectedMachine?.id??"local")&&e.workspaceId!==void 0&&e.workspaceId!==""&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.workspaceId&&this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e==="core:workspace.files"&&await this.files.refreshFiles(),e==="core:workspace.files"&&t!==void 0&&await this.files.restoreFile(t),e==="core:workspace.git"&&await this.git.refreshGit()}async withChatScrollTransition(e){this.chatView?.saveScrollPosition(),await e(),await this.updateComplete,await this.chatView?.updateComplete,await ls(),this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()}shouldAutoFocusPrompt(){return this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e){this.rememberCurrentMachineNavigation(),Gi({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(Ko(this.state))}syncWorkspaceRouteSurfaceToUrl(){this.writeWorkspaceRouteSurfaceToUrl(Ko(this.state).surface)}writeMachineNavigationSnapshotToUrl(e,t){Gi(Vo(e),t),this.writeWorkspaceRouteSurfaceToUrl(e.surface)}writeWorkspaceRouteSurfaceToUrl(e){re(ns,"file",e.selectedFilePath,{replace:!0}),re(as,"diff",e.selectedDiffPath,{replace:!0}),re(Gt,"terminal",e.selectedTerminalId,{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();const i=++this.machineNavigationRestoreSeq,s=this.machineNavigation.latest(e.id)??Cp(e.id);if(await this.restoreRouteFor(Vo(s),!1,s.surface,s.view),!(i!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id)){if(this.shouldPreserveUnrestoredMachineNavigation(s)){this.machineNavigation.remember(s),this.writeMachineNavigationSnapshotToUrl(s);return}this.updateUrl()}}shouldPreserveUnrestoredMachineNavigation(e){return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&this.state.error!==""}openWorkspaceTool(e){e==="core:workspace.terminal"&&(this.terminalAutoStartWorkspaceId=this.state.selectedWorkspace?.id),this.setState({workspaceTool:e,mainView:e}),this.updateUrl(),this.refreshSelectedWorkspaceTool(e),this.git.updatePolling()}openTerminal(e){e?.terminalId!==void 0&&this.selectTerminal(e.terminalId,{replace:!0}),this.openWorkspaceTool("core:workspace.terminal")}terminalCommandRunsForOrigin(e,t=g(this.state)){const i=qr(t,e),s=this.terminalCommandRunRuntimes.get(i);if(s!==void 0)return s;const o=Ku(e,{api:{runTerminalCommand:(r,n)=>ot.runTerminalCommand(r,n,t),listCommandRuns:r=>ot.listCommandRuns(r,t),getCommandRun:r=>ot.getCommandRun(r,t)},openTerminal:(r,n)=>{this.openRuntimeTerminal(t,r,n)}});return this.terminalCommandRunRuntimes.set(i,o),o}async openRuntimeTerminal(e,t,i){if((g(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:i?.terminalId},"core:workspace.terminal"),g(this.state)!==e)){this.setState({error:"未找到用于运行终端命令的机器"});return}this.openTerminal(i)}selectTerminal(e,t){this.rememberSelectedTerminal(e),this.setState({selectedTerminalId:e}),this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(e,t)}rememberSelectedTerminal(e){const 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){re(Gt,"terminal",e,t)}terminalWorkspaceKey(e){return`${g(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,Ji(e)}closeSettings(){this.settingsSection=void 0,Ji(void 0)}navigateSettings(e){this.settingsSection=e,Ji(e)}restoreSettingsRoute(){this.settingsSection=lr()}handleWorkspaceChange(e,t){if(e.selectedWorkspace?.id===t.selectedWorkspace?.id)return;this.terminalAutoStartWorkspaceId=void 0,this.activeTerminalIds.clear();const i=this.routeRestoreInProgress?this.restoringRouteTerminalId:t.selectedWorkspace===void 0?void 0:this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(t.selectedWorkspace));this.setState({activeTerminalCount:0,selectedTerminalId:i}),this.routeRestoreInProgress||(this.rememberCurrentMachineNavigation(),this.writeSelectedTerminalToUrl(i,{replace:!0})),t.selectedWorkspace!==void 0&&(this.refreshActiveTerminals(t.selectedWorkspace),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(t.workspaceTool),this.git.updatePolling())}connectRealtime(){this.realtime.connect(e=>{this.handleRealtimeEvent(e)},()=>{const e=this.state.selectedWorkspace;e!==void 0&&this.refreshActiveTerminals(e),this.refreshWorkspaceActivity()},g(this.state))}syncMachineActivitySubscriptions(){const e=this.machineActivitySubscriptionIds();for(const[t,i]of this.machineActivitySockets.entries())e.has(t)||(i.close(),this.machineActivitySockets.delete(t));for(const t of e){if(this.machineActivitySockets.has(t))continue;const i=new qo;i.connect(s=>{this.handleMachineActivityEvent(t,s)},()=>{this.refreshWorkspaceActivity(t)},t),this.machineActivitySockets.set(t,i)}}closeMachineActivitySockets(){for(const e of this.machineActivitySockets.values())e.close();this.machineActivitySockets.clear()}machineActivitySubscriptionIds(){const e=g(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(t=>pb(t,this.state.machineStatuses[t.id])).map(t=>t.id))}handleMachineActivityEvent(e,t){t.type==="workspace.activity"&&this.activity.applyWorkspaceActivity(t.activity,e)}handleRealtimeEvent(e){e.type==="workspace.activity"?this.activity.applyWorkspaceActivity(e.activity):ub(e)?(this.applyTerminalEvent(e),e.type==="terminal.exited"&&this.refreshWorkspaceDeletionRuns()):this.sessions.applyGlobalEvent(e)}applyTerminalEvent(e){const 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){const t=g(this.state);try{const i=await ot.terminals(e.projectId,e.id,t);if(g(this.state)!==t||this.state.selectedWorkspace?.id!==e.id)return;this.activeTerminalIds.clear();for(const s of i)s.exited||this.activeTerminalIds.add(s.id);this.setState({activeTerminalCount:this.activeTerminalIds.size})}catch(i){this.setState({error:String(i)})}}handleActivityTransition(e,t){const i=Ur(e),s=Ur(t);i&&!s&&(this.setState({fileTreeStale:!0,gitStale:!0}),this.refreshSelectedWorkspaceTool(this.state.workspaceTool))}handleMachineChange(e,t){(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")&&(this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.activeTerminalIds.clear(),this.git.updatePolling(),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e==="core:workspace.files"&&this.files.refreshFiles(),e==="core:workspace.git"&&this.git.refreshGit()}renderWorkspacePanel(){const e=this.state.selectedWorkspace,t=e===void 0?void 0:this.createWorkspacePanelContext(e),i=e===void 0?this.workspacePanelEmptyState():void 0;return l`
|
|
2025
|
+
<workspace-panel
|
|
2026
|
+
id="workspace-panel"
|
|
2027
|
+
.workspace=${e}
|
|
2028
|
+
.panelContext=${t}
|
|
2029
|
+
.emptyState=${i}
|
|
2030
|
+
.tool=${this.state.workspaceTool}
|
|
2031
|
+
.panels=${this.visibleWorkspacePanels()}
|
|
2032
|
+
.onSelectTool=${s=>{this.openWorkspaceTool(s)}}
|
|
2033
|
+
></workspace-panel>
|
|
2034
|
+
`}renderNavigationPanelEdgeControl(){const e=this.resizablePanelConstraints("navigation");return l`
|
|
2035
|
+
<app-panel-edge-control
|
|
2036
|
+
side="navigation"
|
|
2037
|
+
controls="navigation-panel"
|
|
2038
|
+
expandLabel="展开导航面板"
|
|
2039
|
+
collapseLabel="折叠导航面板"
|
|
2040
|
+
resizeLabel="调整导航面板宽度"
|
|
2041
|
+
.collapsed=${this.panelCollapse.navigationPanelCollapsed}
|
|
2042
|
+
.resizable=${!this.appShell.isMobileNavigationLayout}
|
|
2043
|
+
.panelWidth=${this.panelResize.panelWidth("navigation")}
|
|
2044
|
+
.minWidth=${e.minWidth}
|
|
2045
|
+
.maxWidth=${e.maxWidth}
|
|
2046
|
+
.onToggle=${()=>{this.panelCollapse.toggleNavigationPanel()}}
|
|
2047
|
+
.onResizeStart=${()=>this.startPanelResize("navigation")}
|
|
2048
|
+
.onResize=${t=>{this.panelResize.resizePanel("navigation",t,{persist:!1})}}
|
|
2049
|
+
.onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
|
|
2050
|
+
.onReset=${()=>{this.resetResizablePanel("navigation")}}
|
|
2051
|
+
></app-panel-edge-control>
|
|
2052
|
+
`}renderWorkspacePanelEdgeControl(){const e=this.resizablePanelConstraints("workspace");return l`
|
|
2053
|
+
<app-panel-edge-control
|
|
2054
|
+
side="workspace"
|
|
2055
|
+
controls="workspace-panel"
|
|
2056
|
+
expandLabel="展开工作区面板"
|
|
2057
|
+
collapseLabel="折叠工作区面板"
|
|
2058
|
+
resizeLabel="调整工作区面板宽度"
|
|
2059
|
+
.collapsed=${this.panelCollapse.workspacePanelCollapsed}
|
|
2060
|
+
.resizable=${!this.appShell.isMobileNavigationLayout}
|
|
2061
|
+
.panelWidth=${this.panelResize.panelWidth("workspace")}
|
|
2062
|
+
.minWidth=${e.minWidth}
|
|
2063
|
+
.maxWidth=${e.maxWidth}
|
|
2064
|
+
.onToggle=${()=>{this.panelCollapse.toggleWorkspacePanel()}}
|
|
2065
|
+
.onResizeStart=${()=>this.startPanelResize("workspace")}
|
|
2066
|
+
.onResize=${t=>{this.panelResize.resizePanel("workspace",t,{persist:!1})}}
|
|
2067
|
+
.onResizeEnd=${()=>{this.panelResize.persistPanelSizes()}}
|
|
2068
|
+
.onReset=${()=>{this.resetResizablePanel("workspace")}}
|
|
2069
|
+
></app-panel-edge-control>
|
|
2070
|
+
`}startPanelResize(e){return e==="navigation"?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){const t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){const i=this.getBoundingClientRect().width||(typeof window>"u"?0:window.innerWidth);if(i<=0)return t.maxWidth;const s=this.oppositeResizablePanelWidth(e),o=Math.floor(i-s-ab-nb);return Math.max(t.minWidth,Math.min(t.maxWidth,o))}oppositeResizablePanelWidth(e){const 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)?!0:window.matchMedia(lb).matches}measuredPanelWidth(e){const i=(e==="navigation"?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return i===void 0||i<=0?void 0:i}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}renderNavigationPanel(){return l`
|
|
2071
|
+
<app-navigation-panel
|
|
2072
|
+
.machines=${this.state.machines}
|
|
2073
|
+
.selectedMachine=${this.state.selectedMachine}
|
|
2074
|
+
.machineStatuses=${this.state.machineStatuses}
|
|
2075
|
+
.machineActivities=${this.state.machineActivities}
|
|
2076
|
+
.machinesCollapsed=${this.navigationSections.isCollapsed("machines")}
|
|
2077
|
+
.onToggleMachines=${()=>{this.navigationSections.toggle("machines")}}
|
|
2078
|
+
.onSelectMachine=${e=>this.selectNavigationItem("machines","projects",()=>this.selectMachineWithMemory(e))}
|
|
2079
|
+
.onRemoveMachine=${e=>{this.removeMachine(e)}}
|
|
2080
|
+
.projects=${this.state.projects}
|
|
2081
|
+
.selectedProject=${this.state.selectedProject}
|
|
2082
|
+
.workspaceActivities=${this.state.workspaceActivities}
|
|
2083
|
+
.workspacesByProjectId=${this.state.workspacesByProjectId}
|
|
2084
|
+
.workspaces=${this.state.workspaces}
|
|
2085
|
+
.selectedWorkspace=${this.state.selectedWorkspace}
|
|
2086
|
+
.deletingWorkspaceIds=${uh(this.state.workspaceDeletionRuns)}
|
|
2087
|
+
.sessions=${this.state.sessions}
|
|
2088
|
+
.sessionStatuses=${this.state.sessionStatuses}
|
|
2089
|
+
.sessionActivities=${this.state.sessionActivities}
|
|
2090
|
+
.selectedSession=${this.state.selectedSession}
|
|
2091
|
+
.canStartSession=${!!this.state.selectedWorkspace}
|
|
2092
|
+
.collapsible=${!0}
|
|
2093
|
+
.compact=${this.appShell.isMobileNavigationLayout}
|
|
2094
|
+
.projectsCollapsed=${this.navigationSections.isCollapsed("projects")}
|
|
2095
|
+
.workspacesCollapsed=${this.navigationSections.isCollapsed("workspaces")}
|
|
2096
|
+
.sessionsCollapsed=${this.navigationSections.isCollapsed("sessions")}
|
|
2097
|
+
.workspaceLabelItems=${e=>this.workspaceLabelItems(e)}
|
|
2098
|
+
.refreshControl=${this.appShell.shouldShowAppRefreshInHeader()?this.renderAppRefresh():void 0}
|
|
2099
|
+
.onShowActions=${()=>{this.setState({actionPaletteOpen:!0})}}
|
|
2100
|
+
.onToggleProjects=${()=>{this.navigationSections.toggle("projects")}}
|
|
2101
|
+
.onToggleWorkspaces=${()=>{this.navigationSections.toggle("workspaces")}}
|
|
2102
|
+
.onToggleSessions=${()=>{this.navigationSections.toggle("sessions")}}
|
|
2103
|
+
.onSelectProject=${e=>this.selectNavigationItem("projects","workspaces",()=>this.workspaces.selectProject(e))}
|
|
2104
|
+
.onCloseProject=${e=>this.projects.closeProject(e.id)}
|
|
2105
|
+
.onSelectWorkspace=${e=>this.selectNavigationItem("workspaces","sessions",()=>this.workspaces.selectWorkspace(e))}
|
|
2106
|
+
.onDeleteWorkspace=${e=>{this.deleteWorkspace(e)}}
|
|
2107
|
+
.onArchivedCollapsed=${()=>{this.sessions.clearSelectionAfterArchivedCollapse()}}
|
|
2108
|
+
.onStartSession=${()=>this.selectNavigationItem("sessions","chat",()=>this.sessions.startSession())}
|
|
2109
|
+
.onSelectSession=${e=>this.selectNavigationItem("sessions","chat",()=>this.sessions.selectSession(e))}
|
|
2110
|
+
.onArchiveSession=${e=>this.sessions.archiveSession(e)}
|
|
2111
|
+
.onArchiveSessionWithDescendants=${e=>this.sessions.archiveSessionWithDescendants(e)}
|
|
2112
|
+
.onRestoreSession=${e=>this.selectNavigationItem("sessions","chat",()=>this.sessions.restoreSession(e))}
|
|
2113
|
+
.onDeleteCachedNewSession=${e=>this.sessions.deleteCachedNewSession(e)}
|
|
2114
|
+
.onDetachParentSession=${e=>this.sessions.detachParent(e)}
|
|
2115
|
+
.onFocusNavigationTarget=${e=>{this.focusNavigationTarget(e)}}
|
|
2116
|
+
.onCancelKeyboardNavigation=${()=>{this.focusChatComposer()}}
|
|
2117
|
+
></app-navigation-panel>
|
|
2118
|
+
`}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView("navigation")})}async selectNavigationItem(e,t,i){await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),await i()}),await this.focusNavigationTarget(t)}async focusNavigationTarget(e){if(e==="chat"){await this.focusChatComposer();return}await this.focusNavigationSection(e)}async focusNavigationSection(e){if(e==="machines"&&!xi(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 ls(),await this.navigationPanel?.focusSection(e)}async focusChatComposer(){this.state.mainView!=="chat"&&this.selectMainView("chat"),await this.updateComplete,await ls(),this.promptEditor?.focusInput()}visibleWorkspacePanels(){const e=this.state.selectedWorkspace;if(e===void 0)return[];const t=this.createWorkspacePanelContext(e);return this.plugins.getWorkspacePanels().filter(i=>i.visible?.(t)??!0)}workspacePanelEmptyState(){const 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){const 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){const t=Br(this.state);return{machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t.id),host:this.createWorkspaceHost()}}createWorkspaceFiles(e,t){return{readFile:i=>hs.workspaceFile(e.projectId,e.id,i,t)}}createWorkspaceHost(){return{requestRender:()=>{this.requestUpdate()}}}createWorkspacePanelContext(e){const t=Br(this.state),i=t.id,s=o=>{const r=this.terminalCommandRunsForOrigin(o,i);return ou({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,i),terminal:{open:n=>{this.openRuntimeTerminal(i,e,n)},runCommand:n=>r.runCommand({...n,workspace:e})},openTerminal:n=>{this.openRuntimeTerminal(i,e,n)},host:this.createWorkspaceHost(),piWebUnstable:{terminalCommandRuns:r},fileTree:this.state.fileTree,expandedDirs:this.state.expandedDirs,selectedFilePath:this.state.selectedFilePath,selectedFileContent:this.state.selectedFileContent,fileTreeStale:this.state.fileTreeStale,gitStatus:this.state.gitStatus,selectedDiffPath:this.state.selectedDiffPath,selectedDiff:this.state.selectedDiff,selectedStagedDiff:this.state.selectedStagedDiff,gitStale:this.state.gitStale,activeTerminalCount:this.state.activeTerminalCount,selectedTerminalId:this.state.selectedTerminalId,terminalAutoStart:this.terminalAutoStartWorkspaceId===e.id,onRefreshFiles:()=>{this.files.refreshFiles()},onUploadFiles:n=>{this.files.uploadFiles(n)},onCreateFile:n=>{this.files.createFile(n)},onCreateDirectory:n=>{this.files.createDirectory(n)},onMoveSelectedPath:n=>{this.files.moveSelectedPath(n)},onDeleteSelectedPath:()=>{this.files.deleteSelectedPath()},onDownloadSelectedFile:()=>{this.files.downloadSelectedFile()},onExpandDir:n=>{this.files.expandDir(n)},onSelectDirectory:n=>{this.files.selectDirectory(n)},onSelectFile:n=>{this.files.selectFile(n)},onRefreshGit:()=>{this.git.refreshGit()},onSelectDiff:n=>{this.git.selectDiff(n)},onSelectTerminal:(n,a)=>{this.selectTerminal(n,a)}},s)};return s("core")}getActions(){return Hu(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.navigationFocusActions(),...this.panelLayoutActions()]}panelLayoutActions(){return[{id:"app.layout.reset-navigation-panel-size",title:"Reset Navigation Panel Size",description:"Restore the navigation panel to its default width",group:"View",run:()=>{this.resetResizablePanel("navigation")}},{id:"app.layout.reset-workspace-panel-size",title:"Reset Workspace Panel Size",description:"Restore the workspace panel to its default width",group:"View",run:()=>{this.resetResizablePanel("workspace")}},{id:"app.layout.reset-panel-sizes",title:"Reset Panel Sizes",description:"Restore all side panels to their default widths",group:"View",run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:"app.navigation.focus-machines",title:"Focus Machines",description:"Move keyboard focus to the machine selector",shortcut:"mod+g m",group:"Navigation",run:()=>this.focusNavigationSection("machines")},{id:"app.navigation.focus-projects",title:"Focus Projects",description:"Move keyboard focus to the projects list",shortcut:"mod+g p",group:"Navigation",run:()=>this.focusNavigationSection("projects")},{id:"app.navigation.focus-workspaces",title:"Focus Workspaces",description:"Move keyboard focus to the workspaces list",shortcut:"mod+g w",group:"Navigation",run:()=>this.focusNavigationSection("workspaces")},{id:"app.navigation.focus-sessions",title:"Focus Sessions",description:"Move keyboard focus to the sessions list",shortcut:"mod+g s",group:"Navigation",run:()=>this.focusNavigationSection("sessions")}]}ensureGatewayPluginsLoaded(){return this.gatewayPluginLoadPromise??=this.loadExternalPlugins(),this.gatewayPluginLoadPromise}async loadExternalPlugins(){await this.registerExternalPlugins("PI WEB plugins",()=>sr())}async loadPluginsForSelectedMachine(){const e=this.state.selectedMachine;e?.kind==="remote"&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){if(await this.ensureGatewayPluginsLoaded(),e.kind!=="remote"||this.loadedMachinePluginIds.has(e.id))return;const t=this.machinePluginLoadPromises.get(e.id);if(t!==void 0)return t;const i=this.registerExternalPlugins(`PI WEB plugins from ${e.name}`,()=>sr(`/api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id})).then(s=>{s&&this.loadedMachinePluginIds.add(e.id)}).finally(()=>{this.machinePluginLoadPromises.delete(e.id)});this.machinePluginLoadPromises.set(e.id,i),await i}async registerExternalPlugins(e,t){try{const i=await t();for(const s of i)try{this.plugins.register(s)}catch(o){console.warn(`Failed to register PI WEB plugin ${s.id}`,o)}return this.applyPreferredTheme(!1),this.requestUpdate(),!0}catch(i){return console.warn(`Failed to load ${e}`,i),!1}}createPluginRuntimeContext(){const e=t=>su({state:this.state,piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:i=>{this.openSettings(i)}},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.focusChatComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:()=>this.machines.refreshMachineHealth(),removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},selectMainView:i=>{this.selectMainView(i)},selectWorkspaceTool:i=>{this.openWorkspaceTool(i)},openTerminal:i=>{this.openTerminal(i)},refreshFiles:()=>this.files.refreshFiles(),refreshGit:()=>this.git.refreshGit(),refreshAppData:()=>this.refreshAppData(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:i=>this.deleteWorkspace(i),startSession:()=>this.withChatScrollTransition(()=>this.sessions.startSession()),archiveSession:()=>this.sessions.archiveSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e("core")}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;if(!Sp(e)){this.setState({error:"只能删除次级 Git worktree"});return}if(Wn(this.state,e))return;const t=e.branch??e.label;if(!confirm(`删除工作区 ${t}?
|
|
2119
|
+
|
|
2120
|
+
这会运行 git worktree remove 并删除:
|
|
2121
|
+
${e.path}
|
|
2122
|
+
|
|
2123
|
+
Git 分支不会被删除。`))return;const s=g(this.state);try{const o=await hs.deleteWorkspace(e.projectId,e.id,s);if(g(this.state)!==s)return;this.recordWorkspaceDeletionRun(o,s);const r=await this.workspaceForCommandRun(o);if(g(this.state)!==s)return;r!==void 0&&this.openRuntimeTerminal(s,r,{terminalId:o.terminalId})}catch(o){g(this.state)===s&&this.setState({error:`启动工作区删除失败:${fb(o)}`})}}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(i=>i.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(g(this.state)!==t)return;const i=bs(e);i!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[i]:e}}),this.updateWorkspaceDeletionPolling())}async refreshWorkspaceDeletionRuns(){if(this.refreshingWorkspaceDeletionRuns)return;const e=g(this.state),t=this.state.selectedProject;if(t===void 0){this.setState({workspaceDeletionRuns:{}}),this.updateWorkspaceDeletionPolling();return}this.refreshingWorkspaceDeletionRuns=!0;try{const i=await this.terminalCommandRunsForOrigin("core",e).listCommandRuns(ph(t.id));if(g(this.state)!==e)return;const s=hh(i);this.setState({workspaceDeletionRuns:s});for(const o of Object.values(s))hi(o)||await this.handleCompletedWorkspaceDeletionRun(o,e)}catch(i){console.warn("刷新工作区删除任务失败",i)}finally{this.refreshingWorkspaceDeletionRuns=!1,this.updateWorkspaceDeletionPolling()}}updateWorkspaceDeletionPolling(){const e=Object.values(this.state.workspaceDeletionRuns).some(hi);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=g(this.state)){if(g(this.state)!==t)return;const i=qr(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(i))return;const s=bs(e);if(s!==void 0){if(this.handledWorkspaceDeletionRunIds.add(i),e.status==="succeeded"){if(await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,s),g(this.state)!==t)return;this.setState({workspaceDeletionRuns:gb(this.state.workspaceDeletionRuns,s)}),this.updateWorkspaceDeletionPolling();return}e.status==="failed"&&(this.setState({error:"工作区删除失败。请查看终端输出。"}),this.updateWorkspaceDeletionPolling())}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:""})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&this.setState({machineDialogOpen:!1})}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind==="local"||!window.confirm(`移除 ${e.name}?
|
|
2124
|
+
|
|
2125
|
+
这只会将它从当前 PI WEB 网关中移除。`))return;const t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();const i=await this.machines.deleteMachine(e,{selectFallback:!t});this.state.machines.some(s=>s.id===e.id)||this.machineNavigation.forget(e.id),t&&i!==void 0&&await this.selectMachineWithMemory(i,{rememberCurrent:!1})}openSelectedMachine(){const 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=>{const i=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.setState({error:`操作失败:${i}`})})}async openModelDialog(){const e=await this.sessions.listModels(),t=this.state.status?.model?.provider,i=this.state.status?.model?.id;this.setState({modelDialog:{title:"选择模型",...t!==void 0&&i!==void 0?{selectedValue:`${t}/${i}`}:{},options:e.map(s=>{const o=s.provider??"",r=s.id??"",n=o===t&&r===i;return{value:`${o}/${r}`,label:`${r}${n?" ✓ 当前":""}`,description:o}})}})}async pickModel(e){this.setState({modelDialog:void 0});const t=e.indexOf("/");t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){const e=this.plugins.getThemes(),t=this.resolveCurrentThemePreference(e),i=t.selectedTheme?.id,s=this.themePreference.auto?zr:rs;this.setState({themeDialog:{title:"选择主题",selectedValue:i===void 0?s:`${Vt}${i}`,options:[{value:s,label:`自动 ${this.themePreference.auto?"✓ 开":"关"}`,description:this.autoThemeDescription(t)},...e.map(o=>({value:`${Vt}${o.id}`,label:this.themeOptionLabel(o,i),description:this.themeOptionDescription(o)}))]}})}pickTheme(e){if(this.setState({themeDialog:void 0}),e===rs||e===zr){const s=this.resolveCurrentThemePreference().selectedTheme?.id;if(s===void 0)return;this.themePreference={themeId:s,auto:e===rs},this.applyPreferredTheme(!0);return}if(!e.startsWith(Vt))return;const t=e.slice(Vt.length),i=this.plugins.getThemes().find(s=>s.id===t);i!==void 0&&(this.themePreference={themeId:i.id,auto:this.themePreference.auto},this.applyPreferredTheme(!0))}applyPreferredTheme(e){const t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,Qp(t),e&&Zp(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return Xp({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}themePairForTheme(e){return Dn(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){const i=[...e.id===t?["已选择"]:[],...e.id===this.activeThemeId&&e.id!==t?["当前"]:[]];return i.length===0?e.name:`${e.name} ✓ ${i.join(" · ")}`}themeOptionDescription(e){const t=[e.colorScheme];return this.themePairForTheme(e.id)!==void 0&&t.push("自动配对"),e.description!==void 0&&t.push(e.description),t.join(" · ")}async openThinkingDialog(){const e=await this.sessions.listThinkingLevels(),t=this.state.status?.thinkingLevel??"off";this.setState({thinkingDialog:{title:"选择思考级别",selectedValue:t,options:e.map(i=>({value:i,label:`${bb(i)}${i===t?" ✓ 当前":""}`,description:vb(i)}))}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),mb(e)&&await this.sessions.setThinkingLevel(e)}sendPrompt(e,t){t===void 0&&this.auth.handleSlashCommand(e)||this.sessions.send(e,t)}renderContextBar(){return this.appShell.isMobileNavigationLayout?l`
|
|
2126
|
+
<app-context-bar
|
|
2127
|
+
.machines=${this.state.machines}
|
|
2128
|
+
.machine=${this.state.selectedMachine}
|
|
2129
|
+
.project=${this.state.selectedProject}
|
|
2130
|
+
.workspace=${this.state.selectedWorkspace}
|
|
2131
|
+
.session=${this.state.selectedSession}
|
|
2132
|
+
.refreshControl=${this.appShell.shouldShowAppRefreshInContextBar()?this.renderAppRefresh():void 0}
|
|
2133
|
+
.onOpenSection=${e=>{this.openNavigationSection(e)}}
|
|
2134
|
+
.onShowActions=${()=>{this.setState({actionPaletteOpen:!0})}}
|
|
2135
|
+
></app-context-bar>
|
|
2136
|
+
`:null}renderMobileMainTabs(){return l`
|
|
2137
|
+
<app-mobile-main-tabs
|
|
2138
|
+
.tabs=${this.mobileMainTabs()}
|
|
2139
|
+
.selectedView=${this.state.mainView}
|
|
2140
|
+
.onSelect=${e=>{this.selectMainView(e)}}
|
|
2141
|
+
></app-mobile-main-tabs>
|
|
2142
|
+
`}mobileMainTabs(){return[{id:"navigation",label:"会话",icon:"navigation",className:"navigation-tab"},{id:"chat",label:"聊天",icon:"chat"},...this.visibleWorkspacePanels().map(e=>{const t=e.icon??this.mobilePanelIcon(e);return{id:e.id,label:e.title,...t===void 0?{}:{icon:t},badge:this.mobilePanelBadge(e)}})]}renderAppRefresh(){return l`<app-refresh-control .onReload=${()=>{this.hardReloadApp()}}></app-refresh-control>`}render(){const e=this.state;return l`
|
|
2143
|
+
<div class=${this.panelCollapse.shellClass(e.mainView)} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints("navigation"),workspace:this.resizablePanelConstraints("workspace")})}>
|
|
2144
|
+
<aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
|
|
2145
|
+
${this.renderNavigationPanelEdgeControl()}
|
|
2146
|
+
<main class=${zn(e.mainView)}>
|
|
2147
|
+
${this.renderContextBar()}
|
|
2148
|
+
${this.renderMobileMainTabs()}
|
|
2149
|
+
${e.error?l`<div class="error">${e.error}</div>`:null}
|
|
2150
|
+
<div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
|
|
2151
|
+
${e.selectedSession?l`
|
|
2152
|
+
<chat-view .sessionId=${e.selectedSession.id} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isReceivingPartialStream=${e.isReceivingPartialStream} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .status=${e.status} .activity=${e.activity} .onLoadMore=${()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages())}></chat-view>
|
|
2153
|
+
<prompt-editor .sessionId=${e.selectedSession.id} .cwd=${e.selectedWorkspace?.path} .machineId=${g(e)} .disabled=${e.selectedSession.archived===!0} .canSteer=${e.status?.isStreaming===!0} .isCompacting=${e.status?.isCompacting===!0} .canStop=${e.status?.isStreaming===!0||e.status?.isBashRunning===!0||e.status?.isCompacting===!0||(e.status?.pendingMessageCount??0)>0} .status=${e.status} .onSend=${(t,i)=>{this.sendPrompt(t,i)}} .onStop=${()=>this.sessions.stopActiveWork()} .onSelectModel=${()=>{this.openModelDialog()}} .onSelectThinking=${()=>{this.openThinkingDialog()}}></prompt-editor>
|
|
2154
|
+
<status-bar .status=${e.status}></status-bar>
|
|
2155
|
+
${e.commandDialog!==void 0?l`<command-picker .title=${e.commandDialog.title} .options=${e.commandDialog.options} .onPick=${t=>this.sessions.respondToCommand(e.commandDialog?.requestId??"",t)} .onCancel=${()=>{this.sessions.cancelCommand()}}></command-picker>`:null}
|
|
2156
|
+
${e.modelDialog!==void 0?l`<command-picker title=${e.modelDialog.title} .searchable=${!0} .options=${e.modelDialog.options} .selectedValue=${e.modelDialog.selectedValue} .onPick=${t=>{this.pickModel(t)}} .onCancel=${()=>{this.setState({modelDialog:void 0})}}></command-picker>`:null}
|
|
2157
|
+
${e.thinkingDialog!==void 0?l`<command-picker title=${e.thinkingDialog.title} .options=${e.thinkingDialog.options} .selectedValue=${e.thinkingDialog.selectedValue} .onPick=${t=>{this.pickThinking(t)}} .onCancel=${()=>{this.setState({thinkingDialog:void 0})}}></command-picker>`:null}
|
|
2158
|
+
${e.authDialog!==void 0?l`<auth-dialog .state=${e.authDialog} .onChooseMethod=${t=>{this.auth.chooseLoginMethod(t)}} .onSelectProvider=${(t,i)=>{this.auth.selectLoginProvider(t,i)}} .onApiKeyInput=${t=>{this.auth.updateApiKey(t)}} .onSaveApiKey=${()=>{this.auth.saveApiKey()}} .onLogoutProvider=${t=>{this.auth.logoutProvider(t)}} .onOAuthInput=${t=>{this.auth.updateOAuthInput(t)}} .onOAuthRespond=${t=>{this.auth.respondOAuth(t)}} .onOAuthCancel=${()=>{this.auth.cancelOAuth()}} .onCancel=${()=>{this.auth.closeDialog()}}></auth-dialog>`:null}
|
|
2159
|
+
`:l`<div class="empty">${this.sessionEmptyMessage()}</div>`}
|
|
2160
|
+
</main>
|
|
2161
|
+
${this.renderWorkspacePanelEdgeControl()}
|
|
2162
|
+
${this.renderWorkspacePanel()}
|
|
2163
|
+
${e.actionPaletteOpen?l`<action-palette .actions=${this.getActions()} .onRun=${t=>{this.setState({actionPaletteOpen:!1}),this.runAction(t)}} .onCancel=${()=>{this.setState({actionPaletteOpen:!1})}}></action-palette>`:null}
|
|
2164
|
+
${e.projectDialogOpen?l`<project-dialog .machineId=${g(e)} .onSubmit=${(t,i)=>this.projects.addProject(t,i)} .onCancel=${()=>{this.setState({projectDialogOpen:!1})}}></project-dialog>`:null}
|
|
2165
|
+
${e.machineDialogOpen?l`<machine-dialog .error=${e.error} .onSubmit=${t=>this.submitMachineDialog(t)} .onCancel=${()=>{this.setState({machineDialogOpen:!1})}}></machine-dialog>`:null}
|
|
2166
|
+
${e.themeDialog!==void 0?l`<command-picker title=${e.themeDialog.title} .options=${e.themeDialog.options} .selectedValue=${e.themeDialog.selectedValue} .onPick=${t=>{this.pickTheme(t)}} .onCancel=${()=>{this.setState({themeDialog:void 0})}}></command-picker>`:null}
|
|
2167
|
+
${this.settingsSection!==void 0?l`<settings-dialog .section=${this.settingsSection} .actions=${this.getDefaultActions()} .onNavigate=${t=>{this.navigateSettings(t)}} .onClose=${()=>{this.closeSettings()}} .onConfigSaved=${t=>{this.applyClientConfig(t)}}></settings-dialog>`:null}
|
|
2168
|
+
</div>
|
|
2169
|
+
`}};le.styles=nf;$e([w()],le.prototype,"state",2);$e([N("chat-view")],le.prototype,"chatView",2);$e([N("prompt-editor")],le.prototype,"promptEditor",2);$e([N("app-navigation-panel")],le.prototype,"navigationPanel",2);$e([N("#navigation-panel")],le.prototype,"navigationPanelFrame",2);$e([N("#workspace-panel")],le.prototype,"workspacePanelFrame",2);$e([w()],le.prototype,"activeThemeId",2);$e([w()],le.prototype,"isRefreshingApp",2);$e([w()],le.prototype,"settingsSection",2);$e([w()],le.prototype,"shortcutConfig",2);le=$e([R("pi-web-app")],le);function cb(){const e=new tu;return e.register({id:"core",plugin:Nh}),e.register({id:"themes",plugin:Uh}),e}function Br(e){const t=e.selectedMachine;return t!==void 0?{id:t.id,name:t.name,kind:t.kind}:{id:"local",name:"local",kind:"local"}}function db(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??"local")!==(t.selectedMachine?.id??"local")}function pb(e,t){return ya(e,t)}function ya(e,t){if(e.kind==="local")return!0;const i=t?.status??e.status;return i===void 0||i==="unknown"||i==="online"}function hb(e,t){return Object.entries(t).some(([i,s])=>Reflect.get(e,i)!==s)}function Ur(e){return Pi(e.status,e.activity)}function ub(e){return e.type==="terminal.created"||e.type==="terminal.exited"||e.type==="terminal.closed"}function Hr(){return{}}function qr(e,t){return JSON.stringify([e,t])}function fb(e){return e instanceof Error?e.message:String(e)}function gb(e,t){return Object.fromEntries(Object.entries(e).filter(([i])=>i!==t))}function ls(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}function mb(e){return e==="off"||e==="minimal"||e==="low"||e==="medium"||e==="high"||e==="xhigh"}function vb(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)"}}function bb(e){switch(e){case"off":return"关闭";case"minimal":return"极简";case"low":return"低";case"medium":return"中";case"high":return"高";case"xhigh":return"超高"}}export{A as a,l as b,ot as c,Rb as d,N as e,Tb as f,T as i,d as n,w as r,Mb as s,R as t};
|