@chainingintention/pi-web-cn 2.202610.3 → 2.202610.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/{CommandPicker-gK2biReF.js → CommandPicker-8oDe6AaV.js} +1 -1
- package/dist/client/assets/{PiWebApp-DccVSAFd.js → PiWebApp-TCQVYghs.js} +242 -242
- package/dist/client/assets/{SettingsDialog-vGDo1-BJ.js → SettingsDialog-DFUpwUyp.js} +1 -1
- package/dist/client/assets/{index-Chn9pQPv.js → index-DzMPXVth.js} +2 -2
- package/dist/client/index.html +1 -1
- package/dist/pi-packages/relays/relayDiscovery.js +5 -1
- package/dist/pi-web-plugins/custom-ui-codex/README.md +2 -0
- package/dist/pi-web-plugins/custom-ui-codex/chat-settings.css +15 -2
- package/dist/pi-web-plugins/files/browser/pi-web-plugin.js +87 -50
- package/dist/pi-web-plugins/workspace-tasks/tasksPanelElement.js +21 -6
- package/dist/pi-web-plugins/zh-cn/bundled.json +31 -18
- package/dist/pi-web-plugins/zh-cn/components.json +2 -0
- package/dist/pi-web-plugins/zh-cn/files.json +7 -0
- package/dist/pi-web-plugins/zh-cn/server-main.json +4 -4
- package/dist/plugin-api.d.ts +9 -0
- package/dist/server/app.js +3 -0
- package/dist/server/app.js.map +1 -1
- package/dist/server/managementAgents.js +179 -0
- package/dist/server/managementAgents.js.map +1 -0
- package/dist/server/managementAgentsRoutes.js +42 -0
- package/dist/server/managementAgentsRoutes.js.map +1 -0
- package/dist/server/managementEmbed.js +23 -43
- package/dist/server/managementEmbed.js.map +1 -1
- package/dist/server/sessions/piSessionService.js +10 -2
- package/dist/server/sessions/piSessionService.js.map +1 -1
- package/dist/server/workspaceExplorerRoutes.js +3 -1
- package/dist/server/workspaceExplorerRoutes.js.map +1 -1
- package/dist/shared/apiTypes.js.map +1 -1
- package/dist/shared/federatedRoutes.js +2 -0
- package/dist/shared/federatedRoutes.js.map +1 -1
- package/dist/shared/managedAgents.js +2 -0
- package/dist/shared/managedAgents.js.map +1 -0
- package/dist/shared/pluginApiTypes.d.ts +14 -0
- package/docs/config.md +3 -1
- package/docs/plugins.md +20 -5
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./SettingsDialog-
|
|
2
|
-
import{$ as e,$t as t,A as n,At as r,B as i,Bt as a,C as o,Ct as s,D as c,Dt as l,E as u,Et as d,F as f,Ft as p,H as m,Ht as h,I as g,It as ee,J as _,Jt as te,K as ne,Kt as re,L as ie,Lt as ae,M as v,Mt as oe,N as se,Nt as ce,O as le,Ot as ue,P as de,Pt as fe,Q as pe,R as me,Rt as he,S as ge,St as _e,T as ve,Tt as ye,U as be,Ut as xe,Vt as Se,W as Ce,Wt as we,X as Te,Xt as Ee,Y as De,Yt as Oe,Zt as ke,_ as Ae,_t as je,a as Me,an as Ne,at as Pe,b as Fe,bt as Ie,c as Le,cn as y,ct as Re,d as ze,dn as Be,dt as Ve,en as He,f as Ue,fn as We,ft as Ge,g as Ke,gn as qe,gt as Je,hn as Ye,ht as Xe,i as Ze,in as Qe,it as $e,j as et,jt as tt,k as nt,kt as rt,ln as b,lt as it,m as at,mn as ot,mt as x,n as st,nn as ct,nt as lt,o as ut,on as S,ot as dt,pn as ft,pt,q as mt,qt as ht,r as gt,rn as _t,rt as vt,s as yt,sn as C,t as bt,tn as xt,un as St,ut as Ct,v as wt,vt as Tt,w as Et,wt as Dt,x as Ot,xt as kt,y as w,z as At,zt as jt}from"./CommandPicker-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./SettingsDialog-DFUpwUyp.js","./CommandPicker-8oDe6AaV.js","./managementEmbed-Bx8Mwzdw.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{$ as e,$t as t,A as n,At as r,B as i,Bt as a,C as o,Ct as s,D as c,Dt as l,E as u,Et as d,F as f,Ft as p,H as m,Ht as h,I as g,It as ee,J as _,Jt as te,K as ne,Kt as re,L as ie,Lt as ae,M as v,Mt as oe,N as se,Nt as ce,O as le,Ot as ue,P as de,Pt as fe,Q as pe,R as me,Rt as he,S as ge,St as _e,T as ve,Tt as ye,U as be,Ut as xe,Vt as Se,W as Ce,Wt as we,X as Te,Xt as Ee,Y as De,Yt as Oe,Zt as ke,_ as Ae,_t as je,a as Me,an as Ne,at as Pe,b as Fe,bt as Ie,c as Le,cn as y,ct as Re,d as ze,dn as Be,dt as Ve,en as He,f as Ue,fn as We,ft as Ge,g as Ke,gn as qe,gt as Je,hn as Ye,ht as Xe,i as Ze,in as Qe,it as $e,j as et,jt as tt,k as nt,kt as rt,ln as b,lt as it,m as at,mn as ot,mt as x,n as st,nn as ct,nt as lt,o as ut,on as S,ot as dt,pn as ft,pt,q as mt,qt as ht,r as gt,rn as _t,rt as vt,s as yt,sn as C,t as bt,tn as xt,un as St,ut as Ct,v as wt,vt as Tt,w as Et,wt as Dt,x as Ot,xt as kt,y as w,z as At,zt as jt}from"./CommandPicker-8oDe6AaV.js";import{$ as T,D as Mt,F as Nt,H as Pt,I as Ft,J as E,K as It,M as Lt,N as Rt,R as D,U as O,V as zt,W as k,X as Bt,a as Vt,i as Ht,j as Ut,k as Wt,n as Gt,o as Kt,t as qt,y as Jt}from"./managementEmbed-Bx8Mwzdw.js";import{a as Yt,i as Xt,n as Zt,r as Qt,t as $t}from"./preload-helper-XpATwJ5c.js";import{$ as en,A as tn,J as nn,K as rn,N as an,Q as on,X as sn,Y as cn,Z as ln,d as un,et as dn,f as fn,k as pn,l as mn,nt as hn,p as gn,q as _n,rt as vn,u as yn,x as bn}from"./vendor-editor-core-BfnHL1Dg.js";import{n as xn,r as Sn,t as Cn}from"./vendor-editor-languages-bNquDJP0.js";function wn(e,t=e.role){if(e.entryId!==void 0)return Object.freeze({entryId:e.entryId,...e.parts.some(e=>e.type===`askUserQuestion`)?{isQuestion:!0}:{},role:t,text:e.parts.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
3
3
|
|
|
4
4
|
`)})}function Tn(e){return Object.freeze({...e.entryId===void 0?{}:{entryId:e.entryId},role:e.role,text:e.parts.filter(e=>e.type===`text`).map(e=>e.text.trim()).filter(Boolean).join(`
|
|
5
5
|
|
|
@@ -24,7 +24,7 @@ import{$ as e,$t as t,A as n,At as r,B as i,Bt as a,C as o,Ct as s,D as c,Dt as
|
|
|
24
24
|
`)}function zo(e,t){let n=Eo(t);if(n!==void 0)return bo(e,n,!0);let r=mi(t);return r.length===0&&e.at(-1)?.parts.at(-1)?.type===`askUserQuestion`?li([...e,t]):[...e,...r]}function Bo(e,t){let n=e.at(-1);return Vo(e,t)?e:n?.role===t.role&&t.role!==`skill`?[...e.slice(0,-1),{...n,parts:[...n.parts,...t.parts]}]:[...e,t]}function Vo(e,t){let n=No(t);if(t.role!==`skill`||n.length===0)return!1;let r=Uo(e)+1;return n.every(t=>Ho(e,t,r))}function Ho(e,t,n){for(let r=e.length-1;r>=n;r--)if(No(e[r]).some(e=>Fo(e,t)))return!0;return!1}function Uo(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role===`user`)return t;return-1}function Wo(e){return typeof e==`object`&&!!e}function Go(e,t){return Wo(e)?e[t]:void 0}function Ko(e,t){let n=Go(e,t);return typeof n==`string`?n:void 0}function qo(e,t){let n=Go(e,t);return typeof n==`boolean`?n:void 0}var Jo=`pi-web:chat-history:v2:`,Yo=18e5;function Xo(e){try{let t=sessionStorage.getItem(as(e));if(t===null||t===``)return;let n=JSON.parse(t);if(!os(n))return;if(Date.now()-n.savedAt>Yo){sessionStorage.removeItem(as(e));return}return{messages:n.messages,start:n.start,total:n.total,...n.leafId===void 0?{}:{leafId:n.leafId}}}catch{return}}function Zo(e,t){try{sessionStorage.setItem(as(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function Qo(e){try{sessionStorage.removeItem(as(e))}catch{}}function $o(e,t){if(e===void 0||!ss(e))return t;if(!ss(t))return e;if(t.leafId!==e.leafId||ns(e,t))return t;let n=Math.min(e.start,t.start),r=Math.max(e.start+e.messages.length,t.start+t.messages.length),i=Array(r-n);return is(i,n,e),is(i,n,t),rs(i)?t:{start:n,total:Math.max(e.total,t.total),messages:i,...t.leafId===void 0?{}:{leafId:t.leafId}}}function es(e,t){if(!ss(e)||!ss(t)||e.leafId!==t.leafId)return!1;let n=e.start+e.messages.length;if(n>t.total)return!1;if(e.total===0)return!0;let r=Math.max(e.start,t.start),i=Math.min(n,t.start+t.messages.length);return r<i&&JSON.stringify(e.messages.slice(r-e.start,i-e.start))===JSON.stringify(t.messages.slice(r-t.start,i-t.start))}function ts(e,t){if(e===void 0||!ss(t)||e.leafId!==t.leafId||t.total!==e.total)return!1;let n=t.start-e.start;return n<0||n+t.messages.length!==e.messages.length?!1:JSON.stringify(t.messages)===JSON.stringify(e.messages.slice(n))}function ns(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function rs(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function is(e,t,n){n.messages.forEach((r,i)=>{e[n.start-t+i]=r})}function as(e){return`${Jo}${e}`}function os(e){if(typeof e!=`object`||!e||!(`messages`in e)||!(`start`in e)||!(`total`in e)||!(`savedAt`in e))return!1;let{messages:t,start:n,total:r,savedAt:i}=e;return Array.isArray(t)&&(!(`leafId`in e)||e.leafId===null||typeof e.leafId==`string`)&&typeof n==`number`&&typeof r==`number`&&typeof i==`number`&&ss({messages:t,start:n,total:r})}function ss(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(cs)}function cs(e){return typeof e==`object`&&!!e&&`role`in e&&`parts`in e&&!(`content`in e)&&typeof e.role==`string`&&Array.isArray(e.parts)}var ls={read:Xo,write:Zo,remove:Qo},us=class{constructor(e=ls){this.cache=e,this.rawHistoryPages=new Map,this.historyRevisions=new Map}cachedView(e){return ds(this.rawHistoryPage(e))}indexedView(e){return ds(this.rawHistoryPage(e),!0)}mergeHistory(e,t){return this.storeHistory(e,$o(this.rawHistoryPage(e),t))}mergeSnapshot(e,t){let n=this.rawHistoryPage(e);if(n!==void 0&&!es(n,t))return this.discard(e),this.storeHistory(e,t);let r=$o(n,t);return this.storeHistory(e,{...r,total:t.total})}storeHistory(e,t){return this.rawHistoryPages.set(e,t),this.cache.write(e,t),ds(t)}applyLiveEvent(e,t){return fo(e,t)}seedStreamingPartial(e,t){return uo(e,t)}historyRevision(e){return this.historyRevisions.get(e)??0}discard(e){this.historyRevisions.set(e,this.historyRevision(e)+1),this.rawHistoryPages.delete(e),this.cache.remove?.(e)}rawHistoryPage(e){let t=this.rawHistoryPages.get(e)??this.cache.read(e);return t!==void 0&&this.rawHistoryPages.set(e,t),t}};function ds(e,t=!1){let n=e?.start??0;return{messages:li(e?.messages??[],t||e!==void 0?n:void 0),messagePageStart:n,messagePageEnd:n+(e?.messages.length??0),messagePageTotal:e?.total??0,messagePageLeafId:e?.leafId}}function fs(e){return{builtin:D(`ui.settingsPluginsPanel.bundled`,`Bundled`),extension:D(`ui.main.17d13aa49d71`,`Extension`),prompt:D(`ui.main.2f0bb1238738`,`Prompt`),skill:D(`ui.chatView.skill`,`Skill`)}[e]}function ps(e,t=e.length){let n=e.slice(0,t),r=ys(n,t);if(r!==void 0)return r;let i=bs(n,t);if(i!==void 0)return i;let a=Math.max(n.lastIndexOf(` `),n.lastIndexOf(`
|
|
25
25
|
`))+1,o=n.slice(a);if(n.slice(0,a).endsWith(`@ `))return{kind:`file`,query:o,from:a-2,to:t,fileScope:`all`,allPrefix:`@ `};if(o.startsWith(`/`)&&a===0)return{kind:`command`,query:o.slice(1),from:a,to:t};if(o.startsWith(`!@`))return{kind:`file`,query:o.slice(2),from:a,to:t,fileScope:`all`,allPrefix:`!@`};if(o.startsWith(`@`))return{kind:`file`,query:o.slice(1),from:a,to:t,fileScope:`tracked`};if(o.startsWith(`#`))return{kind:`model`,query:o.slice(1),from:a,to:t}}var ms=12;function hs(e,t){let n=t.toLowerCase(),r=[];for(let t of e)if(gs(t)&&_s(t,n)&&(r.push({insertText:`#${t.provider}/${t.id}`,detail:t.provider,...t.name!==void 0&&t.name!==``&&t.name!==t.id?{description:t.name}:{}}),r.length>=ms))break;return r}function gs(e){return typeof e.provider==`string`&&e.provider!==``&&typeof e.id==`string`&&e.id!==``}function _s(e,t){return`${e.provider}/${e.id}`.toLowerCase().includes(t)||e.id.toLowerCase().includes(t)||(e.name?.toLowerCase().includes(t)??!1)}function vs(e,t,n){let r=n??`@`;return!t&&!e.includes(` `)?`${r}${e}`:`${r}"${e}"`}function ys(e,t){let n=e.lastIndexOf(`"`);if(n===-1)return;let r=e.slice(0,n);if(r.endsWith(`!@`))return{kind:`file`,query:e.slice(n+1),from:r.length-2,to:t,fileScope:`all`,allPrefix:`!@`,quoted:!0};if(r.endsWith(`@`))return{kind:`file`,query:e.slice(n+1),from:r.length-1,to:t,fileScope:`tracked`,quoted:!0};if(r.endsWith(`@ `))return{kind:`file`,query:e.slice(n+1),from:r.length-2,to:t,fileScope:`all`,allPrefix:`@ `,quoted:!0}}function bs(e,t){let n=e.lastIndexOf(`
|
|
26
26
|
`)+1,r=e.slice(n),i=xs(r,`@ `),a=xs(r,`!@`),o=Math.max(i,a);if(o===-1)return;let s=o===a?`!@`:`@ `,c=n+o,l=c+s.length;return{kind:`file`,query:e.slice(l),from:c,to:t,fileScope:`all`,allPrefix:s}}function xs(e,t){for(let n=e.lastIndexOf(t);n>=0;n=e.lastIndexOf(t,n-1))if(n===0||Ss(e[n-1]))return n;return-1}function Ss(e){return e===` `||e===` `}function Cs(e){let t=e.trimStart();if(t.startsWith(`!@`))return{kind:`file`};if(t.startsWith(`!`))return{kind:`shell`,excludeFromContext:t.startsWith(`!!`)};if(Es(e).startsWith(`/`))return{kind:`command`};let n=ps(e);return n?.kind===`file`?{kind:`file`}:n?.kind===`model`?{kind:`model`}:{kind:`normal`}}function ws(e){return Cs(e).kind===`shell`}function Ts(e,t){return e.kind===t.kind?e.kind===`shell`&&t.kind===`shell`?e.excludeFromContext===t.excludeFromContext:!0:!1}function Es(e){let t=Math.max(e.lastIndexOf(` `),e.lastIndexOf(`
|
|
27
|
-
`))+1;return e.slice(t)}var Ds=class{constructor(e=`normal`){this.scope=e,this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId=`local`}connect(e,t,n,r=`local`,i){this.close(),this.machineId=r,this.session=e,this.onEvent=t,this.onReconnect=n,this.onInitialOpen=i,this.shouldReconnect=!0,this.open()}setHandler(e){this.onEvent=e}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Fs(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.onInitialOpen=void 0,this.hasOpened=!1,this.machineId=`local`}open(){let e=this.session;if(e===void 0||e.id===``||e.cwd===``||!this.shouldReconnect)return;let t=zn(e,this.machineId,this.scope);this.socket=t,t.onopen=()=>{if(this.socket!==t)return;this.reconnectDelay=500;let e=this.hasOpened;this.hasOpened=!0,e?this.onReconnect?.():this.onInitialOpen?.()},t.onmessage=n=>void this.handleMessage(n.data,t,e),t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t,n){let r=ks(await Ps(e));this.socket===t&&r!==void 0&&(r.type===`session.diagnostic`?console.error(`[PI WEB] Session diagnostic`,{machineId:this.machineId,sessionId:n.id,cwd:n.cwd,message:r.message}):(r.type!==`notifications.inbox`||n.id===r.summary.sessionId&&n.cwd===r.summary.cwd)&&this.onEvent?.(r))}},Os=class{constructor(e=`normal`){this.scope=e,this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId=`local`}connect(e,t,n=`local`){this.close(),this.machineId=n,this.onEvent=e,this.onOpen=t,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Fs(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId=`local`}open(){if(!this.shouldReconnect)return;let e=Bn(this.machineId,this.scope);this.socket=e,e.onopen=()=>{this.socket===e&&(this.reconnectDelay=500,this.onOpen?.())},e.onmessage=t=>void this.handleMessage(t.data,e),e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t){let n=As(await Ps(e));this.socket===t&&n!==void 0&&this.onEvent?.(n)}};function ks(e){let t=Ns(e);if(t===`notifications.inbox`)return Ms(()=>he(e));if(t===`dialog.opened`)return Ms(()=>ae(e));if(t===`dialog.closed`)return Ms(()=>ee(e));let n=Ms(()=>a(e));return n===void 0?void 0:js(n,e)}function As(e){if(Ns(e)===`notices.updated`)return Ms(()=>p(e));if(Ns(e)===`sessions.unread`)return Ms(()=>Se(e));if(Ns(e)===`session.startup`)return Ms(()=>jt(e));if(typeof e==`object`&&e){if(Ns(e)===`terminal.created`||Ns(e)===`terminal.exited`){if(!(`terminal`in e))return;let t=Ms(()=>xe(e.terminal));return t===void 0?void 0:{type:Ns(e)===`terminal.created`?`terminal.created`:`terminal.exited`,terminal:t}}if(Ns(e)===`terminal.closed`)return!(`terminalId`in e)||typeof e.terminalId!=`string`||e.terminalId===``||!(`cwd`in e)||typeof e.cwd!=`string`||e.cwd===``?void 0:{type:`terminal.closed`,terminalId:e.terminalId,cwd:e.cwd};if(Ns(e)===`workspace.activity`){if(!(`activity`in e))return;let t=Ms(()=>we(e.activity));return t===void 0?void 0:{type:`workspace.activity`,activity:t}}}return Ms(()=>fe(e))}function js(e,t){return typeof t!=`object`||!t||!(`seq`in t)?e:typeof t.seq==`number`?{...e,seq:t.seq}:e}function Ms(e){try{return e()}catch{return}}function Ns(e){if(typeof e!=`object`||!e||!(`type`in e))return``;let t=e.type;return typeof t==`string`?t:``}async function Ps(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 Fs(e){e!==void 0&&(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING?e.onopen=()=>{e.close()}:e.close())}function Is(e){return e?.ok===!0}function Ls(e){return{authoritative:Is(e)}}function Rs(e,t,n={}){if(e===void 0)return`unknown`;let r=(t?.sessionId===e.id?t.persisted:void 0)??e.persisted;return r===!0?`persisted`:r===!1||$r(e)?`transient`:n.authoritative===!0?`unknown`:`persisted`}function zs(e,t,n){return e!==void 0&&e.archived!==!0&&Rs(e,t,n)===`persisted`}function Bs(e,t,n){return e!==void 0&&e.archived!==!0&&Rs(e,t,n)===`transient`}function Vs(){try{return typeof sessionStorage>`u`?void 0:sessionStorage}catch{return}}var Hs=class{constructor(e,t,n=Vs()){this.storageKey=e,this.storage=n,this.values=new Map;for(let[r,i]of Ws(e,t,n))this.values.set(r,i)}get(e){return this.values.get(e)}set(e,t){this.values.set(e,t),this.save()}delete(e){this.values.delete(e),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}let e={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(e))}catch{}}};function Us(e){return typeof e==`string`&&e!==``?e:void 0}function Ws(e,t,n){try{let r=n?.getItem(e);if(r==null||r===``)return[];let i=JSON.parse(r);if(!Gs(i))return[];let a=[];for(let e of i.entries){let n=e[0],r=t(e[1]);r!==void 0&&a.push([n,r])}return a}catch{return[]}}function Gs(e){return!Ks(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`&&e[0]!==``)}function Ks(e){return typeof e==`object`&&!!e}var qs=class{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}},Js=`pi-web:session-selection:v1`,Ys=class{constructor(e=Vs()){this.sessionIdsByCwd=new Hs(Js,Us,e)}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}};function Xs(e,t){let n=t?.targetSessionId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestSessionId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>e.archived!==!0):e.find(e=>e.archived!==!0)}function Zs(e,t){return t?.archived===!0&&!e.some(e=>e.archived!==!0)}function Qs(e,t,n){return $s(e,[t],n)}function $s(e,t,n){let r=new Set(t);return e.map(e=>r.has(e.id)?{...e,archived:!0,archivedAt:n}:e)}function ec(e,t,n){return tc(e,t,[n])}function tc(e,t,n){if(t===void 0||!n.includes(t))return{type:`unchanged`};let r=new Set(n),i=e.find(e=>!r.has(e.id)&&e.archived!==!0);return i===void 0?{type:`clear`}:{type:`select`,session:i}}var nc=/timed out|operation was aborted|request cancelled/i;function rc(e){return e instanceof te&&(e.status===504||e.status===499)||e instanceof Error&&nc.test(e.message)}function ic(e){return rc(e)?D(`ui.main.634a1618e706`,`The session daemon request timed out. The conversation is still running.`):e instanceof Error?e.message:String(e)}var ac=[500,1500,3e3],oc=Symbol(`retired-read`);async function sc(e,t,n,r=!0){let i=()=>n?.aborted!==!0&&t(),a=0;for(;i();)try{let t=await cc(e(),n);return t!==oc&&i()?t:void 0}catch(e){if(n?.aborted===!0||r&&!t())return;let i=ac[a];if(!r||!(e instanceof Oe)||i===void 0)throw e;let o;try{await cc(new Promise(e=>{o=setTimeout(e,i)}),n)}finally{o!==void 0&&clearTimeout(o)}a+=1}}function cc(e,t){if(t===void 0)return e;let n=()=>void 0,r=new Promise(e=>{n=()=>{e(oc)},t.addEventListener(`abort`,n,{once:!0}),t.aborted&&n()});return Promise.race([e,r]).finally(()=>{t.removeEventListener(`abort`,n)})}var lc=100,uc=500,dc=5e3,fc=[`machine`,`project`,`workspace`,`session`],pc=[`machine`,`project`,`workspace`,`session`],mc=class{constructor(e,t,n,r=new qs,i={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessionSelection=r,this.selectedSessionLoadDeferred=!1,this.selectionSeq=0,this.pendingTreeActions=new Set,this.disposed=!1,this.pendingTranscriptEvents=[],this.selectedReadGeneration=0,this.workspaceReadGeneration=0,this.selectedReadRecoveries=new Set,this.workspaceReadRecoveries=new Set,this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.sessionRefreshInFlight=!1,this.searchSeq=0,this.searchTargetSeq=0,this.pendingQueuedSendSeq=0,this.pendingSessionStarts=new Map,this.suppressedCreatedSessions=new Map,this.selectedSessionRefreshes=new gr,this.workspaceSessionRefreshes=new gr,this.socket=i.socket??new Ds,this.api=i.api??x,this.transcripts=i.transcripts??new us,this.transcriptSnapshot=i.transcriptSnapshot??((...e)=>this.api.transcriptSnapshot(...e)),this.notifications=i.notifications,this.automaticSessionCandidates=i.automaticSessionCandidates??(e=>e),this.replacePromptEditorText=i.replacePromptEditorText,this.canMutateQueueMessage=i.canMutateQueueMessage??(()=>!1),this.onSelectedSessionReady=i.onSelectedSessionReady,this.observeSessionSnapshot=i.observeSessionSnapshot,this.isChatVisible=i.isChatVisible??(()=>!0),this.isPendingSessionStartRouteCurrent=i.isPendingSessionStartRouteCurrent,this.onPendingSessionStartCommitted=i.onPendingSessionStartCommitted,this.onModelScopeChanged=i.onModelScopeChanged,this.navigateToSession=i.navigateToSession,this.captureNavigation=i.captureNavigation,this.beginNavigationOperation=i.beginNavigationOperation,this.browserErrors=new $n(e,t)}applyGlobalEvent(e){e.type===`status.update`?this.queueStatusUpdate(e.status):e.type===`activity.update`?this.queueActivityUpdate(e.activity):e.type===`session.created`?this.applyCreatedSession(e.session):e.type===`session.name`?this.applySessionName(e.sessionId,e.name):e.type===`models.changed`?this.onModelScopeChanged?.(e.revision):e.type===`session.startup`&&this.queueStartupProgress(e)}dispose(){this.disposed=!0,this.retireReadRecoveries([`machine`]),this.selectedSessionLoadDeferred=!1,this.selectionSeq+=1,this.searchSeq+=1,this.stopPolling(),this.searchTimer!==void 0&&clearTimeout(this.searchTimer),this.searchTimer=void 0,this.selectedSessionJoinNavigation=void 0,this.socket.close(),this.clearPendingUpdates()}updatePolling(){this.stopPolling(),this.getState().selectedWorkspace!==void 0&&(this.sessionPollTimer=setInterval(()=>{this.sessionRefreshInFlight||(this.sessionRefreshInFlight=!0,this.refreshCurrentWorkspaceSessions().finally(()=>{this.sessionRefreshInFlight=!1}))},dc))}clearActiveSession(){this.retireReadRecoveries([`session`]),this.selectedSessionLoadDeferred=!1,this.selectionSeq+=1,this.selectedSessionJoinNavigation=void 0,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0})}deselectSession(e){let t=this.getState(),n=t.selectedSession?.cwd??t.selectedWorkspace?.path;e?.forgetRememberedSelection===!0&&n!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(n)),this.clearActiveSession(),e?.updateUrl!==!1&&this.updateUrl()}async selectSessionAfterNavigation(e,t,n){this.navigateToSession===void 0?await this.selectSession(e,{updateUrl:n?.updateUrl}):await this.navigateToSession(e,{...n?.updateUrl===!1?{replace:!0}:{},expected:t})}async clearSessionAfterNavigation(e){if(!this.navigationSelectionMatchesState(e))return;let t=this.getState().selectedSession?.cwd??this.getState().selectedWorkspace?.path;this.navigateToSession===void 0?this.deselectSession({forgetRememberedSelection:!0}):(t!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(t)),await this.navigateToSession(void 0,{expected:e}))}async clearSelectionAfterArchivedCollapse(){let e=this.getState();Zs(this.automaticSessionCandidates(e.sessions),e.selectedSession)&&await this.clearSessionAfterNavigation(this.navigationSelection())}async startSession(e){let t=this.getState().selectedWorkspace;if(!t)return;let n=M(this.getState()),r=typeof e==`function`?e:void 0,i=typeof e==`function`?void 0:e,a=i?.updateUrl!==!1,o=this.createPendingSessionStart(t,n,this.navigationSelection(),a);this.pendingSessionStarts.set(o.tempId,o),this.insertAndSelectPendingSession(o.session,i),a&&(o.expectedNavigation=this.navigationSelection()),o.navigation=this.beginNavigationOperation?.(fc);try{if(r!==void 0&&!await r()){this.cancelUnstartedSession(o);return}let e=await this.api.startSession(t.path,n,o.tempId);await this.resolvePendingSessionStart(o.tempId,e)}catch(e){this.failPendingSessionStart(o.tempId,e)}}async refreshPinnedSessions(e,t=M(this.getState())){try{let n=await this.api.pinned(e,t);if(M(this.getState())!==t||this.getState().selectedWorkspace?.path!==e)return;this.setState({pinnedSessionIds:n.sessionIds})}catch{M(this.getState())===t&&this.getState().selectedWorkspace?.path===e&&this.setState({pinnedSessionIds:[]})}}togglePinned(e){if(e.persisted===!1)return;let t=this.getState(),n=t.pinnedSessionIds.includes(e.id),r=n?t.pinnedSessionIds.filter(t=>t!==e.id):[...t.pinnedSessionIds,e.id],i=M(t);this.setState({pinnedSessionIds:r}),(async()=>{try{let t=n?await this.api.unpin(e,i):await this.api.pin(e,i),r=this.getState();if(M(r)!==i||r.selectedWorkspace?.path!==e.cwd)return;let a=t.pinned;this.setState({pinnedSessionIds:a?[...new Set([...this.getState().pinnedSessionIds,e.id])]:this.getState().pinnedSessionIds.filter(t=>t!==e.id)})}catch(t){let r=this.getState();if(M(r)!==i||r.selectedWorkspace?.path!==e.cwd)return;this.setState({pinnedSessionIds:n?[...new Set([...r.pinnedSessionIds,e.id])]:r.pinnedSessionIds.filter(t=>t!==e.id)}),this.reportSessionError(e,i,t)}})()}searchSessions(e){let t=this.getState(),n=t.selectedWorkspace,r=M(t);this.searchSeq+=1;let i=this.searchSeq;this.searchTimer!==void 0&&clearTimeout(this.searchTimer),this.searchTimer=void 0,this.setState({sessionSearchQuery:e,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``});let a=e.trim();n!==void 0&&a!==``&&(this.setState({isSearchingSessions:!0}),this.searchTimer=setTimeout(()=>{this.searchTimer=void 0,this.performSessionSearch(i,a,n.id,n.path,r)},250))}async performSessionSearch(e,t,n,r,i){try{let a=await this.api.searchContent(r,t,i),o=this.getState();if(e!==this.searchSeq||M(o)!==i||o.selectedWorkspace?.id!==n||o.sessionSearchQuery.trim()!==t)return;this.setState({sessionSearchResults:a,isSearchingSessions:!1})}catch(t){let r=this.getState();if(e!==this.searchSeq||M(r)!==i||r.selectedWorkspace?.id!==n)return;this.setState({sessionSearchResults:{results:[],matchCount:0,truncated:!1},isSearchingSessions:!1,sessionSearchError:String(t)})}}preferredSession(e,t,n){if(Ca(n)){let t=this.pendingSessionStarts.get(n);return t!==void 0&&!t.discarded&&t.cwd===e&&this.isCurrentPendingStart(t)?t.session:void 0}let r=this.sessionSelection.latestSessionId(this.workspaceSelectionKey(e));return n!==void 0&&n!==``||r!==void 0&&r!==``&&t.some(e=>e.id===r)?Xs(t,{targetSessionId:n,latestSessionId:r}):Xs(this.automaticSessionCandidates(t))}canReuseSelectedSession(){return!this.disposed&&Nc(this.selectedSessionJoinNavigation)}get isChatLoadDeferred(){return this.selectedSessionLoadDeferred}async loadSelectedSession(){if(this.disposed||!this.selectedSessionLoadDeferred||!this.isChatVisible())return;let e=this.getState().selectedSession;if(e===void 0)return;let t=this.beginNavigationOperation?.(pc);await this.selectSession(e,{updateUrl:!1,navigation:t})}async selectSession(e,t){if(this.disposed||!Nc(t?.navigation))return;if(this.retireReadRecoveries([`session`]),I(e)){this.selectClientPendingStartSession(e,t);return}let n=M(this.getState()),r=this.captureSessionErrorOwner(e);this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)});let i=++this.selectionSeq;this.selectedSessionJoinNavigation=t?.navigation,this.socket.close(),this.streamWatermark=void 0,this.clearPendingUpdates(),this.selectedSessionLoadDeferred=t?.deferChatLoading===!0||!this.isChatVisible(),this.selectedSessionLoadDeferred?this.notifications?.clearSelectedSession():this.notifications?.prepareSelectedSession(e,n);let a=this.sessionCacheKey(e.id),o=this.selectedSessionLoadDeferred?{messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,messagePageLeafId:void 0}:this.transcripts.cachedView(a);if(this.setState({selectedSession:e,sessionSearchTarget:void 0,...o,isLoadingEarlierMessages:!1,...t?.preserveTreeDialog===!0?{}:{treeDialog:void 0},status:e.archived===!0?void 0:this.getState().sessionStatuses[e.id],activity:e.archived===!0?void 0:this.getState().sessionActivities[e.id],pendingDialogs:e.archived===!0?[]:this.getState().sessionStatuses[e.id]?.pendingDialogs??[],closedDialogs:[],availableThinkingLevels:[]}),this.selectedSessionLoadDeferred){this.selectedSessionJoinNavigation=void 0,t?.updateUrl!==!1&&this.updateUrl();return}let s=!1;try{if(e.archived===!0){let o=this.browserErrors.captureRecovery(Kn(n,e.id,r),`session-refresh`),s=await this.api.messages(e,{limit:lc},n),c=this.getState().selectedSession;if(i!==this.selectionSeq||M(this.getState())!==n||c?.id!==e.id||c.cwd!==e.cwd||c.path!==e.path||c.archived!==e.archived||!Nc(t?.navigation))return;this.browserErrors.clearRecovered(o);let l=this.transcripts.mergeHistory(a,s);this.setState({...l,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingDialogs:[],closedDialogs:[]}),this.onSelectedSessionReady?.({machineId:n,session:e}),t?.updateUrl!==!1&&this.updateUrl();return}this.socket.connect(e,t=>{this.isCurrentSessionSelection(e.id,n,i)&&this.applyEvent(t)},()=>{this.isCurrentSessionSelection(e.id,n,i)&&this.isSelectedSessionScope(e,n)&&this.refreshSelectedSession(e.id,{recoverNetwork:!0})},n,()=>{let t=this.getState().selectedSession;this.isCurrentSessionSelection(e.id,n,i)&&t?.cwd===e.cwd&&t.path===e.path&&this.refreshSessionNotifications(e,n)}),s=!0;let o={session:e,machineId:n,selectionSeq:i,errorOwner:r,...t?.navigation===void 0?{}:{navigation:t.navigation}};if(t?.propagateRefreshError===!0)await this.requestSelectedSessionRefresh(o);else if(!await this.joinSelectedSessionSnapshot(o))return;if(!this.isCurrentRefreshTarget(o)||!Nc(t?.navigation))return;this.refreshAvailableThinkingLevels(),this.onSelectedSessionReady?.({machineId:n,session:e}),t?.updateUrl!==!1&&this.updateUrl()}catch(a){let o=Nc(t?.navigation);if(!o||i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id){if(this.reportSessionError(e,n,a,r),t?.propagateRefreshError===!0&&o&&this.isSelectedSessionIdentity(e.id,n))throw a;return}if($r(e)&&Mc(a)){await this.recreateCachedNewSession(e,t,i,r);return}if(this.reportSessionError(e,n,a,r),t?.propagateRefreshError===!0)throw a}finally{let r=Nc(t?.navigation);i===this.selectionSeq&&r&&(this.selectedSessionJoinNavigation=void 0),s&&!Nc(t?.navigation)&&this.isCurrentSessionSelection(e.id,n,i)&&this.socket.close()}}async loadEarlierMessages(){let e=this.getState(),t=e.selectedSession;if(!t||e.isLoadingEarlierMessages||e.messagePageStart<=0)return;let n=M(e),r=this.captureSessionErrorOwner(t),i=this.selectionSeq,a=j(n,t.id),o=this.transcripts.historyRevision(a),s=()=>{let e=this.getState();return!this.disposed&&i===this.selectionSeq&&M(e)===n&&e.selectedSession?.id===t.id&&e.selectedSession.cwd===t.cwd&&e.selectedSession.path===t.path&&e.selectedSession.archived===t.archived};this.setState({isLoadingEarlierMessages:!0});try{let r=await this.api.messages(t,{before:e.messagePageStart,limit:lc},n);if(!s()||this.transcripts.historyRevision(a)!==o)return;let i=this.transcripts.mergeHistory(a,r);this.setState(i)}catch(e){if(!s())return;this.reportSessionError(t,n,e,r)}finally{s()&&this.setState({isLoadingEarlierMessages:!1})}}async send(e,t,n,r=`inline`,i,a){let o=this.getState(),s=o.selectedSession;if(!s||s.archived===!0||a!==void 0&&(!Ma(a,{machineId:M(o),sessionId:s.id,cwd:s.cwd})||I(s)))return!1;let c=e.trim(),l=n!==void 0&&n.length>0,u=a!==void 0;if(I(s))return!l&&c.startsWith(`/`)?this.enqueuePendingSessionSend(s,{type:`command`,text:e}):!l&&ws(e)?this.enqueuePendingSessionSend(s,{type:`shell`,text:e}):this.enqueuePendingSessionSend(s,{type:`prompt`,text:e,streamingBehavior:t,attachments:n,delivery:r,folder:i}),!1;if(!u&&!l&&c.startsWith(`/`))return await this.runCommand(e),!1;if(!u&&!l&&ws(e))return await this.runShell(e),!1;let d=M(this.getState()),f=this.captureSessionErrorOwner(s);return this.deliverPromptToSession(s,e,t,n,r,i,d,{markSending:l||u},f)}markSendingPrompt(e,t){let n=this.getState().sendingPrompts;t?n[e]!==!0&&this.setState({sendingPrompts:{...n,[e]:!0}}):e in n&&this.setState({sendingPrompts:_c(n,e)})}async runShell(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;if(I(t)){this.enqueuePendingSessionSend(t,{type:`shell`,text:e});return}let n=M(this.getState()),r=this.captureSessionErrorOwner(t);await this.deliverShellToSession(t,e,n,{optimisticLine:!0},r)}async runCommand(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;if(I(t)){this.enqueuePendingSessionSend(t,{type:`command`,text:e});return}let n=M(this.getState()),r=this.captureSessionErrorOwner(t);await this.deliverCommandToSession(t,e,n,{applyResult:!0},r)}async renameSession(e,t){let n=t.trim();if(n===``||!zs(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let r=M(this.getState()),i=this.getState().selectedWorkspace,a=this.captureSessionErrorOwner(e);try{let t=await this.api.runCommand(e,`/name ${n}`,r);if(t.type===`done`){let a=this.getState();if(this.disposed||M(a)!==r||a.selectedWorkspace?.id!==i?.id||a.selectedWorkspace?.projectId!==i?.projectId||a.selectedWorkspace?.path!==i?.path||!a.sessions.some(t=>t.id===e.id&&t.cwd===e.cwd&&t.path===e.path))return;this.applySessionName(e.id,t.session?.name??n);return}this.reportSessionError(e,r,t.type===`unsupported`?t.message:D(`client.sessionController.failed.to.rename.session.702159`,`Failed to rename session`),a)}catch(t){this.reportSessionError(e,r,t,a)}}enqueuePendingSessionSend(e,t){let n=this.pendingSessionStarts.get(e.id);if(n===void 0||n.discarded){let t=this.captureSessionErrorOwner(e,n?.originWorkspace);this.reportSessionError(e,e.machineId,D(`client.sessionController.the.backend.session.is.not.ready.to.send.queued.messages.copy.your.mes.22460a`,`The backend session is not ready to send queued messages. Copy your messages before discarding this failed start.`),t);return}let r={...t,id:`pending-send-${String(++this.pendingQueuedSendSeq)}`};n.queuedSends.push(r);let i=this.getState(),a=i.clientQueuedSessionMessages[e.id]??[],o=Sc(e.id,n.queuedSends.length);this.setState({clientQueuedSessionMessages:{...i.clientQueuedSessionMessages,[e.id]:[...a,wc(r)]},sessionActivities:{...i.sessionActivities,[e.id]:o},activity:i.selectedSession?.id===e.id?o:i.activity,error:``})}async flushQueuedPendingSends(e,t,n,r){for(let i of n){if(!await this.deliverQueuedPendingSend(e,t,i,r))return;this.dropNextQueuedSessionMessage(e.id)}}async deliverQueuedPendingSend(e,t,n,r){return n.type===`prompt`?this.deliverPromptToSession(e,n.text,n.streamingBehavior,n.attachments,n.delivery,n.folder,t,{markSending:!0},r):n.type===`shell`?this.deliverShellToSession(e,n.text,t,{optimisticLine:!0},r):this.deliverCommandToSession(e,n.text,t,{applyResult:!0},r)}async deliverPromptToSession(e,t,n,r,i,a,o,s,c){let l=r!==void 0&&r.length>0;s.markSending&&this.markSendingPrompt(e.id,!0);try{if(l&&i===`folder`){let i=(await this.api.saveAttachments(e,r,o,a)).map(e=>vs(e.path,!1)).join(` `),s=t===``?i:`${t}\n\n${i}`;await this.api.prompt(e,s,n,o)}else await this.api.prompt(e,t,n,o,r);return this.markCachedNewSessionPersisted(e),!0}catch(t){return this.reportSessionError(e,o,t,c),!1}finally{s.markSending&&this.markSendingPrompt(e.id,!1)}}async deliverShellToSession(e,t,n,r,i){r.optimisticLine&&this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ui(`user`,t)]});try{return await this.api.shell(e,t,n),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ui(`system`,ic(t))]}),this.reportSessionError(e,n,t,i),!1}}async deliverCommandToSession(e,t,n,r,i){let a=this.navigationSelection();this.markSendingPrompt(e.id,!0);try{let o=await this.api.runCommand(e,t,n);return r.applyResult&&this.isSelectedSessionIdentity(e.id,n)?await this.applyCommandResult(o,a):(o.type===`select`||o.type===`tree`)&&this.reportSessionError(e,n,D(`client.sessionController.queued.command.requires.input.open.the.session.and.run.it.again.2a98cf`,`Queued command "{value1}" requires input; open the session and run it again.`,{value1:t}),i),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ui(`system`,ic(t))]}),this.reportSessionError(e,n,t,i),!1}finally{this.markSendingPrompt(e.id,!1)}}dropNextQueuedSessionMessage(e){let t=this.getState(),n=t.clientQueuedSessionMessages[e]??[];if(n.length===0)return;let r=n.slice(1);this.setState({clientQueuedSessionMessages:r.length===0?_c(t.clientQueuedSessionMessages,e):{...t.clientQueuedSessionMessages,[e]:r}})}async respondToCommand(e,t){let n=this.getState().selectedSession;if(!n)return;let r=M(this.getState()),i=this.captureSessionErrorOwner(n),a=this.navigationSelection();this.setState({commandDialog:void 0});try{let i=await this.api.respondToCommand(n,e,t,r);this.isSelectedSessionIdentity(n.id,r)&&await this.applyCommandResult(i,a)}catch(e){this.reportSessionError(n,r,e,i)}}cancelCommand(){this.setState({commandDialog:void 0})}async actOnMessage(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0||I(r))return;let i=M(n),a=this.selectionSeq,o=this.captureSessionErrorOwner(r),s;try{if(s=await this.api.runCommand(r,`/tree`,i),s.type!==`tree`)throw Error(`message`in s?s.message:D(`ui.main.8bcdd03f7054`,`Session history is unavailable.`));if(!s.tree.nodes.some(t=>t.id===e))throw Error(D(`ui.main.e92706bbbf62`,`This message is no longer available in session history.`))}catch(e){throw this.reportSessionError(r,i,e,o),e}this.isCurrentSessionSelection(r.id,i,a)&&this.isSelectedSessionScope(r,i)&&(t===`fork`?await this.forkSessionTree(e,s.tree,!0):await this.navigateSessionTree(e,{mode:`none`},s.tree,!0))}async navigateTree(e,t){return this.navigateSessionTree(e,t,this.getState().treeDialog)}async navigateSessionTree(e,t,n,r){let i=this.getState(),a=i.selectedSession;if(a===void 0||n===void 0||a.archived===!0||I(a))throw Error(D(`client.sessionController.session.tree.navigator.is.no.longer.available.34846d`,`Session tree navigator is no longer available`));let o={...a},s=M(i),c=this.captureSessionErrorOwner(o),l={machineId:s,sessionId:o.id};this.setTreeActionPending(l,!0);try{let i=await this.api.navigateTree(o,{targetId:e,expectedLeafId:n.activeLeafId,summary:t,...r===void 0?{}:{retainCheckpoint:r}},s);return await this.applySessionTreeNavigationResult(o,s,i,n),i}catch(e){throw this.reportSessionError(o,s,e,c),e}finally{this.setTreeActionPending(l,!1)}}async applySessionTreeNavigationResult(e,t,n,r){if(n.cancelled||this.disposed)return;if(this.hasDraftIdentityConflict(e,t)){this.reportSessionError(e,t,D(`client.sessionController.queueContextChanged`,`The conversation context changed before the result returned. The current draft was preserved.`));return}let i=j(t,e.id),a=n.editorText;if(a!==void 0&&za(i,a),this.transcripts.discard(i),!this.isSelectedSessionScope(e,t))return;this.clearPendingUpdates();let o=this.selectionSeq,s=()=>this.isCurrentSessionSelection(e.id,t,o)&&this.isSelectedSessionScope(e,t),c=(async()=>{a!==void 0&&s()&&await this.replacePromptEditorText?.({machineId:t,sessionId:e.id,text:a,isCurrent:s})})(),[l,u]=await Promise.allSettled([c,this.requestSelectedSessionRefresh({session:e,machineId:t,selectionSeq:o,errorOwner:this.captureSessionErrorOwner(e)})]);if(s()){if(l.status===`rejected`)throw l.reason;if(u.status===`rejected`)throw u.reason;this.getState().treeDialog===r&&this.setState({treeDialog:void 0})}}async forkFromTree(e){return this.forkSessionTree(e,this.getState().treeDialog)}async forkSessionTree(e,t,n){let r=this.getState(),i=r.selectedSession;if(i===void 0||t===void 0||i.archived===!0||I(i))throw Error(D(`client.sessionController.session.tree.navigator.is.no.longer.available.34846d`,`Session tree navigator is no longer available`));let a={...i},o=M(r),s=this.captureSessionErrorOwner(a),c=this.navigationSelection(),l={machineId:o,sessionId:a.id};this.setTreeActionPending(l,!0);try{let r=await this.api.forkTree(a,{entryId:e,expectedLeafId:t.activeLeafId,...n===void 0?{}:{retainCheckpoint:n}},o);return await this.applySessionTreeForkResult(a,o,r,c,t),r}catch(e){throw this.reportSessionError(a,o,e,s),e}finally{this.setTreeActionPending(l,!1)}}async applySessionTreeForkResult(e,t,n,r,i){if(n.cancelled)return;let a=j(t,e.id),o=n.session;if(o.id===e.id){await this.applySessionTreeNavigationResult(e,t,{cancelled:!1,...n.promptDraft===void 0?{}:{editorText:n.promptDraft}},i);return}if(n.promptDraft!==void 0&&za(j(t,o.id),n.promptDraft),this.transcripts.discard(a),!this.isSelectedSessionScope(e,t))return;let s=[o,...this.getState().sessions.filter(e=>e.id!==o.id)];this.setState({sessions:s}),this.navigateToSession===void 0?(this.setState({treeDialog:void 0}),await this.selectSession(o)):await this.navigateToSession(o,{expected:r})&&this.isSelectedSessionIdentity(o.id,t)&&this.getState().treeDialog===i&&this.setState({treeDialog:void 0})}async abortTreeNavigation(){let e=this.getState(),t=e.selectedSession;if(t===void 0||e.treeDialog===void 0||I(t))return;let n=M(e),r=this.captureSessionErrorOwner(t);try{await this.api.abort(t,n)}catch(e){throw this.reportSessionError(t,n,e,r),e}}closeTreeDialog(){this.setState({treeDialog:void 0})}applySessionStatus(e){this.applyStatus(e)}archiveScopeProjectId(){return Gt()?this.getState().selectedProject?.id:void 0}async useSuggestedInput(e,t){if(!this.isSelectedSessionIdentity(t,e))return;let n=this.getState(),r=n.selectedSession,i=n.status?.sessionId===t?n.status.suggestedInput:void 0;if(r===void 0||i===void 0)return;let a=this.captureSessionErrorOwner(r);za(j(e,t),i);try{await this.replacePromptEditorText?.({machineId:e,sessionId:t,text:i})}catch(t){this.reportSessionError(r,e,t,a)}}invalidateSessionTree(){let e=this.getState(),t=e.selectedSession,n=M(e);t!==void 0&&this.isSelectedSessionIdentity(t.id,n)&&(this.transcripts.discard(j(n,t.id)),this.clearPendingUpdates(),this.refreshSelectedSession(t.id),e.treeDialog!==void 0&&!this.hasPendingTreeAction(n,t.id)&&this.setState({treeDialog:void 0}))}hasPendingTreeAction(e,t){return[...this.pendingTreeActions].some(n=>n.machineId===e&&n.sessionId===t)}setTreeActionPending(e,t){t?this.pendingTreeActions.add(e):this.pendingTreeActions.delete(e),this.disposed||this.setState({pendingTreeActions:[...this.pendingTreeActions]})}async archiveSession(e=this.getState().selectedSession){if(!e)return;let t=this.statusForSession(e),n=this.sessionPersistenceOptions();if(Bs(e,t,n)){await this.deleteCachedNewSession(e);return}if(!zs(e,t,n))return;let r=M(this.getState()),i=this.captureSessionErrorOwner(e);try{await this.api.archive(e,r,this.archiveScopeProjectId());let t=this.getState(),n=Qs(t.sessions,e.id,new Date().toISOString()),i=ec(this.automaticSessionCandidates(n),t.selectedSession?.id,e.id);this.setState({sessions:n});let a=this.navigationSelection();i.type===`select`?await this.selectSessionAfterNavigation(i.session,a):i.type===`clear`&&await this.clearSessionAfterNavigation(a)}catch(t){this.reportSessionError(e,r,t,i)}}async archiveSessionWithDescendants(e=this.getState().selectedSession){if(e===void 0||!zs(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{let n=await this.api.archiveWithDescendants(e,t,this.archiveScopeProjectId()),r=n.sessionIds!==void 0&&n.sessionIds.length>0?n.sessionIds:[e.id],i=this.getState(),a=$s(i.sessions,r,new Date().toISOString()),o=tc(this.automaticSessionCandidates(a),i.selectedSession?.id,r);this.setState({sessions:a});let s=this.navigationSelection();o.type===`select`?await this.selectSessionAfterNavigation(o.session,s):o.type===`clear`&&await this.clearSessionAfterNavigation(s)}catch(r){this.reportSessionError(e,t,r,n)}}async archiveSessions(e){let t=this.sessionPersistenceOptions(),n=Dc(e).filter(e=>zs(e,this.statusForSession(e),t));if(n.length===0)return;let r=M(this.getState()),i=this.getState().selectedWorkspace,a=n[0];if(a===void 0)return;let o=this.captureSessionErrorOwner(a,i);try{let{succeededIds:e,failures:t,generatedAt:s}=await this.archiveSessionBatch(n,r);if(e.length>0){let t=this.getState(),n=$s(t.sessions,e,s??new Date().toISOString()),r=tc(this.automaticSessionCandidates(n),t.selectedSession?.id,e);this.setState({sessions:n});let i=this.navigationSelection();r.type===`select`?await this.selectSessionAfterNavigation(r.session,i):r.type===`clear`&&await this.clearSessionAfterNavigation(i)}this.applyBulkSessionFailures(D(`ui.sessionCleanupDialog.archive`,`Archive`),t,r,i,a,o)}catch(e){this.reportWorkspaceOrSessionError(i,a,r,D(`client.sessionController.archive.failed.aaa500`,`Archive failed: {value1}`,{value1:kc(e)}),o)}}async deleteArchivedSessions(e){let t=Dc(e).filter(e=>e.archived===!0);if(t.length===0)return;let n=M(this.getState()),r=this.getState().selectedWorkspace,i=t[0];if(i===void 0)return;let a=this.captureSessionErrorOwner(i,r);try{let{succeededIds:e,failures:o}=await this.deleteArchivedSessionBatch(t,n);if(e.length>0){let r=new Set(e),i=this.getState(),a=i.sessions.filter(e=>!r.has(e.id));if(this.setState({sessions:a}),i.selectedSession!==void 0&&r.has(i.selectedSession.id)){let e=this.navigationSelection(),t=this.automaticSessionCandidates(a),n=t.find(e=>e.archived!==!0)??t[0];n===void 0?await this.clearSessionAfterNavigation(e):await this.selectSessionAfterNavigation(n,e)}await this.refreshPinnedSessions(t[0]?.cwd??``,n)}this.applyBulkSessionFailures(D(`ui.sessionList.delete`,`Delete`),o,n,r,i,a)}catch(e){this.reportWorkspaceOrSessionError(r,i,n,D(`client.sessionController.delete.failed.59ec26`,`Delete failed: {value1}`,{value1:kc(e)}),a)}}async archiveSessionBatch(e,t){let n=await this.api.archiveMany(e,t,this.archiveScopeProjectId());return{succeededIds:n.archivedSessionIds,failures:Oc(n.failures),generatedAt:n.generatedAt}}async deleteArchivedSessionBatch(e,t){let n=await this.api.deleteArchivedMany(e,t,this.archiveScopeProjectId());return{succeededIds:n.deletedSessionIds,failures:Oc(n.failures)}}async applySessionCleanupResult(e,t=M(this.getState())){if(M(this.getState())!==t)return;let n=e.archivedSessionIds,r=e.deletedSessionIds;if(n.length>0||r.length>0){let t=this.getState(),i=new Set(r),a=[...n,...r],o=$s(t.sessions,n,e.generatedAt).filter(e=>!i.has(e.id)),s=t.selectedSession!==void 0&&a.includes(t.selectedSession.id);this.setState({sessions:o,sessionStatuses:vc(t.sessionStatuses,a),sessionActivities:vc(t.sessionActivities,a),...s?{status:void 0,activity:void 0,pendingDialogs:[],closedDialogs:[]}:{}});let c=this.navigationSelection();if(t.selectedSession!==void 0&&i.has(t.selectedSession.id)){let e=this.automaticSessionCandidates(o),t=e.find(e=>e.archived!==!0)??e[0];t===void 0?await this.clearSessionAfterNavigation(c):await this.selectSessionAfterNavigation(t,c)}else{let e=tc(this.automaticSessionCandidates(o),t.selectedSession?.id,n);e.type===`select`?await this.selectSessionAfterNavigation(e.session,c):e.type===`clear`&&await this.clearSessionAfterNavigation(c)}}await this.refreshCurrentWorkspaceSessions(t)}retireReadRecoveries(e){let t=e.some(e=>e===`machine`||e===`project`||e===`workspace`);if(t||e.includes(`session`)){this.selectedReadGeneration+=1;for(let e of this.selectedReadRecoveries)e.abort();this.selectedReadRecoveries.clear(),this.refreshEventBuffer=void 0}if(t){this.workspaceReadGeneration+=1;for(let e of this.workspaceReadRecoveries)e.abort();this.workspaceReadRecoveries.clear()}}async refreshCurrentWorkspaceSessions(e=M(this.getState()),t){let n=this.getState().selectedWorkspace;if(n===void 0)return;let r=this.workspaceReadGeneration,i=this.beginNavigationOperation?.([`machine`,`project`,`workspace`]),a=()=>!this.disposed&&r===this.workspaceReadGeneration&&Nc(i)&&M(this.getState())===e&&this.getState().selectedWorkspace?.id===n.id&&this.getState().selectedWorkspace?.projectId===n.projectId&&this.getState().selectedWorkspace?.path===n.path,o=Gn(e,n.projectId,n.id);try{await this.workspaceSessionRefreshes.request(JSON.stringify([e,n.projectId,n.id,n.path]),async()=>{if(!a())return;let r=this.browserErrors.captureRecovery(o,`workspace-sessions-refresh`),i=()=>this.api.sessions(n.path,e),s=new AbortController;this.workspaceReadRecoveries.add(s);let c;try{c=await sc(i,a,s.signal,t?.recoverNetwork===!0)}finally{this.workspaceReadRecoveries.delete(s)}if(c===void 0||!a())return;this.browserErrors.clearRecovered(r);let l=Qr(n.path,c,e).filter(t=>!this.isSuppressedCreatedSession(t,e)),u=this.mergePendingStartSessions(n.path,l,e),d=this.getState().selectedSession;this.setState({sessions:u}),this.refreshPinnedSessions(n.path,e);let f=this.navigationSelection();if(d===void 0)return;let p=u.find(e=>e.id===d.id);if(p!==void 0){p!==d&&this.setState({selectedSession:p});return}let m=this.automaticSessionCandidates(u),h=m.find(e=>e.archived!==!0)??m[0];h===void 0?await this.clearSessionAfterNavigation(f):await this.selectSessionAfterNavigation(h,f)})}catch(i){if(this.disposed||r!==this.workspaceReadGeneration||t?.recoverNetwork===!0&&!a())return;if(i instanceof Oe){this.browserErrors.report(o,D(`client.sessionController.sessionListRefreshUnavailable`,`The session list could not be refreshed. Check your connection and retry.`),`workspace-sessions-refresh`);return}if(rc(i)){console.warn(`Workspace session list refresh timed out`,{machineId:e,workspaceId:n.id,errorCategory:`session-list-refresh`});return}this.reportWorkspaceError(n,e,i)}}stopPolling(){this.sessionPollTimer!==void 0&&clearInterval(this.sessionPollTimer),this.sessionPollTimer=void 0,this.sessionRefreshInFlight=!1}async deleteCachedNewSession(e=this.getState().selectedSession){if(e===void 0||!Bs(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=I(e)?this.pendingSessionStarts.get(e.id):void 0;t===void 0?this.api.stop(e,M(this.getState())).catch(()=>{}):(t.discarded=!0,t.queuedSends=[]),Zr(e.id,M(this.getState())),Ba(this.sessionCacheKey(e.id)),Ka(this.sessionCacheKey(e.id));let n=this.getState(),r=n.sessions.filter(t=>t.id!==e.id);if(this.setState({sessions:r,sessionStatuses:_c(n.sessionStatuses,e.id),sessionActivities:gc(n.sessionActivities,e.id),sendingPrompts:_c(n.sendingPrompts,e.id),clientQueuedSessionMessages:_c(n.clientQueuedSessionMessages,e.id)}),this.getState().selectedSession?.id!==e.id)return;let i=this.navigationSelection(),a=this.automaticSessionCandidates(r),o=a.find(e=>e.archived!==!0)??a[0];o===void 0?await this.clearSessionAfterNavigation(i):await this.selectSessionAfterNavigation(o,i)}async restoreSession(e=this.getState().selectedSession){if(!e)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e),r=this.selectionSeq,i=this.beginNavigationOperation?.(pc);try{await this.api.restore(e,t,this.archiveScopeProjectId())}catch(r){this.reportSessionError(e,t,r,n);return}if(!this.isCurrentRestoreOperation(t,r,i))return;let a={...e};delete a.archived,delete a.archivedAt;let o=this.getState().selectedSession?.id===a.id;this.replaceSession(a),o&&await this.selectSession(a,{updateUrl:!1,...i===void 0?{}:{navigation:i}})}async reloadSession(e=this.getState().selectedSession){if(e===void 0||!zs(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.reloadSession(e,t),this.transcripts.discard(j(t,e.id)),this.isSelectedSessionIdentity(e.id,t)&&await this.selectSession(e,{updateUrl:!1})}catch(r){this.reportSessionError(e,t,r,n)}}async detachParent(e=this.getState().selectedSession){if(e?.parentSessionPath===void 0)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.detachParent(e,t);let n=this.getState();if(this.disposed||M(n)!==t)return;let r=t=>{if(t.id!==e.id||t.cwd!==e.cwd)return t;let n={...t};return delete n.parentSessionPath,delete n.agentSubsession,n};this.setState({sessions:n.sessions.map(r),selectedSession:n.selectedSession===void 0?void 0:r(n.selectedSession)})}catch(r){this.reportSessionError(e,t,r,n)}}async listModels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{return(await this.api.models(e,t)).models}catch(r){return this.reportSessionError(e,t,r,n),[]}}async listModelCatalog(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{return(await this.api.modelCatalog(e,t)).models}catch(r){return this.reportSessionError(e,t,r,n),[]}}async setModelEnabled(e,t,n){let r=this.getState().selectedSession;if(!r||r.archived===!0)return;let i=M(this.getState()),a=this.captureSessionErrorOwner(r);try{return(await this.api.setModelEnabled(r,e,t,n,i)).models}catch(e){this.reportSessionError(r,i,e,a);return}}async setModelScope(e){let t=this.getState(),n=t.selectedSession;if(!n||n.archived===!0)return;let r=M(t),i=this.captureSessionErrorOwner(n);try{return(await this.api.setModelScope(n,e,r)).models}catch(e){this.reportSessionError(n,r,e,i);return}}async getSessionDefaults(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{return await this.api.getSessionDefaults(e,t)}catch(r){this.reportSessionError(e,t,r,n);return}}async setSessionDefaults(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;let n=M(this.getState()),r=this.captureSessionErrorOwner(t);try{return await this.api.setSessionDefaults(t,e,n)}catch(e){this.reportSessionError(t,n,e,r);return}}async setModel(e,t){let n=this.getState().selectedSession;if(!n||n.archived===!0)return;let r=M(this.getState()),i=this.captureSessionErrorOwner(n);try{let i=await this.api.setModel(n,e,t,r);if(M(this.getState())!==r)return;this.applyStatus(i),this.isSelectedSessionIdentity(n.id,r)&&await this.refreshAvailableThinkingLevels()}catch(e){this.reportSessionError(n,r,e,i)}}async cycleModel(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;let n=M(this.getState()),r=this.captureSessionErrorOwner(t);try{let r=await this.api.cycleModel(t,e,n);if(M(this.getState())!==n)return;this.applyStatus(r),this.isSelectedSessionIdentity(t.id,n)&&await this.refreshAvailableThinkingLevels()}catch(e){this.reportSessionError(t,n,e,r)}}async listThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{return(await this.api.thinkingLevels(e,t)).levels}catch(r){return this.reportSessionError(e,t,r,n),[]}}async refreshAvailableThinkingLevels(){let e=this.getState().selectedSession,t=M(this.getState());if(!e||e.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}let n=await this.listThinkingLevels();this.isSelectedSessionIdentity(e.id,t)&&this.setState({availableThinkingLevels:n})}async setThinkingLevel(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;let n=M(this.getState()),r=this.captureSessionErrorOwner(t);try{let r=await this.api.setThinkingLevel(t,e,n);if(M(this.getState())!==n)return;this.applyStatus(r)}catch(e){this.reportSessionError(t,n,e,r)}}async cycleThinkingLevel(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{let n=await this.api.cycleThinkingLevel(e,t);if(M(this.getState())!==t)return;this.applyStatus(n)}catch(r){this.reportSessionError(e,t,r,n)}}async mutateQueuedMessage(e,t,n){let r=this.getState(),i=r.selectedSession;if(i===void 0||i.archived===!0||I(i))return;let a={...i},o=M(r);if(!this.isSelectedSessionScope(a,o)||!this.canMutateQueueMessage(a,o)||r.status?.queueMessageActionsUnavailable!==void 0)return;let s=n.map(e=>({...e}));if(!Number.isInteger(t)||t<0||t>=s.length)return;let c=s[t]?.text??``,l=this.selectionSeq,u=this.captureSessionErrorOwner(a),d=()=>this.isCurrentSessionSelection(a.id,o,l)&&this.isSelectedSessionScope(a,o)&&this.canMutateQueueMessage(a,o)&&this.getState().status?.queueMessageActionsUnavailable===void 0;try{let n=await this.api.mutateQueuedMessage(a,{action:e,index:t,expectedQueue:s},o);if(this.disposed)return;if(n.sessionId!==a.id)throw Error(D(`client.sessionController.queueResponseMismatch`,`The queue response belongs to a different conversation.`));if(!this.canMutateQueueMessage(a,o))throw Error(D(`client.sessionController.queueActionsUnavailable`,`Queued message actions are no longer available.`));if(this.hasDraftIdentityConflict(a,o))throw Error(D(`client.sessionController.queueContextChanged`,`The conversation context changed before the result returned. The current draft was preserved.`));e===`edit`&&(za(j(o,a.id),c),d()&&await this.replacePromptEditorText?.({machineId:o,sessionId:a.id,text:c,isCurrent:d})),d()&&this.applyStatus(n)}catch(e){this.disposed||this.reportSessionError(a,o,e,u)}}async clearServerQueue(){let e=this.getState(),t=e.selectedSession;if(t===void 0||t.archived===!0||I(t))return;let n=M(e),r=this.captureSessionErrorOwner(t),i=this.selectionSeq;try{let e=await this.api.clearQueue(t,n);this.isCurrentSessionSelection(t.id,n,i)&&this.applyStatus(e)}catch(e){this.reportSessionError(t,n,e,r)}}async dismissWarning(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||I(n))return;let r=M(t),i=this.captureSessionErrorOwner(n),a=this.selectionSeq;try{let t=await this.api.dismissWarning(n,e,r);this.isCurrentSessionSelection(n.id,r,a)&&this.applyStatus(t)}catch(e){this.reportSessionError(n,r,e,i)}}submitAsk(e,t){return this.sendAskResponse(e,(n,r)=>this.api.submitAsk(n,e,t,r))}cancelAsk(e){return this.sendAskResponse(e,(t,n)=>this.api.cancelAsk(t,e,n))}answerDialog(e,t){return this.closeOpenDialog(e,(n,r)=>this.api.answerDialog(n,e,t,r))}cancelDialog(e){return this.closeOpenDialog(e,(t,n)=>this.api.cancelDialog(t,e,n))}async closeOpenDialog(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0)return;if(I(r)){await this.closePendingStartDialog(r,e,t);return}let i=M(n),a=this.captureSessionErrorOwner(r),o=this.selectionSeq;try{let e=await t(r,i);if(!this.isCurrentSessionSelection(r.id,i,o))return;this.recordDialogOutcome(e.outcome),this.applyStatus(e.sessionStatus)}catch(e){this.reportSessionError(r,i,e,a)}}async closePendingStartDialog(e,t,n){let r=this.pendingSessionStarts.get(e.id),i=r?.backendSessionId;if(r===void 0||i===void 0)return;let a=this.captureSessionErrorOwner(e,r.originWorkspace),o=this.selectionSeq;try{let t=await n({...e,id:i},r.machineId);if(o!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;this.recordDialogOutcome(t.outcome),this.applyPendingStartStatus(r,t.sessionStatus)}catch(t){this.reportSessionError(e,r.machineId,t,a)}}recordDialogOutcome(e){if(e===void 0)return;let t=this.getState().pendingDialogs.find(t=>t.dialogId===e.dialogId);t!==void 0&&this.recordClosedDialog({dialog:t,reason:e.reason,...e.answer===void 0?{}:{answer:e.answer}})}async sendAskResponse(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0||I(r))return;let i=M(n),a=this.captureSessionErrorOwner(r),o=this.selectionSeq;try{let n=await t(r,i);Qa(j(i,r.id),e),this.isCurrentSessionSelection(r.id,i,o)&&this.applyStatus(n)}catch(e){this.reportSessionError(r,i,e,a)}}async stopActiveWork(){let e=this.getState().selectedSession;if(!e)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.abort(e,t)}catch(r){this.reportSessionError(e,t,r,n)}}refreshSelectedSession(e=this.getState().selectedSession?.id,t){let n=this.getState().selectedSession;if(e===void 0||n?.id!==e||this.selectedSessionLoadDeferred||n.archived===!0||I(n))return Promise.resolve();let r=M(this.getState()),i={session:n,machineId:r,selectionSeq:this.selectionSeq,errorOwner:this.captureSessionErrorOwner(n),...t?.recoverNetwork===!0?{recoverNetwork:!0}:{}},a=this.selectedReadGeneration;return this.requestSelectedSessionRefresh(i).catch(e=>{this.disposed||a!==this.selectedReadGeneration||t?.recoverNetwork===!0&&!this.isCurrentRefreshTarget(i)||(t?.silent===!0?console.warn(`Selected session background refresh failed`,{machineId:r,sessionId:n.id,errorCategory:`session-refresh`}):e instanceof Oe?this.browserErrors.report(Kn(r,n.id,i.errorOwner),D(`client.sessionController.conversationRefreshUnavailable`,`The conversation could not be refreshed. Check your connection and retry.`),`session-refresh`):this.reportSessionError(i.session,i.machineId,e,i.errorOwner))})}bufferRefreshEvents(e){if(this.refreshEventBuffer!==void 0&&this.isCurrentRefreshTarget(this.refreshEventBuffer.target))return this.refreshEventBuffer;this.flushPendingUpdates();let t={target:e,events:[],pendingDialogs:this.getState().pendingDialogs};return this.refreshEventBuffer=t,t}async refreshSessionNotifications(e,t){try{await this.notifications?.refreshSelectedSession(e,t)}catch{console.warn(`Selected session notification refresh failed`,{machineId:t,sessionId:e.id,errorCategory:`notification-refresh`})}}async joinSelectedSessionSnapshot(e){let t=!1,n,r=new Promise(e=>{n=()=>{t=!0,e(!0)}}),i={selectionSeq:e.selectionSeq,complete:n};this.initialSnapshotReady=i;let a=this.requestSelectedSessionRefresh(e).then(()=>t,n=>{if(!t)throw n;return this.reportSessionError(e.session,e.machineId,n,e.errorOwner),!0});try{return await Promise.race([r,a])}finally{this.initialSnapshotReady===i&&(this.initialSnapshotReady=void 0)}}requestSelectedSessionRefresh(e){if(!this.isCurrentRefreshTarget(e))return Promise.resolve();let t=j(e.machineId,e.session.id),n=this.selectedReadGeneration,r=()=>n===this.selectedReadGeneration&&this.isCurrentRefreshTarget(e);return this.selectedSessionRecoveryTarget!==void 0&&this.isCurrentRefreshTarget(this.selectedSessionRecoveryTarget)||this.bufferRefreshEvents(e),Promise.resolve().then(()=>{if(r())return this.refreshSessionNotifications(e.session,e.machineId)}),this.selectedSessionRefreshes.request(t,async()=>{if(!r())return;let n=new AbortController;this.selectedReadRecoveries.add(n),e.recoverNetwork===!0&&(this.selectedSessionRecoveryTarget=e);try{await sc(()=>this.readSelectedSessionSnapshot(e,t,()=>r()&&!n.signal.aborted,n.signal),r,n.signal,e.recoverNetwork===!0)}finally{this.selectedReadRecoveries.delete(n),this.selectedSessionRecoveryTarget===e&&(this.selectedSessionRecoveryTarget=void 0)}})}async readSelectedSessionSnapshot(e,t,n,r){let i=this.bufferRefreshEvents(e),a=this.transcripts.historyRevision(t),o=this.observeSessionSnapshot?.(e.machineId,e.session.id),s,c=this.browserErrors.captureRecovery(Kn(e.machineId,e.session.id,e.errorOwner),`session-refresh`),l=!1,u=()=>{if(!l&&(l=!0,this.refreshEventBuffer===i&&(this.refreshEventBuffer=void 0),n()))for(let e of i.events){if(!n())break;this.applyEvent(e)}};r?.addEventListener(`abort`,u,{once:!0});try{let r=await this.transcriptSnapshot(e.session,{limit:lc},e.machineId);if(!n()||this.transcripts.historyRevision(t)!==a)return;this.browserErrors.clearRecovered(c);let{page:l,status:u}=r;if(this.preserveBufferedDialogOutcomes(i,r.seq),!this.isUnchangedSelectedRefresh(e,t,l,u,r)){let n=this.transcripts.mergeSnapshot(t,l),i=this.transcripts.seedStreamingPartial(n.messages,r.partial);this.streamWatermark={sessionId:e.session.id,seq:r.seq},this.setState({...n,messages:i,status:u,activity:this.getState().sessionActivities[e.session.id]}),this.applyStatus(u),this.lastAppliedSelectedRefresh={selectionSeq:e.selectionSeq,partialJson:hc(r)}}s=this.transcripts.historyRevision(t),o?.(u)}finally{r?.removeEventListener(`abort`,u),u()}this.transcripts.historyRevision(t)===s&&n()&&this.initialSnapshotReady?.selectionSeq===e.selectionSeq&&this.initialSnapshotReady.complete()}preserveBufferedDialogOutcomes(e,t){let n=new Map(e.pendingDialogs.map(e=>[e.dialogId,e]));for(let r of e.events)if(!(r.seq===void 0||r.seq>t||this.isStreamEventBelowWatermark(r))&&(r.type===`dialog.opened`&&n.set(r.dialog.dialogId,r.dialog),r.type===`dialog.closed`)){let e=n.get(r.dialogId);e!==void 0&&this.recordClosedDialog({dialog:e,reason:r.reason,...r.answer===void 0?{}:{answer:r.answer}}),n.delete(r.dialogId)}}isUnchangedSelectedRefresh(e,t,n,r,i){let a=this.lastAppliedSelectedRefresh;return a?.selectionSeq!==e.selectionSeq||i.seq<(this.streamWatermark?.seq??0)||hc(i)!==a.partialJson||!ts(this.transcripts.rawHistoryPage(t),n)||JSON.stringify(r)!==JSON.stringify(this.getState().status)?!1:this.getState().sessionActivities[r.sessionId]?.phase!==`active`||rr(r)}isCurrentRefreshTarget(e){let t=this.getState().selectedSession;return this.isCurrentSessionSelection(e.session.id,e.machineId,e.selectionSeq)&&t?.cwd===e.session.cwd&&t.path===e.session.path&&t.archived===e.session.archived&&Nc(e.navigation)}isCurrentSessionSelection(e,t,n){return n===this.selectionSeq&&this.isSelectedSessionIdentity(e,t)}isCurrentRestoreOperation(e,t,n){return t===this.selectionSeq&&M(this.getState())===e&&Nc(n)}isSelectedSessionIdentity(e,t){if(this.disposed)return!1;let n=this.getState(),r=n.selectedSession;return M(n)===t&&r?.id===e&&r.archived!==!0&&!I(r)}isSelectedSessionScope(e,t){let n=this.getState().selectedSession;return this.isSelectedSessionIdentity(e.id,t)&&n?.cwd===e.cwd&&n.path===e.path}hasDraftIdentityConflict(e,t){let n=this.getState(),r=n.selectedSession;return M(n)===t&&r?.id===e.id&&(r.cwd!==e.cwd||r.path!==e.path)}reportSessionError(e,t,n,r={cwd:e.cwd}){this.browserErrors.report(Kn(t,e.id,r),ic(n))}captureSessionErrorOwner(e,t=this.workspaceForSessionError(e)){return{cwd:e.cwd,...t===void 0?{}:{projectId:t.projectId,workspaceId:t.id}}}workspaceForSessionError(e){let t=this.getState();return[t.selectedWorkspace,...t.workspaces,...Object.values(t.workspacesByProjectId).flat()].find(t=>t?.path===e.cwd)}reportWorkspaceError(e,t,n){this.browserErrors.report(Gn(t,e.projectId,e.id),ic(n))}applyBulkSessionFailures(e,t,n,r,i,a){t.length!==0&&this.reportWorkspaceOrSessionError(r,i,n,D(`client.sessionController.failed.for.sessions.5ef9b2`,`{value1} failed for {value2} sessions: {value3}`,{value1:e,value2:String(t.length),value3:t.join(`;`)}),a)}reportWorkspaceOrSessionError(e,t,n,r,i){e===void 0?t!==void 0&&this.reportSessionError(t,n,r,i):this.reportWorkspaceError(e,n,r)}sessionCacheKey(e){return j(M(this.getState()),e)}statusForSession(e){if(e===void 0)return;let t=this.getState();return t.status?.sessionId===e.id&&t.selectedSession?.id===e.id?t.status:t.sessionStatuses[e.id]}sessionPersistenceOptions(){let e=this.getState();return Ls(e.machineRuntimes[M(e)])}workspaceSelectionKey(e){return`${M(this.getState())}:${e}`}replaceSession(e){let t=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(t=>t.id===e.id?e:t),selectedSession:t?.id===e.id?e:t})}navigationSelection(){if(this.captureNavigation!==void 0)return this.captureNavigation();let e=this.getState();return{machineId:M(e),projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id}}navigationSelectionMatchesState(e){let t=this.navigationSelection();return t.machineId===e.machineId&&t.projectId===e.projectId&&t.workspaceId===e.workspaceId&&t.sessionId===e.sessionId&&t.tool===e.tool&&t.view===e.view}createPendingSessionStart(e,t,n,r){let i=`creating:${Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,`0`)).join(``)}`,a=new Date().toISOString(),o={id:i,path:`pi-web://pending-session/${i}`,cwd:e.path,persisted:!1,name:D(`client.sessionController.new.session.c57c30`,`New session`),created:a,modified:a,messageCount:0,firstMessage:``,clientPendingStart:!0,machineId:t};return{tempId:i,originWorkspace:e,workspaceId:e.id,cwd:e.path,machineId:t,expectedNavigation:n,pendingUrlPublished:r,session:o,queuedSends:[],discarded:!1}}insertAndSelectPendingSession(e,t){let n=this.getState();this.selectClientPendingStartSession(e,{activity:Sc(e.id),sessions:[e,...n.sessions.filter(t=>t.id!==e.id)],updateUrl:t?.updateUrl})}selectClientPendingStartSession(e,t){this.retireReadRecoveries([`session`]),this.selectedSessionLoadDeferred=!1,this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)}),this.selectionSeq+=1,this.selectedSessionJoinNavigation=void 0,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates();let n=this.getState(),r=this.pendingSessionStarts.get(e.id),i=t?.activity??n.sessionActivities[e.id]??(r===void 0?void 0:Sc(e.id,r.queuedSends.length));this.setState({sessions:t?.sessions??(n.sessions.some(t=>t.id===e.id)?n.sessions:[e,...n.sessions]),selectedSession:e,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:i,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0,...i===void 0?{}:{sessionActivities:{...n.sessionActivities,[e.id]:i}},error:``}),r?.backendSessionId!==void 0&&this.connectPendingStartSocket(r),t?.updateUrl!==!1&&this.updateUrl()}async resolvePendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.queuedSends.splice(0),i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId,t.id);if(n.discarded){Ba(j(n.machineId,e)),Ka(j(n.machineId,e)),this.setState({clientQueuedSessionMessages:_c(this.getState().clientQueuedSessionMessages,e)}),this.applyReleasedCreatedSessions(i,n.machineId),this.api.stop(t,n.machineId).catch(()=>{});return}Yr(t,n.machineId),Va(j(n.machineId,e),j(n.machineId,t.id)),qa(j(n.machineId,e),j(n.machineId,t.id));let a=Xr(t,n.machineId),o=this.captureSessionErrorOwner(t,n.originWorkspace);if(!this.isCurrentPendingStart(n)){this.setState({clientQueuedSessionMessages:_c(this.getState().clientQueuedSessionMessages,e)}),await this.flushQueuedPendingSends(a,n.machineId,r,o);return}let s=this.getState(),c=s.selectedSession?.id===e,l={machineId:n.machineId,projectId:n.originWorkspace.projectId,workspaceId:n.workspaceId,sessionId:e},u=c&&(this.navigateToSession!==void 0||!n.pendingUrlPublished),d=c&&!u&&(this.isPendingSessionStartRouteCurrent?.(l)??!0);c&&!u&&!d&&this.clearActiveSession(),this.setState({sessions:bc(s.sessions,e,a),sessionActivities:gc(s.sessionActivities,e),sendingPrompts:yc(s.sendingPrompts,e,a.id),clientQueuedSessionMessages:yc(s.clientQueuedSessionMessages,e,a.id),...d?{selectedSession:a,status:s.sessionStatuses[a.id],activity:s.sessionActivities[a.id],pendingDialogs:s.sessionStatuses[a.id]?.pendingDialogs??[],closedDialogs:[]}:{},error:``}),this.applyReleasedCreatedSessions(i,n.machineId),u?await this.reconcileCompletedPendingSelection(n,a):d&&(this.onPendingSessionStartCommitted?.(l,a),this.onPendingSessionStartCommitted===void 0&&this.updateUrl({replace:!0}),await this.selectSession(a,{updateUrl:!1,navigation:n.navigation})),await this.flushQueuedPendingSends(a,n.machineId,r,o)}async reconcileCompletedPendingSelection(e,t){let n=e.navigation;if(!e.pendingUrlPublished&&!Nc(n))this.clearUnreconciledPendingSelection(e,t);else if(e.expectedNavigation=this.pendingStartExpectedNavigation(e),this.navigateToSession!==void 0)try{let r=await this.navigateToSession(t,{...e.pendingUrlPublished?{replace:!0,creationHandoff:!0}:{},expected:e.expectedNavigation});if(r&&this.getState().selectedSession?.id!==e.tempId)return;this.clearUnreconciledPendingSelection(e,t,r||e.pendingUrlPublished||!Nc(n)?void 0:D(`ui.main.0a71e48cd0f9`,`Session started, but its navigation changed before selection completed. Select it from the session list.`))}catch(n){this.clearUnreconciledPendingSelection(e,t,D(`ui.main.d15d396c9633`,`Session started but could not be selected: {arg0}`,{arg0:kc(n)}))}else try{if(await this.selectSession(t,{updateUrl:!1,navigation:n}),!Nc(n)){this.clearUnreconciledPendingSelection(e,t);return}if(this.getState().selectedSession?.id!==t.id){this.clearUnreconciledPendingSelection(e,t,D(`ui.main.8cd247b86afd`,`Session started, but its selection changed before navigation completed. Select it from the session list.`));return}this.updateUrl(e.pendingUrlPublished?{replace:!0}:void 0)}catch(n){this.clearUnreconciledPendingSelection(e,t,D(`ui.main.d15d396c9633`,`Session started but could not be selected: {arg0}`,{arg0:kc(n)}))}}pendingStartExpectedNavigation(e){return e.pendingUrlPublished?{machineId:e.machineId,projectId:e.originWorkspace.projectId,workspaceId:e.workspaceId,sessionId:e.tempId}:{...this.navigationSelection(),sessionId:e.expectedNavigation.sessionId}}clearUnreconciledPendingSelection(e,t,n){let r=this.getState().selectedSession?.id;(r===e.tempId||r===t.id)&&(this.clearActiveSession(),n!==void 0&&this.browserErrors.report(Gn(e.machineId,e.originWorkspace.projectId,e.workspaceId),n))}cancelUnstartedSession(e){if(this.pendingSessionStarts.get(e.tempId)!==e)return;this.pendingSessionStarts.delete(e.tempId),e.discarded=!0,e.queuedSends=[],Zr(e.tempId,e.machineId);let t=j(e.machineId,e.tempId);Ba(t),Ka(t);let n=this.getState(),r=n.selectedSession?.id===e.tempId;if(this.setState({sessions:n.sessions.filter(t=>t.id!==e.tempId),sessionStatuses:_c(n.sessionStatuses,e.tempId),sessionActivities:gc(n.sessionActivities,e.tempId),sendingPrompts:_c(n.sendingPrompts,e.tempId),clientQueuedSessionMessages:_c(n.clientQueuedSessionMessages,e.tempId)}),!r)return;this.clearActiveSession();let i={machineId:e.machineId,projectId:e.originWorkspace.projectId,workspaceId:e.workspaceId,sessionId:e.tempId};(this.isPendingSessionStartRouteCurrent?.(i)??!0)&&this.updateUrl({replace:!0})}failPendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.discarded;n.discarded=!0,this.getState().selectedSession?.id===e&&this.socket.close();let i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId),a=this.isCurrentPendingStart(n);if(r){a&&this.applyReleasedCreatedSessions(i,n.machineId);return}let o=kc(t),s=D(`client.sessionController.failed.to.start.session.881118`,`Failed to start session: {value1}`,{value1:o});if(!a){this.browserErrors.report(Gn(n.machineId,n.originWorkspace.projectId,n.originWorkspace.id),s);return}let c=this.getState(),l=Cc(e,o,n.queuedSends.length),u=c.sessions.some(t=>t.id===e);this.setState({sessions:u?c.sessions:[n.session,...c.sessions],sessionActivities:{...c.sessionActivities,[e]:l},activity:c.selectedSession?.id===e?l:c.activity,...c.selectedSession?.id===e?{pendingDialogs:[]}:{}}),this.reportSessionError(n.session,n.machineId,s,this.captureSessionErrorOwner(n.session,n.originWorkspace)),this.applyReleasedCreatedSessions(i,n.machineId)}isCurrentPendingStart(e){let t=this.getState();return M(t)===e.machineId&&t.selectedWorkspace?.id===e.workspaceId&&t.selectedWorkspace.projectId===e.originWorkspace.projectId}hasPendingStartFor(e,t){return Array.from(this.pendingSessionStarts.values()).some(n=>n.cwd===e&&n.machineId===t)}isSuppressedCreatedSession(e,t){let n=this.suppressedCreatedSessions.get(e.id);return n?.session.cwd===e.cwd&&n.machineId===t}takeSuppressedCreatedSessionsFor(e,t,n){if(n!==void 0&&this.suppressedCreatedSessions.delete(n),this.hasPendingStartFor(e,t))return[];let r=[];for(let[n,i]of this.suppressedCreatedSessions)i.session.cwd===e&&i.machineId===t&&(this.suppressedCreatedSessions.delete(n),r.push(i.session));return r}applyReleasedCreatedSessions(e,t){if(e.length===0||M(this.getState())!==t)return;let n=this.getState();if(n.selectedWorkspace===void 0)return;let r=new Set(n.sessions.map(e=>e.id)),i=e.filter(e=>e.cwd===n.selectedWorkspace?.path&&!r.has(e.id));i.length!==0&&this.setState({sessions:[...i.reverse(),...n.sessions]})}mergePendingStartSessions(e,t,n){let r=this.getState().sessions.filter(t=>I(t)&&t.cwd===e&&t.machineId===n);if(r.length===0)return t;let i=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!i.has(e.id))]}async recreateCachedNewSession(e,t,n=this.selectionSeq,r=this.captureSessionErrorOwner(e)){let i=M(this.getState()),a=this.navigationSelection();try{let r=await this.api.startSession(e.cwd,i);if(!this.isCurrentSessionSelection(e.id,i,n)||!this.isSelectedSessionScope(e,i)||!Nc(t?.navigation))return;Yr(r,i),Va(j(i,e.id),j(i,r.id)),qa(j(i,e.id),j(i,r.id)),Zr(e.id,i);let o=Xr(r,i);if(this.setState({sessions:[o,...this.getState().sessions.filter(t=>t.id!==e.id&&t.id!==r.id)],error:``}),this.navigateToSession!==void 0){let r=this.navigationSelection();!await this.navigateToSession(o,{...t?.updateUrl===!1?{replace:!0}:{},expected:{...a,tool:r.tool,view:r.view}})&&this.isCurrentSessionSelection(e.id,i,n)&&this.clearActiveSession()}else await this.selectSession(o,{updateUrl:!1}),this.updateUrl(t?.updateUrl===!1?{replace:!0}:void 0)}catch(t){this.reportSessionError(e,i,t,r)}}markCachedNewSessionPersisted(e){if(!$r(e))return;let t=this.getState().sessions.find(t=>t.id===e.id)??e;this.replaceSession(ei(t))}async applyCommandResult(e,t){if(e.type===`select`){this.setState({commandDialog:e});return}if(e.type===`tree`){this.setState({treeDialog:e.tree});return}let n=(e.type,e.message);if(n!==void 0&&n!==``&&this.setState({messages:[...this.getState().messages,ui(e.type===`unsupported`?`system`:`tool`,n)]}),e.type===`done`&&e.session){e.promptDraft!==void 0&&za(this.sessionCacheKey(e.session.id),e.promptDraft);let n=this.getState().selectedSession,r=[e.session,...this.getState().sessions.filter(t=>t.id!==e.session?.id)];if(this.setState({sessions:r,...n?.id===e.session.id?{selectedSession:e.session}:{}}),n?.id===e.session.id||!this.navigationSelectionMatchesState(t))return;this.navigateToSession===void 0?await this.selectSession(e.session):await this.navigateToSession(e.session,{expected:t})}}applyCreatedSession(e){let t=this.getState();if(t.selectedWorkspace?.path!==e.cwd||t.sessions.some(t=>t.id===e.id))return;let n=M(t);this.hasPendingStartFor(e.cwd,n)?this.suppressedCreatedSessions.set(e.id,{session:e,machineId:n}):this.setState({sessions:[e,...t.sessions]})}applyActivity(e){this.setState({sessionActivities:{...this.getState().sessionActivities,[e.sessionId]:e},activity:this.getState().selectedSession?.id===e.sessionId?e:this.getState().activity})}applyStatus(e){let t=this.getState(),n=t.selectedSession?.id===e.sessionId,r=t.sessionActivities[e.sessionId]?.phase===`active`&&!rr(e);this.setState({sessionStatuses:{...t.sessionStatuses,[e.sessionId]:e},...Ac(t,e.sessionId,e.messageCount),...r?{sessionActivities:gc(t.sessionActivities,e.sessionId)}:{},status:n?e:t.status,activity:n&&r?void 0:t.activity,...n?{pendingDialogs:e.pendingDialogs??[]}:{}})}applyOpenedDialog(e){let t=this.getState();t.selectedSession===void 0||t.pendingDialogs.some(t=>t.dialogId===e.dialogId)||this.setState({pendingDialogs:[...t.pendingDialogs,e]})}applyClosedDialog(e,t,n){let r=this.getState().pendingDialogs.find(t=>t.dialogId===e);r!==void 0&&this.recordClosedDialog({dialog:r,reason:t,...n===void 0?{}:{answer:n}})}recordClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e.dialog.dialogId)||this.setState({pendingDialogs:t.pendingDialogs.filter(t=>t.dialogId!==e.dialog.dialogId),closedDialogs:[...t.closedDialogs,e]})}dismissClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e)&&this.setState({closedDialogs:t.closedDialogs.filter(t=>t.dialog.dialogId!==e)})}applySessionName(e,t){let n=n=>{if(n.id!==e)return n;let r={...n};return t===void 0||t===``?delete r.name:r.name=t,r},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(n),selectedSession:r===void 0?void 0:n(r)})}applyEvent(e){if(e.type===`session.diagnostic`){console.warn(e.message);return}if(e.type===`notifications.inbox`){this.notifications?.applyInboxEvent(M(this.getState()),e);return}if(e.type===`command.output`&&this.notifications?.shouldFilterLegacyNotification(M(this.getState()),e.notificationId)===!0)return;let t=this.refreshEventBuffer;if(t!==void 0&&this.isCurrentRefreshTarget(t.target)){t.events.push(e);return}if(this.isStreamEventBelowWatermark(e))return;if(e.type===`session.tree.changed`){this.invalidateSessionTree();return}if(e.type===`status.update`){this.queueStatusUpdate(e.status);return}if(e.type===`activity.update`){this.queueActivityUpdate(e.activity);return}if(jc(e)){this.queueTranscriptEvent(e);return}if(this.flushPendingUpdates(),e.type===`dialog.opened`){this.applyOpenedDialog(e.dialog);return}if(e.type===`dialog.closed`){this.applyClosedDialog(e.dialogId,e.reason,e.answer);return}let n=this.transcripts.applyLiveEvent(this.getState().messages,e);n?this.setState({messages:n}):e.type===`session.name`&&this.applySessionName(e.sessionId,e.name)}queueTranscriptEvent(e){this.pendingTranscriptEvents.push(e),this.schedulePendingFlush()}queueStatusUpdate(e){this.pendingStatusBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueActivityUpdate(e){this.pendingActivityBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueStartupProgress(e){if(this.getState().sessions.some(t=>t.id===e.activity.sessionId)){this.queueActivityUpdate(e.activity);return}let t=e.startupToken===void 0?void 0:this.pendingSessionStarts.get(e.startupToken);t===void 0||t.discarded||(this.learnPendingStartBackendSession(t,e.activity.sessionId),this.queueActivityUpdate(e.activity.phase===`idle`?Sc(t.tempId,t.queuedSends.length):xc(e.activity,t.tempId)))}learnPendingStartBackendSession(e,t){t!==``&&e.backendSessionId===void 0&&(e.backendSessionId=t,this.getState().selectedSession?.id===e.tempId&&this.connectPendingStartSocket(e))}connectPendingStartSocket(e){let t=e.backendSessionId;if(t===void 0||e.discarded)return;let n={id:t,cwd:e.cwd};this.socket.connect(n,t=>{this.applyPendingStartEvent(e,t)},()=>{this.resyncPendingStartDialogs(e)},e.machineId),this.resyncPendingStartDialogs(e)}resyncPendingStartDialogs(e){let t=e.backendSessionId;t!==void 0&&this.api.status({id:t,cwd:e.cwd},e.machineId).then(t=>{if(e.discarded||this.getState().selectedSession?.id!==e.tempId)return;this.applyStatus(t);let n=this.getState(),r=new Set([...n.pendingDialogs.map(e=>e.dialogId),...n.closedDialogs.map(e=>e.dialog.dialogId)]),i=(t.pendingDialogs??[]).filter(e=>!r.has(e.dialogId));i.length>0&&this.setState({pendingDialogs:[...n.pendingDialogs,...i]})},()=>void 0)}applyPendingStartEvent(e,t){e.discarded||this.getState().selectedSession?.id!==e.tempId||(t.type===`dialog.opened`?this.applyOpenedDialog(t.dialog):t.type===`dialog.closed`?this.applyClosedDialog(t.dialogId,t.reason,t.answer):t.type===`status.update`&&this.applyPendingStartStatus(e,t.status))}applyPendingStartStatus(e,t){this.applyStatus(t),!(e.discarded||this.getState().selectedSession?.id!==e.tempId)&&this.setState({pendingDialogs:t.pendingDialogs??[]})}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){if(this.pendingTranscriptEvents.length>0){let e=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let t=this.getState().messages;for(let n of e)t=this.transcripts.applyLiveEvent(t,n)??t;t!==this.getState().messages&&this.setState({messages:t})}if(this.pendingActivityBySession.size>0){let e=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(let t of e)this.applyActivity(t)}if(this.pendingStatusBySession.size>0){let e=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(let t of e)this.applyStatus(t)}}clearPendingUpdates(){this.refreshEventBuffer=void 0,this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=void 0)}isStreamEventBelowWatermark(e){if(e.type===`session.name`||e.type===`session.error`||e.type===`command.output`||e.type===`session.tree.changed`)return!1;let t=this.streamWatermark;return t===void 0||t.sessionId!==this.getState().selectedSession?.id?!1:e.seq!==void 0&&e.seq<=t.seq}async selectSearchMatch(e,t,n){await this.selectSessionAfterNavigation(e,this.navigationSelection());let r=M(this.getState()),i=this.captureSessionErrorOwner(e),a=this.selectionSeq;try{for(;this.isCurrentSearchJump(e.id,r,a)&&this.getState().messagePageStart>t.messageIndex;){let t=this.getState().messagePageStart,n=await this.api.messages(e,{before:t,limit:uc},r);if(!this.isCurrentSearchJump(e.id,r,a))return;let i=this.transcripts.mergeHistory(this.sessionCacheKey(e.id),n);if(this.setState(i),i.messagePageStart>=t)break}}catch(t){this.reportSessionError(e,r,t,i);return}this.isCurrentSearchJump(e.id,r,a)&&this.setState({...this.transcripts.indexedView(this.sessionCacheKey(e.id)),sessionSearchTarget:{sessionId:e.id,messageIndex:t.messageIndex,query:n,requestId:++this.searchTargetSeq}})}isCurrentSearchJump(e,t,n){return this.selectionSeq===n&&M(this.getState())===t&&this.getState().selectedSession?.id===e}};function hc(e){return JSON.stringify(e.partial??null)}function gc(e,t){return _c(e,t)}function _c(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function vc(e,t){if(t.length===0)return e;let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function yc(e,t,n){if(t===n||!(t in e))return e;let r=e[t];return r===void 0?e:{..._c(e,t),[n]:r}}function bc(e,t,n){let r=[],i=!1;for(let a of e)a.id===t?i||=(r.push(n),!0):a.id!==n.id&&r.push(a);return i?r:[n,...r]}function I(e){return e!==void 0&&`clientPendingStart`in e&&e.clientPendingStart===!0}function xc(e,t){return{sessionId:t,phase:e.phase,label:e.label,...e.detail===void 0?{}:{detail:e.detail},at:e.at}}function Sc(e,t=0){return{sessionId:e,phase:`active`,label:D(`activity.creating`,`Creating session`),detail:t>0?D(`client.sessionController.will.send.queued.messages.when.the.backend.session.is.ready.f49381`,`Will send {value1} queued messages when the backend session is ready`,{value1:String(t)}):D(`client.sessionController.waiting.for.the.backend.session.3a8a3d`,`Waiting for the backend session`),at:new Date().toISOString()}}function Cc(e,t,n=0){let r=n>0?D(`client.sessionController.queued.messages.retained.below.2194c6`,` · {value1} queued messages retained below`,{value1:String(n)}):``;return{sessionId:e,phase:`error`,label:D(`client.sessionController.session.creation.failed.aff35c`,`Session creation failed`),detail:`${t}${r}`,at:new Date().toISOString()}}function wc(e){if(e.type===`prompt`){let t=e.attachments?.length??0;return{kind:e.streamingBehavior===`steer`?`steer`:`followUp`,text:Tc(e.text,e.attachments),...t>0?{hasAttachments:!0,attachmentCount:t}:{}}}return{kind:`followUp`,text:e.text}}function Tc(e,t){let n=Ec(t);return n===void 0?e:e.trim()===``?n:`${e}\n\n${n}`}function Ec(e){if(e===void 0||e.length===0)return;let t=e.map(e=>e.name?.trim()).filter(e=>e!==void 0&&e!==``),n=e.length,r=D(`client.sessionController.attachments.092014`,`{value1} attachments`,{value1:String(n)});if(t.length===0)return D(`client.sessionController.queued.6fc044`,`[Queued {value1}]`,{value1:r});let i=t.slice(0,3).join(`、`),a=t.length>3?D(`client.sessionController.plus.more.675fd5`,`, plus {value1} more`,{value1:String(t.length-3)}):``;return D(`client.sessionController.queued.871266`,`[Queued {value1}: {value2}{value3}]`,{value1:r,value2:i,value3:a})}function Dc(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function Oc(e){return e.map(e=>`${e.sessionId}: ${e.error}`)}function kc(e){return e instanceof Error?e.message:String(e)}function Ac(e,t,n){if(n===void 0)return{};let r=e.sessions.some(e=>e.id===t&&e.messageCount!==n)?e.sessions.map(e=>e.id===t?{...e,messageCount:n}:e):void 0,i=e.selectedSession?.id===t&&e.selectedSession.messageCount!==n?{...e.selectedSession,messageCount:n}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...i===e.selectedSession?{}:{selectedSession:i}}}function jc(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`||e.type===`shell.chunk`}function Mc(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`session not found`)||t.includes(D(`session.notFound`,`Session not found`))}function Nc(e){return e===void 0||e.isCurrent()}var Pc=class{constructor(){this.active=new Map,this.revisions=new Map,this.generation=0}observe(e,t){let n=t.type===`status.update`?t.status.sessionId:t.activity.sessionId,r=JSON.stringify([e,n]);this.revisions.set(r,(this.revisions.get(r)??0)+1);let i=this.active.get(r),a={statusActive:i?.statusActive??!1,activityActive:i?.activityActive??!1};if(t.type===`status.update`?(a.statusActive=rr(t.status),a.statusActive||(a.activityActive=!1)):a.activityActive=rr(void 0,t.activity),a.statusActive||a.activityActive)this.active.set(r,a);else return this.active.delete(r),i===void 0?void 0:n}snapshotObserver(e,t){let n=JSON.stringify([e,t]),r=this.revisions.get(n),i=this.generation;return a=>{if(a.sessionId===t&&i===this.generation&&this.revisions.get(n)===r)return this.observe(e,{type:`status.update`,status:a})}}clear(){this.active.clear(),this.revisions.clear(),this.generation+=1}};async function Fc(e){let t=await Promise.allSettled(e),n=[];for(let e of t)e.status===`rejected`&&n.push(e.reason);if(n.length===1)throw n[0];if(n.length>1)throw AggregateError(n,n.map(e=>e instanceof Error?e.message:String(e)).join(`; `))}var Ic={order:0,overflowWatermark:0};function Lc(e){return{...e,status:`loading`,catalogRevision:0,notifications:[],dismissThrough:Ic,optimisticDismissedIds:[],announcements:[]}}function Rc(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)throw Error(`Notification inbox snapshot does not match the selected session`);let r=e!==void 0&&Qc(e,t)&&e.daemonInstanceId===n.daemonInstanceId;return{...t,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:n.notifications,dismissThrough:n.dismissThrough,optimisticDismissedIds:r?e.optimisticDismissedIds:[],...r&&e.optimisticDismissAllThrough!==void 0?{optimisticDismissAllThrough:e.optimisticDismissAllThrough}:{},announcements:r?e.announcements:[]}}function zc(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)return{value:e??Lc(t),needsRefresh:!1,changed:!1};if(e===void 0||!Qc(e,t))return{value:el(t),needsRefresh:!0,changed:!0};if(e.daemonInstanceId!==n.daemonInstanceId)return{value:el(t),needsRefresh:!0,changed:e.status!==`stale`||e.daemonInstanceId!==void 0||e.notifications.length>0};let r=e.summary?.inboxRevision??0;if(n.summary.inboxRevision<=r)return{value:e,needsRefresh:!1,changed:!1};if(e.status!==`fresh`||n.summary.inboxRevision!==r+1||n.delta.kind===`resync`)return{value:{...e,status:`stale`},needsRefresh:!0,changed:e.status!==`stale`};let i,a;switch(n.delta.kind){case`added`:{let t=n.delta;if(e.notifications.some(e=>e.id===t.notification.id))return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};i=[t.notification,...e.notifications].filter(e=>e.id!==t.evictedNotificationId).sort((e,t)=>t.order-e.order).slice(0,100),a={id:`${n.daemonInstanceId}:${String(n.summary.inboxRevision)}:${t.notification.id}`,severity:t.notification.severity,message:t.notification.message};break}case`dismissed`:{let t=new Set(n.delta.notificationIds);i=e.notifications.filter(e=>!t.has(e.id));break}case`cleared`:i=[]}let o=i[0]?.order??0;if(!tl(i,n.summary)||n.dismissThrough.order!==o||n.dismissThrough.overflowWatermark<n.summary.discardedCount)return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};let s=a===void 0?e.announcements:[...e.announcements,a].slice(-100);return{value:{...e,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:i,dismissThrough:n.dismissThrough,announcements:s},needsRefresh:!1,changed:!0}}function Bc(e){if(e?.status!==`fresh`||e.daemonInstanceId===void 0||e.summary===void 0)return;let t=new Set(e.optimisticDismissedIds),n=e.optimisticDismissAllThrough,r=e.notifications.filter(e=>!t.has(e.id)&&(n===void 0||e.order>n.order)),i=rl(e.summary.discardedCount,e.dismissThrough.overflowWatermark,n?.overflowWatermark);return r.length===0&&t.size>0&&(i=0),{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd,daemonInstanceId:e.daemonInstanceId,notifications:r,retainedCount:r.length,discardedCount:i,...il(nl(r)),dismissThrough:e.dismissThrough,pendingDismissedIds:t,dismissAllPending:n!==void 0,announcements:e.announcements}}function Vc(e){return e===`error`?D(`client.sessionNotifications.error.0bc1fb`,`Error`):e===`warning`?D(`client.sessionNotifications.warning.a8b7a4`,`Warning`):D(`client.sessionNotifications.info.e70286`,`Info`)}function Hc(e){return D(`client.sessionNotifications.notification.received.0cb785`,`{value1} notification received.`,{value1:Vc(e.severity)})}function Uc(e){return e.retainedCount+e.discardedCount}function Wc(e){return D(`client.sessionNotifications.notifications.38c528`,`Notifications ({value1})`,{value1:String(Uc(e))})}function Gc(e){let t=e.message.replace(/\s+/gu,` `).trim();if(t===``)return D(`client.sessionNotifications.dismiss.notification.137f92`,`Dismiss {value1} notification`,{value1:Vc(e.severity)});let n=Array.from(t),r=n.length<=80?t:`${n.slice(0,79).join(``).trimEnd()}…`;return D(`client.sessionNotifications.dismiss.notification.600367`,`Dismiss notification: {value1}`,{value1:r})}function Kc(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1)return{kind:`header`};let r=e[n+1];if(r!==void 0)return{kind:`notification`,notificationId:r.id};let i=e[n-1];return i===void 0?{kind:`header`}:{kind:`notification`,notificationId:i.id}}function qc(e){return JSON.stringify([e.machineId,e.cwd,e.sessionId])}function Jc(e,t){return e.has(qc(t))}function Yc(e,t,n){let r=new Set(e),i=qc(t);return n?r.add(i):r.delete(i),r}function Xc(e){return D(`client.sessionNotifications.older.notifications.not.shown.7c54ee`,`{value1} older notifications not shown.`,{value1:String(e)})}function Zc(e){if(!e.truncated)return;let t=Lt/1024;return D(`client.sessionNotifications.message.truncated.at.kib.ac3119`,`Message truncated at {value1} KiB.`,{value1:String(t)})}function Qc(e,t){return e.machineId===t.machineId&&e.sessionId===t.sessionId&&e.cwd===t.cwd}function $c(e,t){if(e===`error`||t===`error`)return`error`;if(e===`warning`||t===`warning`)return`warning`;if(e===`info`||t===`info`)return`info`}function el(e){return{...Lc(e),status:`stale`}}function tl(e,t){return e.length===t.retainedCount&&nl(e)===t.highestSeverity}function nl(e){let t;for(let n of e)t=$c(t,n.severity);return t}function rl(e,t,n){if(e===0||n===void 0)return e;let r=t-e+1;return e-Math.max(0,Math.min(e,n-r+1))}function il(e){return e===void 0?{}:{highestSeverity:e}}var al=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.acceptedSupportByMachine=new Set,this.selectedGeneration=0,this.dismissingNotificationIds=new Set,this.dismissAllPending=!1,this.disposed=!1,this.api=n.api??x,this.onBackgroundError=n.onBackgroundError??((e,t)=>{console.warn(e,t)})}dispose(){this.disposed=!0,this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.acceptedSupportByMachine.clear(),this.dismissingNotificationIds.clear(),this.dismissAllPending=!1}prepareSelectedSession(e,t){this.selectedGeneration+=1,this.selectedTarget=e.archived===!0?void 0:{machineId:t,sessionId:e.id,cwd:e.cwd},this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.selectedTarget===void 0||!this.machineSupportsNotifications(t)?this.setState({selectedNotificationInbox:void 0}):this.setState({selectedNotificationInbox:Lc(this.selectedTarget)})}clearSelectedSession(){this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.setState({selectedNotificationInbox:void 0})}refreshSelectedSession(e,t){let n=this.selectedTarget;if(this.disposed||n?.machineId!==t||n.sessionId!==e.id||n.cwd!==e.cwd||!this.machineSupportsNotifications(t)||!this.machineIsReachable(t))return Promise.resolve();let r=this.selectedGeneration,i=this.selectedRefresh;if(i?.generation===r)return i.trailing=!0,i.promise;this.ensureSelectedProjection(n);let a={generation:r,promise:Promise.resolve(),trailing:!1};return a.promise=this.runSelectedRefresh(a,n).finally(()=>{this.selectedRefresh===a&&(this.selectedRefresh=void 0)}),this.selectedRefresh=a,a.promise}applyInboxEvent(e,t){let n=this.selectedTarget;if(n?.machineId!==e||n.sessionId!==t.summary.sessionId||n.cwd!==t.summary.cwd)return;this.acceptedSupportByMachine.add(e);let r=this.selectedJoin;if(r?.generation===this.selectedGeneration){r.events.push(t);return}let i=zc(this.getState().selectedNotificationInbox,n,t);i.changed&&this.setState({selectedNotificationInbox:i.value}),i.needsRefresh&&this.scheduleSelectedRefresh(n)}syncEnvironment(e,t){if(this.disposed)return;e.machines!==t.machines&&this.pruneRemovedMachines(t.machines);let n=e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||e.machineRuntimes!==t.machineRuntimes,r=this.selectedTarget;if(!n||r===void 0)return;let i=this.machineSupportsNotificationsInState(e,r.machineId)&&this.machineIsReachableInState(e,r.machineId);!this.machineSupportsNotifications(r.machineId)||!this.machineIsReachable(r.machineId)?this.markSelectedStale(r):(this.ensureSelectedProjection(r),i&&this.getState().selectedNotificationInbox?.status===`fresh`||this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId))}shouldFilterLegacyNotification(e,t){return t!==void 0&&t!==``&&this.machineSupportsNotifications(e)}async dismissNotification(e){let t=this.getState().selectedNotificationInbox,n=Bc(t);if(t===void 0||n===void 0||this.dismissAllPending||this.dismissingNotificationIds.has(e)||!n.notifications.some(t=>t.id===e))return;let r=ol(t),i=this.selectedGeneration;this.dismissingNotificationIds.add(e),this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:[...new Set([...t.optimisticDismissedIds,e])]}));try{let t=await this.api.dismissNotification({id:r.sessionId,cwd:r.cwd},n.daemonInstanceId,e,r.machineId);this.isCurrentTarget(r,i)&&this.applyMutationSnapshot(r,t,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)}))}catch(t){this.isCurrentTarget(r,i)&&(this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)})),this.setState({error:D(`client.sessionNotificationController.failed.to.dismiss.notification.080d8f`,`Failed to dismiss notification: {value1}`,{value1:cl(t)})}),await this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId))}finally{this.dismissingNotificationIds.delete(e)}}async dismissAll(){let e=this.getState().selectedNotificationInbox,t=Bc(e);if(e===void 0||t===void 0||this.dismissAllPending||t.retainedCount+t.discardedCount===0)return;let n=ol(e),r=this.selectedGeneration,i={...e.dismissThrough};this.dismissAllPending=!0,this.patchSelectedOverlay(n,e=>({...e,optimisticDismissAllThrough:i}));try{let e=await this.api.dismissAllNotifications({id:n.sessionId,cwd:n.cwd},t.daemonInstanceId,i,n.machineId);this.isCurrentTarget(n,r)&&this.applyMutationSnapshot(n,e,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t})}catch(e){this.isCurrentTarget(n,r)&&(this.patchSelectedOverlay(n,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t}),this.setState({error:D(`client.sessionNotificationController.failed.to.dismiss.session.notifications.5621de`,`Failed to dismiss session notifications: {value1}`,{value1:cl(e)})}),await this.refreshSelectedSession({id:n.sessionId,cwd:n.cwd},n.machineId))}finally{r===this.selectedGeneration&&(this.dismissAllPending=!1)}}async runSelectedRefresh(e,t){do{e.trailing=!1;let n={generation:e.generation,events:[]};this.selectedJoin=n;try{let r=await this.api.notificationInbox({id:t.sessionId,cwd:t.cwd},t.machineId);if(!this.isCurrentTarget(t,e.generation))return;if(!this.machineSupportsNotifications(t.machineId)||!this.machineIsReachable(t.machineId)){this.markSelectedStale(t);return}this.acceptedSupportByMachine.add(t.machineId);let i=this.getState().selectedNotificationInbox,a=i===void 0||sl(i,t,r)?Rc(i,t,r):i;for(let r of[...n.events].sort((e,t)=>e.summary.inboxRevision-t.summary.inboxRevision)){let n=zc(a,t,r);a=n.value,n.needsRefresh&&(e.trailing=!0)}this.setState({selectedNotificationInbox:a})}catch(n){if(this.isCurrentTarget(t,e.generation)){let e=this.getState().selectedNotificationInbox;e!==void 0&&Qc(e,t)&&e.status!==`stale`&&this.setState({selectedNotificationInbox:{...e,status:`stale`}}),this.onBackgroundError(`Failed to refresh notifications for session ${t.sessionId}`,n)}return}finally{this.selectedJoin===n&&(this.selectedJoin=void 0)}}while(e.trailing&&this.isCurrentTarget(t,e.generation)&&this.machineIsReachable(t.machineId))}applyMutationSnapshot(e,t,n){let r=this.getState().selectedNotificationInbox;if(r===void 0||!Qc(r,e))return;if(!this.machineSupportsNotifications(e.machineId)||!this.machineIsReachable(e.machineId)){this.setState({selectedNotificationInbox:{...n(r),status:`stale`}});return}let i=sl(r,e,t)?Rc(r,e,t):r;this.setState({selectedNotificationInbox:n(i)})}patchSelectedOverlay(e,t){let n=this.getState().selectedNotificationInbox;n!==void 0&&Qc(n,e)&&this.setState({selectedNotificationInbox:t(n)})}ensureSelectedProjection(e){let t=this.getState().selectedNotificationInbox;t!==void 0&&Qc(t,e)||this.setState({selectedNotificationInbox:Lc(e)})}scheduleSelectedRefresh(e){queueMicrotask(()=>{!this.disposed&&this.selectedTarget!==void 0&&Qc(this.selectedTarget,e)&&this.refreshSelectedSession({id:e.sessionId,cwd:e.cwd},e.machineId)})}markSelectedStale(e){let t=this.getState().selectedNotificationInbox;t!==void 0&&Qc(t,e)&&t.status!==`stale`&&this.setState({selectedNotificationInbox:{...t,status:`stale`}})}pruneRemovedMachines(e){let t=new Set(e.map(e=>e.id));t.size===0&&t.add(`local`);for(let e of[...this.acceptedSupportByMachine])t.has(e)||this.acceptedSupportByMachine.delete(e)}isCurrentTarget(e,t){return!this.disposed&&t===this.selectedGeneration&&this.selectedTarget!==void 0&&Qc(this.selectedTarget,e)}machineSupportsNotifications(e){return this.machineSupportsNotificationsInState(this.getState(),e)}machineSupportsNotificationsInState(e,t){return this.acceptedSupportByMachine.has(t)||e.machineRuntimes[t]?.ok===!0}machineIsReachable(e){return this.machineIsReachableInState(this.getState(),e)}machineIsReachableInState(e,t){let n=e.machines.find(e=>e.id===t);if(t===`local`||n?.kind===`local`)return!0;let r=e.machineStatuses[t]?.status??n?.status;return r===void 0||r===`unknown`||r===`online`}};function ol(e){return{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd}}function sl(e,t,n){return!Qc(e,t)||e.daemonInstanceId!==n.daemonInstanceId||e.summary===void 0||n.summary.inboxRevision>=e.summary.inboxRevision}function cl(e){return e instanceof Error?e.message:String(e)}function ll(e){return e?.status!==`folder`}var ul=class{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}},dl=`pi-web:workspace-selection:v1`,fl=class{constructor(e=Vs()){this.workspaceIdsByProject=new Hs(dl,Us,e)}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}};function pl(e,t){let n=t?.targetWorkspaceId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestWorkspaceId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e[0]:e[0]}var ml=50,hl=[`machine`,`project`,`workspace`,`session`],gl=class{constructor(e,t,n,r,i=new ul,a={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessions=r,this.workspaceSelection=i,this.workspaceListRequests=new Map,this.api=a.api??x,this.navigateToWorkspace=a.navigateToWorkspace,this.captureNavigation=a.captureNavigation,this.beginNavigationOperation=a.beginNavigationOperation,this.onBackgroundError=a.onBackgroundError??((e,t)=>{console.warn(e,t)}),this.browserErrors=new $n(e,t),this.topologyRefreshes=new gr(a.topologyRefreshDebounceMs??ml)}clearSelection(e){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,workspaceResolution:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...Hn()}),e?.updateUrl!==!1&&this.updateUrl()}forgetProject(e){let t=M(this.getState());this.browserErrors.discard(Wn(t,e)),this.workspaceSelection.forgetProject(hr(t,e));let n=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([t])=>t!==e));this.setState({workspacesByProjectId:n})}async selectProject(e,t){let n=t?.navigation??this.beginNavigationOperation?.(hl);if(!this.navigationIsCurrent(n)||!vl(t))return;let r=M(this.getState()),i=Wn(r,e.id);this.sessions.clearActiveSession(),this.setState({selectedProject:e,workspaceResolution:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...Hn()});let a=this.beginWorkspaceListRequest(e.id,r);try{let o=t?.signal===void 0?await this.api.workspaceResolution(e.id,r):await this.api.workspaceResolution(e.id,r,{signal:t.signal}),s=[...o.workspaces];if(!a()||!this.navigationIsCurrent(n)||!vl(t)||M(this.getState())!==r||this.getState().selectedProject?.id!==e.id)return;if(this.setState({workspaceResolution:o,workspaces:s,workspacesByProjectId:{...this.getState().workspacesByProjectId,[e.id]:s},isLoadingWorkspaces:!1}),o.status===`degraded`)throw Sl(o);let c=pl(s,{targetWorkspaceId:t?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(hr(r,e.id))});if(c)return await this.selectWorkspace(c,{...t,sessionId:t?.sessionId,updateUrl:t?.updateUrl,navigation:n});if(t?.workspaceId!==void 0&&t.workspaceId!==``)return this.browserErrors.report(i,D(`ui.main.06529052d1e0`,`Workspace not found: {arg0}`,{arg0:t.workspaceId})),D(`ui.main.06529052d1e0`,`Workspace not found: {arg0}`,{arg0:t.workspaceId});t?.updateUrl!==!1&&this.navigationIsCurrent(n)&&this.updateUrl()}catch(a){return this.navigationIsCurrent(n)&&vl(t)&&M(this.getState())===r&&this.getState().selectedProject?.id===e.id&&this.setState({isLoadingWorkspaces:!1}),t?.signal?.aborted!==!0&&this.browserErrors.report(i,String(a)),String(a)}}async selectWorkspace(e,t){let n=t?.navigation??this.beginNavigationOperation?.(hl);if(!this.navigationIsCurrent(n)||!vl(t))return;let r=M(this.getState()),i=Gn(r,e.projectId,e.id);this.workspaceSelection.rememberWorkspace({...e,projectId:hr(r,e.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:e,isLoadingWorkspaces:!1,...Hn()});try{let a=t?.signal===void 0?await this.api.sessions(e.path,r):await this.api.sessions(e.path,r,{signal:t.signal}),o=Qr(e.path,a,r);if(!this.navigationIsCurrent(n)||!vl(t)||M(this.getState())!==r||this.getState().selectedWorkspace?.id!==e.id||this.getState().selectedProject?.id!==e.projectId)return;this.setState({sessions:o});let s=this.sessions.preferredSession(e.path,o,t?.sessionId);if(!this.navigationIsCurrent(n)||!vl(t))return;if(s)await this.sessions.selectSession(s,{deferChatLoading:!0,updateUrl:t?.updateUrl,...n===void 0?{}:{navigation:n}});else if(t?.sessionId!==void 0&&t.sessionId!==``)return this.browserErrors.report(i,D(`ui.main.0041c3cf98cd`,`Session not found: {arg0}`,{arg0:t.sessionId})),D(`ui.main.0041c3cf98cd`,`Session not found: {arg0}`,{arg0:t.sessionId});else t?.updateUrl!==!1&&this.updateUrl()}catch(e){return t?.signal?.aborted!==!0&&this.browserErrors.report(i,String(e)),String(e)}}async refreshProjectWorkspaces(e,t=M(this.getState()),n){return(await this.refreshProjectWorkspaceList(e,t,n)).workspaces}async refreshProjectWorkspaceList(e,t,n){if(!vl(n))return{workspaces:[],isCurrent:()=>!1};let r=this.getState().projects.find(t=>t.id===e);if(r===void 0)throw Error(D(`client.workspaceController.project.not.found.3b6bf4`,`Project not found`));let i=this.beginWorkspaceListRequest(e,t),a=n?.signal===void 0?await this.api.workspaceResolution(r.id,t):await this.api.workspaceResolution(r.id,t,{signal:n.signal}),o=[...a.workspaces];if(i()&&vl(n)&&M(this.getState())===t){if(this.getState().selectedProject?.id===r.id&&this.setState({workspaceResolution:a}),a.status===`degraded`)throw Sl(a);this.applyProjectWorkspaces(r.id,o)}return{workspaces:o,isCurrent:i}}async refreshSelectedProjectTopology(){let e=this.getState(),t=e.selectedProject;if(t===void 0||e.isLoadingWorkspaces)return;let n=M(e);await this.topologyRefreshes.request(hr(n,t.id),async()=>{if(this.getState().isLoadingWorkspaces)return;let e=this.beginWorkspaceListRequest(t.id,n);try{let r=await this.api.workspaceResolution(t.id,n),i=this.getState();if(!e()||M(i)!==n||i.selectedProject?.id!==t.id)return;if(this.setState({workspaceResolution:r}),r.status===`degraded`)throw Sl(r);this.applyProjectWorkspaces(t.id,[...r.workspaces])}catch(e){this.onBackgroundError(`Failed to refresh workspaces for project ${t.id} on ${n}`,e)}})}async refreshAfterWorkspaceDeleted(e,t,n=M(this.getState()),r){if(!vl(r))return;let i=this.beginNavigationOperation?.(hl),{workspaces:a,isCurrent:o}=await this.refreshProjectWorkspaceList(e,n,r);if(!o()||!this.navigationIsCurrent(i)||!vl(r))return;let s=this.getState();if(M(s)!==n||s.selectedProject?.id!==e||s.selectedWorkspace?.id!==t)return;let c=_l(this.getState(),this.captureNavigation),l=yl(a);this.navigateToWorkspace===void 0?l===void 0?this.navigationIsCurrent(i)&&vl(r)&&this.clearSelection():await this.selectWorkspace(l,{...r,...i===void 0?{}:{navigation:i}}):await this.navigateToWorkspace(l,{expected:c})}beginWorkspaceListRequest(e,t){let n=hr(t,e),r=(this.workspaceListRequests.get(n)??0)+1;return this.workspaceListRequests.set(n,r),()=>this.workspaceListRequests.get(n)===r}applyProjectWorkspaces(e,t){let n=this.getState(),r={...n.workspacesByProjectId,[e]:t};n.selectedProject?.id===e?this.setState({workspaces:t,workspacesByProjectId:r,...this.refreshedSelection(n.selectedWorkspace,t)}):this.setState({workspacesByProjectId:r})}refreshedSelection(e,t){if(e===void 0)return;let n=t.find(t=>t.id===e.id);if(!(n===void 0||bl(e,n)))return{selectedWorkspace:n}}navigationIsCurrent(e){return e===void 0||e.isCurrent()}};function _l(e,t){return t?.()??{machineId:M(e),projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,...e.selectedSession===void 0||Reflect.get(e.selectedSession,`clientPendingStart`)!==!0?{sessionId:e.selectedSession?.id}:{}}}function vl(e){return e?.signal?.aborted!==!0&&e?.isCurrent?.()!==!1}function yl(e){return e.find(e=>e.isMain)??e[0]}function bl(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>bl(e,t[n]));if(!xl(e)||!xl(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&bl(e[n],t[n]))}function xl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Sl(e){return Error(e.diagnostics.map(({message:e})=>e).join(`; `)||D(`client.workspaceController.authorityDegraded`,`Workspace authority is degraded`))}var Cl=`core.workspace.files--file`,wl=`core.workspace.terminal--terminal`,Tl=`pi-web:machine-navigation:v1`,El=class{constructor(e=Vs()){this.snapshotsByMachine=new Hs(Tl,jl,e)}latest(e){let t=this.snapshotsByMachine.get(e);return t?.machineId===e?Al(t):void 0}remember(e){this.snapshotsByMachine.set(e.machineId,Al(e))}forget(e){this.snapshotsByMachine.delete(e)}};function Dl(e){return{machineId:e,surface:{}}}function Ol(e,t={}){let n=e.selectedWorkspace===void 0?{}:ra(t),r=e.selectedSession?.id;return{machineId:e.selectedMachine?.id??`local`,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:r,tool:e.workspaceTool,view:e.mainView,surface:{...Object.keys(n).length===0?{}:{contributionQuery:n}}}}function kl(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view}}function Al(e){let t=e.surface.contributionQuery;return{...e,surface:{...e.surface,...t===void 0?{}:{contributionQuery:ra(t)}}}}function jl(e){if(!Il(e))return;let t=Fl(e,`machineId`);if(t===void 0)return;let n=Fl(e,`view`),r=n===`files`||n===`core:workspace.files`?`core:workspace.files`:n===`git`||n===`core:workspace.git`?`core:workspace.git`:n===`terminal`||n===`core:workspace.terminal`?`core:workspace.terminal`:void 0,i=Nl(Fl(e,`tool`))??r,a=Sa(n)??(r===void 0?void 0:`workspace`);return{machineId:t,projectId:Fl(e,`projectId`),workspaceId:Fl(e,`workspaceId`),sessionId:Fl(e,`sessionId`),...i===void 0?{}:{tool:i},...a===void 0?{}:{view:a},surface:Ml(e.surface)}}function Ml(e){if(!Il(e))return{};let t=Il(e.contributionQuery)?e.contributionQuery:{},n=Fl(e,`selectedFilePath`),r=Fl(e,`selectedTerminalId`),i=Fl(e,`selectedDiffPath`),a=ra({...n===void 0?{}:{[Cl]:n},...r===void 0?{}:{[wl]:r},...i===void 0?{}:{"core.workspace.git--diff":i},...t});return{...Object.keys(a).length===0?{}:{contributionQuery:a}}}function Nl(e){return Pl(e)?e:void 0}function Pl(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Fl(e,t){let n=e[t];return typeof n==`string`&&n!==``?n:void 0}function Il(e){return typeof e==`object`&&!!e}function Ll(e,t,n){if(t!==void 0&&zl(t.path)===zl(n.cwd))return{machineId:e,projectId:t.projectId,workspaceId:t.id,root:t.path}}function Rl(e,t){let n=e.trim();if(n===``||/^[#?]/.test(n)||n.startsWith(`//`)||/^[a-z][a-z\d+.-]*:/i.test(n))return;let r;try{r=decodeURIComponent(n.split(/[?#]/,1)[0]??``)}catch{return}if(r===``||/[\\\u0000-\u001f\u007f]/.test(r))return;if(r.startsWith(`/`)){let e=`${zl(t.root)}/`;if(!r.startsWith(e)||(r=r.slice(e.length),r===``))return}let i=r.split(`/`).filter(e=>e!==``&&e!==`.`).join(`/`);return i===``?void 0:i}function zl(e){return e.replace(/\/+$/,``)}var Bl={archiveIdleEnabled:!0,archiveIdleDays:`30`,deleteArchivedEnabled:!1,deleteArchivedDays:`90`};function Vl(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:D(`client.sessionCleanupUi.enable.at.least.one.cleanup.action.d2ce50`,`Enable at least one cleanup action.`)};let t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){let n=Zl(e.archiveIdleDays,D(`client.sessionCleanupUi.archive.idle.sessions.after.6d41ea`,`Archive idle sessions after`));if(typeof n==`string`)return{ok:!1,error:n};t.archiveIdleDays=n}if(e.deleteArchivedEnabled){let n=Zl(e.deleteArchivedDays,D(`client.sessionCleanupUi.delete.archived.sessions.after.923bee`,`Delete archived sessions after`));if(typeof n==`string`)return{ok:!1,error:n};t.deleteArchivedDays=n}return{ok:!0,request:t}}function Hl(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null,projectId:e?.projectId??null})}function Ul(e){if(e.canCleanup===!1||e.loading===!0||e.running===!0||e.preview===void 0)return!1;let t=Vl(e.draft);if(!t.ok)return!1;if(e.previewRequest===void 0){if(e.canCleanup!==!0||!Wl(e.draft,e.preview))return!1}else if(Ql(t.request)!==Ql(e.previewRequest))return!1;return Gl(e.preview)}function Wl(e,t){let n=Vl(e);return n.ok?Ql(n.request)===Ql(t.thresholds):!1}function Gl(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function Kl(e,t){let n=e.projects.map(e=>e.cwd);if(t===void 0)return n;let r=new Set(t);return n.filter(e=>r.has(e))}function ql(e,t){let n=new Set(Kl(e,t)),r=e.projects.filter(e=>n.has(e.cwd));return{...e,projects:r,totals:r.reduce((e,t)=>({archiveCount:e.archiveCount+t.archiveCount,deleteCount:e.deleteCount+t.deleteCount}),{archiveCount:0,deleteCount:0})}}function Jl(e,t){return t(Yl(e))}function Yl(e){let t=e.totals.archiveCount,n=e.totals.deleteCount,r=[];t>0&&r.push(D(`client.sessionCleanupUi.archive.idle.sessions.27a4f1`,`archive {value1} idle sessions`,{value1:String(t)})),n>0&&r.push(D(`client.sessionCleanupUi.permanently.delete.archived.sessions.360209`,`permanently delete {value1} archived sessions`,{value1:String(n)}));let i=r.length===0?D(`client.sessionCleanupUi.run.cleanup.233f8e`,`run cleanup`):r.join(D(`client.sessionCleanupUi.and.2f4b60`,` and `));return D(`client.sessionCleanupUi.run.cleanup.and.permanent.deletion.only.applies.to.archived.sessions.a.9775e2`,`Run cleanup and {value1}?
|
|
27
|
+
`))+1;return e.slice(t)}var Ds=class{constructor(e=`normal`){this.scope=e,this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId=`local`}connect(e,t,n,r=`local`,i){this.close(),this.machineId=r,this.session=e,this.onEvent=t,this.onReconnect=n,this.onInitialOpen=i,this.shouldReconnect=!0,this.open()}setHandler(e){this.onEvent=e}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Fs(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.onInitialOpen=void 0,this.hasOpened=!1,this.machineId=`local`}open(){let e=this.session;if(e===void 0||e.id===``||e.cwd===``||!this.shouldReconnect)return;let t=zn(e,this.machineId,this.scope);this.socket=t,t.onopen=()=>{if(this.socket!==t)return;this.reconnectDelay=500;let e=this.hasOpened;this.hasOpened=!0,e?this.onReconnect?.():this.onInitialOpen?.()},t.onmessage=n=>void this.handleMessage(n.data,t,e),t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t,n){let r=ks(await Ps(e));this.socket===t&&r!==void 0&&(r.type===`session.diagnostic`?console.error(`[PI WEB] Session diagnostic`,{machineId:this.machineId,sessionId:n.id,cwd:n.cwd,message:r.message}):(r.type!==`notifications.inbox`||n.id===r.summary.sessionId&&n.cwd===r.summary.cwd)&&this.onEvent?.(r))}},Os=class{constructor(e=`normal`){this.scope=e,this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId=`local`}connect(e,t,n=`local`){this.close(),this.machineId=n,this.onEvent=e,this.onOpen=t,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Fs(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId=`local`}open(){if(!this.shouldReconnect)return;let e=Bn(this.machineId,this.scope);this.socket=e,e.onopen=()=>{this.socket===e&&(this.reconnectDelay=500,this.onOpen?.())},e.onmessage=t=>void this.handleMessage(t.data,e),e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t){let n=As(await Ps(e));this.socket===t&&n!==void 0&&this.onEvent?.(n)}};function ks(e){let t=Ns(e);if(t===`notifications.inbox`)return Ms(()=>he(e));if(t===`dialog.opened`)return Ms(()=>ae(e));if(t===`dialog.closed`)return Ms(()=>ee(e));let n=Ms(()=>a(e));return n===void 0?void 0:js(n,e)}function As(e){if(Ns(e)===`notices.updated`)return Ms(()=>p(e));if(Ns(e)===`sessions.unread`)return Ms(()=>Se(e));if(Ns(e)===`session.startup`)return Ms(()=>jt(e));if(typeof e==`object`&&e){if(Ns(e)===`terminal.created`||Ns(e)===`terminal.exited`){if(!(`terminal`in e))return;let t=Ms(()=>xe(e.terminal));return t===void 0?void 0:{type:Ns(e)===`terminal.created`?`terminal.created`:`terminal.exited`,terminal:t}}if(Ns(e)===`terminal.closed`)return!(`terminalId`in e)||typeof e.terminalId!=`string`||e.terminalId===``||!(`cwd`in e)||typeof e.cwd!=`string`||e.cwd===``?void 0:{type:`terminal.closed`,terminalId:e.terminalId,cwd:e.cwd};if(Ns(e)===`workspace.activity`){if(!(`activity`in e))return;let t=Ms(()=>we(e.activity));return t===void 0?void 0:{type:`workspace.activity`,activity:t}}}return Ms(()=>fe(e))}function js(e,t){return typeof t!=`object`||!t||!(`seq`in t)?e:typeof t.seq==`number`?{...e,seq:t.seq}:e}function Ms(e){try{return e()}catch{return}}function Ns(e){if(typeof e!=`object`||!e||!(`type`in e))return``;let t=e.type;return typeof t==`string`?t:``}async function Ps(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 Fs(e){e!==void 0&&(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING?e.onopen=()=>{e.close()}:e.close())}function Is(e){return e?.ok===!0}function Ls(e){return{authoritative:Is(e)}}function Rs(e,t,n={}){if(e===void 0)return`unknown`;let r=(t?.sessionId===e.id?t.persisted:void 0)??e.persisted;return r===!0?`persisted`:r===!1||$r(e)?`transient`:n.authoritative===!0?`unknown`:`persisted`}function zs(e,t,n){return e!==void 0&&e.archived!==!0&&Rs(e,t,n)===`persisted`}function Bs(e,t,n){return e!==void 0&&e.archived!==!0&&Rs(e,t,n)===`transient`}function Vs(){try{return typeof sessionStorage>`u`?void 0:sessionStorage}catch{return}}var Hs=class{constructor(e,t,n=Vs()){this.storageKey=e,this.storage=n,this.values=new Map;for(let[r,i]of Ws(e,t,n))this.values.set(r,i)}get(e){return this.values.get(e)}set(e,t){this.values.set(e,t),this.save()}delete(e){this.values.delete(e),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}let e={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(e))}catch{}}};function Us(e){return typeof e==`string`&&e!==``?e:void 0}function Ws(e,t,n){try{let r=n?.getItem(e);if(r==null||r===``)return[];let i=JSON.parse(r);if(!Gs(i))return[];let a=[];for(let e of i.entries){let n=e[0],r=t(e[1]);r!==void 0&&a.push([n,r])}return a}catch{return[]}}function Gs(e){return!Ks(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`&&e[0]!==``)}function Ks(e){return typeof e==`object`&&!!e}var qs=class{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}},Js=`pi-web:session-selection:v1`,Ys=class{constructor(e=Vs()){this.sessionIdsByCwd=new Hs(Js,Us,e)}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}};function Xs(e,t){let n=t?.targetSessionId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestSessionId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>e.archived!==!0):e.find(e=>e.archived!==!0)}function Zs(e,t){return t?.archived===!0&&!e.some(e=>e.archived!==!0)}function Qs(e,t,n){return $s(e,[t],n)}function $s(e,t,n){let r=new Set(t);return e.map(e=>r.has(e.id)?{...e,archived:!0,archivedAt:n}:e)}function ec(e,t,n){return tc(e,t,[n])}function tc(e,t,n){if(t===void 0||!n.includes(t))return{type:`unchanged`};let r=new Set(n),i=e.find(e=>!r.has(e.id)&&e.archived!==!0);return i===void 0?{type:`clear`}:{type:`select`,session:i}}var nc=/timed out|operation was aborted|request cancelled/i;function rc(e){return e instanceof te&&(e.status===504||e.status===499)||e instanceof Error&&nc.test(e.message)}function ic(e){return rc(e)?D(`ui.main.634a1618e706`,`The session daemon request timed out. The conversation is still running.`):e instanceof Error?e.message:String(e)}var ac=[500,1500,3e3],oc=Symbol(`retired-read`);async function sc(e,t,n,r=!0){let i=()=>n?.aborted!==!0&&t(),a=0;for(;i();)try{let t=await cc(e(),n);return t!==oc&&i()?t:void 0}catch(e){if(n?.aborted===!0||r&&!t())return;let i=ac[a];if(!r||!(e instanceof Oe)||i===void 0)throw e;let o;try{await cc(new Promise(e=>{o=setTimeout(e,i)}),n)}finally{o!==void 0&&clearTimeout(o)}a+=1}}function cc(e,t){if(t===void 0)return e;let n=()=>void 0,r=new Promise(e=>{n=()=>{e(oc)},t.addEventListener(`abort`,n,{once:!0}),t.aborted&&n()});return Promise.race([e,r]).finally(()=>{t.removeEventListener(`abort`,n)})}var lc=100,uc=500,dc=5e3,fc=[`machine`,`project`,`workspace`,`session`],pc=[`machine`,`project`,`workspace`,`session`],mc=class{constructor(e,t,n,r=new qs,i={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessionSelection=r,this.selectedSessionLoadDeferred=!1,this.selectionSeq=0,this.pendingTreeActions=new Set,this.disposed=!1,this.pendingTranscriptEvents=[],this.selectedReadGeneration=0,this.workspaceReadGeneration=0,this.selectedReadRecoveries=new Set,this.workspaceReadRecoveries=new Set,this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.sessionRefreshInFlight=!1,this.searchSeq=0,this.searchTargetSeq=0,this.pendingQueuedSendSeq=0,this.pendingSessionStarts=new Map,this.suppressedCreatedSessions=new Map,this.selectedSessionRefreshes=new gr,this.workspaceSessionRefreshes=new gr,this.socket=i.socket??new Ds,this.api=i.api??x,this.transcripts=i.transcripts??new us,this.transcriptSnapshot=i.transcriptSnapshot??((...e)=>this.api.transcriptSnapshot(...e)),this.notifications=i.notifications,this.automaticSessionCandidates=i.automaticSessionCandidates??(e=>e),this.replacePromptEditorText=i.replacePromptEditorText,this.canMutateQueueMessage=i.canMutateQueueMessage??(()=>!1),this.onSelectedSessionReady=i.onSelectedSessionReady,this.observeSessionSnapshot=i.observeSessionSnapshot,this.isChatVisible=i.isChatVisible??(()=>!0),this.isPendingSessionStartRouteCurrent=i.isPendingSessionStartRouteCurrent,this.onPendingSessionStartCommitted=i.onPendingSessionStartCommitted,this.onModelScopeChanged=i.onModelScopeChanged,this.navigateToSession=i.navigateToSession,this.captureNavigation=i.captureNavigation,this.beginNavigationOperation=i.beginNavigationOperation,this.browserErrors=new $n(e,t)}applyGlobalEvent(e){e.type===`status.update`?this.queueStatusUpdate(e.status):e.type===`activity.update`?this.queueActivityUpdate(e.activity):e.type===`session.created`?this.applyCreatedSession(e.session):e.type===`session.name`?this.applySessionName(e.sessionId,e.name):e.type===`models.changed`?this.onModelScopeChanged?.(e.revision):e.type===`session.startup`&&this.queueStartupProgress(e)}dispose(){this.disposed=!0,this.retireReadRecoveries([`machine`]),this.selectedSessionLoadDeferred=!1,this.selectionSeq+=1,this.searchSeq+=1,this.stopPolling(),this.searchTimer!==void 0&&clearTimeout(this.searchTimer),this.searchTimer=void 0,this.selectedSessionJoinNavigation=void 0,this.socket.close(),this.clearPendingUpdates()}updatePolling(){this.stopPolling(),this.getState().selectedWorkspace!==void 0&&(this.sessionPollTimer=setInterval(()=>{this.sessionRefreshInFlight||(this.sessionRefreshInFlight=!0,this.refreshCurrentWorkspaceSessions().finally(()=>{this.sessionRefreshInFlight=!1}))},dc))}clearActiveSession(){this.retireReadRecoveries([`session`]),this.selectedSessionLoadDeferred=!1,this.selectionSeq+=1,this.selectedSessionJoinNavigation=void 0,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0})}deselectSession(e){let t=this.getState(),n=t.selectedSession?.cwd??t.selectedWorkspace?.path;e?.forgetRememberedSelection===!0&&n!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(n)),this.clearActiveSession(),e?.updateUrl!==!1&&this.updateUrl()}async selectSessionAfterNavigation(e,t,n){this.navigateToSession===void 0?await this.selectSession(e,{updateUrl:n?.updateUrl}):await this.navigateToSession(e,{...n?.updateUrl===!1?{replace:!0}:{},expected:t})}async clearSessionAfterNavigation(e){if(!this.navigationSelectionMatchesState(e))return;let t=this.getState().selectedSession?.cwd??this.getState().selectedWorkspace?.path;this.navigateToSession===void 0?this.deselectSession({forgetRememberedSelection:!0}):(t!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(t)),await this.navigateToSession(void 0,{expected:e}))}async clearSelectionAfterArchivedCollapse(){let e=this.getState();Zs(this.automaticSessionCandidates(e.sessions),e.selectedSession)&&await this.clearSessionAfterNavigation(this.navigationSelection())}async startSession(e){let t=this.getState().selectedWorkspace;if(!t)return;let n=M(this.getState()),r=typeof e==`function`?e:void 0,i=typeof e==`function`?void 0:e,a=i?.updateUrl!==!1,o=this.createPendingSessionStart(t,n,this.navigationSelection(),a);this.pendingSessionStarts.set(o.tempId,o),this.insertAndSelectPendingSession(o.session,i),a&&(o.expectedNavigation=this.navigationSelection()),o.navigation=this.beginNavigationOperation?.(fc);try{if(r!==void 0&&!await r()){this.cancelUnstartedSession(o);return}let e=await this.api.startSession(t.path,n,o.tempId);await this.resolvePendingSessionStart(o.tempId,e)}catch(e){this.failPendingSessionStart(o.tempId,e)}}async refreshPinnedSessions(e,t=M(this.getState())){try{let n=await this.api.pinned(e,t);if(M(this.getState())!==t||this.getState().selectedWorkspace?.path!==e)return;this.setState({pinnedSessionIds:n.sessionIds})}catch{M(this.getState())===t&&this.getState().selectedWorkspace?.path===e&&this.setState({pinnedSessionIds:[]})}}togglePinned(e){if(e.persisted===!1)return;let t=this.getState(),n=t.pinnedSessionIds.includes(e.id),r=n?t.pinnedSessionIds.filter(t=>t!==e.id):[...t.pinnedSessionIds,e.id],i=M(t);this.setState({pinnedSessionIds:r}),(async()=>{try{let t=n?await this.api.unpin(e,i):await this.api.pin(e,i),r=this.getState();if(M(r)!==i||r.selectedWorkspace?.path!==e.cwd)return;let a=t.pinned;this.setState({pinnedSessionIds:a?[...new Set([...this.getState().pinnedSessionIds,e.id])]:this.getState().pinnedSessionIds.filter(t=>t!==e.id)})}catch(t){let r=this.getState();if(M(r)!==i||r.selectedWorkspace?.path!==e.cwd)return;this.setState({pinnedSessionIds:n?[...new Set([...r.pinnedSessionIds,e.id])]:r.pinnedSessionIds.filter(t=>t!==e.id)}),this.reportSessionError(e,i,t)}})()}searchSessions(e){let t=this.getState(),n=t.selectedWorkspace,r=M(t);this.searchSeq+=1;let i=this.searchSeq;this.searchTimer!==void 0&&clearTimeout(this.searchTimer),this.searchTimer=void 0,this.setState({sessionSearchQuery:e,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``});let a=e.trim();n!==void 0&&a!==``&&(this.setState({isSearchingSessions:!0}),this.searchTimer=setTimeout(()=>{this.searchTimer=void 0,this.performSessionSearch(i,a,n.id,n.path,r)},250))}async performSessionSearch(e,t,n,r,i){try{let a=await this.api.searchContent(r,t,i),o=this.getState();if(e!==this.searchSeq||M(o)!==i||o.selectedWorkspace?.id!==n||o.sessionSearchQuery.trim()!==t)return;this.setState({sessionSearchResults:a,isSearchingSessions:!1})}catch(t){let r=this.getState();if(e!==this.searchSeq||M(r)!==i||r.selectedWorkspace?.id!==n)return;this.setState({sessionSearchResults:{results:[],matchCount:0,truncated:!1},isSearchingSessions:!1,sessionSearchError:String(t)})}}preferredSession(e,t,n){if(Ca(n)){let t=this.pendingSessionStarts.get(n);return t!==void 0&&!t.discarded&&t.cwd===e&&this.isCurrentPendingStart(t)?t.session:void 0}if(n!==void 0&&n!==``)return Xs(t,{targetSessionId:n});let r=Gt()?t.filter(e=>!$r(e)):t,i=this.sessionSelection.latestSessionId(this.workspaceSelectionKey(e));return i!==void 0&&i!==``&&r.some(e=>e.id===i)?Xs(r,{latestSessionId:i}):Xs(this.automaticSessionCandidates(r))}canReuseSelectedSession(){return!this.disposed&&Nc(this.selectedSessionJoinNavigation)}get isChatLoadDeferred(){return this.selectedSessionLoadDeferred}async loadSelectedSession(){if(this.disposed||!this.selectedSessionLoadDeferred||!this.isChatVisible())return;let e=this.getState().selectedSession;if(e===void 0)return;let t=this.beginNavigationOperation?.(pc);await this.selectSession(e,{updateUrl:!1,navigation:t})}async selectSession(e,t){if(this.disposed||!Nc(t?.navigation))return;if(this.retireReadRecoveries([`session`]),I(e)){this.selectClientPendingStartSession(e,t);return}let n=M(this.getState()),r=this.captureSessionErrorOwner(e);this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)});let i=++this.selectionSeq;this.selectedSessionJoinNavigation=t?.navigation,this.socket.close(),this.streamWatermark=void 0,this.clearPendingUpdates(),this.selectedSessionLoadDeferred=t?.deferChatLoading===!0||!this.isChatVisible(),this.selectedSessionLoadDeferred?this.notifications?.clearSelectedSession():this.notifications?.prepareSelectedSession(e,n);let a=this.sessionCacheKey(e.id),o=this.selectedSessionLoadDeferred?{messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,messagePageLeafId:void 0}:this.transcripts.cachedView(a);if(this.setState({selectedSession:e,sessionSearchTarget:void 0,...o,isLoadingEarlierMessages:!1,...t?.preserveTreeDialog===!0?{}:{treeDialog:void 0},status:e.archived===!0?void 0:this.getState().sessionStatuses[e.id],activity:e.archived===!0?void 0:this.getState().sessionActivities[e.id],pendingDialogs:e.archived===!0?[]:this.getState().sessionStatuses[e.id]?.pendingDialogs??[],closedDialogs:[],availableThinkingLevels:[]}),this.selectedSessionLoadDeferred){this.selectedSessionJoinNavigation=void 0,t?.updateUrl!==!1&&this.updateUrl();return}let s=!1;try{if(e.archived===!0){let o=this.browserErrors.captureRecovery(Kn(n,e.id,r),`session-refresh`),s=await this.api.messages(e,{limit:lc},n),c=this.getState().selectedSession;if(i!==this.selectionSeq||M(this.getState())!==n||c?.id!==e.id||c.cwd!==e.cwd||c.path!==e.path||c.archived!==e.archived||!Nc(t?.navigation))return;this.browserErrors.clearRecovered(o);let l=this.transcripts.mergeHistory(a,s);this.setState({...l,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingDialogs:[],closedDialogs:[]}),this.onSelectedSessionReady?.({machineId:n,session:e}),t?.updateUrl!==!1&&this.updateUrl();return}this.socket.connect(e,t=>{this.isCurrentSessionSelection(e.id,n,i)&&this.applyEvent(t)},()=>{this.isCurrentSessionSelection(e.id,n,i)&&this.isSelectedSessionScope(e,n)&&this.refreshSelectedSession(e.id,{recoverNetwork:!0})},n,()=>{let t=this.getState().selectedSession;this.isCurrentSessionSelection(e.id,n,i)&&t?.cwd===e.cwd&&t.path===e.path&&this.refreshSessionNotifications(e,n)}),s=!0;let o={session:e,machineId:n,selectionSeq:i,errorOwner:r,...t?.navigation===void 0?{}:{navigation:t.navigation}};if(t?.propagateRefreshError===!0)await this.requestSelectedSessionRefresh(o);else if(!await this.joinSelectedSessionSnapshot(o))return;if(!this.isCurrentRefreshTarget(o)||!Nc(t?.navigation))return;this.refreshAvailableThinkingLevels(),this.onSelectedSessionReady?.({machineId:n,session:e}),t?.updateUrl!==!1&&this.updateUrl()}catch(a){let o=Nc(t?.navigation);if(!o||i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id){if(this.reportSessionError(e,n,a,r),t?.propagateRefreshError===!0&&o&&this.isSelectedSessionIdentity(e.id,n))throw a;return}if($r(e)&&Mc(a)){await this.recreateCachedNewSession(e,t,i,r);return}if(this.reportSessionError(e,n,a,r),t?.propagateRefreshError===!0)throw a}finally{let r=Nc(t?.navigation);i===this.selectionSeq&&r&&(this.selectedSessionJoinNavigation=void 0),s&&!Nc(t?.navigation)&&this.isCurrentSessionSelection(e.id,n,i)&&this.socket.close()}}async loadEarlierMessages(){let e=this.getState(),t=e.selectedSession;if(!t||e.isLoadingEarlierMessages||e.messagePageStart<=0)return;let n=M(e),r=this.captureSessionErrorOwner(t),i=this.selectionSeq,a=j(n,t.id),o=this.transcripts.historyRevision(a),s=()=>{let e=this.getState();return!this.disposed&&i===this.selectionSeq&&M(e)===n&&e.selectedSession?.id===t.id&&e.selectedSession.cwd===t.cwd&&e.selectedSession.path===t.path&&e.selectedSession.archived===t.archived};this.setState({isLoadingEarlierMessages:!0});try{let r=await this.api.messages(t,{before:e.messagePageStart,limit:lc},n);if(!s()||this.transcripts.historyRevision(a)!==o)return;let i=this.transcripts.mergeHistory(a,r);this.setState(i)}catch(e){if(!s())return;this.reportSessionError(t,n,e,r)}finally{s()&&this.setState({isLoadingEarlierMessages:!1})}}async send(e,t,n,r=`inline`,i,a){let o=this.getState(),s=o.selectedSession;if(!s||s.archived===!0||a!==void 0&&(!Ma(a,{machineId:M(o),sessionId:s.id,cwd:s.cwd})||I(s)))return!1;let c=e.trim(),l=n!==void 0&&n.length>0,u=a!==void 0;if(I(s))return!l&&c.startsWith(`/`)?this.enqueuePendingSessionSend(s,{type:`command`,text:e}):!l&&ws(e)?this.enqueuePendingSessionSend(s,{type:`shell`,text:e}):this.enqueuePendingSessionSend(s,{type:`prompt`,text:e,streamingBehavior:t,attachments:n,delivery:r,folder:i}),!1;if(!u&&!l&&c.startsWith(`/`))return await this.runCommand(e),!1;if(!u&&!l&&ws(e))return await this.runShell(e),!1;let d=M(this.getState()),f=this.captureSessionErrorOwner(s);return this.deliverPromptToSession(s,e,t,n,r,i,d,{markSending:l||u},f)}markSendingPrompt(e,t){let n=this.getState().sendingPrompts;t?n[e]!==!0&&this.setState({sendingPrompts:{...n,[e]:!0}}):e in n&&this.setState({sendingPrompts:_c(n,e)})}async runShell(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;if(I(t)){this.enqueuePendingSessionSend(t,{type:`shell`,text:e});return}let n=M(this.getState()),r=this.captureSessionErrorOwner(t);await this.deliverShellToSession(t,e,n,{optimisticLine:!0},r)}async runCommand(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;if(I(t)){this.enqueuePendingSessionSend(t,{type:`command`,text:e});return}let n=M(this.getState()),r=this.captureSessionErrorOwner(t);await this.deliverCommandToSession(t,e,n,{applyResult:!0},r)}async renameSession(e,t){let n=t.trim();if(n===``||!zs(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let r=M(this.getState()),i=this.getState().selectedWorkspace,a=this.captureSessionErrorOwner(e);try{let t=await this.api.runCommand(e,`/name ${n}`,r);if(t.type===`done`){let a=this.getState();if(this.disposed||M(a)!==r||a.selectedWorkspace?.id!==i?.id||a.selectedWorkspace?.projectId!==i?.projectId||a.selectedWorkspace?.path!==i?.path||!a.sessions.some(t=>t.id===e.id&&t.cwd===e.cwd&&t.path===e.path))return;this.applySessionName(e.id,t.session?.name??n);return}this.reportSessionError(e,r,t.type===`unsupported`?t.message:D(`client.sessionController.failed.to.rename.session.702159`,`Failed to rename session`),a)}catch(t){this.reportSessionError(e,r,t,a)}}enqueuePendingSessionSend(e,t){let n=this.pendingSessionStarts.get(e.id);if(n===void 0||n.discarded){let t=this.captureSessionErrorOwner(e,n?.originWorkspace);this.reportSessionError(e,e.machineId,D(`client.sessionController.the.backend.session.is.not.ready.to.send.queued.messages.copy.your.mes.22460a`,`The backend session is not ready to send queued messages. Copy your messages before discarding this failed start.`),t);return}let r={...t,id:`pending-send-${String(++this.pendingQueuedSendSeq)}`};n.queuedSends.push(r);let i=this.getState(),a=i.clientQueuedSessionMessages[e.id]??[],o=Sc(e.id,n.queuedSends.length);this.setState({clientQueuedSessionMessages:{...i.clientQueuedSessionMessages,[e.id]:[...a,wc(r)]},sessionActivities:{...i.sessionActivities,[e.id]:o},activity:i.selectedSession?.id===e.id?o:i.activity,error:``})}async flushQueuedPendingSends(e,t,n,r){for(let i of n){if(!await this.deliverQueuedPendingSend(e,t,i,r))return;this.dropNextQueuedSessionMessage(e.id)}}async deliverQueuedPendingSend(e,t,n,r){return n.type===`prompt`?this.deliverPromptToSession(e,n.text,n.streamingBehavior,n.attachments,n.delivery,n.folder,t,{markSending:!0},r):n.type===`shell`?this.deliverShellToSession(e,n.text,t,{optimisticLine:!0},r):this.deliverCommandToSession(e,n.text,t,{applyResult:!0},r)}async deliverPromptToSession(e,t,n,r,i,a,o,s,c){let l=r!==void 0&&r.length>0;s.markSending&&this.markSendingPrompt(e.id,!0);try{if(l&&i===`folder`){let i=(await this.api.saveAttachments(e,r,o,a)).map(e=>vs(e.path,!1)).join(` `),s=t===``?i:`${t}\n\n${i}`;await this.api.prompt(e,s,n,o)}else await this.api.prompt(e,t,n,o,r);return this.markCachedNewSessionPersisted(e),!0}catch(t){return this.reportSessionError(e,o,t,c),!1}finally{s.markSending&&this.markSendingPrompt(e.id,!1)}}async deliverShellToSession(e,t,n,r,i){r.optimisticLine&&this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ui(`user`,t)]});try{return await this.api.shell(e,t,n),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ui(`system`,ic(t))]}),this.reportSessionError(e,n,t,i),!1}}async deliverCommandToSession(e,t,n,r,i){let a=this.navigationSelection();this.markSendingPrompt(e.id,!0);try{let o=await this.api.runCommand(e,t,n);return r.applyResult&&this.isSelectedSessionIdentity(e.id,n)?await this.applyCommandResult(o,a):(o.type===`select`||o.type===`tree`)&&this.reportSessionError(e,n,D(`client.sessionController.queued.command.requires.input.open.the.session.and.run.it.again.2a98cf`,`Queued command "{value1}" requires input; open the session and run it again.`,{value1:t}),i),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ui(`system`,ic(t))]}),this.reportSessionError(e,n,t,i),!1}finally{this.markSendingPrompt(e.id,!1)}}dropNextQueuedSessionMessage(e){let t=this.getState(),n=t.clientQueuedSessionMessages[e]??[];if(n.length===0)return;let r=n.slice(1);this.setState({clientQueuedSessionMessages:r.length===0?_c(t.clientQueuedSessionMessages,e):{...t.clientQueuedSessionMessages,[e]:r}})}async respondToCommand(e,t){let n=this.getState().selectedSession;if(!n)return;let r=M(this.getState()),i=this.captureSessionErrorOwner(n),a=this.navigationSelection();this.setState({commandDialog:void 0});try{let i=await this.api.respondToCommand(n,e,t,r);this.isSelectedSessionIdentity(n.id,r)&&await this.applyCommandResult(i,a)}catch(e){this.reportSessionError(n,r,e,i)}}cancelCommand(){this.setState({commandDialog:void 0})}async actOnMessage(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0||I(r))return;let i=M(n),a=this.selectionSeq,o=this.captureSessionErrorOwner(r),s;try{if(s=await this.api.runCommand(r,`/tree`,i),s.type!==`tree`)throw Error(`message`in s?s.message:D(`ui.main.8bcdd03f7054`,`Session history is unavailable.`));if(!s.tree.nodes.some(t=>t.id===e))throw Error(D(`ui.main.e92706bbbf62`,`This message is no longer available in session history.`))}catch(e){throw this.reportSessionError(r,i,e,o),e}this.isCurrentSessionSelection(r.id,i,a)&&this.isSelectedSessionScope(r,i)&&(t===`fork`?await this.forkSessionTree(e,s.tree,!0):await this.navigateSessionTree(e,{mode:`none`},s.tree,!0))}async navigateTree(e,t){return this.navigateSessionTree(e,t,this.getState().treeDialog)}async navigateSessionTree(e,t,n,r){let i=this.getState(),a=i.selectedSession;if(a===void 0||n===void 0||a.archived===!0||I(a))throw Error(D(`client.sessionController.session.tree.navigator.is.no.longer.available.34846d`,`Session tree navigator is no longer available`));let o={...a},s=M(i),c=this.captureSessionErrorOwner(o),l={machineId:s,sessionId:o.id};this.setTreeActionPending(l,!0);try{let i=await this.api.navigateTree(o,{targetId:e,expectedLeafId:n.activeLeafId,summary:t,...r===void 0?{}:{retainCheckpoint:r}},s);return await this.applySessionTreeNavigationResult(o,s,i,n),i}catch(e){throw this.reportSessionError(o,s,e,c),e}finally{this.setTreeActionPending(l,!1)}}async applySessionTreeNavigationResult(e,t,n,r){if(n.cancelled||this.disposed)return;if(this.hasDraftIdentityConflict(e,t)){this.reportSessionError(e,t,D(`client.sessionController.queueContextChanged`,`The conversation context changed before the result returned. The current draft was preserved.`));return}let i=j(t,e.id),a=n.editorText;if(a!==void 0&&za(i,a),this.transcripts.discard(i),!this.isSelectedSessionScope(e,t))return;this.clearPendingUpdates();let o=this.selectionSeq,s=()=>this.isCurrentSessionSelection(e.id,t,o)&&this.isSelectedSessionScope(e,t),c=(async()=>{a!==void 0&&s()&&await this.replacePromptEditorText?.({machineId:t,sessionId:e.id,text:a,isCurrent:s})})(),[l,u]=await Promise.allSettled([c,this.requestSelectedSessionRefresh({session:e,machineId:t,selectionSeq:o,errorOwner:this.captureSessionErrorOwner(e)})]);if(s()){if(l.status===`rejected`)throw l.reason;if(u.status===`rejected`)throw u.reason;this.getState().treeDialog===r&&this.setState({treeDialog:void 0})}}async forkFromTree(e){return this.forkSessionTree(e,this.getState().treeDialog)}async forkSessionTree(e,t,n){let r=this.getState(),i=r.selectedSession;if(i===void 0||t===void 0||i.archived===!0||I(i))throw Error(D(`client.sessionController.session.tree.navigator.is.no.longer.available.34846d`,`Session tree navigator is no longer available`));let a={...i},o=M(r),s=this.captureSessionErrorOwner(a),c=this.navigationSelection(),l={machineId:o,sessionId:a.id};this.setTreeActionPending(l,!0);try{let r=await this.api.forkTree(a,{entryId:e,expectedLeafId:t.activeLeafId,...n===void 0?{}:{retainCheckpoint:n}},o);return await this.applySessionTreeForkResult(a,o,r,c,t),r}catch(e){throw this.reportSessionError(a,o,e,s),e}finally{this.setTreeActionPending(l,!1)}}async applySessionTreeForkResult(e,t,n,r,i){if(n.cancelled)return;let a=j(t,e.id),o=n.session;if(o.id===e.id){await this.applySessionTreeNavigationResult(e,t,{cancelled:!1,...n.promptDraft===void 0?{}:{editorText:n.promptDraft}},i);return}if(n.promptDraft!==void 0&&za(j(t,o.id),n.promptDraft),this.transcripts.discard(a),!this.isSelectedSessionScope(e,t))return;let s=[o,...this.getState().sessions.filter(e=>e.id!==o.id)];this.setState({sessions:s}),this.navigateToSession===void 0?(this.setState({treeDialog:void 0}),await this.selectSession(o)):await this.navigateToSession(o,{expected:r})&&this.isSelectedSessionIdentity(o.id,t)&&this.getState().treeDialog===i&&this.setState({treeDialog:void 0})}async abortTreeNavigation(){let e=this.getState(),t=e.selectedSession;if(t===void 0||e.treeDialog===void 0||I(t))return;let n=M(e),r=this.captureSessionErrorOwner(t);try{await this.api.abort(t,n)}catch(e){throw this.reportSessionError(t,n,e,r),e}}closeTreeDialog(){this.setState({treeDialog:void 0})}applySessionStatus(e){this.applyStatus(e)}archiveScopeProjectId(){return Gt()?this.getState().selectedProject?.id:void 0}async useSuggestedInput(e,t){if(!this.isSelectedSessionIdentity(t,e))return;let n=this.getState(),r=n.selectedSession,i=n.status?.sessionId===t?n.status.suggestedInput:void 0;if(r===void 0||i===void 0)return;let a=this.captureSessionErrorOwner(r);za(j(e,t),i);try{await this.replacePromptEditorText?.({machineId:e,sessionId:t,text:i})}catch(t){this.reportSessionError(r,e,t,a)}}invalidateSessionTree(){let e=this.getState(),t=e.selectedSession,n=M(e);t!==void 0&&this.isSelectedSessionIdentity(t.id,n)&&(this.transcripts.discard(j(n,t.id)),this.clearPendingUpdates(),this.refreshSelectedSession(t.id),e.treeDialog!==void 0&&!this.hasPendingTreeAction(n,t.id)&&this.setState({treeDialog:void 0}))}hasPendingTreeAction(e,t){return[...this.pendingTreeActions].some(n=>n.machineId===e&&n.sessionId===t)}setTreeActionPending(e,t){t?this.pendingTreeActions.add(e):this.pendingTreeActions.delete(e),this.disposed||this.setState({pendingTreeActions:[...this.pendingTreeActions]})}async archiveSession(e=this.getState().selectedSession){if(!e)return;let t=this.statusForSession(e),n=this.sessionPersistenceOptions();if(Bs(e,t,n)){await this.deleteCachedNewSession(e);return}if(!zs(e,t,n))return;let r=M(this.getState()),i=this.captureSessionErrorOwner(e);try{await this.api.archive(e,r,this.archiveScopeProjectId());let t=this.getState(),n=Qs(t.sessions,e.id,new Date().toISOString()),i=ec(this.automaticSessionCandidates(n),t.selectedSession?.id,e.id);this.setState({sessions:n});let a=this.navigationSelection();i.type===`select`?await this.selectSessionAfterNavigation(i.session,a):i.type===`clear`&&await this.clearSessionAfterNavigation(a)}catch(t){this.reportSessionError(e,r,t,i)}}async archiveSessionWithDescendants(e=this.getState().selectedSession){if(e===void 0||!zs(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{let n=await this.api.archiveWithDescendants(e,t,this.archiveScopeProjectId()),r=n.sessionIds!==void 0&&n.sessionIds.length>0?n.sessionIds:[e.id],i=this.getState(),a=$s(i.sessions,r,new Date().toISOString()),o=tc(this.automaticSessionCandidates(a),i.selectedSession?.id,r);this.setState({sessions:a});let s=this.navigationSelection();o.type===`select`?await this.selectSessionAfterNavigation(o.session,s):o.type===`clear`&&await this.clearSessionAfterNavigation(s)}catch(r){this.reportSessionError(e,t,r,n)}}async archiveSessions(e){let t=this.sessionPersistenceOptions(),n=Dc(e).filter(e=>zs(e,this.statusForSession(e),t));if(n.length===0)return;let r=M(this.getState()),i=this.getState().selectedWorkspace,a=n[0];if(a===void 0)return;let o=this.captureSessionErrorOwner(a,i);try{let{succeededIds:e,failures:t,generatedAt:s}=await this.archiveSessionBatch(n,r);if(e.length>0){let t=this.getState(),n=$s(t.sessions,e,s??new Date().toISOString()),r=tc(this.automaticSessionCandidates(n),t.selectedSession?.id,e);this.setState({sessions:n});let i=this.navigationSelection();r.type===`select`?await this.selectSessionAfterNavigation(r.session,i):r.type===`clear`&&await this.clearSessionAfterNavigation(i)}this.applyBulkSessionFailures(D(`ui.sessionCleanupDialog.archive`,`Archive`),t,r,i,a,o)}catch(e){this.reportWorkspaceOrSessionError(i,a,r,D(`client.sessionController.archive.failed.aaa500`,`Archive failed: {value1}`,{value1:kc(e)}),o)}}async deleteArchivedSessions(e){let t=Dc(e).filter(e=>e.archived===!0);if(t.length===0)return;let n=M(this.getState()),r=this.getState().selectedWorkspace,i=t[0];if(i===void 0)return;let a=this.captureSessionErrorOwner(i,r);try{let{succeededIds:e,failures:o}=await this.deleteArchivedSessionBatch(t,n);if(e.length>0){let r=new Set(e),i=this.getState(),a=i.sessions.filter(e=>!r.has(e.id));if(this.setState({sessions:a}),i.selectedSession!==void 0&&r.has(i.selectedSession.id)){let e=this.navigationSelection(),t=this.automaticSessionCandidates(a),n=t.find(e=>e.archived!==!0)??t[0];n===void 0?await this.clearSessionAfterNavigation(e):await this.selectSessionAfterNavigation(n,e)}await this.refreshPinnedSessions(t[0]?.cwd??``,n)}this.applyBulkSessionFailures(D(`ui.sessionList.delete`,`Delete`),o,n,r,i,a)}catch(e){this.reportWorkspaceOrSessionError(r,i,n,D(`client.sessionController.delete.failed.59ec26`,`Delete failed: {value1}`,{value1:kc(e)}),a)}}async archiveSessionBatch(e,t){let n=await this.api.archiveMany(e,t,this.archiveScopeProjectId());return{succeededIds:n.archivedSessionIds,failures:Oc(n.failures),generatedAt:n.generatedAt}}async deleteArchivedSessionBatch(e,t){let n=await this.api.deleteArchivedMany(e,t,this.archiveScopeProjectId());return{succeededIds:n.deletedSessionIds,failures:Oc(n.failures)}}async applySessionCleanupResult(e,t=M(this.getState())){if(M(this.getState())!==t)return;let n=e.archivedSessionIds,r=e.deletedSessionIds;if(n.length>0||r.length>0){let t=this.getState(),i=new Set(r),a=[...n,...r],o=$s(t.sessions,n,e.generatedAt).filter(e=>!i.has(e.id)),s=t.selectedSession!==void 0&&a.includes(t.selectedSession.id);this.setState({sessions:o,sessionStatuses:vc(t.sessionStatuses,a),sessionActivities:vc(t.sessionActivities,a),...s?{status:void 0,activity:void 0,pendingDialogs:[],closedDialogs:[]}:{}});let c=this.navigationSelection();if(t.selectedSession!==void 0&&i.has(t.selectedSession.id)){let e=this.automaticSessionCandidates(o),t=e.find(e=>e.archived!==!0)??e[0];t===void 0?await this.clearSessionAfterNavigation(c):await this.selectSessionAfterNavigation(t,c)}else{let e=tc(this.automaticSessionCandidates(o),t.selectedSession?.id,n);e.type===`select`?await this.selectSessionAfterNavigation(e.session,c):e.type===`clear`&&await this.clearSessionAfterNavigation(c)}}await this.refreshCurrentWorkspaceSessions(t)}retireReadRecoveries(e){let t=e.some(e=>e===`machine`||e===`project`||e===`workspace`);if(t||e.includes(`session`)){this.selectedReadGeneration+=1;for(let e of this.selectedReadRecoveries)e.abort();this.selectedReadRecoveries.clear(),this.refreshEventBuffer=void 0}if(t){this.workspaceReadGeneration+=1;for(let e of this.workspaceReadRecoveries)e.abort();this.workspaceReadRecoveries.clear()}}async refreshCurrentWorkspaceSessions(e=M(this.getState()),t){let n=this.getState().selectedWorkspace;if(n===void 0)return;let r=this.workspaceReadGeneration,i=this.beginNavigationOperation?.([`machine`,`project`,`workspace`]),a=()=>!this.disposed&&r===this.workspaceReadGeneration&&Nc(i)&&M(this.getState())===e&&this.getState().selectedWorkspace?.id===n.id&&this.getState().selectedWorkspace?.projectId===n.projectId&&this.getState().selectedWorkspace?.path===n.path,o=Gn(e,n.projectId,n.id);try{await this.workspaceSessionRefreshes.request(JSON.stringify([e,n.projectId,n.id,n.path]),async()=>{if(!a())return;let r=this.browserErrors.captureRecovery(o,`workspace-sessions-refresh`),i=()=>this.api.sessions(n.path,e),s=new AbortController;this.workspaceReadRecoveries.add(s);let c;try{c=await sc(i,a,s.signal,t?.recoverNetwork===!0)}finally{this.workspaceReadRecoveries.delete(s)}if(c===void 0||!a())return;this.browserErrors.clearRecovered(r);let l=Qr(n.path,c,e).filter(t=>!this.isSuppressedCreatedSession(t,e)),u=this.mergePendingStartSessions(n.path,l,e),d=this.getState().selectedSession;this.setState({sessions:u}),this.refreshPinnedSessions(n.path,e);let f=this.navigationSelection();if(d===void 0)return;let p=u.find(e=>e.id===d.id);if(p!==void 0){p!==d&&this.setState({selectedSession:p});return}let m=this.automaticSessionCandidates(u),h=m.find(e=>e.archived!==!0)??m[0];h===void 0?await this.clearSessionAfterNavigation(f):await this.selectSessionAfterNavigation(h,f)})}catch(i){if(this.disposed||r!==this.workspaceReadGeneration||t?.recoverNetwork===!0&&!a())return;if(i instanceof Oe){this.browserErrors.report(o,D(`client.sessionController.sessionListRefreshUnavailable`,`The session list could not be refreshed. Check your connection and retry.`),`workspace-sessions-refresh`);return}if(rc(i)){console.warn(`Workspace session list refresh timed out`,{machineId:e,workspaceId:n.id,errorCategory:`session-list-refresh`});return}this.reportWorkspaceError(n,e,i)}}stopPolling(){this.sessionPollTimer!==void 0&&clearInterval(this.sessionPollTimer),this.sessionPollTimer=void 0,this.sessionRefreshInFlight=!1}async deleteCachedNewSession(e=this.getState().selectedSession){if(e===void 0||!Bs(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=I(e)?this.pendingSessionStarts.get(e.id):void 0;t===void 0?this.api.stop(e,M(this.getState())).catch(()=>{}):(t.discarded=!0,t.queuedSends=[]),Zr(e.id,M(this.getState())),Ba(this.sessionCacheKey(e.id)),Ka(this.sessionCacheKey(e.id));let n=this.getState(),r=n.sessions.filter(t=>t.id!==e.id);if(this.setState({sessions:r,sessionStatuses:_c(n.sessionStatuses,e.id),sessionActivities:gc(n.sessionActivities,e.id),sendingPrompts:_c(n.sendingPrompts,e.id),clientQueuedSessionMessages:_c(n.clientQueuedSessionMessages,e.id)}),this.getState().selectedSession?.id!==e.id)return;let i=this.navigationSelection(),a=this.automaticSessionCandidates(r),o=a.find(e=>e.archived!==!0)??a[0];o===void 0?await this.clearSessionAfterNavigation(i):await this.selectSessionAfterNavigation(o,i)}async restoreSession(e=this.getState().selectedSession){if(!e)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e),r=this.selectionSeq,i=this.beginNavigationOperation?.(pc);try{await this.api.restore(e,t,this.archiveScopeProjectId())}catch(r){this.reportSessionError(e,t,r,n);return}if(!this.isCurrentRestoreOperation(t,r,i))return;let a={...e};delete a.archived,delete a.archivedAt;let o=this.getState().selectedSession?.id===a.id;this.replaceSession(a),o&&await this.selectSession(a,{updateUrl:!1,...i===void 0?{}:{navigation:i}})}async reloadSession(e=this.getState().selectedSession){if(e===void 0||!zs(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.reloadSession(e,t),this.transcripts.discard(j(t,e.id)),this.isSelectedSessionIdentity(e.id,t)&&await this.selectSession(e,{updateUrl:!1})}catch(r){this.reportSessionError(e,t,r,n)}}async detachParent(e=this.getState().selectedSession){if(e?.parentSessionPath===void 0)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.detachParent(e,t);let n=this.getState();if(this.disposed||M(n)!==t)return;let r=t=>{if(t.id!==e.id||t.cwd!==e.cwd)return t;let n={...t};return delete n.parentSessionPath,delete n.agentSubsession,n};this.setState({sessions:n.sessions.map(r),selectedSession:n.selectedSession===void 0?void 0:r(n.selectedSession)})}catch(r){this.reportSessionError(e,t,r,n)}}async listModels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{return(await this.api.models(e,t)).models}catch(r){return this.reportSessionError(e,t,r,n),[]}}async listModelCatalog(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{return(await this.api.modelCatalog(e,t)).models}catch(r){return this.reportSessionError(e,t,r,n),[]}}async setModelEnabled(e,t,n){let r=this.getState().selectedSession;if(!r||r.archived===!0)return;let i=M(this.getState()),a=this.captureSessionErrorOwner(r);try{return(await this.api.setModelEnabled(r,e,t,n,i)).models}catch(e){this.reportSessionError(r,i,e,a);return}}async setModelScope(e){let t=this.getState(),n=t.selectedSession;if(!n||n.archived===!0)return;let r=M(t),i=this.captureSessionErrorOwner(n);try{return(await this.api.setModelScope(n,e,r)).models}catch(e){this.reportSessionError(n,r,e,i);return}}async getSessionDefaults(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{return await this.api.getSessionDefaults(e,t)}catch(r){this.reportSessionError(e,t,r,n);return}}async setSessionDefaults(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;let n=M(this.getState()),r=this.captureSessionErrorOwner(t);try{return await this.api.setSessionDefaults(t,e,n)}catch(e){this.reportSessionError(t,n,e,r);return}}async setModel(e,t){let n=this.getState().selectedSession;if(!n||n.archived===!0)return;let r=M(this.getState()),i=this.captureSessionErrorOwner(n);try{let i=await this.api.setModel(n,e,t,r);if(M(this.getState())!==r)return;this.applyStatus(i),this.isSelectedSessionIdentity(n.id,r)&&await this.refreshAvailableThinkingLevels()}catch(e){this.reportSessionError(n,r,e,i)}}async cycleModel(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;let n=M(this.getState()),r=this.captureSessionErrorOwner(t);try{let r=await this.api.cycleModel(t,e,n);if(M(this.getState())!==n)return;this.applyStatus(r),this.isSelectedSessionIdentity(t.id,n)&&await this.refreshAvailableThinkingLevels()}catch(e){this.reportSessionError(t,n,e,r)}}async listThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{return(await this.api.thinkingLevels(e,t)).levels}catch(r){return this.reportSessionError(e,t,r,n),[]}}async refreshAvailableThinkingLevels(){let e=this.getState().selectedSession,t=M(this.getState());if(!e||e.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}let n=await this.listThinkingLevels();this.isSelectedSessionIdentity(e.id,t)&&this.setState({availableThinkingLevels:n})}async setThinkingLevel(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;let n=M(this.getState()),r=this.captureSessionErrorOwner(t);try{let r=await this.api.setThinkingLevel(t,e,n);if(M(this.getState())!==n)return;this.applyStatus(r)}catch(e){this.reportSessionError(t,n,e,r)}}async cycleThinkingLevel(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{let n=await this.api.cycleThinkingLevel(e,t);if(M(this.getState())!==t)return;this.applyStatus(n)}catch(r){this.reportSessionError(e,t,r,n)}}async mutateQueuedMessage(e,t,n){let r=this.getState(),i=r.selectedSession;if(i===void 0||i.archived===!0||I(i))return;let a={...i},o=M(r);if(!this.isSelectedSessionScope(a,o)||!this.canMutateQueueMessage(a,o)||r.status?.queueMessageActionsUnavailable!==void 0)return;let s=n.map(e=>({...e}));if(!Number.isInteger(t)||t<0||t>=s.length)return;let c=s[t]?.text??``,l=this.selectionSeq,u=this.captureSessionErrorOwner(a),d=()=>this.isCurrentSessionSelection(a.id,o,l)&&this.isSelectedSessionScope(a,o)&&this.canMutateQueueMessage(a,o)&&this.getState().status?.queueMessageActionsUnavailable===void 0;try{let n=await this.api.mutateQueuedMessage(a,{action:e,index:t,expectedQueue:s},o);if(this.disposed)return;if(n.sessionId!==a.id)throw Error(D(`client.sessionController.queueResponseMismatch`,`The queue response belongs to a different conversation.`));if(!this.canMutateQueueMessage(a,o))throw Error(D(`client.sessionController.queueActionsUnavailable`,`Queued message actions are no longer available.`));if(this.hasDraftIdentityConflict(a,o))throw Error(D(`client.sessionController.queueContextChanged`,`The conversation context changed before the result returned. The current draft was preserved.`));e===`edit`&&(za(j(o,a.id),c),d()&&await this.replacePromptEditorText?.({machineId:o,sessionId:a.id,text:c,isCurrent:d})),d()&&this.applyStatus(n)}catch(e){this.disposed||this.reportSessionError(a,o,e,u)}}async clearServerQueue(){let e=this.getState(),t=e.selectedSession;if(t===void 0||t.archived===!0||I(t))return;let n=M(e),r=this.captureSessionErrorOwner(t),i=this.selectionSeq;try{let e=await this.api.clearQueue(t,n);this.isCurrentSessionSelection(t.id,n,i)&&this.applyStatus(e)}catch(e){this.reportSessionError(t,n,e,r)}}async dismissWarning(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||I(n))return;let r=M(t),i=this.captureSessionErrorOwner(n),a=this.selectionSeq;try{let t=await this.api.dismissWarning(n,e,r);this.isCurrentSessionSelection(n.id,r,a)&&this.applyStatus(t)}catch(e){this.reportSessionError(n,r,e,i)}}submitAsk(e,t){return this.sendAskResponse(e,(n,r)=>this.api.submitAsk(n,e,t,r))}cancelAsk(e){return this.sendAskResponse(e,(t,n)=>this.api.cancelAsk(t,e,n))}answerDialog(e,t){return this.closeOpenDialog(e,(n,r)=>this.api.answerDialog(n,e,t,r))}cancelDialog(e){return this.closeOpenDialog(e,(t,n)=>this.api.cancelDialog(t,e,n))}async closeOpenDialog(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0)return;if(I(r)){await this.closePendingStartDialog(r,e,t);return}let i=M(n),a=this.captureSessionErrorOwner(r),o=this.selectionSeq;try{let e=await t(r,i);if(!this.isCurrentSessionSelection(r.id,i,o))return;this.recordDialogOutcome(e.outcome),this.applyStatus(e.sessionStatus)}catch(e){this.reportSessionError(r,i,e,a)}}async closePendingStartDialog(e,t,n){let r=this.pendingSessionStarts.get(e.id),i=r?.backendSessionId;if(r===void 0||i===void 0)return;let a=this.captureSessionErrorOwner(e,r.originWorkspace),o=this.selectionSeq;try{let t=await n({...e,id:i},r.machineId);if(o!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;this.recordDialogOutcome(t.outcome),this.applyPendingStartStatus(r,t.sessionStatus)}catch(t){this.reportSessionError(e,r.machineId,t,a)}}recordDialogOutcome(e){if(e===void 0)return;let t=this.getState().pendingDialogs.find(t=>t.dialogId===e.dialogId);t!==void 0&&this.recordClosedDialog({dialog:t,reason:e.reason,...e.answer===void 0?{}:{answer:e.answer}})}async sendAskResponse(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0||I(r))return;let i=M(n),a=this.captureSessionErrorOwner(r),o=this.selectionSeq;try{let n=await t(r,i);Qa(j(i,r.id),e),this.isCurrentSessionSelection(r.id,i,o)&&this.applyStatus(n)}catch(e){this.reportSessionError(r,i,e,a)}}async stopActiveWork(){let e=this.getState().selectedSession;if(!e)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.abort(e,t)}catch(r){this.reportSessionError(e,t,r,n)}}refreshSelectedSession(e=this.getState().selectedSession?.id,t){let n=this.getState().selectedSession;if(e===void 0||n?.id!==e||this.selectedSessionLoadDeferred||n.archived===!0||I(n))return Promise.resolve();let r=M(this.getState()),i={session:n,machineId:r,selectionSeq:this.selectionSeq,errorOwner:this.captureSessionErrorOwner(n),...t?.recoverNetwork===!0?{recoverNetwork:!0}:{}},a=this.selectedReadGeneration;return this.requestSelectedSessionRefresh(i).catch(e=>{this.disposed||a!==this.selectedReadGeneration||t?.recoverNetwork===!0&&!this.isCurrentRefreshTarget(i)||(t?.silent===!0?console.warn(`Selected session background refresh failed`,{machineId:r,sessionId:n.id,errorCategory:`session-refresh`}):e instanceof Oe?this.browserErrors.report(Kn(r,n.id,i.errorOwner),D(`client.sessionController.conversationRefreshUnavailable`,`The conversation could not be refreshed. Check your connection and retry.`),`session-refresh`):this.reportSessionError(i.session,i.machineId,e,i.errorOwner))})}bufferRefreshEvents(e){if(this.refreshEventBuffer!==void 0&&this.isCurrentRefreshTarget(this.refreshEventBuffer.target))return this.refreshEventBuffer;this.flushPendingUpdates();let t={target:e,events:[],pendingDialogs:this.getState().pendingDialogs};return this.refreshEventBuffer=t,t}async refreshSessionNotifications(e,t){try{await this.notifications?.refreshSelectedSession(e,t)}catch{console.warn(`Selected session notification refresh failed`,{machineId:t,sessionId:e.id,errorCategory:`notification-refresh`})}}async joinSelectedSessionSnapshot(e){let t=!1,n,r=new Promise(e=>{n=()=>{t=!0,e(!0)}}),i={selectionSeq:e.selectionSeq,complete:n};this.initialSnapshotReady=i;let a=this.requestSelectedSessionRefresh(e).then(()=>t,n=>{if(!t)throw n;return this.reportSessionError(e.session,e.machineId,n,e.errorOwner),!0});try{return await Promise.race([r,a])}finally{this.initialSnapshotReady===i&&(this.initialSnapshotReady=void 0)}}requestSelectedSessionRefresh(e){if(!this.isCurrentRefreshTarget(e))return Promise.resolve();let t=j(e.machineId,e.session.id),n=this.selectedReadGeneration,r=()=>n===this.selectedReadGeneration&&this.isCurrentRefreshTarget(e);return this.selectedSessionRecoveryTarget!==void 0&&this.isCurrentRefreshTarget(this.selectedSessionRecoveryTarget)||this.bufferRefreshEvents(e),Promise.resolve().then(()=>{if(r())return this.refreshSessionNotifications(e.session,e.machineId)}),this.selectedSessionRefreshes.request(t,async()=>{if(!r())return;let n=new AbortController;this.selectedReadRecoveries.add(n),e.recoverNetwork===!0&&(this.selectedSessionRecoveryTarget=e);try{await sc(()=>this.readSelectedSessionSnapshot(e,t,()=>r()&&!n.signal.aborted,n.signal),r,n.signal,e.recoverNetwork===!0)}finally{this.selectedReadRecoveries.delete(n),this.selectedSessionRecoveryTarget===e&&(this.selectedSessionRecoveryTarget=void 0)}})}async readSelectedSessionSnapshot(e,t,n,r){let i=this.bufferRefreshEvents(e),a=this.transcripts.historyRevision(t),o=this.observeSessionSnapshot?.(e.machineId,e.session.id),s,c=this.browserErrors.captureRecovery(Kn(e.machineId,e.session.id,e.errorOwner),`session-refresh`),l=!1,u=()=>{if(!l&&(l=!0,this.refreshEventBuffer===i&&(this.refreshEventBuffer=void 0),n()))for(let e of i.events){if(!n())break;this.applyEvent(e)}};r?.addEventListener(`abort`,u,{once:!0});try{let r=await this.transcriptSnapshot(e.session,{limit:lc},e.machineId);if(!n()||this.transcripts.historyRevision(t)!==a)return;this.browserErrors.clearRecovered(c);let{page:l,status:u}=r;if(this.preserveBufferedDialogOutcomes(i,r.seq),!this.isUnchangedSelectedRefresh(e,t,l,u,r)){let n=this.transcripts.mergeSnapshot(t,l),i=this.transcripts.seedStreamingPartial(n.messages,r.partial);this.streamWatermark={sessionId:e.session.id,seq:r.seq},this.setState({...n,messages:i,status:u,activity:this.getState().sessionActivities[e.session.id]}),this.applyStatus(u),this.lastAppliedSelectedRefresh={selectionSeq:e.selectionSeq,partialJson:hc(r)}}s=this.transcripts.historyRevision(t),o?.(u)}finally{r?.removeEventListener(`abort`,u),u()}this.transcripts.historyRevision(t)===s&&n()&&this.initialSnapshotReady?.selectionSeq===e.selectionSeq&&this.initialSnapshotReady.complete()}preserveBufferedDialogOutcomes(e,t){let n=new Map(e.pendingDialogs.map(e=>[e.dialogId,e]));for(let r of e.events)if(!(r.seq===void 0||r.seq>t||this.isStreamEventBelowWatermark(r))&&(r.type===`dialog.opened`&&n.set(r.dialog.dialogId,r.dialog),r.type===`dialog.closed`)){let e=n.get(r.dialogId);e!==void 0&&this.recordClosedDialog({dialog:e,reason:r.reason,...r.answer===void 0?{}:{answer:r.answer}}),n.delete(r.dialogId)}}isUnchangedSelectedRefresh(e,t,n,r,i){let a=this.lastAppliedSelectedRefresh;return a?.selectionSeq!==e.selectionSeq||i.seq<(this.streamWatermark?.seq??0)||hc(i)!==a.partialJson||!ts(this.transcripts.rawHistoryPage(t),n)||JSON.stringify(r)!==JSON.stringify(this.getState().status)?!1:this.getState().sessionActivities[r.sessionId]?.phase!==`active`||rr(r)}isCurrentRefreshTarget(e){let t=this.getState().selectedSession;return this.isCurrentSessionSelection(e.session.id,e.machineId,e.selectionSeq)&&t?.cwd===e.session.cwd&&t.path===e.session.path&&t.archived===e.session.archived&&Nc(e.navigation)}isCurrentSessionSelection(e,t,n){return n===this.selectionSeq&&this.isSelectedSessionIdentity(e,t)}isCurrentRestoreOperation(e,t,n){return t===this.selectionSeq&&M(this.getState())===e&&Nc(n)}isSelectedSessionIdentity(e,t){if(this.disposed)return!1;let n=this.getState(),r=n.selectedSession;return M(n)===t&&r?.id===e&&r.archived!==!0&&!I(r)}isSelectedSessionScope(e,t){let n=this.getState().selectedSession;return this.isSelectedSessionIdentity(e.id,t)&&n?.cwd===e.cwd&&n.path===e.path}hasDraftIdentityConflict(e,t){let n=this.getState(),r=n.selectedSession;return M(n)===t&&r?.id===e.id&&(r.cwd!==e.cwd||r.path!==e.path)}reportSessionError(e,t,n,r={cwd:e.cwd}){this.browserErrors.report(Kn(t,e.id,r),ic(n))}captureSessionErrorOwner(e,t=this.workspaceForSessionError(e)){return{cwd:e.cwd,...t===void 0?{}:{projectId:t.projectId,workspaceId:t.id}}}workspaceForSessionError(e){let t=this.getState();return[t.selectedWorkspace,...t.workspaces,...Object.values(t.workspacesByProjectId).flat()].find(t=>t?.path===e.cwd)}reportWorkspaceError(e,t,n){this.browserErrors.report(Gn(t,e.projectId,e.id),ic(n))}applyBulkSessionFailures(e,t,n,r,i,a){t.length!==0&&this.reportWorkspaceOrSessionError(r,i,n,D(`client.sessionController.failed.for.sessions.5ef9b2`,`{value1} failed for {value2} sessions: {value3}`,{value1:e,value2:String(t.length),value3:t.join(`;`)}),a)}reportWorkspaceOrSessionError(e,t,n,r,i){e===void 0?t!==void 0&&this.reportSessionError(t,n,r,i):this.reportWorkspaceError(e,n,r)}sessionCacheKey(e){return j(M(this.getState()),e)}statusForSession(e){if(e===void 0)return;let t=this.getState();return t.status?.sessionId===e.id&&t.selectedSession?.id===e.id?t.status:t.sessionStatuses[e.id]}sessionPersistenceOptions(){let e=this.getState();return Ls(e.machineRuntimes[M(e)])}workspaceSelectionKey(e){return`${M(this.getState())}:${e}`}replaceSession(e){let t=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(t=>t.id===e.id?e:t),selectedSession:t?.id===e.id?e:t})}navigationSelection(){if(this.captureNavigation!==void 0)return this.captureNavigation();let e=this.getState();return{machineId:M(e),projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id}}navigationSelectionMatchesState(e){let t=this.navigationSelection();return t.machineId===e.machineId&&t.projectId===e.projectId&&t.workspaceId===e.workspaceId&&t.sessionId===e.sessionId&&t.tool===e.tool&&t.view===e.view}createPendingSessionStart(e,t,n,r){let i=`creating:${Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,`0`)).join(``)}`,a=new Date().toISOString(),o={id:i,path:`pi-web://pending-session/${i}`,cwd:e.path,persisted:!1,name:D(`client.sessionController.new.session.c57c30`,`New session`),created:a,modified:a,messageCount:0,firstMessage:``,clientPendingStart:!0,machineId:t};return{tempId:i,originWorkspace:e,workspaceId:e.id,cwd:e.path,machineId:t,expectedNavigation:n,pendingUrlPublished:r,session:o,queuedSends:[],discarded:!1}}insertAndSelectPendingSession(e,t){let n=this.getState();this.selectClientPendingStartSession(e,{activity:Sc(e.id),sessions:[e,...n.sessions.filter(t=>t.id!==e.id)],updateUrl:t?.updateUrl})}selectClientPendingStartSession(e,t){this.retireReadRecoveries([`session`]),this.selectedSessionLoadDeferred=!1,this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)}),this.selectionSeq+=1,this.selectedSessionJoinNavigation=void 0,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates();let n=this.getState(),r=this.pendingSessionStarts.get(e.id),i=t?.activity??n.sessionActivities[e.id]??(r===void 0?void 0:Sc(e.id,r.queuedSends.length));this.setState({sessions:t?.sessions??(n.sessions.some(t=>t.id===e.id)?n.sessions:[e,...n.sessions]),selectedSession:e,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:i,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0,...i===void 0?{}:{sessionActivities:{...n.sessionActivities,[e.id]:i}},error:``}),r?.backendSessionId!==void 0&&this.connectPendingStartSocket(r),t?.updateUrl!==!1&&this.updateUrl()}async resolvePendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.queuedSends.splice(0),i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId,t.id);if(n.discarded){Ba(j(n.machineId,e)),Ka(j(n.machineId,e)),this.setState({clientQueuedSessionMessages:_c(this.getState().clientQueuedSessionMessages,e)}),this.applyReleasedCreatedSessions(i,n.machineId),this.api.stop(t,n.machineId).catch(()=>{});return}Yr(t,n.machineId),Va(j(n.machineId,e),j(n.machineId,t.id)),qa(j(n.machineId,e),j(n.machineId,t.id));let a=Xr(t,n.machineId),o=this.captureSessionErrorOwner(t,n.originWorkspace);if(!this.isCurrentPendingStart(n)){this.setState({clientQueuedSessionMessages:_c(this.getState().clientQueuedSessionMessages,e)}),await this.flushQueuedPendingSends(a,n.machineId,r,o);return}let s=this.getState(),c=s.selectedSession?.id===e,l={machineId:n.machineId,projectId:n.originWorkspace.projectId,workspaceId:n.workspaceId,sessionId:e},u=c&&(this.navigateToSession!==void 0||!n.pendingUrlPublished),d=c&&!u&&(this.isPendingSessionStartRouteCurrent?.(l)??!0);c&&!u&&!d&&this.clearActiveSession(),this.setState({sessions:bc(s.sessions,e,a),sessionActivities:gc(s.sessionActivities,e),sendingPrompts:yc(s.sendingPrompts,e,a.id),clientQueuedSessionMessages:yc(s.clientQueuedSessionMessages,e,a.id),...d?{selectedSession:a,status:s.sessionStatuses[a.id],activity:s.sessionActivities[a.id],pendingDialogs:s.sessionStatuses[a.id]?.pendingDialogs??[],closedDialogs:[]}:{},error:``}),this.applyReleasedCreatedSessions(i,n.machineId),u?await this.reconcileCompletedPendingSelection(n,a):d&&(this.onPendingSessionStartCommitted?.(l,a),this.onPendingSessionStartCommitted===void 0&&this.updateUrl({replace:!0}),await this.selectSession(a,{updateUrl:!1,navigation:n.navigation})),await this.flushQueuedPendingSends(a,n.machineId,r,o)}async reconcileCompletedPendingSelection(e,t){let n=e.navigation;if(!e.pendingUrlPublished&&!Nc(n))this.clearUnreconciledPendingSelection(e,t);else if(e.expectedNavigation=this.pendingStartExpectedNavigation(e),this.navigateToSession!==void 0)try{let r=await this.navigateToSession(t,{...e.pendingUrlPublished?{replace:!0,creationHandoff:!0}:{},expected:e.expectedNavigation});if(r&&this.getState().selectedSession?.id!==e.tempId)return;this.clearUnreconciledPendingSelection(e,t,r||e.pendingUrlPublished||!Nc(n)?void 0:D(`ui.main.0a71e48cd0f9`,`Session started, but its navigation changed before selection completed. Select it from the session list.`))}catch(n){this.clearUnreconciledPendingSelection(e,t,D(`ui.main.d15d396c9633`,`Session started but could not be selected: {arg0}`,{arg0:kc(n)}))}else try{if(await this.selectSession(t,{updateUrl:!1,navigation:n}),!Nc(n)){this.clearUnreconciledPendingSelection(e,t);return}if(this.getState().selectedSession?.id!==t.id){this.clearUnreconciledPendingSelection(e,t,D(`ui.main.8cd247b86afd`,`Session started, but its selection changed before navigation completed. Select it from the session list.`));return}this.updateUrl(e.pendingUrlPublished?{replace:!0}:void 0)}catch(n){this.clearUnreconciledPendingSelection(e,t,D(`ui.main.d15d396c9633`,`Session started but could not be selected: {arg0}`,{arg0:kc(n)}))}}pendingStartExpectedNavigation(e){return e.pendingUrlPublished?{machineId:e.machineId,projectId:e.originWorkspace.projectId,workspaceId:e.workspaceId,sessionId:e.tempId}:{...this.navigationSelection(),sessionId:e.expectedNavigation.sessionId}}clearUnreconciledPendingSelection(e,t,n){let r=this.getState().selectedSession?.id;(r===e.tempId||r===t.id)&&(this.clearActiveSession(),n!==void 0&&this.browserErrors.report(Gn(e.machineId,e.originWorkspace.projectId,e.workspaceId),n))}cancelUnstartedSession(e){if(this.pendingSessionStarts.get(e.tempId)!==e)return;this.pendingSessionStarts.delete(e.tempId),e.discarded=!0,e.queuedSends=[],Zr(e.tempId,e.machineId);let t=j(e.machineId,e.tempId);Ba(t),Ka(t);let n=this.getState(),r=n.selectedSession?.id===e.tempId;if(this.setState({sessions:n.sessions.filter(t=>t.id!==e.tempId),sessionStatuses:_c(n.sessionStatuses,e.tempId),sessionActivities:gc(n.sessionActivities,e.tempId),sendingPrompts:_c(n.sendingPrompts,e.tempId),clientQueuedSessionMessages:_c(n.clientQueuedSessionMessages,e.tempId)}),!r)return;this.clearActiveSession();let i={machineId:e.machineId,projectId:e.originWorkspace.projectId,workspaceId:e.workspaceId,sessionId:e.tempId};(this.isPendingSessionStartRouteCurrent?.(i)??!0)&&this.updateUrl({replace:!0})}failPendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.discarded;n.discarded=!0,this.getState().selectedSession?.id===e&&this.socket.close();let i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId),a=this.isCurrentPendingStart(n);if(r){a&&this.applyReleasedCreatedSessions(i,n.machineId);return}let o=kc(t),s=D(`client.sessionController.failed.to.start.session.881118`,`Failed to start session: {value1}`,{value1:o});if(!a){this.browserErrors.report(Gn(n.machineId,n.originWorkspace.projectId,n.originWorkspace.id),s);return}let c=this.getState(),l=Cc(e,o,n.queuedSends.length),u=c.sessions.some(t=>t.id===e);this.setState({sessions:u?c.sessions:[n.session,...c.sessions],sessionActivities:{...c.sessionActivities,[e]:l},activity:c.selectedSession?.id===e?l:c.activity,...c.selectedSession?.id===e?{pendingDialogs:[]}:{}}),this.reportSessionError(n.session,n.machineId,s,this.captureSessionErrorOwner(n.session,n.originWorkspace)),this.applyReleasedCreatedSessions(i,n.machineId)}isCurrentPendingStart(e){let t=this.getState();return M(t)===e.machineId&&t.selectedWorkspace?.id===e.workspaceId&&t.selectedWorkspace.projectId===e.originWorkspace.projectId}hasPendingStartFor(e,t){return Array.from(this.pendingSessionStarts.values()).some(n=>n.cwd===e&&n.machineId===t)}isSuppressedCreatedSession(e,t){let n=this.suppressedCreatedSessions.get(e.id);return n?.session.cwd===e.cwd&&n.machineId===t}takeSuppressedCreatedSessionsFor(e,t,n){if(n!==void 0&&this.suppressedCreatedSessions.delete(n),this.hasPendingStartFor(e,t))return[];let r=[];for(let[n,i]of this.suppressedCreatedSessions)i.session.cwd===e&&i.machineId===t&&(this.suppressedCreatedSessions.delete(n),r.push(i.session));return r}applyReleasedCreatedSessions(e,t){if(e.length===0||M(this.getState())!==t)return;let n=this.getState();if(n.selectedWorkspace===void 0)return;let r=new Set(n.sessions.map(e=>e.id)),i=e.filter(e=>e.cwd===n.selectedWorkspace?.path&&!r.has(e.id));i.length!==0&&this.setState({sessions:[...i.reverse(),...n.sessions]})}mergePendingStartSessions(e,t,n){let r=this.getState().sessions.filter(t=>I(t)&&t.cwd===e&&t.machineId===n);if(r.length===0)return t;let i=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!i.has(e.id))]}async recreateCachedNewSession(e,t,n=this.selectionSeq,r=this.captureSessionErrorOwner(e)){let i=M(this.getState()),a=this.navigationSelection();try{let r=await this.api.startSession(e.cwd,i);if(!this.isCurrentSessionSelection(e.id,i,n)||!this.isSelectedSessionScope(e,i)||!Nc(t?.navigation))return;Yr(r,i),Va(j(i,e.id),j(i,r.id)),qa(j(i,e.id),j(i,r.id)),Zr(e.id,i);let o=Xr(r,i);if(this.setState({sessions:[o,...this.getState().sessions.filter(t=>t.id!==e.id&&t.id!==r.id)],error:``}),this.navigateToSession!==void 0){let r=this.navigationSelection();!await this.navigateToSession(o,{...t?.updateUrl===!1?{replace:!0}:{},expected:{...a,tool:r.tool,view:r.view}})&&this.isCurrentSessionSelection(e.id,i,n)&&this.clearActiveSession()}else await this.selectSession(o,{updateUrl:!1}),this.updateUrl(t?.updateUrl===!1?{replace:!0}:void 0)}catch(t){this.reportSessionError(e,i,t,r)}}markCachedNewSessionPersisted(e){if(!$r(e))return;let t=this.getState().sessions.find(t=>t.id===e.id)??e;this.replaceSession(ei(t))}async applyCommandResult(e,t){if(e.type===`select`){this.setState({commandDialog:e});return}if(e.type===`tree`){this.setState({treeDialog:e.tree});return}let n=(e.type,e.message);if(n!==void 0&&n!==``&&this.setState({messages:[...this.getState().messages,ui(e.type===`unsupported`?`system`:`tool`,n)]}),e.type===`done`&&e.session){e.promptDraft!==void 0&&za(this.sessionCacheKey(e.session.id),e.promptDraft);let n=this.getState().selectedSession,r=[e.session,...this.getState().sessions.filter(t=>t.id!==e.session?.id)];if(this.setState({sessions:r,...n?.id===e.session.id?{selectedSession:e.session}:{}}),n?.id===e.session.id||!this.navigationSelectionMatchesState(t))return;this.navigateToSession===void 0?await this.selectSession(e.session):await this.navigateToSession(e.session,{expected:t})}}applyCreatedSession(e){let t=this.getState();if(t.selectedWorkspace?.path!==e.cwd||t.sessions.some(t=>t.id===e.id))return;let n=M(t);this.hasPendingStartFor(e.cwd,n)?this.suppressedCreatedSessions.set(e.id,{session:e,machineId:n}):this.setState({sessions:[e,...t.sessions]})}applyActivity(e){this.setState({sessionActivities:{...this.getState().sessionActivities,[e.sessionId]:e},activity:this.getState().selectedSession?.id===e.sessionId?e:this.getState().activity})}applyStatus(e){let t=this.getState(),n=t.selectedSession?.id===e.sessionId,r=t.sessionActivities[e.sessionId]?.phase===`active`&&!rr(e);this.setState({sessionStatuses:{...t.sessionStatuses,[e.sessionId]:e},...Ac(t,e.sessionId,e.messageCount),...r?{sessionActivities:gc(t.sessionActivities,e.sessionId)}:{},status:n?e:t.status,activity:n&&r?void 0:t.activity,...n?{pendingDialogs:e.pendingDialogs??[]}:{}})}applyOpenedDialog(e){let t=this.getState();t.selectedSession===void 0||t.pendingDialogs.some(t=>t.dialogId===e.dialogId)||this.setState({pendingDialogs:[...t.pendingDialogs,e]})}applyClosedDialog(e,t,n){let r=this.getState().pendingDialogs.find(t=>t.dialogId===e);r!==void 0&&this.recordClosedDialog({dialog:r,reason:t,...n===void 0?{}:{answer:n}})}recordClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e.dialog.dialogId)||this.setState({pendingDialogs:t.pendingDialogs.filter(t=>t.dialogId!==e.dialog.dialogId),closedDialogs:[...t.closedDialogs,e]})}dismissClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e)&&this.setState({closedDialogs:t.closedDialogs.filter(t=>t.dialog.dialogId!==e)})}applySessionName(e,t){let n=n=>{if(n.id!==e)return n;let r={...n};return t===void 0||t===``?delete r.name:r.name=t,r},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(n),selectedSession:r===void 0?void 0:n(r)})}applyEvent(e){if(e.type===`session.diagnostic`){console.warn(e.message);return}if(e.type===`notifications.inbox`){this.notifications?.applyInboxEvent(M(this.getState()),e);return}if(e.type===`command.output`&&this.notifications?.shouldFilterLegacyNotification(M(this.getState()),e.notificationId)===!0)return;let t=this.refreshEventBuffer;if(t!==void 0&&this.isCurrentRefreshTarget(t.target)){t.events.push(e);return}if(this.isStreamEventBelowWatermark(e))return;if(e.type===`session.tree.changed`){this.invalidateSessionTree();return}if(e.type===`status.update`){this.queueStatusUpdate(e.status);return}if(e.type===`activity.update`){this.queueActivityUpdate(e.activity);return}if(jc(e)){this.queueTranscriptEvent(e);return}if(this.flushPendingUpdates(),e.type===`dialog.opened`){this.applyOpenedDialog(e.dialog);return}if(e.type===`dialog.closed`){this.applyClosedDialog(e.dialogId,e.reason,e.answer);return}let n=this.transcripts.applyLiveEvent(this.getState().messages,e);n?this.setState({messages:n}):e.type===`session.name`&&this.applySessionName(e.sessionId,e.name)}queueTranscriptEvent(e){this.pendingTranscriptEvents.push(e),this.schedulePendingFlush()}queueStatusUpdate(e){this.pendingStatusBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueActivityUpdate(e){this.pendingActivityBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueStartupProgress(e){if(this.getState().sessions.some(t=>t.id===e.activity.sessionId)){this.queueActivityUpdate(e.activity);return}let t=e.startupToken===void 0?void 0:this.pendingSessionStarts.get(e.startupToken);t===void 0||t.discarded||(this.learnPendingStartBackendSession(t,e.activity.sessionId),this.queueActivityUpdate(e.activity.phase===`idle`?Sc(t.tempId,t.queuedSends.length):xc(e.activity,t.tempId)))}learnPendingStartBackendSession(e,t){t!==``&&e.backendSessionId===void 0&&(e.backendSessionId=t,this.getState().selectedSession?.id===e.tempId&&this.connectPendingStartSocket(e))}connectPendingStartSocket(e){let t=e.backendSessionId;if(t===void 0||e.discarded)return;let n={id:t,cwd:e.cwd};this.socket.connect(n,t=>{this.applyPendingStartEvent(e,t)},()=>{this.resyncPendingStartDialogs(e)},e.machineId),this.resyncPendingStartDialogs(e)}resyncPendingStartDialogs(e){let t=e.backendSessionId;t!==void 0&&this.api.status({id:t,cwd:e.cwd},e.machineId).then(t=>{if(e.discarded||this.getState().selectedSession?.id!==e.tempId)return;this.applyStatus(t);let n=this.getState(),r=new Set([...n.pendingDialogs.map(e=>e.dialogId),...n.closedDialogs.map(e=>e.dialog.dialogId)]),i=(t.pendingDialogs??[]).filter(e=>!r.has(e.dialogId));i.length>0&&this.setState({pendingDialogs:[...n.pendingDialogs,...i]})},()=>void 0)}applyPendingStartEvent(e,t){e.discarded||this.getState().selectedSession?.id!==e.tempId||(t.type===`dialog.opened`?this.applyOpenedDialog(t.dialog):t.type===`dialog.closed`?this.applyClosedDialog(t.dialogId,t.reason,t.answer):t.type===`status.update`&&this.applyPendingStartStatus(e,t.status))}applyPendingStartStatus(e,t){this.applyStatus(t),!(e.discarded||this.getState().selectedSession?.id!==e.tempId)&&this.setState({pendingDialogs:t.pendingDialogs??[]})}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){if(this.pendingTranscriptEvents.length>0){let e=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let t=this.getState().messages;for(let n of e)t=this.transcripts.applyLiveEvent(t,n)??t;t!==this.getState().messages&&this.setState({messages:t})}if(this.pendingActivityBySession.size>0){let e=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(let t of e)this.applyActivity(t)}if(this.pendingStatusBySession.size>0){let e=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(let t of e)this.applyStatus(t)}}clearPendingUpdates(){this.refreshEventBuffer=void 0,this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=void 0)}isStreamEventBelowWatermark(e){if(e.type===`session.name`||e.type===`session.error`||e.type===`command.output`||e.type===`session.tree.changed`)return!1;let t=this.streamWatermark;return t===void 0||t.sessionId!==this.getState().selectedSession?.id?!1:e.seq!==void 0&&e.seq<=t.seq}async selectSearchMatch(e,t,n){await this.selectSessionAfterNavigation(e,this.navigationSelection());let r=M(this.getState()),i=this.captureSessionErrorOwner(e),a=this.selectionSeq;try{for(;this.isCurrentSearchJump(e.id,r,a)&&this.getState().messagePageStart>t.messageIndex;){let t=this.getState().messagePageStart,n=await this.api.messages(e,{before:t,limit:uc},r);if(!this.isCurrentSearchJump(e.id,r,a))return;let i=this.transcripts.mergeHistory(this.sessionCacheKey(e.id),n);if(this.setState(i),i.messagePageStart>=t)break}}catch(t){this.reportSessionError(e,r,t,i);return}this.isCurrentSearchJump(e.id,r,a)&&this.setState({...this.transcripts.indexedView(this.sessionCacheKey(e.id)),sessionSearchTarget:{sessionId:e.id,messageIndex:t.messageIndex,query:n,requestId:++this.searchTargetSeq}})}isCurrentSearchJump(e,t,n){return this.selectionSeq===n&&M(this.getState())===t&&this.getState().selectedSession?.id===e}};function hc(e){return JSON.stringify(e.partial??null)}function gc(e,t){return _c(e,t)}function _c(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function vc(e,t){if(t.length===0)return e;let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function yc(e,t,n){if(t===n||!(t in e))return e;let r=e[t];return r===void 0?e:{..._c(e,t),[n]:r}}function bc(e,t,n){let r=[],i=!1;for(let a of e)a.id===t?i||=(r.push(n),!0):a.id!==n.id&&r.push(a);return i?r:[n,...r]}function I(e){return e!==void 0&&`clientPendingStart`in e&&e.clientPendingStart===!0}function xc(e,t){return{sessionId:t,phase:e.phase,label:e.label,...e.detail===void 0?{}:{detail:e.detail},at:e.at}}function Sc(e,t=0){return{sessionId:e,phase:`active`,label:D(`activity.creating`,`Creating session`),detail:t>0?D(`client.sessionController.will.send.queued.messages.when.the.backend.session.is.ready.f49381`,`Will send {value1} queued messages when the backend session is ready`,{value1:String(t)}):D(`client.sessionController.waiting.for.the.backend.session.3a8a3d`,`Waiting for the backend session`),at:new Date().toISOString()}}function Cc(e,t,n=0){let r=n>0?D(`client.sessionController.queued.messages.retained.below.2194c6`,` · {value1} queued messages retained below`,{value1:String(n)}):``;return{sessionId:e,phase:`error`,label:D(`client.sessionController.session.creation.failed.aff35c`,`Session creation failed`),detail:`${t}${r}`,at:new Date().toISOString()}}function wc(e){if(e.type===`prompt`){let t=e.attachments?.length??0;return{kind:e.streamingBehavior===`steer`?`steer`:`followUp`,text:Tc(e.text,e.attachments),...t>0?{hasAttachments:!0,attachmentCount:t}:{}}}return{kind:`followUp`,text:e.text}}function Tc(e,t){let n=Ec(t);return n===void 0?e:e.trim()===``?n:`${e}\n\n${n}`}function Ec(e){if(e===void 0||e.length===0)return;let t=e.map(e=>e.name?.trim()).filter(e=>e!==void 0&&e!==``),n=e.length,r=D(`client.sessionController.attachments.092014`,`{value1} attachments`,{value1:String(n)});if(t.length===0)return D(`client.sessionController.queued.6fc044`,`[Queued {value1}]`,{value1:r});let i=t.slice(0,3).join(`、`),a=t.length>3?D(`client.sessionController.plus.more.675fd5`,`, plus {value1} more`,{value1:String(t.length-3)}):``;return D(`client.sessionController.queued.871266`,`[Queued {value1}: {value2}{value3}]`,{value1:r,value2:i,value3:a})}function Dc(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function Oc(e){return e.map(e=>`${e.sessionId}: ${e.error}`)}function kc(e){return e instanceof Error?e.message:String(e)}function Ac(e,t,n){if(n===void 0)return{};let r=e.sessions.some(e=>e.id===t&&e.messageCount!==n)?e.sessions.map(e=>e.id===t?{...e,messageCount:n}:e):void 0,i=e.selectedSession?.id===t&&e.selectedSession.messageCount!==n?{...e.selectedSession,messageCount:n}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...i===e.selectedSession?{}:{selectedSession:i}}}function jc(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`||e.type===`shell.chunk`}function Mc(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`session not found`)||t.includes(D(`session.notFound`,`Session not found`))}function Nc(e){return e===void 0||e.isCurrent()}var Pc=class{constructor(){this.active=new Map,this.revisions=new Map,this.generation=0}observe(e,t){let n=t.type===`status.update`?t.status.sessionId:t.activity.sessionId,r=JSON.stringify([e,n]);this.revisions.set(r,(this.revisions.get(r)??0)+1);let i=this.active.get(r),a={statusActive:i?.statusActive??!1,activityActive:i?.activityActive??!1};if(t.type===`status.update`?(a.statusActive=rr(t.status),a.statusActive||(a.activityActive=!1)):a.activityActive=rr(void 0,t.activity),a.statusActive||a.activityActive)this.active.set(r,a);else return this.active.delete(r),i===void 0?void 0:n}snapshotObserver(e,t){let n=JSON.stringify([e,t]),r=this.revisions.get(n),i=this.generation;return a=>{if(a.sessionId===t&&i===this.generation&&this.revisions.get(n)===r)return this.observe(e,{type:`status.update`,status:a})}}clear(){this.active.clear(),this.revisions.clear(),this.generation+=1}};async function Fc(e){let t=await Promise.allSettled(e),n=[];for(let e of t)e.status===`rejected`&&n.push(e.reason);if(n.length===1)throw n[0];if(n.length>1)throw AggregateError(n,n.map(e=>e instanceof Error?e.message:String(e)).join(`; `))}var Ic={order:0,overflowWatermark:0};function Lc(e){return{...e,status:`loading`,catalogRevision:0,notifications:[],dismissThrough:Ic,optimisticDismissedIds:[],announcements:[]}}function Rc(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)throw Error(`Notification inbox snapshot does not match the selected session`);let r=e!==void 0&&Qc(e,t)&&e.daemonInstanceId===n.daemonInstanceId;return{...t,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:n.notifications,dismissThrough:n.dismissThrough,optimisticDismissedIds:r?e.optimisticDismissedIds:[],...r&&e.optimisticDismissAllThrough!==void 0?{optimisticDismissAllThrough:e.optimisticDismissAllThrough}:{},announcements:r?e.announcements:[]}}function zc(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)return{value:e??Lc(t),needsRefresh:!1,changed:!1};if(e===void 0||!Qc(e,t))return{value:el(t),needsRefresh:!0,changed:!0};if(e.daemonInstanceId!==n.daemonInstanceId)return{value:el(t),needsRefresh:!0,changed:e.status!==`stale`||e.daemonInstanceId!==void 0||e.notifications.length>0};let r=e.summary?.inboxRevision??0;if(n.summary.inboxRevision<=r)return{value:e,needsRefresh:!1,changed:!1};if(e.status!==`fresh`||n.summary.inboxRevision!==r+1||n.delta.kind===`resync`)return{value:{...e,status:`stale`},needsRefresh:!0,changed:e.status!==`stale`};let i,a;switch(n.delta.kind){case`added`:{let t=n.delta;if(e.notifications.some(e=>e.id===t.notification.id))return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};i=[t.notification,...e.notifications].filter(e=>e.id!==t.evictedNotificationId).sort((e,t)=>t.order-e.order).slice(0,100),a={id:`${n.daemonInstanceId}:${String(n.summary.inboxRevision)}:${t.notification.id}`,severity:t.notification.severity,message:t.notification.message};break}case`dismissed`:{let t=new Set(n.delta.notificationIds);i=e.notifications.filter(e=>!t.has(e.id));break}case`cleared`:i=[]}let o=i[0]?.order??0;if(!tl(i,n.summary)||n.dismissThrough.order!==o||n.dismissThrough.overflowWatermark<n.summary.discardedCount)return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};let s=a===void 0?e.announcements:[...e.announcements,a].slice(-100);return{value:{...e,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:i,dismissThrough:n.dismissThrough,announcements:s},needsRefresh:!1,changed:!0}}function Bc(e){if(e?.status!==`fresh`||e.daemonInstanceId===void 0||e.summary===void 0)return;let t=new Set(e.optimisticDismissedIds),n=e.optimisticDismissAllThrough,r=e.notifications.filter(e=>!t.has(e.id)&&(n===void 0||e.order>n.order)),i=rl(e.summary.discardedCount,e.dismissThrough.overflowWatermark,n?.overflowWatermark);return r.length===0&&t.size>0&&(i=0),{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd,daemonInstanceId:e.daemonInstanceId,notifications:r,retainedCount:r.length,discardedCount:i,...il(nl(r)),dismissThrough:e.dismissThrough,pendingDismissedIds:t,dismissAllPending:n!==void 0,announcements:e.announcements}}function Vc(e){return e===`error`?D(`client.sessionNotifications.error.0bc1fb`,`Error`):e===`warning`?D(`client.sessionNotifications.warning.a8b7a4`,`Warning`):D(`client.sessionNotifications.info.e70286`,`Info`)}function Hc(e){return D(`client.sessionNotifications.notification.received.0cb785`,`{value1} notification received.`,{value1:Vc(e.severity)})}function Uc(e){return e.retainedCount+e.discardedCount}function Wc(e){return D(`client.sessionNotifications.notifications.38c528`,`Notifications ({value1})`,{value1:String(Uc(e))})}function Gc(e){let t=e.message.replace(/\s+/gu,` `).trim();if(t===``)return D(`client.sessionNotifications.dismiss.notification.137f92`,`Dismiss {value1} notification`,{value1:Vc(e.severity)});let n=Array.from(t),r=n.length<=80?t:`${n.slice(0,79).join(``).trimEnd()}…`;return D(`client.sessionNotifications.dismiss.notification.600367`,`Dismiss notification: {value1}`,{value1:r})}function Kc(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1)return{kind:`header`};let r=e[n+1];if(r!==void 0)return{kind:`notification`,notificationId:r.id};let i=e[n-1];return i===void 0?{kind:`header`}:{kind:`notification`,notificationId:i.id}}function qc(e){return JSON.stringify([e.machineId,e.cwd,e.sessionId])}function Jc(e,t){return e.has(qc(t))}function Yc(e,t,n){let r=new Set(e),i=qc(t);return n?r.add(i):r.delete(i),r}function Xc(e){return D(`client.sessionNotifications.older.notifications.not.shown.7c54ee`,`{value1} older notifications not shown.`,{value1:String(e)})}function Zc(e){if(!e.truncated)return;let t=Lt/1024;return D(`client.sessionNotifications.message.truncated.at.kib.ac3119`,`Message truncated at {value1} KiB.`,{value1:String(t)})}function Qc(e,t){return e.machineId===t.machineId&&e.sessionId===t.sessionId&&e.cwd===t.cwd}function $c(e,t){if(e===`error`||t===`error`)return`error`;if(e===`warning`||t===`warning`)return`warning`;if(e===`info`||t===`info`)return`info`}function el(e){return{...Lc(e),status:`stale`}}function tl(e,t){return e.length===t.retainedCount&&nl(e)===t.highestSeverity}function nl(e){let t;for(let n of e)t=$c(t,n.severity);return t}function rl(e,t,n){if(e===0||n===void 0)return e;let r=t-e+1;return e-Math.max(0,Math.min(e,n-r+1))}function il(e){return e===void 0?{}:{highestSeverity:e}}var al=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.acceptedSupportByMachine=new Set,this.selectedGeneration=0,this.dismissingNotificationIds=new Set,this.dismissAllPending=!1,this.disposed=!1,this.api=n.api??x,this.onBackgroundError=n.onBackgroundError??((e,t)=>{console.warn(e,t)})}dispose(){this.disposed=!0,this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.acceptedSupportByMachine.clear(),this.dismissingNotificationIds.clear(),this.dismissAllPending=!1}prepareSelectedSession(e,t){this.selectedGeneration+=1,this.selectedTarget=e.archived===!0?void 0:{machineId:t,sessionId:e.id,cwd:e.cwd},this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.selectedTarget===void 0||!this.machineSupportsNotifications(t)?this.setState({selectedNotificationInbox:void 0}):this.setState({selectedNotificationInbox:Lc(this.selectedTarget)})}clearSelectedSession(){this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.setState({selectedNotificationInbox:void 0})}refreshSelectedSession(e,t){let n=this.selectedTarget;if(this.disposed||n?.machineId!==t||n.sessionId!==e.id||n.cwd!==e.cwd||!this.machineSupportsNotifications(t)||!this.machineIsReachable(t))return Promise.resolve();let r=this.selectedGeneration,i=this.selectedRefresh;if(i?.generation===r)return i.trailing=!0,i.promise;this.ensureSelectedProjection(n);let a={generation:r,promise:Promise.resolve(),trailing:!1};return a.promise=this.runSelectedRefresh(a,n).finally(()=>{this.selectedRefresh===a&&(this.selectedRefresh=void 0)}),this.selectedRefresh=a,a.promise}applyInboxEvent(e,t){let n=this.selectedTarget;if(n?.machineId!==e||n.sessionId!==t.summary.sessionId||n.cwd!==t.summary.cwd)return;this.acceptedSupportByMachine.add(e);let r=this.selectedJoin;if(r?.generation===this.selectedGeneration){r.events.push(t);return}let i=zc(this.getState().selectedNotificationInbox,n,t);i.changed&&this.setState({selectedNotificationInbox:i.value}),i.needsRefresh&&this.scheduleSelectedRefresh(n)}syncEnvironment(e,t){if(this.disposed)return;e.machines!==t.machines&&this.pruneRemovedMachines(t.machines);let n=e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||e.machineRuntimes!==t.machineRuntimes,r=this.selectedTarget;if(!n||r===void 0)return;let i=this.machineSupportsNotificationsInState(e,r.machineId)&&this.machineIsReachableInState(e,r.machineId);!this.machineSupportsNotifications(r.machineId)||!this.machineIsReachable(r.machineId)?this.markSelectedStale(r):(this.ensureSelectedProjection(r),i&&this.getState().selectedNotificationInbox?.status===`fresh`||this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId))}shouldFilterLegacyNotification(e,t){return t!==void 0&&t!==``&&this.machineSupportsNotifications(e)}async dismissNotification(e){let t=this.getState().selectedNotificationInbox,n=Bc(t);if(t===void 0||n===void 0||this.dismissAllPending||this.dismissingNotificationIds.has(e)||!n.notifications.some(t=>t.id===e))return;let r=ol(t),i=this.selectedGeneration;this.dismissingNotificationIds.add(e),this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:[...new Set([...t.optimisticDismissedIds,e])]}));try{let t=await this.api.dismissNotification({id:r.sessionId,cwd:r.cwd},n.daemonInstanceId,e,r.machineId);this.isCurrentTarget(r,i)&&this.applyMutationSnapshot(r,t,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)}))}catch(t){this.isCurrentTarget(r,i)&&(this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)})),this.setState({error:D(`client.sessionNotificationController.failed.to.dismiss.notification.080d8f`,`Failed to dismiss notification: {value1}`,{value1:cl(t)})}),await this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId))}finally{this.dismissingNotificationIds.delete(e)}}async dismissAll(){let e=this.getState().selectedNotificationInbox,t=Bc(e);if(e===void 0||t===void 0||this.dismissAllPending||t.retainedCount+t.discardedCount===0)return;let n=ol(e),r=this.selectedGeneration,i={...e.dismissThrough};this.dismissAllPending=!0,this.patchSelectedOverlay(n,e=>({...e,optimisticDismissAllThrough:i}));try{let e=await this.api.dismissAllNotifications({id:n.sessionId,cwd:n.cwd},t.daemonInstanceId,i,n.machineId);this.isCurrentTarget(n,r)&&this.applyMutationSnapshot(n,e,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t})}catch(e){this.isCurrentTarget(n,r)&&(this.patchSelectedOverlay(n,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t}),this.setState({error:D(`client.sessionNotificationController.failed.to.dismiss.session.notifications.5621de`,`Failed to dismiss session notifications: {value1}`,{value1:cl(e)})}),await this.refreshSelectedSession({id:n.sessionId,cwd:n.cwd},n.machineId))}finally{r===this.selectedGeneration&&(this.dismissAllPending=!1)}}async runSelectedRefresh(e,t){do{e.trailing=!1;let n={generation:e.generation,events:[]};this.selectedJoin=n;try{let r=await this.api.notificationInbox({id:t.sessionId,cwd:t.cwd},t.machineId);if(!this.isCurrentTarget(t,e.generation))return;if(!this.machineSupportsNotifications(t.machineId)||!this.machineIsReachable(t.machineId)){this.markSelectedStale(t);return}this.acceptedSupportByMachine.add(t.machineId);let i=this.getState().selectedNotificationInbox,a=i===void 0||sl(i,t,r)?Rc(i,t,r):i;for(let r of[...n.events].sort((e,t)=>e.summary.inboxRevision-t.summary.inboxRevision)){let n=zc(a,t,r);a=n.value,n.needsRefresh&&(e.trailing=!0)}this.setState({selectedNotificationInbox:a})}catch(n){if(this.isCurrentTarget(t,e.generation)){let e=this.getState().selectedNotificationInbox;e!==void 0&&Qc(e,t)&&e.status!==`stale`&&this.setState({selectedNotificationInbox:{...e,status:`stale`}}),this.onBackgroundError(`Failed to refresh notifications for session ${t.sessionId}`,n)}return}finally{this.selectedJoin===n&&(this.selectedJoin=void 0)}}while(e.trailing&&this.isCurrentTarget(t,e.generation)&&this.machineIsReachable(t.machineId))}applyMutationSnapshot(e,t,n){let r=this.getState().selectedNotificationInbox;if(r===void 0||!Qc(r,e))return;if(!this.machineSupportsNotifications(e.machineId)||!this.machineIsReachable(e.machineId)){this.setState({selectedNotificationInbox:{...n(r),status:`stale`}});return}let i=sl(r,e,t)?Rc(r,e,t):r;this.setState({selectedNotificationInbox:n(i)})}patchSelectedOverlay(e,t){let n=this.getState().selectedNotificationInbox;n!==void 0&&Qc(n,e)&&this.setState({selectedNotificationInbox:t(n)})}ensureSelectedProjection(e){let t=this.getState().selectedNotificationInbox;t!==void 0&&Qc(t,e)||this.setState({selectedNotificationInbox:Lc(e)})}scheduleSelectedRefresh(e){queueMicrotask(()=>{!this.disposed&&this.selectedTarget!==void 0&&Qc(this.selectedTarget,e)&&this.refreshSelectedSession({id:e.sessionId,cwd:e.cwd},e.machineId)})}markSelectedStale(e){let t=this.getState().selectedNotificationInbox;t!==void 0&&Qc(t,e)&&t.status!==`stale`&&this.setState({selectedNotificationInbox:{...t,status:`stale`}})}pruneRemovedMachines(e){let t=new Set(e.map(e=>e.id));t.size===0&&t.add(`local`);for(let e of[...this.acceptedSupportByMachine])t.has(e)||this.acceptedSupportByMachine.delete(e)}isCurrentTarget(e,t){return!this.disposed&&t===this.selectedGeneration&&this.selectedTarget!==void 0&&Qc(this.selectedTarget,e)}machineSupportsNotifications(e){return this.machineSupportsNotificationsInState(this.getState(),e)}machineSupportsNotificationsInState(e,t){return this.acceptedSupportByMachine.has(t)||e.machineRuntimes[t]?.ok===!0}machineIsReachable(e){return this.machineIsReachableInState(this.getState(),e)}machineIsReachableInState(e,t){let n=e.machines.find(e=>e.id===t);if(t===`local`||n?.kind===`local`)return!0;let r=e.machineStatuses[t]?.status??n?.status;return r===void 0||r===`unknown`||r===`online`}};function ol(e){return{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd}}function sl(e,t,n){return!Qc(e,t)||e.daemonInstanceId!==n.daemonInstanceId||e.summary===void 0||n.summary.inboxRevision>=e.summary.inboxRevision}function cl(e){return e instanceof Error?e.message:String(e)}function ll(e){return e?.status!==`folder`}var ul=class{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}},dl=`pi-web:workspace-selection:v1`,fl=class{constructor(e=Vs()){this.workspaceIdsByProject=new Hs(dl,Us,e)}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}};function pl(e,t){let n=t?.targetWorkspaceId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestWorkspaceId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e[0]:e[0]}var ml=50,hl=[`machine`,`project`,`workspace`,`session`],gl=class{constructor(e,t,n,r,i=new ul,a={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessions=r,this.workspaceSelection=i,this.workspaceListRequests=new Map,this.api=a.api??x,this.navigateToWorkspace=a.navigateToWorkspace,this.captureNavigation=a.captureNavigation,this.beginNavigationOperation=a.beginNavigationOperation,this.onBackgroundError=a.onBackgroundError??((e,t)=>{console.warn(e,t)}),this.browserErrors=new $n(e,t),this.topologyRefreshes=new gr(a.topologyRefreshDebounceMs??ml)}clearSelection(e){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,workspaceResolution:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...Hn()}),e?.updateUrl!==!1&&this.updateUrl()}forgetProject(e){let t=M(this.getState());this.browserErrors.discard(Wn(t,e)),this.workspaceSelection.forgetProject(hr(t,e));let n=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([t])=>t!==e));this.setState({workspacesByProjectId:n})}async selectProject(e,t){let n=t?.navigation??this.beginNavigationOperation?.(hl);if(!this.navigationIsCurrent(n)||!vl(t))return;let r=M(this.getState()),i=Wn(r,e.id);this.sessions.clearActiveSession(),this.setState({selectedProject:e,workspaceResolution:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...Hn()});let a=this.beginWorkspaceListRequest(e.id,r);try{let o=t?.signal===void 0?await this.api.workspaceResolution(e.id,r):await this.api.workspaceResolution(e.id,r,{signal:t.signal}),s=[...o.workspaces];if(!a()||!this.navigationIsCurrent(n)||!vl(t)||M(this.getState())!==r||this.getState().selectedProject?.id!==e.id)return;if(this.setState({workspaceResolution:o,workspaces:s,workspacesByProjectId:{...this.getState().workspacesByProjectId,[e.id]:s},isLoadingWorkspaces:!1}),o.status===`degraded`)throw Sl(o);let c=pl(s,{targetWorkspaceId:t?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(hr(r,e.id))});if(c)return await this.selectWorkspace(c,{...t,sessionId:t?.sessionId,updateUrl:t?.updateUrl,navigation:n});if(t?.workspaceId!==void 0&&t.workspaceId!==``)return this.browserErrors.report(i,D(`ui.main.06529052d1e0`,`Workspace not found: {arg0}`,{arg0:t.workspaceId})),D(`ui.main.06529052d1e0`,`Workspace not found: {arg0}`,{arg0:t.workspaceId});t?.updateUrl!==!1&&this.navigationIsCurrent(n)&&this.updateUrl()}catch(a){return this.navigationIsCurrent(n)&&vl(t)&&M(this.getState())===r&&this.getState().selectedProject?.id===e.id&&this.setState({isLoadingWorkspaces:!1}),t?.signal?.aborted!==!0&&this.browserErrors.report(i,String(a)),String(a)}}async selectWorkspace(e,t){let n=t?.navigation??this.beginNavigationOperation?.(hl);if(!this.navigationIsCurrent(n)||!vl(t))return;let r=M(this.getState()),i=Gn(r,e.projectId,e.id);this.workspaceSelection.rememberWorkspace({...e,projectId:hr(r,e.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:e,isLoadingWorkspaces:!1,...Hn()});try{let a=t?.signal===void 0?await this.api.sessions(e.path,r):await this.api.sessions(e.path,r,{signal:t.signal}),o=Qr(e.path,a,r);if(!this.navigationIsCurrent(n)||!vl(t)||M(this.getState())!==r||this.getState().selectedWorkspace?.id!==e.id||this.getState().selectedProject?.id!==e.projectId)return;this.setState({sessions:o});let s=this.sessions.preferredSession(e.path,o,t?.sessionId);if(!this.navigationIsCurrent(n)||!vl(t))return;if(s)await this.sessions.selectSession(s,{deferChatLoading:!0,updateUrl:t?.updateUrl,...n===void 0?{}:{navigation:n}});else if(t?.sessionId!==void 0&&t.sessionId!==``)return this.browserErrors.report(i,D(`ui.main.0041c3cf98cd`,`Session not found: {arg0}`,{arg0:t.sessionId})),D(`ui.main.0041c3cf98cd`,`Session not found: {arg0}`,{arg0:t.sessionId});else t?.updateUrl!==!1&&this.updateUrl()}catch(e){return t?.signal?.aborted!==!0&&this.browserErrors.report(i,String(e)),String(e)}}async refreshProjectWorkspaces(e,t=M(this.getState()),n){return(await this.refreshProjectWorkspaceList(e,t,n)).workspaces}async refreshProjectWorkspaceList(e,t,n){if(!vl(n))return{workspaces:[],isCurrent:()=>!1};let r=this.getState().projects.find(t=>t.id===e);if(r===void 0)throw Error(D(`client.workspaceController.project.not.found.3b6bf4`,`Project not found`));let i=this.beginWorkspaceListRequest(e,t),a=n?.signal===void 0?await this.api.workspaceResolution(r.id,t):await this.api.workspaceResolution(r.id,t,{signal:n.signal}),o=[...a.workspaces];if(i()&&vl(n)&&M(this.getState())===t){if(this.getState().selectedProject?.id===r.id&&this.setState({workspaceResolution:a}),a.status===`degraded`)throw Sl(a);this.applyProjectWorkspaces(r.id,o)}return{workspaces:o,isCurrent:i}}async refreshSelectedProjectTopology(){let e=this.getState(),t=e.selectedProject;if(t===void 0||e.isLoadingWorkspaces)return;let n=M(e);await this.topologyRefreshes.request(hr(n,t.id),async()=>{if(this.getState().isLoadingWorkspaces)return;let e=this.beginWorkspaceListRequest(t.id,n);try{let r=await this.api.workspaceResolution(t.id,n),i=this.getState();if(!e()||M(i)!==n||i.selectedProject?.id!==t.id)return;if(this.setState({workspaceResolution:r}),r.status===`degraded`)throw Sl(r);this.applyProjectWorkspaces(t.id,[...r.workspaces])}catch(e){this.onBackgroundError(`Failed to refresh workspaces for project ${t.id} on ${n}`,e)}})}async refreshAfterWorkspaceDeleted(e,t,n=M(this.getState()),r){if(!vl(r))return;let i=this.beginNavigationOperation?.(hl),{workspaces:a,isCurrent:o}=await this.refreshProjectWorkspaceList(e,n,r);if(!o()||!this.navigationIsCurrent(i)||!vl(r))return;let s=this.getState();if(M(s)!==n||s.selectedProject?.id!==e||s.selectedWorkspace?.id!==t)return;let c=_l(this.getState(),this.captureNavigation),l=yl(a);this.navigateToWorkspace===void 0?l===void 0?this.navigationIsCurrent(i)&&vl(r)&&this.clearSelection():await this.selectWorkspace(l,{...r,...i===void 0?{}:{navigation:i}}):await this.navigateToWorkspace(l,{expected:c})}beginWorkspaceListRequest(e,t){let n=hr(t,e),r=(this.workspaceListRequests.get(n)??0)+1;return this.workspaceListRequests.set(n,r),()=>this.workspaceListRequests.get(n)===r}applyProjectWorkspaces(e,t){let n=this.getState(),r={...n.workspacesByProjectId,[e]:t};n.selectedProject?.id===e?this.setState({workspaces:t,workspacesByProjectId:r,...this.refreshedSelection(n.selectedWorkspace,t)}):this.setState({workspacesByProjectId:r})}refreshedSelection(e,t){if(e===void 0)return;let n=t.find(t=>t.id===e.id);if(!(n===void 0||bl(e,n)))return{selectedWorkspace:n}}navigationIsCurrent(e){return e===void 0||e.isCurrent()}};function _l(e,t){return t?.()??{machineId:M(e),projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,...e.selectedSession===void 0||Reflect.get(e.selectedSession,`clientPendingStart`)!==!0?{sessionId:e.selectedSession?.id}:{}}}function vl(e){return e?.signal?.aborted!==!0&&e?.isCurrent?.()!==!1}function yl(e){return e.find(e=>e.isMain)??e[0]}function bl(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>bl(e,t[n]));if(!xl(e)||!xl(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&bl(e[n],t[n]))}function xl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Sl(e){return Error(e.diagnostics.map(({message:e})=>e).join(`; `)||D(`client.workspaceController.authorityDegraded`,`Workspace authority is degraded`))}var Cl=`core.workspace.files--file`,wl=`core.workspace.terminal--terminal`,Tl=`pi-web:machine-navigation:v1`,El=class{constructor(e=Vs()){this.snapshotsByMachine=new Hs(Tl,jl,e)}latest(e){let t=this.snapshotsByMachine.get(e);return t?.machineId===e?Al(t):void 0}remember(e){this.snapshotsByMachine.set(e.machineId,Al(e))}forget(e){this.snapshotsByMachine.delete(e)}};function Dl(e){return{machineId:e,surface:{}}}function Ol(e,t={}){let n=e.selectedWorkspace===void 0?{}:ra(t),r=e.selectedSession?.id;return{machineId:e.selectedMachine?.id??`local`,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:r,tool:e.workspaceTool,view:e.mainView,surface:{...Object.keys(n).length===0?{}:{contributionQuery:n}}}}function kl(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view}}function Al(e){let t=e.surface.contributionQuery;return{...e,surface:{...e.surface,...t===void 0?{}:{contributionQuery:ra(t)}}}}function jl(e){if(!Il(e))return;let t=Fl(e,`machineId`);if(t===void 0)return;let n=Fl(e,`view`),r=n===`files`||n===`core:workspace.files`?`core:workspace.files`:n===`git`||n===`core:workspace.git`?`core:workspace.git`:n===`terminal`||n===`core:workspace.terminal`?`core:workspace.terminal`:void 0,i=Nl(Fl(e,`tool`))??r,a=Sa(n)??(r===void 0?void 0:`workspace`);return{machineId:t,projectId:Fl(e,`projectId`),workspaceId:Fl(e,`workspaceId`),sessionId:Fl(e,`sessionId`),...i===void 0?{}:{tool:i},...a===void 0?{}:{view:a},surface:Ml(e.surface)}}function Ml(e){if(!Il(e))return{};let t=Il(e.contributionQuery)?e.contributionQuery:{},n=Fl(e,`selectedFilePath`),r=Fl(e,`selectedTerminalId`),i=Fl(e,`selectedDiffPath`),a=ra({...n===void 0?{}:{[Cl]:n},...r===void 0?{}:{[wl]:r},...i===void 0?{}:{"core.workspace.git--diff":i},...t});return{...Object.keys(a).length===0?{}:{contributionQuery:a}}}function Nl(e){return Pl(e)?e:void 0}function Pl(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Fl(e,t){let n=e[t];return typeof n==`string`&&n!==``?n:void 0}function Il(e){return typeof e==`object`&&!!e}function Ll(e,t,n){if(t!==void 0&&zl(t.path)===zl(n.cwd))return{machineId:e,projectId:t.projectId,workspaceId:t.id,root:t.path}}function Rl(e,t){let n=e.trim();if(n===``||/^[#?]/.test(n)||n.startsWith(`//`)||/^[a-z][a-z\d+.-]*:/i.test(n))return;let r;try{r=decodeURIComponent(n.split(/[?#]/,1)[0]??``)}catch{return}if(r===``||/[\\\u0000-\u001f\u007f]/.test(r))return;if(r.startsWith(`/`)){let e=`${zl(t.root)}/`;if(!r.startsWith(e)||(r=r.slice(e.length),r===``))return}let i=r.split(`/`).filter(e=>e!==``&&e!==`.`).join(`/`);return i===``?void 0:i}function zl(e){return e.replace(/\/+$/,``)}var Bl={archiveIdleEnabled:!0,archiveIdleDays:`30`,deleteArchivedEnabled:!1,deleteArchivedDays:`90`};function Vl(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:D(`client.sessionCleanupUi.enable.at.least.one.cleanup.action.d2ce50`,`Enable at least one cleanup action.`)};let t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){let n=Zl(e.archiveIdleDays,D(`client.sessionCleanupUi.archive.idle.sessions.after.6d41ea`,`Archive idle sessions after`));if(typeof n==`string`)return{ok:!1,error:n};t.archiveIdleDays=n}if(e.deleteArchivedEnabled){let n=Zl(e.deleteArchivedDays,D(`client.sessionCleanupUi.delete.archived.sessions.after.923bee`,`Delete archived sessions after`));if(typeof n==`string`)return{ok:!1,error:n};t.deleteArchivedDays=n}return{ok:!0,request:t}}function Hl(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null,projectId:e?.projectId??null})}function Ul(e){if(e.canCleanup===!1||e.loading===!0||e.running===!0||e.preview===void 0)return!1;let t=Vl(e.draft);if(!t.ok)return!1;if(e.previewRequest===void 0){if(e.canCleanup!==!0||!Wl(e.draft,e.preview))return!1}else if(Ql(t.request)!==Ql(e.previewRequest))return!1;return Gl(e.preview)}function Wl(e,t){let n=Vl(e);return n.ok?Ql(n.request)===Ql(t.thresholds):!1}function Gl(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function Kl(e,t){let n=e.projects.map(e=>e.cwd);if(t===void 0)return n;let r=new Set(t);return n.filter(e=>r.has(e))}function ql(e,t){let n=new Set(Kl(e,t)),r=e.projects.filter(e=>n.has(e.cwd));return{...e,projects:r,totals:r.reduce((e,t)=>({archiveCount:e.archiveCount+t.archiveCount,deleteCount:e.deleteCount+t.deleteCount}),{archiveCount:0,deleteCount:0})}}function Jl(e,t){return t(Yl(e))}function Yl(e){let t=e.totals.archiveCount,n=e.totals.deleteCount,r=[];t>0&&r.push(D(`client.sessionCleanupUi.archive.idle.sessions.27a4f1`,`archive {value1} idle sessions`,{value1:String(t)})),n>0&&r.push(D(`client.sessionCleanupUi.permanently.delete.archived.sessions.360209`,`permanently delete {value1} archived sessions`,{value1:String(n)}));let i=r.length===0?D(`client.sessionCleanupUi.run.cleanup.233f8e`,`run cleanup`):r.join(D(`client.sessionCleanupUi.and.2f4b60`,` and `));return D(`client.sessionCleanupUi.run.cleanup.and.permanent.deletion.only.applies.to.archived.sessions.a.9775e2`,`Run cleanup and {value1}?
|
|
28
28
|
|
|
29
29
|
Permanent deletion only applies to archived sessions and cannot be undone.`,{value1:i})}function Xl(e){return D(`client.sessionCleanupUi.update.and.restart.pi.web.on.before.cleaning.up.sessions.3c493f`,`Update and restart Pi-Web on {value1} before cleaning up sessions.`,{value1:e??D(`client.sessionCleanupUi.this.machine.74a83f`,`this machine`)})}function Zl(e,t){let n=e.trim();if(n===``)return D(`client.sessionCleanupUi.must.be.set.208394`,`{value1} must be set.`,{value1:t});let r=Number(n);return!Number.isInteger(r)||r<0?D(`client.sessionCleanupUi.must.be.a.non.negative.integer.number.of.days.7ed7a9`,`{value1} must be a non-negative integer number of days.`,{value1:t}):r}function Ql(e){return JSON.stringify({archiveIdleDays:e.archiveIdleDays??null,deleteArchivedDays:e.deleteArchivedDays??null})}var $l=new Set,eu=Nt+1,tu={unreadCatalog:e=>s.unreadCatalog(e),acknowledgeUnread:(e,t,n,r)=>s.acknowledgeUnread(e,t,n,r)},nu=class{constructor(e={}){this.machines=new Map,this.api=e.api??tu,this.onChange=e.onChange??(()=>void 0),this.onBackgroundError=e.onBackgroundError??(()=>void 0)}retainMachines(e){for(let[t,n]of this.machines){if(e.has(t))continue;let r=n.projection!==void 0;n.generation+=1,n.observers.clear(),n.acknowledgements.clear(),this.machines.delete(t),r&&this.onChange(t)}}projection(e){let t=this.machines.get(e),n=t?.projection;if(t!==void 0&&n!==void 0)return{status:t.status,catalogId:n.catalogId,catalogRevision:n.catalogRevision,sessions:[...n.summariesByIdentity.values()].sort((e,t)=>t.completionOrder-e.completionOrder).map(e=>({...e}))}}unreadSessionIds(e,t){let n=this.machines.get(e)?.projection;if(n===void 0||t.length===0)return $l;let r=new Set;for(let e of t)n.summariesByIdentity.has(cu(e))&&r.add(e.id);return r.size===0?$l:r}isUnread(e,t){return this.machines.get(e)?.projection?.summariesByIdentity.has(cu(t))===!0}applyEvent(e,t){let n=this.machine(e);this.recordObservedEvent(n,t);let r=ru(n.projection,n.status,t);this.installProjection(n,r.projection,r.status)&&this.onChange(e),r.requiresRefresh&&(n.refreshPromise===void 0?this.refresh(e):n.refreshQueued=!0)}refresh(e){let t=this.machine(e);if(t.refreshPromise!==void 0)return t.refreshQueued=!0,t.refreshPromise;let n=t.generation,r=this.runRefreshLoop(t,n);return t.refreshPromise=r,r.finally(()=>{if(!this.isCurrent(t,n)||t.refreshPromise!==r)return;t.refreshPromise=void 0;let e=t.refreshQueued;t.refreshQueued=!1,e&&this.refresh(t.machineId)}),r}async refreshAll(){await Promise.all([...this.machines.values()].map(async e=>{await this.refresh(e.machineId)}))}acknowledge(e,t){let n=this.machines.get(e),r=n?.projection;if(n===void 0||r===void 0)return Promise.resolve();let i=r.summariesByIdentity.get(cu(t));if(i===void 0)return Promise.resolve();let a=lu(r.catalogId,i),o=n.acknowledgements.get(a);if(o!==void 0)return o;let s=n.generation,c=this.runAcknowledgement(n,s,t,r.catalogId,i.completionOrder);return n.acknowledgements.set(a,c),c.finally(()=>{n.acknowledgements.get(a)===c&&n.acknowledgements.delete(a)}),c}acknowledgeLoaded(e,t,n){let r=this.machines.get(e),i=r?.projection?.summariesByIdentity.get(cu(t));if(r?.status!==`fresh`||i===void 0)return Promise.resolve();let a=i.messageRange;if(a===void 0){if(n.start!==0||n.end<n.total)return Promise.resolve()}else if(n.leafId!==a.leafId||n.start>a.start||n.end<a.end)return Promise.resolve();return this.acknowledge(e,t)}needsHistoryRefresh(e,t,n,r){let i=this.machines.get(e)?.projection?.summariesByIdentity.get(cu(t))?.messageRange;return i!==void 0&&(i.leafId!==r||i.end>n)}async runRefreshLoop(e,t){do{if(e.refreshQueued=!1,!this.isCurrent(e,t))return;let n=e.status;this.markRefreshStarted(e)&&this.onChange(e.machineId);let r=this.beginNetworkObservation(e,t,n);try{let n=await this.api.unreadCatalog(e.machineId);if(!this.isCurrent(e,t))return;this.applyNetworkSnapshot(e,n,r)&&(e.refreshQueued=!0)}catch(n){if(this.isCurrent(e,t)){let t=e.status!==`stale`;e.status=`stale`,t&&this.onChange(e.machineId),this.reportError(`snapshot`,e.machineId,n)}}finally{e.observers.delete(r)}}while(e.refreshQueued&&this.isCurrent(e,t))}async runAcknowledgement(e,t,n,r,i){let a=this.beginNetworkObservation(e,t);try{let o=await this.api.acknowledgeUnread(n,r,i,e.machineId);if(!this.isCurrent(e,t))return;this.applyNetworkSnapshot(e,o,a)&&this.refresh(e.machineId)}catch(n){this.isCurrent(e,t)&&this.reportError(`acknowledge`,e.machineId,n)}finally{e.observers.delete(a)}}applyNetworkSnapshot(e,t,n){let r=e.projection;if(e.projectionVersion!==n.projectionVersion&&r!==void 0&&r.catalogId!==t.catalogId||n.overflowed||n.events.some(e=>e.catalogId!==t.catalogId)){let t=e.status!==`stale`;return e.status=`stale`,t&&this.onChange(e.machineId),!0}let i=au(t),a=`fresh`,o=!1;for(let e of n.events){let t=ru(i,a,e);i=t.projection,a=t.status,o||=t.requiresRefresh}if(r?.catalogId===i.catalogId&&r.catalogRevision>i.catalogRevision){if(e.projectionVersion===n.projectionVersion&&n.projectionStatus===`fresh`){let t=e.status!==`fresh`;e.status=`fresh`,t&&this.onChange(e.machineId)}o||=e.status===`stale`}else this.installProjection(e,i,a)&&this.onChange(e.machineId);return o}beginNetworkObservation(e,t,n=e.status){let r={generation:t,projectionVersion:e.projectionVersion,projectionStatus:n,events:[],overflowed:!1};return e.observers.add(r),r}recordObservedEvent(e,t){for(let n of e.observers)n.generation!==e.generation||n.overflowed||(n.events.length>=eu?(n.events.length=0,n.overflowed=!0):n.events.push(t))}markRefreshStarted(e){let t=e.projection===void 0?`loading`:`stale`;return e.status!==t&&(e.status=t,!0)}installProjection(e,t,n){let r=!su(e.projection,t);return e.status===n&&!r?!1:(r&&(e.projection=t,e.projectionVersion+=1),e.status=n,!0)}machine(e){let t=this.machines.get(e);if(t!==void 0)return t;let n={machineId:e,status:`stale`,projection:void 0,projectionVersion:0,generation:0,observers:new Set,acknowledgements:new Map,refreshPromise:void 0,refreshQueued:!1};return this.machines.set(e,n),n}isCurrent(e,t){return this.machines.get(e.machineId)===e&&e.generation===t}reportError(e,t,n){this.onBackgroundError(e,t,n)}};function ru(e,t,n){if(e===void 0){let e=ou(n.catalogId);return n.catalogRevision===1?iu(e,`fresh`,n):{projection:e,status:`stale`,requiresRefresh:!0}}if(e.catalogId!==n.catalogId){let e=ou(n.catalogId);return n.catalogRevision===1?iu(e,`stale`,n):{projection:e,status:`stale`,requiresRefresh:!0}}return n.catalogRevision<=e.catalogRevision?{projection:e,status:t,requiresRefresh:t===`stale`}:n.catalogRevision===e.catalogRevision+1?iu(e,t,n):{projection:e,status:`stale`,requiresRefresh:!0}}function iu(e,t,n){let r=new Map(e.summariesByIdentity),i=cu(n);n.unread===null?r.delete(i):r.set(i,{...n.unread});let a=t===`stale`?`stale`:`fresh`;return{projection:{catalogId:n.catalogId,catalogRevision:n.catalogRevision,summariesByIdentity:r},status:a,requiresRefresh:a===`stale`}}function au(e){return{catalogId:e.catalogId,catalogRevision:e.catalogRevision,summariesByIdentity:new Map(e.sessions.map(e=>[cu(e),{...e}]))}}function ou(e){return{catalogId:e,catalogRevision:0,summariesByIdentity:new Map}}function su(e,t){if(e?.catalogId!==t.catalogId||e.catalogRevision!==t.catalogRevision||e.summariesByIdentity.size!==t.summariesByIdentity.size)return!1;for(let[n,r]of e.summariesByIdentity){let e=t.summariesByIdentity.get(n);if(e?.completionOrder!==r.completionOrder||e.completedAt!==r.completedAt)return!1}return!0}function cu(e){let t=`id`in e?e.id:e.sessionId;return JSON.stringify([t,e.cwd])}function lu(e,t){return JSON.stringify([e,t.sessionId,t.cwd,t.completionOrder])}var uu={machines:new Set,projects:new Set,workspaces:new Set};function du(e){let t=pu(e.projectionFor(e.selectedMachineId));return{machines:mu(e.machineIds,e.projectionFor),projects:gu(e.projects,e.workspacesByProjectId,t),workspaces:hu(e.workspaces,t)}}function fu(e){return e!==void 0&&e.sessions.length>0}function pu(e){return e===void 0||e.sessions.length===0?vu:new Set(e.sessions.map(e=>e.cwd))}function mu(e,t){let n=new Set;for(let r of e)fu(t(r))&&n.add(r);return n}function hu(e,t){let n=new Set;for(let r of e)t.has(r.path)&&n.add(r.id);return n}function gu(e,t,n){let r=new Set;for(let i of e)(t[i.id]??[]).some(e=>n.has(e.path))&&r.add(i.id);return r}function _u(e,t){return yu(e.machines,t.machines)&&yu(e.projects,t.projects)&&yu(e.workspaces,t.workspaces)}var vu=new Set;function yu(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function bu(){return{selectedSessionKey:void 0,warningSetSignature:xu(void 0),warningCount:0,collapsed:!1,collapsedWarningSets:new Map}}function xu(e){let t=(e??[]).map(e=>JSON.stringify([e.severity,e.message,e.source,e.path,e.dismiss?.id])).sort();return JSON.stringify(t)}function Su(e,t,n){let r=xu(n),i=n?.length??0,a=n!==void 0,o=t===void 0?void 0:e.collapsedWarningSets.get(t),s=e.collapsedWarningSets;if(a&&t!==void 0&&o!==void 0&&o!==r){let n=new Map(e.collapsedWarningSets);n.delete(t),s=n}let c=a&&i>0&&o===r;return e.selectedSessionKey===t&&e.warningSetSignature===r&&e.warningCount===i&&e.collapsed===c&&e.collapsedWarningSets===s?e:{selectedSessionKey:t,warningSetSignature:r,warningCount:i,collapsed:c,collapsedWarningSets:s}}function Cu(e){if(e.collapsed||e.warningCount===0||e.selectedSessionKey===void 0)return e;let t=new Map(e.collapsedWarningSets);return t.set(e.selectedSessionKey,e.warningSetSignature),{...e,collapsed:!0,collapsedWarningSets:t}}function wu(e){if(!e.collapsed)return e;let t=new Map(e.collapsedWarningSets);return e.selectedSessionKey!==void 0&&t.delete(e.selectedSessionKey),{...e,collapsed:!1,collapsedWarningSets:t}}function Tu(e){return e.collapsed?wu(e):Cu(e)}var Eu=100;function Du(e,t){return e.filter(e=>Au(e,t))}var Ou={snapshot:e=>Tt.snapshot(e),dismiss:(e,t,n)=>Tt.dismiss(e,t,n)},ku=class{constructor(e={}){this.machines=new Map,this.api=e.api??Ou,this.onChange=e.onChange??(()=>void 0),this.onBackgroundError=e.onBackgroundError??(()=>void 0)}retainMachines(e){for(let[t,n]of this.machines){if(e.has(t))continue;let r=n.projection!==void 0;n.generation+=1,n.observers.clear(),n.pendingDismissedIds.clear(),n.dismissals.clear(),this.machines.delete(t),r&&this.onChange(t)}}projection(e){let t=this.machines.get(e),n=t?.projection;if(t!==void 0&&n!==void 0)return{machineId:e,status:t.status,daemonInstanceId:n.daemonInstanceId,revision:n.revision,notices:n.notices.filter(e=>!t.pendingDismissedIds.has(e.id))}}hasNotice(e,t){let n=this.projection(e);return n?.status===`fresh`&&n.notices.some(t)}applyEvent(e,t){let n=this.machine(e);this.recordObservedEvent(n,t);let r=n.projection;if(r===void 0)this.installProjection(n,ju(t.snapshot),`fresh`)&&this.onChange(e);else if(r.daemonInstanceId!==t.snapshot.daemonInstanceId){let t=n.status!==`stale`;n.status=`stale`,t&&this.onChange(e),n.refreshPromise===void 0?this.refresh(e):n.refreshQueued=!0}else t.snapshot.revision<=r.revision?n.status===`stale`&&(n.refreshPromise===void 0?this.refresh(e):n.refreshQueued=!0):this.installProjection(n,ju(t.snapshot),`fresh`)&&this.onChange(e)}refresh(e){let t=this.machine(e);if(t.refreshPromise!==void 0)return t.refreshQueued=!0,t.refreshPromise;let n=t.generation,r=this.runRefreshLoop(t,n);return t.refreshPromise=r,r.finally(()=>{if(!this.isCurrent(t,n)||t.refreshPromise!==r)return;t.refreshPromise=void 0;let e=t.refreshQueued;t.refreshQueued=!1,e&&this.refresh(t.machineId)}),r}async refreshAll(){await Promise.all([...this.machines.values()].map(async e=>{await this.refresh(e.machineId)}))}dismiss(e,t){let n=this.machines.get(e),r=n?.projection;if(n===void 0||r===void 0||r.notices.find(e=>e.id===t)===void 0||n.pendingDismissedIds.has(t))return Promise.resolve();let i=`${r.daemonInstanceId}:${t}`,a=n.dismissals.get(i);if(a!==void 0)return a;let o=n.generation,s=this.beginNetworkObservation(n,o);n.pendingDismissedIds.add(t),this.onChange(e);let c=this.runDismissal(n,o,s,r.daemonInstanceId,t);return n.dismissals.set(i,c),c.finally(()=>{n.dismissals.get(i)===c&&n.dismissals.delete(i)}),c}async runRefreshLoop(e,t){do{if(e.refreshQueued=!1,!this.isCurrent(e,t))return;this.markRefreshStarted(e)&&this.onChange(e.machineId);let n=this.beginNetworkObservation(e,t);try{let r=await this.api.snapshot(e.machineId);if(!this.isCurrent(e,t))return;this.applyNetworkSnapshot(e,r,n)&&(e.refreshQueued=!0)}catch(n){if(this.isCurrent(e,t)){let t=e.status!==`stale`;e.status=`stale`,t&&this.onChange(e.machineId),this.onBackgroundError(`snapshot`,e.machineId,n)}}finally{e.observers.delete(n)}}while(e.refreshQueued&&this.isCurrent(e,t))}async runDismissal(e,t,n,r,i){try{let a=await this.api.dismiss(e.machineId,r,i);if(!this.isCurrent(e,t))return;let o=this.applyNetworkSnapshot(e,a,n);e.pendingDismissedIds.delete(i),o&&this.refresh(e.machineId)}catch(n){this.isCurrent(e,t)&&this.onBackgroundError(`dismiss`,e.machineId,n)}finally{e.observers.delete(n),this.isCurrent(e,t)&&(e.pendingDismissedIds.delete(i),this.onChange(e.machineId))}}applyNetworkSnapshot(e,t,n){if(n.overflowed)return this.markStale(e);let r=t;for(let t of n.events){if(t.snapshot.daemonInstanceId!==r.daemonInstanceId)return this.markStale(e);t.snapshot.revision>r.revision&&(r=t.snapshot)}let i=e.projection;if(i!==void 0&&e.projectionVersion!==n.projectionVersion){if(i.daemonInstanceId!==r.daemonInstanceId)return this.markStale(e);i.revision>r.revision&&(r={daemonInstanceId:i.daemonInstanceId,revision:i.revision,notices:i.notices})}return this.installProjection(e,ju(r),`fresh`)&&this.onChange(e.machineId),!1}beginNetworkObservation(e,t){let n={generation:t,projectionVersion:e.projectionVersion,events:[],overflowed:!1};return e.observers.add(n),n}recordObservedEvent(e,t){for(let n of e.observers)n.generation!==e.generation||n.overflowed||(n.events.length>=Eu?(n.events.length=0,n.overflowed=!0):n.events.push(t))}markRefreshStarted(e){let t=e.projection===void 0?`loading`:`stale`;return e.status!==t&&(e.status=t,!0)}markStale(e){let t=e.status!==`stale`;return e.status=`stale`,t&&this.onChange(e.machineId),!0}installProjection(e,t,n){let r=!Mu(e.projection,t);return e.status===n&&!r?!1:(r&&(e.projection=t,e.projectionVersion+=1),e.status=n,!0)}machine(e){let t=this.machines.get(e);if(t!==void 0)return t;let n={machineId:e,status:`stale`,projection:void 0,projectionVersion:0,generation:0,observers:new Set,pendingDismissedIds:new Set,dismissals:new Map,refreshPromise:void 0,refreshQueued:!1};return this.machines.set(e,n),n}isCurrent(e,t){return this.machines.get(e.machineId)===e&&e.generation===t}};function Au(e,t){let n=e.scope;return n===void 0||(n.projectId===void 0||n.projectId===t.projectId)&&(n.workspaceId===void 0||n.workspaceId===t.workspaceId)&&(n.sessionId===void 0||n.sessionId===t.sessionId)}function ju(e){return{daemonInstanceId:e.daemonInstanceId,revision:e.revision,notices:e.notices.map(e=>({...e,...e.scope===void 0?{}:{scope:{...e.scope}},...e.context===void 0?{}:{context:{...e.context}}}))}}function Mu(e,t){return e?.daemonInstanceId!==t.daemonInstanceId||e.revision!==t.revision||e.notices.length!==t.notices.length?!1:e.notices.every((e,n)=>JSON.stringify(e)===JSON.stringify(t.notices[n]))}function Nu(e,t,n,r,i,a,o){Iu(t);let s=t?.mode===`patch`;Lu(e,s);let c=e.machineId===void 0?o??(s?n.machineId??`local`:i):Fu(e.machineId)??`local`,l=!s||c!==(n.machineId??`local`),u=Pu(e.projectId,l?void 0:n.projectId),d=l||u!==n.projectId,f=Pu(e.workspaceId,d?void 0:n.workspaceId),p=d||f!==n.workspaceId,m={machineId:c,projectId:u,workspaceId:f,sessionId:Pu(e.sessionId,p?void 0:n.sessionId),tool:Pu(e.tool,l?void 0:n.tool),view:Pu(e.view,s?n.view:void 0)},h=ra(p?{}:r);if(e.query!==void 0){if(!Ru(e.query))throw TypeError(`Navigation query must be an object`);if(m.tool===void 0||m.projectId===void 0||m.workspaceId===void 0)throw TypeError(`Navigation query requires tool, projectId, and workspaceId`);try{let t=s?a?.(m.tool,c):void 0,n=t?.sourceContributionId===void 0||t.sourceContributionId===t.contributionId?[]:[t.sourceContributionId];h=ia(h,t?.contributionId??m.tool,n,e.query)}catch(e){throw TypeError(e instanceof Error?e.message:String(e),{cause:e})}}return{route:m,contributionQuery:h}}function Pu(e,t){return e===void 0?t:Fu(e)}function Fu(e){return e===null||e===``?void 0:e}function Iu(e){if(e!==void 0){if(!Ru(e))throw TypeError(`Navigation options must be an object`);if(e.mode!==void 0&&e.mode!==`replace`&&e.mode!==`patch`)throw TypeError(`Navigation mode must be replace or patch`);if(e.history!==void 0&&e.history!==`push`&&e.history!==`replace`)throw TypeError(`Navigation history must be push or replace`)}}function Lu(e,t){if(!Ru(e))throw TypeError(`Navigation destination must be an object`);for(let n of[`machineId`,`projectId`,`workspaceId`,`sessionId`,`tool`]){let r=e[n];if(r!==void 0&&typeof r!=`string`&&!(t&&r===null))throw TypeError(`Navigation ${n} must be a string${t?` or null`:``}`)}let n=e.view;if(n!==void 0&&!(t&&n===null)&&n!==`navigation`&&n!==`chat`&&n!==`workspace`)throw TypeError(`Navigation view must be navigation, chat, or workspace`)}function Ru(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zu(e){return e?.removal!==void 0&&!e.isMain}function Bu(e){return e.removal?.confirmation}function Vu(e){return{...e===void 0?{}:{projectId:e},metadata:{[ar]:ir}}}function Hu(e){let t={};for(let n of e){let e=Gu(n);if(e===void 0)continue;let r=t[e];(r===void 0||n.createdAt.localeCompare(r.createdAt)>=0)&&(t[e]=n)}return t}function Uu(e){return Object.entries(e).filter(([,e])=>Ku(e)).map(([e])=>e)}function Wu(e,t){if(t===void 0)return!1;let n=e.workspaceDeletionRuns[t.id];return n!==void 0&&Ku(n)}function Gu(e){return e.metadata[or]}function Ku(e){return e.status===`queued`||e.status===`running`}function qu(){return[{id:`actions.show`,title:D(`client.actions.show.actions.a514ad`,`Show actions`),description:D(`client.actions.open.the.command.palette.36dd5f`,`Open the command palette`),shortcut:`mod+k`,group:D(`client.actions.general.835b70`,`General`),run:e=>{e.openActionPalette()}},{id:`prompt.focus`,title:D(`client.actions.focus.prompt.e171a7`,`Focus prompt`),description:D(`client.actions.move.keyboard.focus.to.the.message.editor.74d2ce`,`Move keyboard focus to the message editor`),shortcut:`mod+g c`,group:D(`client.actions.general.835b70`,`General`),run:e=>{e.focusPrompt()}},{id:`machine.add`,title:D(`client.actions.add.machine.e4ad1b`,`Add machine`),description:D(`client.actions.register.another.pi.web.runtime.reachable.from.this.gateway.d20488`,`Register another PI WEB runtime reachable from this gateway`),group:D(`bundled.info.machine.ece969`,`Machine`),run:e=>e.addMachine()},{id:`machine.refresh`,title:D(`client.actions.refresh.selected.machine.b85d96`,`Refresh selected machine`),description:D(`client.actions.check.whether.the.selected.pi.web.runtime.is.online.a856dd`,`Check whether the selected PI WEB runtime is online`),group:D(`bundled.info.machine.ece969`,`Machine`),run:e=>e.refreshSelectedMachine()},{id:`machine.open`,title:D(`client.actions.open.selected.machine.s.pi.web.15ce06`,`Open selected machine's PI WEB`),description:D(`client.actions.open.the.selected.remote.pi.web.directly.in.a.new.tab.a27228`,`Open the selected remote PI WEB directly in a new tab`),group:D(`bundled.info.machine.ece969`,`Machine`),enabled:e=>e.state.selectedMachine?.kind===`remote`&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:`machine.remove`,title:D(`client.actions.remove.selected.machine.ca967c`,`Remove selected machine`),description:D(`client.actions.remove.the.selected.remote.machine.from.this.gateway.51ce12`,`Remove the selected remote machine from this gateway`),group:D(`bundled.info.machine.ece969`,`Machine`),enabled:e=>e.state.selectedMachine?.kind===`remote`,run:e=>e.removeSelectedMachine()},{id:`project.add`,title:D(`client.actions.add.project.8964f5`,`Add project`),group:D(`client.actions.project.79f326`,`Project`),run:e=>e.addProject()},{id:`auth.login`,title:D(`client.actions.configure.provider.authentication.for.this.project.3e0f43`,`Configure provider authentication for this project`),description:D(`client.actions.run.login.for.this.project.bab71f`,`Run /login for this project`),group:D(`client.actions.general.835b70`,`General`),run:e=>e.configureAuth()},{id:`auth.logout`,title:D(`client.actions.remove.provider.authentication.for.this.project.d527aa`,`Remove provider authentication for this project`),description:D(`client.actions.remove.saved.credentials.for.this.project.1a3567`,`Remove saved credentials for this project`),group:D(`client.actions.general.835b70`,`General`),run:e=>e.logoutAuth()},{id:`mcp.login`,title:D(`ui.mcp.loginAction`,`MCP login`),description:D(`ui.mcp.loginDescription`,`Choose an MCP server for the selected session and sign in`),group:`MCP`,enabled:e=>Xu(e)&&e.piWebUnstable?.openMcpAuth!==void 0,disabledReason:e=>Xu(e)?void 0:D(`ui.mcp.selectSession`,`Select a session to authenticate MCP servers.`),run:e=>e.piWebUnstable?.openMcpAuth?.(`login`)},{id:`mcp.logout`,title:D(`ui.mcp.logoutAction`,`MCP logout`),description:D(`ui.mcp.logoutDescription`,`Remove local MCP credentials without disabling the server or revoking provider access`),group:`MCP`,enabled:e=>Xu(e)&&e.piWebUnstable?.openMcpAuth!==void 0,disabledReason:e=>Xu(e)?void 0:D(`ui.mcp.selectSession`,`Select a session to authenticate MCP servers.`),run:e=>e.piWebUnstable?.openMcpAuth?.(`logout`)},{id:`theme.select`,title:D(`client.actions.choose.theme.07a79a`,`Choose theme`),description:D(`client.actions.choose.a.pi.web.color.theme.fdc708`,`Choose a PI WEB color theme`),group:D(`client.actions.preferences.57907a`,`Preferences`),run:e=>{e.openThemePicker()}},{id:`settings.open`,title:D(`client.actions.open.settings.37aa6a`,`Open settings`),description:D(`client.actions.manage.pi.web.configuration.and.keyboard.shortcuts.cb1723`,`Manage PI WEB configuration and keyboard shortcuts`),shortcut:`mod+,`,group:D(`client.actions.preferences.57907a`,`Preferences`),run:e=>{e.piWebUnstable?.openSettings?.()}},{id:`app.reload-page`,title:D(`ui.appRefreshControl.reloadEntirePage`,`Reload entire page`),description:D(`client.actions.reload.the.pi.web.browser.page.cc27a2`,`Reload the PI WEB browser page`),group:D(`client.actions.general.835b70`,`General`),run:e=>{e.reloadPage()}},{id:`view.chat`,title:D(`client.actions.go.to.chat.6ba944`,`Go to chat`),shortcut:`mod+1`,group:D(`client.actions.navigation.e72622`,`Navigation`),run:e=>{e.focusPrompt()}},{id:`workspace.delete`,title:D(`client.actions.delete.workspace.1bca7e`,`Delete workspace`),description:D(`ui.main.c3e7f4dcb44f`,`Run the owning provider's workspace removal operation`),group:D(`bundled.workspace-tasks.workspace.379798`,`Workspace`),enabled:Yu,run:e=>e.deleteWorkspace()},{id:`session.start`,title:D(`client.actions.start.session.21780f`,`Start session`),shortcut:`mod+enter`,group:D(`ui.sessionSearchDialog.sessions`,`Sessions`),enabled:Ju,run:e=>e.startSession()},{id:`model.select`,title:D(`client.actions.choose.model.1afed6`,`Choose model`),description:D(`client.actions.choose.a.model.for.the.selected.session.60aa76`,`Choose a model for the selected session`),group:D(`ui.sessionSearchDialog.sessions`,`Sessions`),enabled:Xu,run:e=>e.openModelPicker()},{id:`thinking.select`,title:D(`client.actions.choose.thinking.level.77e3b8`,`Choose thinking level`),description:D(`client.actions.choose.a.thinking.level.for.the.selected.session.403bab`,`Choose a thinking level for the selected session`),group:D(`ui.sessionSearchDialog.sessions`,`Sessions`),enabled:Xu,run:e=>e.openThinkingLevelPicker()},{id:`session.archive`,title:D(`client.actions.archive.session.0a3885`,`Archive session`),description:D(`client.actions.archive.the.selected.session.6d7088`,`Archive the selected session`),group:D(`ui.sessionSearchDialog.sessions`,`Sessions`),enabled:Zu,run:e=>e.archiveSession()},{id:`session.reload`,title:D(`client.actions.reload.session.05361c`,`Reload session`),description:D(`client.actions.close.and.reopen.the.selected.session.from.its.file.use.reload.in.the..869a6b`,`Close and reopen the selected session from its file; use /reload in the prompt to reload Pi runtime resources`),group:D(`ui.sessionSearchDialog.sessions`,`Sessions`),enabled:$u,disabledReason:ed,run:e=>e.reloadSession()},{id:`session.delete`,title:D(`client.actions.delete.new.session.4c6f58`,`Delete new session`),description:D(`client.actions.delete.the.selected.temporary.new.session.480813`,`Delete the selected temporary new session`),group:D(`ui.sessionSearchDialog.sessions`,`Sessions`),enabled:Qu,run:e=>e.deleteCachedNewSession()},{id:`session.stop`,title:D(`client.actions.stop.active.work.95304d`,`Stop active work`),shortcut:`mod+.`,group:D(`ui.sessionSearchDialog.sessions`,`Sessions`),enabled:e=>e.state.selectedSession!==void 0&&rr(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function Ju(e){return e.state.selectedWorkspace!==void 0}function Yu(e){let t=e.state.selectedWorkspace;return zu(t)&&!Wu(e.state,t)}function Xu(e){let t=e.state.selectedSession;return t!==void 0&&t.archived!==!0}function Zu(e){return zs(e.state.selectedSession,e.state.status,td(e.state))}function Qu(e){return Bs(e.state.selectedSession,e.state.status,td(e.state))}function $u(e){return!zs(e.state.selectedSession,e.state.status,td(e.state))||ed(e)!==void 0?!1:!rr(e.state.status,e.state.activity)}function ed(e){if(zs(e.state.selectedSession,e.state.status,td(e.state))&&!rr(e.state.status,e.state.activity))return nd(e.state,D(`client.actions.reload.the.session.from.disk.45d1dc`,`reload the session from disk`))}function td(e){return Ls(e.machineRuntimes[M(e)])}function nd(e,t){if(e.machineRuntimes[M(e)]?.ok===!0)return;let n=e.selectedMachine?.name;return n!==void 0&&n!==``?D(`client.actions.update.and.restart.pi.web.on.to.aa2e7e`,`Update and restart Pi-Web on {value1} to {value2}.`,{value1:n,value2:t}):D(`client.actions.update.and.restart.pi.web.on.this.machine.to.da2f57`,`Update and restart Pi-Web on this machine to {value1}.`,{value1:t})}async function rd(e,t=id()){if(!t.isSecureContext)return t.fallbackWriteText(e);if(t.writeText!==void 0)try{return await t.writeText(e),!0}catch{return t.fallbackWriteText(e)}return t.fallbackWriteText(e)}function id(){let e=e=>sd(e),t=od();return t===void 0?{isSecureContext:ad(),fallbackWriteText:e}:{isSecureContext:ad(),writeText:t,fallbackWriteText:e}}function ad(){return typeof window<`u`&&window.isSecureContext}function od(){if(typeof navigator<`u`&&`clipboard`in navigator)return navigator.clipboard.writeText.bind(navigator.clipboard)}function sd(e){if(typeof document>`u`)return!1;let t=document.activeElement,n=document.getSelection(),r=n===null?[]:cd(n),i=document.createElement(`textarea`);i.value=e,i.readOnly=!0,i.setAttribute(`aria-hidden`,`true`),i.style.position=`fixed`,i.style.top=`0`,i.style.left=`-9999px`,i.style.width=`1px`,i.style.height=`1px`,i.style.padding=`0`,i.style.border=`0`,i.style.opacity=`0`,i.style.pointerEvents=`none`,document.body.append(i),i.focus(),i.select(),i.setSelectionRange(0,i.value.length);try{return document.execCommand(`copy`)}catch{return!1}finally{i.remove(),ld(n,r),ud(t)}}function cd(e){let t=[];for(let n=0;n<e.rangeCount;n+=1)t.push(e.getRangeAt(n));return t}function ld(e,t){if(e!==null)try{e.removeAllRanges();for(let n of t)e.addRange(n)}catch{}}function ud(e){if(typeof HTMLElement<`u`&&e instanceof HTMLElement)try{e.focus({preventScroll:!0})}catch{e.focus()}}function dd(e=rd){let t={visible:({message:e})=>e.role===`user`||e.role===`assistant`||e.role===`tool`&&e.isQuestion===!0,enabled:({session:e})=>!e.archived&&!e.pending&&!e.busy};return[{...t,id:`message.fork`,title:D(`ui.main.4e737b072caa`,`Clone session from this message`),ariaLabel:()=>D(`session.fork`,`Fork`),icon:E`<span class="msg-fork-icon" aria-hidden="true">⑂</span>`,run:async({history:e})=>{window.confirm(D(`ui.main.5b7be2382217`,`Are you sure you want to fork this session?`))&&await e.fork()}},{...t,id:`message.back`,title:D(`ui.main.c99fd586dc20`,`Go back to this message`),ariaLabel:()=>D(`ui.main.dedece75f412`,`Go back to this message`),icon:E`<svg aria-hidden="true" width="16" height="16" viewBox="-3 -3 30 30" fill="none" stroke="currentColor" stroke-width="0.85" stroke-linecap="round" stroke-linejoin="round"><path vector-effect="non-scaling-stroke" d="M4 5h11a6 6 0 0 1 0 12H4m5-5-5 5 5 5" /></svg>`,run:async({history:e})=>{window.confirm(D(`ui.main.92fa96db248a`,`Are you sure you want to go back to this message?`))&&await e.goBack()}},{target:`display`,id:`message.copy`,title:D(`ui.chatView.copyMessage`,`Copy message`),ariaLabel:({message:e})=>D(`ui.chatView.message`,`{copied} {role} message`,{copied:D(`bundled.updates.copy.63d90d`,`Copy`),role:e.role===`user`?D(`ui.chatView.user`,`User`):D(`ui.chatView.assistant`,`Assistant`)}),icon:E`<span aria-hidden="true">⧉</span>`,visible:({message:e})=>(e.role===`user`||e.role===`assistant`)&&e.text!==``,run:async({message:t})=>{if(!await e(t.text))throw Error(D(`ui.messageActions.clipboardFailed`,`Unable to copy message to the clipboard.`));return{title:D(`ui.toolExecutionView.copied`,`Copied`),ariaLabel:D(`ui.chatView.message`,`{copied} {role} message`,{copied:D(`ui.toolExecutionView.copied`,`Copied`),role:t.role===`user`?D(`ui.chatView.user`,`User`):D(`ui.chatView.assistant`,`Assistant`)}),icon:E`<span aria-hidden="true">✓</span>`}}}]}var fd={apiVersion:5,name:D(`client.index.pi.web.core.d120ca`,`PI WEB Core`),activate:()=>({contributions:{actions:qu(),messageActions:dd()}})},pd={apiVersion:5,name:D(`client.index.pi.web.themes.9c5a30`,`PI WEB Themes`),activate:()=>({contributions:{themes:[{id:`pi-web-dark`,name:D(`client.index.pi.web.dark.91b604`,`PI WEB Dark`),description:D(`client.index.pi.web.dark.color.scheme.9d56a4`,`Dark PI WEB palette.`),order:10,colorScheme:`dark`,stylesheets:[{id:`palette`,url:new URL(new URL(`pi-web-dark-D_KtbM95.css`,import.meta.url).href,``+import.meta.url).href}]},{id:`pi-web-light`,name:D(`client.index.pi.web.light.081df9`,`PI WEB Light`),description:D(`client.index.pi.web.light.color.scheme.b51736`,`Light PI WEB palette.`),order:20,colorScheme:`light`,stylesheets:[{id:`palette`,url:new URL(new URL(`pi-web-light-DSNLMIBI.css`,import.meta.url).href,``+import.meta.url).href}]},{id:`classic`,name:D(`client.index.pi.web.classic.4793fe`,`PI WEB Classic`),description:D(`client.index.original.pi.web.dark.color.scheme.80bcd3`,`The original PI WEB dark palette.`),order:30,colorScheme:`dark`,stylesheets:[{id:`palette`,url:new URL(new URL(`classic-CyM97Akm.css`,import.meta.url).href,``+import.meta.url).href}]}],themePairs:[{id:`pi-web`,name:`PI WEB`,description:D(`client.index.follow.the.system.light.dark.preference.with.pi.web.themes.33941c`,`Follow the system light/dark preference with PI WEB themes.`),order:10,light:`pi-web-light`,dark:`pi-web-dark`}]}})};function md(e,t){return Object.freeze({machineId:t,listProjects:async()=>(await e.projects(t)).map(({id:e,name:t,path:n})=>({id:e,name:t,path:n})),suggestDirectories:async n=>(await e.projectDirectories(n,t)).map(({path:e})=>({path:e}))})}var hd=Object.freeze({pluginId:`pi-web.host`,id:`catalog`,version:1,parse:gd});function gd(e){let t=Cd(e);if(t.version!==1)throw Od();let n=_d(t.projects),r=_d(t.workspaces),i=_d(t.sessions);return Object.freeze({version:1,projects:Object.freeze({list:async e=>Sd(await n.list(e),vd),get:async(e,t)=>{let r=Td(e),i=vd(await n.get(r,t));if(i.id!==r)throw Od();return i}}),workspaces:Object.freeze({list:async(e,t)=>{let n=Td(e);return Sd(await r.list(n,t),e=>yd(e,n))},get:async(e,t)=>{let n=xd(e),i=yd(await r.get(n,t),n.projectId);if(i.id!==n.workspaceId)throw Od();return i}}),sessions:Object.freeze({list:async(e,t)=>Sd(await i.list(xd(e),t),bd),get:async(e,t)=>{let n=xd(e,!0),r=bd(await i.get(n,t));if(r.id!==n.sessionId)throw Od();return r}})})}function _d(e){let t=Cd(e),n=t.list,r=t.get;if(typeof n!=`function`||typeof r!=`function`)throw Od();return{list:(...e)=>Promise.resolve(Reflect.apply(n,t,e)),get:(...e)=>Promise.resolve(Reflect.apply(r,t,e))}}function vd(e){let t=Cd(e);return Object.freeze({id:Td(t.id),name:Td(t.name),path:Td(t.path)})}function yd(e,t){let n=Cd(e);if(n.projectId!==t||typeof n.isMain!=`boolean`)throw Od();let r;if(n.provider!==void 0){let e=Cd(n.provider),t=Cd(e.capabilities);if(typeof t.remove!=`boolean`)throw Od();r=Object.freeze({pluginId:Td(e.pluginId),capabilities:Object.freeze({remove:t.remove}),...e.metadata===void 0?{}:{metadata:Ed(e.metadata)}})}let i=n.removal===void 0?void 0:Cd(n.removal);return Object.freeze({id:Td(n.id),projectId:t,path:Td(n.path),label:Td(n.label),isMain:n.isMain,...r===void 0?{}:{provider:r},...i===void 0?{}:{removal:Object.freeze({actionLabel:Td(i.actionLabel),confirmation:Td(i.confirmation)})}})}function bd(e){let t=Cd(e),n=t.runtime;if(typeof t.archived!=`boolean`||n!==`not-hosted`&&n!==`idle`&&n!==`busy`)throw Od();let r;if(t.metadata!==void 0&&(r=Object.freeze(Object.fromEntries(Object.entries(Cd(t.metadata)).map(([e,t])=>[e,Ed(t)])))),t.name!==void 0&&typeof t.name!=`string`)throw Od();return Object.freeze({id:Td(t.id),cwd:Td(t.cwd),archived:t.archived,runtime:n,...t.name===void 0?{}:{name:t.name},...r===void 0?{}:{metadata:r}})}function xd(e,t=!1){let n=Cd(e),r=t?[`projectId`,`workspaceId`,`sessionId`]:[`projectId`,`workspaceId`];if(Reflect.ownKeys(n).some(e=>typeof e!=`string`||!r.includes(e)))throw Od();return Object.freeze({projectId:Td(n.projectId),workspaceId:Td(n.workspaceId),...t?{sessionId:Td(n.sessionId)}:{}})}function Sd(e,t){if(!Array.isArray(e))throw Od();return Object.freeze(e.map(t))}function Cd(e){if(!wd(e))throw Od();return e}function wd(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Td(e){if(typeof e!=`string`||e.trim()===``)throw Od();return e}function Ed(e,t=new Set){let n=Cd(e);if(t.has(n))throw Od();t.add(n);let r=Object.freeze(Object.fromEntries(Object.entries(n).map(([e,n])=>[e,Dd(n,t)])));return t.delete(n),r}function Dd(e,t){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(Array.isArray(e)){if(t.has(e))throw Od();t.add(e);let n=Object.freeze(e.map(e=>Dd(e,t)));return t.delete(e),n}return Ed(e,t)}function Od(){return Error(`Invalid PI WEB host catalog capability v1 data`)}function kd(e,t,n=(e,t)=>Ee(e,e=>e,t)){if(e===``)throw Error(`Catalog machine id is required`);let r=`api/machines/${encodeURIComponent(e)}/plugin-catalog/projects`,i=e=>`${r}/${encodeURIComponent(e)}`,a=({projectId:e,workspaceId:t})=>`${i(e)}/workspaces/${encodeURIComponent(t)}`,o=async(e,r)=>{let i=t===void 0?r?.signal:r?.signal===void 0?t:AbortSignal.any([t,r.signal]);i?.throwIfAborted();let a=await n(e,{cache:`no-store`,...i===void 0?{}:{signal:i}});return i?.throwIfAborted(),a},s=hd.parse({version:1,projects:{list:e=>o(r,e),get:(e,t)=>o(i(e),t)},workspaces:{list:(e,t)=>o(`${i(e)}/workspaces`,t),get:(e,t)=>o(a(e),t)},sessions:{list:(e,t)=>o(`${a(e)}/sessions`,t),get:(e,t)=>o(`${a(e)}/sessions/${encodeURIComponent(e.sessionId)}`,t)}});return Object.freeze({...s,machineId:e})}function Ad(e,t,n,r=vt,i=lt){if(e.pairedRequestVersion!==1&&e.pairedChannelVersion!==1)return;let a=Md(e,t,n);if(a!==void 0){if(e.pairedRequestVersion===1&&e.pairedChannelVersion===1)return{request:(e,t,n)=>r(a,e,t,n),openChannel:(e,t,n)=>i(a,e,t,n)};if(e.pairedRequestVersion===1)return{request:(e,t,n)=>r(a,e,t,n)};if(e.pairedChannelVersion===1)return{openChannel:(e,t,n)=>i(a,e,t,n)}}}function jd(e,t,n,r=vt,i=lt){if(e.backendRevision===void 0||e.pairedRequestVersion!==1&&e.pairedChannelVersion!==1)return;let a=e.backendRevision,o=e=>n===void 0?e:e===void 0?n:AbortSignal.any([n,e]);return Object.freeze({machineId:t,forScope(s){if(n?.throwIfAborted(),s.kind!==`machine`&&(typeof s.projectId!=`string`||s.projectId===``))throw Error(`Project id is required`);if(s.kind===`workspace`&&(typeof s.workspaceId!=`string`||s.workspaceId===``))throw Error(`Workspace id is required`);let c=Object.freeze({pluginId:e.sourcePluginId,backendRevision:a,machineId:t,scope:s.kind,...s.kind===`machine`?{}:{projectId:s.projectId},...s.kind===`workspace`?{workspaceId:s.workspaceId}:{}}),l=(e,t,n)=>{let i=o(n?.signal);return i?.throwIfAborted(),r(c,e,t,{...i===void 0?{}:{signal:i}})},u=(e,t,n)=>{let r=o(n.signal);return r?.throwIfAborted(),i(c,e,t,{...n,...r===void 0?{}:{signal:r}})};return e.pairedRequestVersion===1?Object.freeze({request:l,...e.pairedChannelVersion===1?{openChannel:u}:{}}):Object.freeze({openChannel:u})}})}function Md(e,t,n){let r=e.backendRevision;if(r!==void 0)return{pluginId:e.sourcePluginId,backendRevision:r,machineId:n,projectId:t.projectId,workspaceId:t.id}}var Nd=class{constructor(e){this.readSelection=e,this.subscribers=new Set,this.lastSelection=JSON.stringify(e())}notifyChanged(){let e=this.readSelection(),t=JSON.stringify(e);if(t!==this.lastSelection){this.lastSelection=t;for(let t of[...this.subscribers])this.subscribers.has(t)&&t(e)}}forPlugin(e,t){return Object.freeze({getSnapshot:()=>structuredClone(this.readSelection()),subscribe:n=>{if(t.aborted)return()=>void 0;let r=t=>{console.warn(`PI WEB plugin ${e} selection subscriber failed`,t)},i=e=>{try{let t=n(structuredClone(e));t!==void 0&&Promise.resolve(t).catch(r)}catch(e){r(e)}},a=()=>{this.subscribers.delete(i),t.removeEventListener(`abort`,a)};return this.subscribers.add(i),t.addEventListener(`abort`,a,{once:!0}),a}})}};function Pd(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n?.renderer.renderMode===`automatic`)return n}return e[0]}function Fd(e,t){let n=t.language?.trim().split(/\s/u)[0]?.toLowerCase(),r=t.filePath?.split(/[\\/]/u).at(-1)?.toLowerCase(),i=(e.languages?.length??0)+(e.fileExtensions?.length??0)>0,a=n!==void 0&&e.languages?.includes(n)===!0||r!==void 0&&e.fileExtensions?.some(e=>r.endsWith(`.${e}`))===!0;if(i&&!a)return!1;try{if(e.supports===void 0)return a;let n=e.supports(Object.freeze({...t}));if(typeof n==`object`&&n&&`then`in n&&typeof n.then==`function`&&Promise.resolve(n).catch(()=>{console.warn(`Content renderer eligibility failed`,{rendererId:e.id,category:`eligibility`})}),typeof n!=`boolean`)throw Error(`Content renderer supports must return a boolean synchronously`);return n}catch{return console.warn(`Content renderer eligibility failed`,{rendererId:e.id,category:`eligibility`}),!1}}function Id(e){if(typeof e.render!=`function`)throw Error(`Content renderer must have a synchronous render callback`);let t=e.renderMode;if(t!==void 0&&t!==`manual`&&t!==`automatic`)throw Error(`Content renderer renderMode must be manual or automatic`);if(e.supports!==void 0&&typeof e.supports!=`function`)throw Error(`Content renderer supports must be a callback`);if(e.title!==void 0&&(typeof e.title!=`string`||e.title.trim()===``))throw Error(`Content renderer title must be a non-empty string`);return Object.freeze({id:e.id,...Ld(e,e.supports!==void 0),...e.title===void 0?{}:{title:e.title},...e.supports===void 0?{}:{supports:e.supports.bind(e)},renderMode:e.renderMode??`manual`,render:e.render.bind(e)})}function Ld(e,t=!1){let n=e=>{if(e===void 0)return Object.freeze([]);if(!Array.isArray(e)||e.some(e=>typeof e!=`string`||!/^[a-z0-9][a-z0-9_+.-]*$/iu.test(e)))throw Error(`Content renderer selectors must be non-empty language names or extensions without a leading dot`);return Object.freeze([...new Set(e.map(e=>e.toLowerCase()))])},r=n(e.languages),i=n(e.fileExtensions);if(!t&&r.length+i.length===0)throw Error(`Content renderer must declare a selector`);return Object.freeze({languages:r,fileExtensions:i})}var Rd={pluginId:`pi-web`,id:`syntax-highlighting`,version:1,parse(e){if(!zd(e))throw Error(`Syntax highlighting capability v1 is unavailable`);return e}};function zd(e){return typeof e==`object`&&!!e&&`highlight`in e&&typeof e.highlight==`function`&&`supports`in e&&typeof e.supports==`function`}var Bd=new Set([`keyword`,`string`,`number`,`comment`,`type`,`function`,`variable`,`operator`,`punctuation`,`property`,`literal`,`meta`]);function Vd(e){return typeof e==`string`&&Bd.has(e)}function Hd(e,t){if(!Array.isArray(e))throw Error(`Syntax highlighter must return an array of tokens`);let n=0;return Object.freeze(Array.from(e,e=>{if(typeof e!=`object`||!e||!(`from`in e)||!(`to`in e)||!(`kind`in e)||typeof e.from!=`number`||typeof e.to!=`number`||!Number.isInteger(e.from)||!Number.isInteger(e.to)||e.from<n||e.to<=e.from||e.to>t.length||!Vd(e.kind))throw Error(`Invalid syntax highlight token: expected sorted, nonoverlapping UTF-16 bounds and a standard kind`);return n=e.to,Object.freeze({from:e.from,to:e.to,kind:e.kind})}))}function Ud(e){if(typeof e.highlight!=`function`)throw Error(`Syntax highlighter must have a highlight callback`);return Object.freeze({id:e.id,...Ld(e),highlight:e.highlight.bind(e)})}async function Wd(e,t,n){n.throwIfAborted();let r,i=new Promise((e,t)=>{r=()=>{t(n.reason)},n.addEventListener(`abort`,r,{once:!0})});try{let r=Promise.resolve().then(()=>(n.throwIfAborted(),e.highlight({text:t,signal:n}))),a=await Promise.race([r,i]);return n.throwIfAborted(),Hd(a,t)}catch(t){throw n.aborted?n.reason:Error(`Syntax highlighter ${e.id} failed`,{cause:t})}finally{r!==void 0&&n.removeEventListener(`abort`,r)}}function Gd(e){return Object.freeze({supports:t=>e(t)!==void 0,async highlight(t){if(t.signal.throwIfAborted(),!(t.text.length>1e5))return e(t)?.highlight({text:t.text,signal:t.signal})}})}var Kd=Symbol.for(``),qd=e=>{if(e?.r===Kd)return e?._$litStatic$},Jd=e=>({_$litStatic$:e,r:Kd}),Yd=new Map,Xd=(e=>(t,...n)=>{let r=n.length,i,a,o=[],s=[],c,l=0,u=!1;for(;l<r;){for(c=t[l];l<r&&(a=n[l],(i=qd(a))!==void 0);)c+=i+t[++l],u=!0;l!==r&&s.push(a),o.push(c),l++}if(l===r&&o.push(t[r]),u){let e=o.join(`$$lit$$`);(t=Yd.get(e))===void 0&&(o.raw=o,Yd.set(e,t=o)),n=s}return e(t,...n)})(E),Zd=(e,t)=>{let n=e._$AN;if(n===void 0)return!1;for(let e of n)e._$AO?.(t,!1),Zd(e,t);return!0},Qd=e=>{let t,n;do{if((t=e._$AM)===void 0)break;n=t._$AN,n.delete(e),e=t}while(n?.size===0)},$d=e=>{for(let t;t=e._$AM;e=t){let n=t._$AN;if(n===void 0)t._$AN=n=new Set;else if(n.has(e))break;n.add(e),nf(t)}};function ef(e){this._$AN===void 0?this._$AM=e:(Qd(this),this._$AM=e,$d(this))}function tf(e,t=!1,n=0){let r=this._$AH,i=this._$AN;if(i!==void 0&&i.size!==0){if(t){if(Array.isArray(r))for(let e=n;e<r.length;e++)Zd(r[e],!1),Qd(r[e]);else r!=null&&(Zd(r,!1),Qd(r))}else Zd(this,e)}}var nf=e=>{e.type==Ne.CHILD&&(e._$AP??=tf,e._$AQ??=ef)},rf=class extends Qe{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,n){super._$AT(e,t,n),$d(this),this.isConnected=e._$AU}_$AO(e,t=!0){e!==this.isConnected&&(this.isConnected=e,e?this.reconnected?.():this.disconnected?.()),t&&(Zd(this,e),Qd(this))}setValue(e){if(o(this._$Ct))this._$Ct._$AI(e,this);else{let t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}},af=new WeakMap,of=_t(class extends rf{render(e){return k}update(e,[t]){let n=t!==this.G;return n&&this.rt(void 0),(n||this.lt!==this.ct)&&(this.G=t,this.ht=e.options?.host,this.rt(this.ct=e.element)),k}rt(e){if(this.G!==void 0){if(this.isConnected||(e=void 0),typeof this.G==`function`){let t=this.ht??globalThis,n=af.get(t);n===void 0&&(n=new WeakMap,af.set(t,n)),n.get(this.G)!==void 0&&this.G.call(this.ht,void 0),n.set(this.G,e),e!==void 0&&this.G.call(this.ht,e)}else this.G.value=e}}get lt(){return typeof this.G==`function`?af.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}}),sf=class extends Qe{constructor(e){if(super(e),this.it=k,e.type!==Ne.CHILD)throw Error(this.constructor.directiveName+`() can only be used in child bindings`)}render(e){if(e===k||e==null)return this._t=void 0,this.it=e;if(e===It)return e;if(typeof e!=`string`)throw Error(this.constructor.directiveName+`() called with a non-string value`);if(e===this.it)return this._t;this.it=e;let t=[e];return t.raw=t,this._t={_$litType$:this.constructor.resultType,strings:t,values:[]}}};sf.directiveName=`unsafeHTML`,sf.resultType=1;var cf=_t(sf);function lf(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var uf=lf();function df(e){uf=e}var ff={exec:()=>null};function pf(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function L(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(R.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var mf=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),R={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,leadingSpaceTab:/^[ \t]+/,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,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,numericCharacterReferenceOrAmpersand:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:pf(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:pf(e=>RegExp(`^ {0,${e}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:pf(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:pf(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:pf(e=>RegExp(`^ {0,${e}}(?:</?(?:${kf})(?: +|$|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`,`i`)),blockquoteBeginRegex:pf(e=>RegExp(`^ {0,${e}}>`))},hf=/^(?:[ \t]*(?:\n|$))+/,gf=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,_f=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,vf=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,yf=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,bf=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,xf=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Sf=L(xf).replace(/bull/g,bf).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}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),Cf=L(xf).replace(/bull/g,bf).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}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),wf=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Tf=/^[^\n]+/,Ef=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Df=L(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,Ef).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Of=L(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,bf).getRegex(),kf=`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`,Af=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,jf=L(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!(?:script|pre|style|textarea)(?![a-z0-9-]))([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</[a-z][a-z0-9-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,Af).replace(`tag`,kf).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Mf=e=>L(wf).replace(`hr`,vf).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,e).replace(`html`,` {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`).replace(`tag`,kf).getRegex(),Nf=Mf(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Pf=Mf(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Ff={blockquote:L(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,Pf).getRegex(),code:gf,def:Df,fences:_f,heading:yf,hr:vf,html:jf,lheading:Sf,list:Of,newline:hf,paragraph:Nf,table:ff,text:Tf},If=L(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,vf).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,` {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`).replace(`tag`,kf).getRegex(),Lf={...Ff,lheading:Cf,table:If,paragraph:L(wf).replace(`hr`,vf).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,If).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,` {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`).replace(`tag`,kf).getRegex()},Rf={...Ff,html:L(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,Af).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:ff,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:L(wf).replace(`hr`,vf).replace(`heading`,` *#{1,6} *[^
|
|
30
30
|
]`).replace(`lheading`,Sf).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},zf=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Bf=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Vf=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,Hf=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Uf=/[\p{P}\p{S}]/u,Wf=/[\s\p{P}\p{S}]/u,Gf=/[^\s\p{P}\p{S}]/u,Kf=L(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,Wf).getRegex(),qf=/[\p{Pi}\p{Ps}"']/u,Jf=/(?!~)[\p{P}\p{S}]/u,Yf=/(?!~)[\s\p{P}\p{S}]/u,Xf=/(?:[^\s\p{P}\p{S}]|~)/u,Zf=L(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,mf?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),Qf=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,$f=L(Qf,`u`).replace(/punct/g,Uf).getRegex(),ep=L(Qf,`u`).replace(/punct/g,Jf).getRegex(),tp=L(/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,`u`).replace(/openQuote/g,qf).replace(/punct/g,Uf).getRegex(),np=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,rp=L(np,`gu`).replace(/notPunctSpace/g,Gf).replace(/punctSpace/g,Wf).replace(/punct/g,Uf).getRegex(),ip=L(np,`gu`).replace(/notPunctSpace/g,Xf).replace(/punctSpace/g,Yf).replace(/punct/g,Jf).getRegex(),ap=L(`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Gf).replace(/punctSpace/g,Wf).replace(/punct/g,Uf).getRegex(),op=L(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,Gf).replace(/punctSpace/g,Wf).replace(/punct/g,Uf).getRegex(),sp=L(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Gf).replace(/punctSpace/g,Wf).replace(/punct/g,Uf).getRegex(),cp=L(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,Uf).getRegex(),lp=L(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Gf).replace(/punctSpace/g,Wf).replace(/punct/g,Uf).getRegex(),up=L(/\\(punct)/,`gu`).replace(/punct/g,Uf).getRegex(),dp=L(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,`gu`).replace(/punct/g,Uf).getRegex(),fp=L(/^<(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(),pp=L(Af).replace(`(?:-->|$)`,`-->`).getRegex(),mp=L(`^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\s*>|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,pp).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),hp=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,gp=L(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace(`brackets`,hp).getRegex(),_p=L(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace(`label`,gp).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),vp=L(/^!?\[(label)\]\[(ref)\]/).replace(`label`,gp).replace(`ref`,Ef).getRegex(),yp=L(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,Ef).getRegex(),bp=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,xp=L(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace(`brackets`,hp).getRegex(),Sp=L(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,L(/^!?\[(label)\]\[(ref)\]/).replace(`label`,xp).replace(`ref`,bp).getRegex()).replace(`nolink`,L(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,bp).getRegex()).getRegex(),Cp=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,wp=L(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),Tp={_backpedal:ff,anyPunctuation:up,anyPunctuationOutsideCode:dp,autolink:fp,blockSkip:Zf,br:Vf,code:Bf,del:ff,delLDelim:ff,delRDelim:ff,emStrongLDelim:$f,emStrongRDelimAst:rp,emStrongRDelimUnd:op,escape:zf,link:_p,nolink:yp,punctuation:Kf,reflink:vp,reflinkSearch:Sp,tag:mp,text:Hf,url:ff},Ep={...Tp,emStrongLDelim:tp,emStrongRDelimAst:ap,emStrongRDelimUnd:sp,link:L(/^!?\[(label)\]\((.*?)\)/).replace(`label`,gp).getRegex(),reflink:L(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,gp).getRegex()},Dp={...Tp,emStrongRDelimAst:ip,emStrongLDelim:ep,delLDelim:cp,delRDelim:lp,url:L(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`emailProtocol`,wp).replace(`protocol`,Cp).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:L(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9](?=emailProtocol)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))))/).replace(`protocol`,Cp).replace(/emailProtocol/g,/(?:mailto|xmpp):/).getRegex()},Op={...Dp,br:L(Vf).replace(`{2,}`,`*`).getRegex(),text:L(Dp.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},kp={normal:Ff,gfm:Lf,pedantic:Rf},Ap={normal:Tp,gfm:Dp,breaks:Op,pedantic:Ep},jp={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},Mp=e=>jp[e];function Np(e,t){if(t){if(R.escapeTest.test(e))return e.replace(R.escapeReplace,Mp)}else if(R.escapeTestNoEncode.test(e))return e.replace(R.escapeReplaceNoEncode,Mp);return e}function Pp(e){return R.numericCharacterReference.test(e)?e.replace(R.numericCharacterReferenceOrAmpersand,(e,t,n)=>{if(t===void 0&&n===void 0)return`&`;let r=t===void 0?Number.parseInt(n,16):Number.parseInt(t,10);return r===0||r>1114111||r>=55296&&r<=57343?`�`:r===38?`&`:String.fromCodePoint(r)}):e}function Fp(e){try{e=encodeURI(e).replace(R.percentDecode,`%`)}catch{return null}return e}function Ip(e,t){let n=e.replace(R.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(R.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t){if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``)}for(;r<n.length;r++)n[r]=n[r].trim().replace(R.slashPipe,`|`);return n}function Lp(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function Rp(e){let t=e.split(`
|
|
@@ -133,11 +133,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
133
133
|
.renderingRevision=${t?.(e)} .codeBlocks=${s} .intentKey=${o} .externalControls=${r} .text=${e.text} .machineId=${e.machineId} .language=${e.language} .filePath=${e.filePath} .choices=${n} .rendererId=${i} .allowManualPreview=${a}
|
|
134
134
|
></pi-web-content-renderer>`,i=(e,t,i)=>{let a=document.createElement(`template`);a.innerHTML=e.toSafeHtml(e.text);let o=[];z.walkTokens(z.lexer(e.text,{gfm:!0,breaks:!0}),e=>{gm(e)&&o.push(e)});let s=new Map,c=`pre, .plain-code-block`;a.content.querySelectorAll(c).forEach((a,c)=>{let l=o[c];if(l===void 0||a.tagName===`PRE`&&a.querySelector(`code`)===null)return;let u=l.text,d=_m(l)?n({machineId:e.machineId,text:u,...l.lang===void 0?{}:{language:l.lang},...e.truncated===void 0?{}:{truncated:e.truncated}}):[],f=t===void 0?void 0:JSON.stringify([e.machineId,t,c]);if(f!==void 0&&rm.read(f,u,d.map(({id:e})=>e)),d.length>0){let t=a.parentElement?.classList.contains(`code-block-wrapper`)===!0?a.parentElement:a;s.set(t,r({machineId:e.machineId,text:u,...l.lang===void 0?{}:{language:l.lang}},d,!1,void 0,e.allowManualPreview,f,i))}});let l=e=>{let t=s.get(e);if(t!==void 0)return t;if(!(e instanceof Element))return e.textContent;if(!e.querySelector(c))return cf(e.outerHTML);let n=Jd(e.tagName.toLowerCase()),r=[...e.attributes].map(({name:e,value:t})=>[e,t]);return Xd`<${n} ${of(e=>{if(e!==void 0){for(let t of[...e.attributes])e.removeAttribute(t.name);for(let[t,n]of r)e.setAttribute(t,n)}})}>${[...e.childNodes].map(l)}</${n}>`};return E`${[...a.content.childNodes].map(l)}`};return{capability:Object.freeze({listRenderers(e){return n(e).map(({id:e,label:t,renderer:n})=>({id:e,label:t,renderMode:n.renderMode??`manual`,...n.title===void 0?{}:{title:n.title}}))},renderText(e){let t=n(e),i=e.controls===`external`;return t.length===0?void 0:r(e,t,i,i?e.rendererId:void 0,e.allowManualPreview)},renderMarkdown:e=>E`<pi-web-content-rendering-boundary
|
|
135
135
|
style="display: contents" .identity=${e.machineId} .source=${e.text} .renderContent=${()=>i(e)}
|
|
136
|
-
></pi-web-content-rendering-boundary>`}),renderMarkdown:i}}var bm=/^[a-z][a-z0-9.:-]*$/u,xm=/^[a-z][a-z0-9.-]*$/u,Sm=/^[a-z][a-z0-9.-]*$/u,Cm=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u,wm=new WeakMap,Tm=new WeakMap,Em=new WeakMap,Dm=new WeakMap,Om=new WeakMap,km=1e4,Am=class{promptChipMethods(e,t){let n=()=>{if(t===void 0)throw Error(`Select a ready, non-archived conversation to stage prompt chips`);if(!this.promptChipOwnerAvailable(e,t.machineId))throw Error(`Prompt chips unavailable for plugin ${e} on machine ${t.machineId}`);return t};return{setChip:t=>{this.promptChips.set(e,n(),t)},removeChip:t=>{this.promptChips.remove(e,n(),t)}}}promptChipOwnerAvailable(e,t){let n=this.declarationsById.get(e);return this.hasPlugin(e)&&n!==void 0&&this.isContributionActive(e,n.machineId,t,n.sourcePluginId)}get contentRendererVersion(){return this.contentRendererRevision}compareDiscoveryOrder(e,t){let n=[...this.declarationsById.keys()];return n.indexOf(e.pluginId)-n.indexOf(t.pluginId)}syntaxHighlightingRevision(e){let t=this.syntaxHighlighters.filter(t=>this.isContributionActive(t.pluginId,t.machineId,e,t.sourcePluginId)).sort((e,t)=>this.compareDiscoveryOrder(e,t)),n=this.syntaxHighlightingViews.get(e);return n?.length===t.length&&t.every((e,t)=>e===n[t])?n:(this.syntaxHighlightingViews.set(e,t),t)}getChatContentRendering(e){let t=this.activeContentRendererChoices(e),n=this.syntaxHighlightingRevision(e),r=this.chatContentRenderingViews.get(e);if(r?.grammars===n&&r.choices.length===t.length&&t.every((e,t)=>e.renderer===r.choices[t]?.renderer))return r.rendering;let i=ym(n=>n.machineId===e?t.filter(({renderer:e})=>Fd(e,n)):[],()=>n);return this.chatContentRenderingViews.set(e,{choices:t,grammars:n,rendering:i}),i}matchContentRenderers(e){return this.activeContentRendererChoices(e.machineId).filter(({renderer:t})=>Fd(t,e))}activeContentRendererChoices(e){return this.contentRenderers.filter(t=>this.isContributionActive(t.pluginId,t.machineId,e,t.sourcePluginId)).sort((e,t)=>this.compareDiscoveryOrder(e,t)).map(e=>({id:e.id,label:e.label,renderer:e}))}getMessageActions(e){let t=this.messageActions.filter(t=>this.isContributionActive(t.binding.registrationPluginId,t.machineId,e,t.binding.sourcePluginId));return(t.length!==this.messageActionView.length||t.some((e,t)=>e!==this.messageActionView[t]))&&(this.messageActionView=t),this.messageActionView}async runMessageAction(e,t,n){let r=En(this.getMessageActions(t.machine.id).filter(t=>t.id===e),t)[0];if(r?.enabled===!0&&r.action.target!==`display`)return r.action.run(n(r.action.binding))}async runDisplayedMessageAction(e,t,n){let r=Dn(this.getMessageActions(t.machine.id).filter(t=>t.id===e),t)[0];if(r?.enabled===!0&&r.action.target===`display`)return r.action.run(n(r.action.binding))}constructor(e={}){this.options=e,this.contentRenderers=[],this.syntaxHighlighters=[],this.syntaxHighlighting=Gd(e=>this.syntaxHighlightingRevision(e.machineId).filter(t=>Fd(t,{...e,text:``})).at(-1)),this.chatContentRendering=ym(e=>this.matchContentRenderers(e),e=>this.syntaxHighlightingRevision(e.machineId)),this.contentRendererRevision=0,this.syntaxHighlightingViews=new Map,this.chatContentRenderingViews=new Map,this.contentRendering=vm(e=>this.matchContentRenderers(e),e=>this.syntaxHighlightingRevision(e.machineId)),this.messageActions=[],this.messageActionView=[],this.actions=[],this.workspacePanels=[],this.applicationPanels=[],this.workspaceLabels=[],this.sessionLabels=[],this.stylesheets=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.warnedLegacyPluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.gatewayPresentationPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set,this.declarationsById=new Map,this.activeCapabilitiesByRegistration=new Map,this.hostCapabilitySnapshotsByRegistration=new Map,this.hostCapabilitiesByKey=new Map,this.activatingLifetimes=new Set,this.activePlugins=[],this.stagedPlugins=[],this.registrationTail=Promise.resolve(),this.shuttingDown=!1,this.uiPresentation=new u((t,n)=>{e.onUiPresentationError===void 0?console.warn(`UI presentation failed for ${t}`,n):e.onUiPresentationError(t,n)}),this.promptChips=new ja(e.onPromptChipsChanged),this.selection=new Nd(e.getSelection??(()=>({}))),this.lifecycleTimeoutMs=yh(e.lifecycleTimeoutMs,km,`lifecycleTimeoutMs`);for(let t of eh([{capability:mm,value:this.contentRendering},{capability:Rd,value:this.syntaxHighlighting},{capability:se,value:v},{capability:le,value:c},...e.hostCapabilities??[]],void 0,`Browser host capability provisions`)){let e=ah(t);if(this.hostCapabilitiesByKey.has(e.key))throw new H(`Browser capability ${V(e.capability)} is provided more than once by the host`);this.hostCapabilitiesByKey.set(e.key,e)}}notifySelectionChanged(){this.selection.notifyChanged()}failUiPresentationStylesheetError(e){let t=!1;for(let n of xh(e)){let e=this.stylesheets.find(e=>e.id===n.contributionId&&e.url===n.url)?.pluginId??this.themes.find(e=>e.stylesheets?.some(e=>e.id===n.contributionId&&e.url===n.url)===!0)?.pluginId;e!==void 0&&this.gatewayPresentationPluginIds.has(e)&&(t=this.uiPresentation.failPlugin(e,n)||t)}return t}async register(e){let t=(await this.registerBatch([e])).failures.find(({declaration:t})=>t.id===e.id);if(t!==void 0)throw t.error}registerBatch(e,t={}){let n=[...e],r=[...t.declarations??e.map(Gm)],i=[...t.failures??[]],a=[...t.requiredCapabilities??[]],o=this.registrationTail.then(async()=>this.performRegistrationBatch(n,r,i,a));return this.registrationTail=o.then(()=>void 0,()=>void 0),o}beginShutdown(){if(this.shuttingDown)return;this.shuttingDown=!0,this.promptChips.clear();let e=new DOMException(`Browser plugin host is shutting down`,`AbortError`);for(let t of this.activatingLifetimes)dh(t,e);for(let t of[...this.activePlugins,...this.stagedPlugins])dh(t.lifetimeController,e)}dispose(){return this.disposePromise===void 0&&(this.beginShutdown(),this.disposePromise=this.performDispose()),this.disposePromise}async performDispose(){await this.registrationTail;let e=[...this.activePlugins,...this.stagedPlugins].reverse();this.activePlugins=[],this.stagedPlugins=[],this.activeCapabilitiesByRegistration.clear(),this.hostCapabilitySnapshotsByRegistration.clear(),this.pluginIds.clear(),this.actions.splice(0),(this.contentRenderers.length>0||this.syntaxHighlighters.length>0)&&(this.contentRendererRevision+=1),this.messageActions.splice(0),this.contentRenderers.splice(0),this.syntaxHighlighters.splice(0),this.syntaxHighlightingViews.clear(),this.chatContentRenderingViews.clear(),this.workspacePanels.splice(0),this.applicationPanels.splice(0),this.workspaceLabels.splice(0),this.sessionLabels.splice(0),this.stylesheets.splice(0),this.uiPresentation.clear(),this.gatewayPresentationPluginIds.clear(),this.themes.splice(0),this.themePairs.splice(0),this.contributionIds.clear();for(let t of e){let e=t.activation.dispose?.bind(t.activation);if(e!==void 0)try{await uh(t.registration.id,`dispose`,this.lifecycleTimeoutMs,void 0,t=>e(t))}catch(e){console.warn(`Failed to dispose PI WEB plugin ${t.registration.id}`,e)}}}resolveCapability(e,t){let n=nh(t,`Browser host capability request`),r=ch(n),i=this.activeCapabilitiesByRegistration.get(e)?.get(r);if(i===void 0)throw Error(`Browser capability ${V(n)} is not active for ${e}`);let a=this.hostCapabilitySnapshotsByRegistration.get(e)?.get(r);return a!==void 0&&oh(a,t)?a.value:sh(n,i.value,`Browser capability ${V(n)} for ${e}`)}async performRegistrationBatch(e,t,n,r){if(this.shuttingDown)throw Error(`Browser plugin registry is shutting down`);let i=[...n],a=new Set,o=new Set;for(let e of t)try{let t=this.normalizeDeclaration(e);if(o.has(t.id))throw Error(`Duplicate plugin id: ${t.id}`);o.add(t.id),this.recordDeclaration(t)&&a.add(t.id)}catch(t){i.push(Km(e,`validate`,t))}let s=new Map,c=new Set;for(let t of[...e].sort((e,t)=>e.id.localeCompare(t.id))){let e=Gm(t);if(!o.has(t.id))i.push(Km(e,`validate`,Error(`Plugin ${t.id} has no registration declaration`)));else if(a.has(t.id)){if(this.shutdownHasStarted())i.push(Km(e,`activate`,fh()));else try{if(c.has(t.id)||this.pluginIds.has(t.id))throw Error(`Duplicate plugin id: ${t.id}`);c.add(t.id);let n=this.declarationsById.get(t.id);if(n===void 0)throw Error(`Plugin ${t.id} has no valid registration declaration`);if(!Jm(n,this.normalizeDeclaration(e)))throw Error(`Plugin registration topology does not match its declaration: ${t.id}`);let r=await this.stageRegistration(t,n);s.set(t.id,r),this.stagedPlugins.push(r)}catch(t){i.push(Km(e,gh(t,`validate`),t))}}}let l=new Map(s);for(;l.size>0;){let e=!1,t=[...l.values()].sort((e,t)=>e.registration.id.localeCompare(t.registration.id));for(let n of t){let t=this.dependencyFailure(n,l,s);if(t!==void 0){l.delete(n.registration.id),i.push(await this.failBeforeStart(n,t)),e=!0;continue}if(this.waitingForDependencies(n,l,s))continue;l.delete(n.registration.id);let a=await this.startStagedPlugin(n,r);a!==void 0&&i.push(a),e=!0}if(e)continue;let n=this.findCapabilityCycle(l,s),a=n.length===0?[t[0]?.registration.id].filter(e=>e!==void 0):n;for(let e of a){let t=l.get(e);if(t===void 0)continue;l.delete(e);let n=Error(`Browser plugin ${e} has an unresolved capability dependency cycle`);i.push(await this.failBeforeStart(t,n))}}return Object.freeze({failures:Object.freeze(i)})}shutdownHasStarted(){return this.shuttingDown}async stageRegistration(e,t){let n=this.parseBackendRevision(e.id,e.backendRevision),r=this.parsePairedCapabilityVersion(e.id,`request`,e.pairedRequestVersion,n),i=this.parsePairedCapabilityVersion(e.id,`channel`,e.pairedChannelVersion,n),a=Xm(e.plugin,t.sourcePluginId);a.apiVersion===4&&!this.warnedLegacyPluginIds.has(t.sourcePluginId)&&(this.warnedLegacyPluginIds.add(t.sourcePluginId),console.warn(`Browser plugin ${t.sourcePluginId} uses deprecated API v4; migrate to API v5`));let o=new AbortController;this.activatingLifetimes.add(o);let s=`activate`,c;try{let l=await uh(e.id,s,this.lifecycleTimeoutMs,o.signal,n=>a.activate(Object.freeze({apiVersion:a.apiVersion,pluginId:t.sourcePluginId,runtimePluginId:e.id,html:E,svg:Bt,signal:n,lifetimeSignal:o.signal,translate:D,selection:this.selection.forPlugin(e.id,o.signal)})));c=Qm(l),s=`validate`;let u=Zm(l,e.id,t.sourcePluginId),d=(u.provides??[]).map(ah),f=Th(u.contributions,a.apiVersion);if((f.uiPresentations?.length??0)>0&&!a.requires.some(e=>e.pluginId===`pi-web`&&e.id===`ui-presentation`&&e.version===1))throw new H(`UI presentations require ui-presentation capability v1`);let p=this.prepareContributions(e,a.apiVersion===5?Ym(f,e,zm(e.id,t.sourcePluginId,n,r,i),o.signal):f,n,r,i,o.signal);if(this.shuttingDown)throw Error(`Browser plugin registry is shutting down`);return Object.freeze({registration:e,declaration:t,plugin:a,activation:u,lifetimeController:o,provisions:d,contributions:p})}catch(t){dh(o,new DOMException(`Browser plugin ${e.id} activation failed`,`AbortError`));let n=c===void 0?void 0:await this.runRollbackDispose(e.id,c);throw hh(s,mh(t,n))}finally{this.activatingLifetimes.delete(o)}}prepareContributions(e,t,n,r,i,a){let o=e.id,s=new Set,c=new Set,l=(t.uiPresentations??[]).map(t=>{if(e.machineId!==void 0||e.machineSpecific===!0)throw Error(`UI presentations are gateway-owned and cannot be machine-specific`);if(!wh(t)||!nt.includes(t.region)||typeof t.render!=`function`)throw Error(`Invalid UI presentation contribution`);let n=Reflect.get(t,`navigationLayout`);if(n!==void 0&&(t.region!==`navigation`||n!==`tree`))throw Error(`Invalid UI presentation navigation layout`);if(c.has(t.region)||this.uiPresentation.hasRegion(t.region)||this.stagedPlugins.some(e=>e.contributions.uiPresentations.some(e=>e.region===t.region)))throw Error(`UI presentation region ${t.region} already has an owner`);c.add(t.region);let r=t.render.bind(t);return Object.freeze({id:this.qualify(o,t.id,s),pluginId:o,region:t.region,render:r,...n===void 0?{}:{navigationLayout:n},active:()=>!a.aborted&&this.isContributionEnabled(o,void 0)})}),u=(t.contentRenderers??[]).map(t=>{let n=Id(t),r=n.supports?.bind(n);return{...n,id:this.qualify(o,t.id,s),pluginId:o,localId:t.id,label:n.title??`${e.sourcePluginId??o} / ${t.id}`,...r===void 0?{}:{supports:e=>!a.aborted&&r(e)},...e.machineId===void 0?{}:{machineId:e.machineId},...e.sourcePluginId===void 0?{}:{sourcePluginId:e.sourcePluginId},render:e=>{let t=AbortSignal.any([e.signal,a]);return n.render({...e,signal:t,fail:n=>{t.aborted||e.fail(n)}})}}}),d=(t.syntaxHighlighters??[]).map(t=>{let n=Ud(t),r=this.qualify(o,n.id,s);return Object.freeze({...n,id:r,pluginId:o,localId:n.id,label:`${e.sourcePluginId??o} / ${n.id}`,...e.machineId===void 0?{}:{machineId:e.machineId},...e.sourcePluginId===void 0?{}:{sourcePluginId:e.sourcePluginId},highlight:e=>Wd({...n,id:r},e.text,AbortSignal.any([e.signal,a]))})}),f=(t.messageActions??[]).map(t=>Object.freeze({...t,id:this.qualify(o,t.id,s),binding:zm(o,e.sourcePluginId,n,r,i),...e.machineId===void 0?{}:{machineId:e.machineId}})),p=(t.actions??[]).map(t=>this.qualifyAction(o,t,e.machineId,e.sourcePluginId,s)),m=(t.applicationPanels??[]).map(t=>this.qualifyApplicationPanel(o,t,e.machineId,e.sourcePluginId,s)),h=(t.workspacePanels??[]).map(t=>this.qualifyWorkspacePanel(o,t,e.machineId,e.sourcePluginId,n,r,i,s)),g=(t.workspaceLabels??[]).map(t=>this.qualifyWorkspaceLabelContribution(o,t,e.machineId,e.sourcePluginId,n,r,i,s)),ee=(t.sessionLabels??[]).map(t=>this.qualifySessionLabelContribution(o,t,e.machineId,e.sourcePluginId,n,r,i,s)),_=(t.stylesheets??[]).map(t=>({...this.qualifyStylesheet(o,t,s),...e.machineId===void 0?{}:{machineId:e.machineId},...e.sourcePluginId===void 0?{}:{sourcePluginId:e.sourcePluginId}})),te=e.machineId===void 0?(t.themes??[]).map(e=>this.qualifyTheme(o,e,s)):[],ne=e.machineId===void 0?(t.themePairs??[]).map(e=>this.qualifyThemePair(o,e,s)):[];return Object.freeze({ids:s,uiPresentations:l,contentRenderers:u,syntaxHighlighters:d,actions:p,messageActions:f,applicationPanels:m,workspacePanels:h,workspaceLabels:g,sessionLabels:ee,stylesheets:_,themes:te,themePairs:ne})}dependencyFailure(e,t,n){for(let r of e.plugin.requires){if(this.hostCapabilitiesByKey.has(ch(r)))continue;let i=this.providerDeclaration(e.declaration,r.pluginId);if(i===void 0)return Error(`Browser plugin ${e.registration.id} requires unavailable capability ${V(r)}`);let a=this.activeCapabilitiesByRegistration.get(i.id);if(a?.has(ch(r))===!0)continue;if(a!==void 0)return Error(`Browser plugin ${e.registration.id} requires unavailable capability ${V(r)} from ${i.id}`);let o=n.get(i.id);if(o!==void 0&&!o.provisions.some(({key:e})=>e===ch(r)))return Error(`Browser plugin ${e.registration.id} requires unavailable capability ${V(r)} from ${i.id}`);if(!t.has(i.id))return Error(`Browser plugin ${e.registration.id} requires ${V(r)}, but provider plugin ${i.id} did not start`)}}waitingForDependencies(e,t,n){return e.plugin.requires.some(r=>{if(this.hostCapabilitiesByKey.has(ch(r)))return!1;let i=this.providerDeclaration(e.declaration,r.pluginId);return i===void 0||this.activeCapabilitiesByRegistration.get(i.id)?.has(ch(r))===!0?!1:t.has(i.id)&&n.get(i.id)?.provisions.some(({key:e})=>e===ch(r))===!0})}async startStagedPlugin(e,t){try{let t=e.activation.start?.bind(e.activation);if(t!==void 0){let n=this.capabilityResolver(e);await uh(e.registration.id,`start`,this.lifecycleTimeoutMs,e.lifetimeController.signal,e=>t(Object.freeze({capabilities:n,signal:e})))}}catch(t){return await this.failBeforeStart(e,t,`start`)}let n=[];try{for(let r of t){if(r.registrationPluginId!==e.registration.id)continue;let t=nh(r.capability,`Host requirement for browser plugin ${e.registration.id}`),i=ch(t);if(n.some(e=>e.key===i))throw Error(`Host requires ${V(t)} from browser plugin ${e.registration.id} more than once`);let a=e.provisions.find(e=>e.key===i);if(a===void 0)throw Error(`Browser plugin ${e.registration.id} did not provide required capability ${V(t)}`);let o=sh(t,a.value,`Required host capability ${V(t)} from browser plugin ${e.registration.id}`);n.push(Object.freeze({token:r.capability,key:i,value:o}))}}catch(t){return await this.failBeforeStart(e,t,`validate`)}if(this.shuttingDown)return await this.failBeforeStart(e,fh(),`start`);this.publish(e,n)}capabilityResolver(e){let t=new Map;for(let n of e.plugin.requires){let r=ch(n),i=this.hostCapabilitiesByKey.get(r),a=i===void 0?this.providerDeclaration(e.declaration,n.pluginId):void 0,o=i??(a===void 0?void 0:this.activeCapabilitiesByRegistration.get(a.id)?.get(r));if(o===void 0)throw Error(`Browser plugin ${e.registration.id} requires inactive capability ${V(n)}`);sh(n,o.value,`Required capability ${V(n)} for browser plugin ${e.registration.id}`),t.set(r,o.value)}return lh(e.registration.id,t)}publish(e,t){this.removeStaged(e.registration.id),this.activePlugins.push(e),this.pluginIds.add(e.registration.id);for(let t of e.contributions.ids)this.contributionIds.add(t);this.contentRenderers.push(...e.contributions.contentRenderers),this.syntaxHighlighters.push(...e.contributions.syntaxHighlighters),(e.contributions.contentRenderers.length>0||e.contributions.syntaxHighlighters.length>0)&&(this.contentRendererRevision+=1),this.actions.push(...e.contributions.actions),this.messageActions.push(...e.contributions.messageActions),this.workspacePanels.push(...e.contributions.workspacePanels),this.applicationPanels.push(...e.contributions.applicationPanels),this.workspaceLabels.push(...e.contributions.workspaceLabels),this.sessionLabels.push(...e.contributions.sessionLabels),this.stylesheets.push(...e.contributions.stylesheets),e.contributions.uiPresentations.length>0&&this.gatewayPresentationPluginIds.add(e.registration.id),this.uiPresentation.register(e.contributions.uiPresentations),this.themes.push(...e.contributions.themes),this.themePairs.push(...e.contributions.themePairs),this.activeCapabilitiesByRegistration.set(e.registration.id,new Map(e.provisions.map(e=>[e.key,e]))),t.length>0&&this.hostCapabilitySnapshotsByRegistration.set(e.registration.id,new Map(t.map(e=>[e.key,e]))),e.declaration.machineId===void 0&&(this.gatewayPluginIds.add(e.registration.id),e.declaration.machineSpecific&&this.gatewayMachineSpecificPluginIds.add(e.registration.id))}async failBeforeStart(e,t,n=`start`){dh(e.lifetimeController,new DOMException(`Browser plugin ${e.registration.id} startup failed`,`AbortError`)),this.removeStaged(e.registration.id);let r=e.activation.dispose?.bind(e.activation),i=r===void 0?void 0:await this.runRollbackDispose(e.registration.id,r);return Km(Gm(e.registration),n,mh(t,i))}async runRollbackDispose(e,t){try{await uh(e,`dispose`,this.lifecycleTimeoutMs,void 0,e=>t(e));return}catch(e){return e}}removeStaged(e){this.stagedPlugins=this.stagedPlugins.filter(({registration:t})=>t.id!==e)}providerDeclaration(e,t){let n=[...this.declarationsById.values()].filter(e=>e.sourcePluginId===t);return e.machineId===void 0&&!e.machineSpecific?n.find(e=>e.machineId===void 0&&!e.machineSpecific):(e.machineId===void 0?n.find(e=>e.machineId===void 0&&e.machineSpecific):n.find(t=>t.machineId===e.machineId))??n.find(e=>e.machineId===void 0&&!e.machineSpecific)}findCapabilityCycle(e,t){let n=new Map,r=[],i=a=>{n.set(a,`visiting`),r.push(a);let o=e.get(a),s=(o?.plugin.requires??[]).flatMap(n=>{if(this.hostCapabilitiesByKey.has(ch(n))||o===void 0)return[];let r=this.providerDeclaration(o.declaration,n.pluginId);return r!==void 0&&e.has(r.id)&&t.get(r.id)?.provisions.some(({key:e})=>e===ch(n))===!0?[r.id]:[]}).sort((e,t)=>e.localeCompare(t));for(let e of s){if(n.get(e)===`visiting`)return r.slice(r.indexOf(e));if(n.get(e)!==`visited`){let t=i(e);if(t!==void 0)return t}}r.pop(),n.set(a,`visited`)};for(let t of[...e.keys()].sort((e,t)=>e.localeCompare(t))){if(n.has(t))continue;let e=i(t);if(e!==void 0)return e}return[]}normalizeDeclaration(e){this.validatePluginId(e.id);let t=e.sourcePluginId??e.id;this.validatePluginId(t);let n=this.parseMachineSpecific(e.id,e.machineSpecific);if(e.machineId!==void 0&&e.machineId===``)throw Error(`Invalid plugin machine id for ${e.id}`);return Object.freeze({id:e.id,sourcePluginId:t,...e.machineId===void 0?{}:{machineId:e.machineId},...e.manifestSource===void 0?{}:{manifestSource:e.manifestSource},...e.manifestScope===void 0?{}:{manifestScope:e.manifestScope},machineSpecific:n})}recordDeclaration(e){if(this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId===e.id?void 0:e.sourcePluginId,e.machineId,e.machineSpecific))return!1;let t=this.declarationsById.get(e.id);if(t!==void 0&&!Jm(t,e))throw Error(`Plugin registration scope changed for ${e.id}; reload PI WEB before activating a replacement`);return this.declarationsById.set(e.id,e),e.machineId!==void 0&&e.machineSpecific&&Bm(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId),!0}hasPlugin(e){return this.pluginIds.has(e)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=Wm(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=jm(e,t.pluginId),r=t.enabled?.(n),i=r===!1?t.disabledReason?.(n):void 0,a={id:t.id,pluginId:t.pluginId,localId:t.localId,...t.machineId===void 0?{}:{machineId:t.machineId},title:t.title,run:()=>this.isContributionActive(t.pluginId,t.machineId,Wm(e),t.sourcePluginId)?t.run(jm(e,t.pluginId)):void 0};return t.description!==void 0&&(a.description=t.description),t.shortcut!==void 0&&(a.shortcut=t.shortcut),t.shortcutAliases!==void 0&&(a.shortcutAliases=[...t.shortcutAliases]),t.group!==void 0&&(a.group=t.group),r!==void 0&&(a.enabled=r),i!==void 0&&i!==``&&(a.disabledReason=i),a})}getApplicationPanels(){return[...this.applicationPanels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}getWorkspacePanels(){return[...this.workspacePanels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}resolveWorkspaceFileOpen(e,t){for(let n of this.getWorkspacePanels()){if(n.visible?.(e)===!1)continue;let r=n.fileOpenQuery?.(e,t);if(r!==void 0)return{contributionId:n.id,sourceContributionId:n.sourceContributionId,navigationAliases:n.navigationAliases,query:r}}}resolveWorkspacePanelRouteId(e,t){let n=[...this.workspacePanels,...this.applicationPanels].filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)),r=n.find(t=>t.id===e);if(r!==void 0)return r.id;let i=n.filter(t=>t.sourceContributionId===e||t.routeAliases?.includes(e)===!0);if(i.length===1)return i[0]?.id;i.length>1&&console.warn(`Ambiguous PI WEB workspace panel source identity: ${e}`)}async invalidateWorkspacePanels(e,t){await this.invalidateMatchingWorkspacePanels(e,e=>t===void 0||e.id===t)}async invalidateWorkspaceResources(e,t){let n=new Set(t.resources);await this.invalidateMatchingWorkspacePanels(e,e=>e.invalidationResources?.some(e=>n.has(e))===!0,t)}async invalidateMatchingWorkspacePanels(e,t,n){await Promise.all(this.workspacePanels.map(async r=>{if(r.onInvalidate!==void 0&&t(r))try{n===void 0?await r.onInvalidate(e):await r.onInvalidate(e,n)}catch(e){console.warn(`Failed to invalidate PI WEB plugin panel ${r.id}`,e)}}))}getThemes(){return this.themes.filter(e=>this.isContributionEnabled(e.pluginId,void 0)).sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getThemePairs(){return this.themePairs.filter(e=>this.isContributionEnabled(e.pluginId,void 0)).sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getWorkspaceLabelItems(e){return[...this.workspaceLabels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.id.localeCompare(t.id)).flatMap(t=>t.visible?.(e)===!1?[]:t.items(e))}getSessionLabelItems(e){return[...this.sessionLabels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.id.localeCompare(t.id)).flatMap(t=>{let n=(n,r)=>{console.warn(`PI WEB plugin session label ${t.id} ${n} failed for session ${e.session.id} on machine ${e.machine.id}`,r)},r=`visible`;try{return t.visible?.(e)===!1?[]:(r=`items`,t.items(e).flatMap(e=>{if(e.type!==`render`)return[e];try{let t=e.render();return[{...e,render:()=>t}]}catch(e){return n(`render`,e),[]}}))}catch(e){return n(r,e),[]}})}qualifyAction(e,t,n,r,i){let a=this.qualify(e,t.id,i),o=`${r??e}:${t.id}`,s=this.parseShortcutAliases(a,t.shortcutAliases,o);return{...t,id:a,pluginId:e,localId:t.id,...s.length===0?{}:{shortcutAliases:s},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyApplicationPanel(e,t,n,r,i){let a=this.qualify(e,t.id,i),o=this.parseRouteAliases(a,t.routeAliases,`${r??e}:${t.id}`),s=`${r??e}:${t.id}`,c=t=>Em.get(t)?.(e)??t;return{...t,id:a,sourceContributionId:s,pluginId:e,localId:t.id,...o.length===0?{}:{routeAliases:o},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r},visible:i=>this.isContributionActive(e,n,i.machine.id,r)&&(t.visible?.(c(i))??!0),...t.badge===void 0?{}:{badge:i=>this.isContributionActive(e,n,i.machine.id,r)?t.badge?.(c(i)):void 0},render:i=>this.isContributionActive(e,n,i.machine.id,r)?t.render(c(i)):E``}}qualifyWorkspacePanel(e,t,n,r,i,a,o,s){let c=this.qualify(e,t.id,s),l=t.fileOpenQuery,u=t.badge,d=t.visible,f=t.onInvalidate,p=zm(e,r,i,a,o),m=this.parseRouteAliases(c,t.routeAliases,`${r??e}:${t.id}`),h=this.parseNavigationAliases(c,t.navigationAliases,`${r??e}:${t.id}`),g=`${r??e}:${t.id}`,ee=this.parseInvalidationResources(c,t.invalidationResources),_=e=>Mm(e,p,c,h);return{...t,id:c,pluginId:e,localId:t.id,sourceContributionId:g,routeAliases:m,navigationAliases:h,...t.invalidationResources===void 0?{}:{invalidationResources:ee},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(d?.(_(t))??!0),...l===void 0?{}:{fileOpenQuery:(t,i)=>this.isContributionActive(e,n,t.machine.id,r)?l(_(t),i):void 0},...u===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?u(_(t)):void 0},...f===void 0?{}:{onInvalidate:(t,i)=>{if(!this.isContributionActive(e,n,t.machine.id,r))return;let a=_(t);return i===void 0?f(a):f(a,i)}},render:i=>this.isContributionActive(e,n,i.machine.id,r)?t.render(_(i)):E``}}qualifyWorkspaceLabelContribution(e,t,n,r,i,a,o,s){let c=this.qualify(e,t.id,s),l=t.visible,u=t.items,d=zm(e,r,i,a,o);return{...t,id:c,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(l?.(Nm(t,d))??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?u(Nm(t,d)):[]}}qualifySessionLabelContribution(e,t,n,r,i,a,o,s){let c=this.qualify(e,t.id,s),l=t.visible,u=t.items,d=zm(e,r,i,a,o),f=e=>Om.get(e)?.(d)??e;return{...t,id:c,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(l?.(f(t))??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?u(f(t)):[]}}qualifyTheme(e,t,n){let r=this.qualify(e,t.id,n),i=new Set,a=t.stylesheets?.map(n=>this.qualifyStylesheet(`${e}:${t.id}`,n,i));return{...t,id:r,pluginId:e,localId:t.id,...t.tokens===void 0?{}:{tokens:Object.freeze({...t.tokens})},...a===void 0?{}:{stylesheets:a}}}qualifyThemePair(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t,n){this.validateLocalId(t);let r=`${e}:${t}`;if(this.contributionIds.has(r)||n.has(r))throw Error(`Duplicate contribution id: ${r}`);return n.add(r),r}qualifyReference(e,t){return this.validateLocalId(t),`${e}:${t}`}isContributionActive(e,t,n,r){return this.isContributionEnabled(e,t??n)?t===void 0?!this.isGatewayPluginHiddenForMachine(e,n):t===n&&!this.isRemotePluginHiddenByGateway(r,t):!1}isContributionEnabled(e,t){return!this.shuttingDown&&!this.uiPresentation.isFailed(e)&&(this.options.isContributionEnabled?.(e,t)??!0)}isRemoteDuplicateHiddenByGateway(e,t,n){return e!==void 0&&t!==void 0&&this.gatewayPluginIds.has(e)&&!this.gatewayMachineSpecificPluginIds.has(e)&&!n}isRemotePluginHiddenByGateway(e,t){return e===void 0||this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0?!1:this.gatewayPluginIds.has(e)}isGatewayPluginHiddenForMachine(e,t){return t!==`local`&&(this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0)}parseShortcutAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e),i=r.find(e=>!Hm(e));if(i!==void 0)throw Error(`Invalid shortcut alias for ${e}: ${i}`);return r.filter(Hm)}parseRouteAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e);for(let t of r)if(!bm.test(t))throw Error(`Invalid workspace panel route alias for ${e}: ${t}`);return r}parseNavigationAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e),i=r.find(e=>!Hm(e));if(i!==void 0)throw Error(`Invalid workspace panel navigation alias for ${e}: ${i}`);return r.filter(Hm)}parseInvalidationResources(e,t){if(t===void 0)return[];if(!Vm(t))throw Error(`Invalid workspace-panel invalidation resources for ${e}`);let n=[];for(let r of t){if(r!==`workspace.files`)throw Error(`Invalid workspace-panel invalidation resource for ${e}: ${Um(r)}`);n.includes(r)||n.push(r)}return n}validatePluginId(e){if(!xm.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!Sm.test(e))throw Error(`Invalid contribution id: ${e}`)}parseBackendRevision(e,t){if(t!==void 0)try{return Jt(t)}catch{throw Error(`Invalid plugin backend revision for ${e}`)}}parsePairedCapabilityVersion(e,t,n,r){if(n!==void 0){if(n!==1||r===void 0)throw Error(`Invalid plugin paired backend ${t} version for ${e}`);return n}}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${Um(t)}`);return t}getStylesheets(e){return this.stylesheets.filter(t=>this.gatewayPresentationPluginIds.has(t.pluginId)?this.isContributionEnabled(t.pluginId,void 0):this.isContributionActive(t.pluginId,t.machineId,e,t.sourcePluginId))}qualifyStylesheet(e,t,n){let r=this.qualify(e,t.id,n);if(typeof t.url!=`string`)throw Error(`Stylesheet ${r} requires a file URL`);let i=new URL(t.url);if(i.protocol!==`http:`&&i.protocol!==`https:`)throw Error(`Stylesheet ${r} requires an HTTP(S) file URL`);if(t.order!==void 0&&!Number.isFinite(t.order))throw Error(`Stylesheet ${r} order must be finite`);return Object.freeze({id:r,pluginId:e,url:i.href,...t.order===void 0?{}:{order:t.order}})}};function jm(e,t){return wm.get(e)?.(t)??e}function Mm(e,t,n,r){return Tm.get(e)?.(t,n,r)??e}function Nm(e,t){return Dm.get(e)?.(t)??e}function Pm(e,t){return wm.set(e,t),e}function Fm(e,t){return Em.set(e,t),e}function Im(e,t){return Tm.set(e,t),e}function Lm(e,t){return Dm.set(e,t),e}function Rm(e,t){return Om.set(e,t),e}function zm(e,t,n,r,i){return Object.freeze({registrationPluginId:e,sourcePluginId:t??e,...n===void 0?{}:{backendRevision:n},...r===void 0?{}:{pairedRequestVersion:r},...i===void 0?{}:{pairedChannelVersion:i}})}function Bm(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function Vm(e){return Array.isArray(e)}function Hm(e){return Cm.test(e)}function Um(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`||typeof e==`function`||e==null)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function Wm(e){return e.state.selectedMachine?.id??`local`}function Gm(e){return Object.freeze({id:e.id,...e.machineId===void 0?{}:{machineId:e.machineId},...e.sourcePluginId===void 0?{}:{sourcePluginId:e.sourcePluginId},...e.manifestSource===void 0?{}:{manifestSource:e.manifestSource},...e.manifestScope===void 0?{}:{manifestScope:e.manifestScope},...e.machineSpecific===void 0?{}:{machineSpecific:e.machineSpecific}})}function Km(e,t,n){return Object.freeze({declaration:qm(e),phase:t,error:n})}function qm(e){return Object.freeze({id:e.id,...e.machineId===void 0?{}:{machineId:e.machineId},...e.sourcePluginId===void 0?{}:{sourcePluginId:e.sourcePluginId},...e.manifestSource===void 0?{}:{manifestSource:e.manifestSource},...e.manifestScope===void 0?{}:{manifestScope:e.manifestScope},...e.machineSpecific===void 0?{}:{machineSpecific:e.machineSpecific}})}function Jm(e,t){return e.id===t.id&&e.sourcePluginId===t.sourcePluginId&&e.machineId===t.machineId&&e.manifestSource===t.manifestSource&&e.manifestScope===t.manifestScope&&e.machineSpecific===t.machineSpecific}function Ym(e,t,n,r){let i=t.machineId??(t.machineSpecific===!0?`local`:void 0),a=e=>{let t=e.machine?.id??e.state?.selectedMachine?.id??`local`,a=i===t?jd(n,t,r):void 0;return{...e,catalog:kd(t,r),backend:a}},o=e=>(t,...n)=>e(a(t),...n);return{...e,...e.actions===void 0?{}:{actions:e.actions.map(({enabled:e,disabledReason:t,run:n,...r})=>({...r,...e===void 0?{}:{enabled:o(e)},...t===void 0?{}:{disabledReason:o(t)},run:o(n)}))},...e.applicationPanels===void 0?{}:{applicationPanels:e.applicationPanels.map(({visible:e,badge:t,render:n,...r})=>({...r,...e===void 0?{}:{visible:o(e)},...t===void 0?{}:{badge:o(t)},render:o(n)}))},...e.workspacePanels===void 0?{}:{workspacePanels:e.workspacePanels.map(({visible:e,fileOpenQuery:t,badge:n,onInvalidate:r,render:i,...a})=>({...a,...e===void 0?{}:{visible:o(e)},...t===void 0?{}:{fileOpenQuery:o(t)},...n===void 0?{}:{badge:o(n)},...r===void 0?{}:{onInvalidate:o(r)},render:o(i)}))},...e.workspaceLabels===void 0?{}:{workspaceLabels:e.workspaceLabels.map(({visible:e,items:t,...n})=>({...n,...e===void 0?{}:{visible:o(e)},items:o(t)}))},...e.sessionLabels===void 0?{}:{sessionLabels:e.sessionLabels.map(({visible:e,items:t,...n})=>({...n,...e===void 0?{}:{visible:o(e)},items:o(t)}))},...e.messageActions===void 0?{}:{messageActions:e.messageActions.map(e=>(e.target,{...e,run:o(e.run)}))}}}function Xm(e,t){if(!wh(e))throw new H(`Browser plugin ${t} must export an object`);let n=e.apiVersion;if(n!==4&&n!==5)throw new H(`Unsupported browser plugin API version for ${t}: ${String(n)} (expected 4 or 5)`);let r=e.name,i=e.activate;if(typeof r!=`string`||r===``)throw new H(`Browser plugin ${t} name must be a non-empty string`);if(typeof i!=`function`)throw new H(`Browser plugin ${t} activate must be a function`);let a=$m(e.requires,`Browser plugin ${t} requirements`);return Object.freeze({apiVersion:n,name:r,requires:a,activate(t){return Reflect.apply(i,e,[t])}})}function Zm(e,t,n){if(!wh(e))throw new H(`Browser plugin ${t} activation must be an object`);if(e.requiredTerminalFacade!==void 0)throw new H(`requiredTerminalFacade was removed in browser plugin API v4; use a typed capability provision`);let r=e.contributions;if(!Ch(r))throw new H(`Browser plugin ${t} contributions must contain contribution arrays`);for(let e of Object.keys(r))Sh.includes(e)||console.warn(`PI WEB plugin ${t} has unknown contribution: ${e}`);let i=eh(e.provides,n,`Browser plugin ${t} provisions`),a=e.start,o=e.dispose;if(a!==void 0&&typeof a!=`function`)throw new H(`Browser plugin ${t} start must be a function`);if(o!==void 0&&typeof o!=`function`)throw new H(`Browser plugin ${t} dispose must be a function`);return Object.freeze({contributions:r,...i.length===0?{}:{provides:i},...a===void 0?{}:{start:async t=>{await Reflect.apply(a,e,[t])}},...o===void 0?{}:{dispose:async t=>{await Reflect.apply(o,e,[t])}}})}function Qm(e){if(!wh(e)||typeof e.dispose!=`function`)return;let t=e.dispose;return async n=>{await Reflect.apply(t,e,[n])}}function $m(e,t){if(e===void 0)return Object.freeze([]);if(!Array.isArray(e))throw new H(`${t} must be an array`);let n=new Set,r=[];for(let i=0;i<e.length;i+=1){if(!Object.hasOwn(e,i))throw new H(`${t} must not be sparse`);let a=th(e[i],`${t}[${String(i)}]`),o=ch(a);if(n.has(o))throw new H(`${t} declares ${V(a)} more than once`);n.add(o),r.push(a)}return Object.freeze(r)}function eh(e,t,n){if(e===void 0)return Object.freeze([]);if(!Array.isArray(e))throw new H(`${n} must be an array`);let r=new Set,i=[];for(let a=0;a<e.length;a+=1){if(!Object.hasOwn(e,a))throw new H(`${n} must not be sparse`);let o=e[a];if(!wh(o))throw new H(`${n}[${String(a)}] must be an object`);let s=th(o.capability,`${n}[${String(a)}].capability`);if(t!==void 0&&s.pluginId!==t)throw new H(`Browser plugin ${t} cannot provide capability owned by ${s.pluginId}`);let c=ch(s);if(r.has(c))throw new H(`${n} publishes ${V(s)} more than once`);r.add(c);let l=sh(s,o.value,`Provided capability ${V(s)}`);i.push(Object.freeze({capability:s,value:l}))}return Object.freeze(i)}function th(e,t){if(!wh(e))throw new H(`${t} must be an object`);let n=rh(e.pluginId,e.id,e.version,e.parse,t);return Object.freeze({pluginId:n.pluginId,id:n.id,version:n.version,parse(t){return Reflect.apply(n.parse,e,[t])}})}function nh(e,t){return rh(e.pluginId,e.id,e.version,e.parse,t),Object.freeze({pluginId:e.pluginId,id:e.id,version:e.version,parse:t=>e.parse(t)})}function rh(e,t,n,r,i){if(typeof e!=`string`||!xm.test(e))throw new H(`${i} pluginId must be a valid plugin id`);if(typeof t!=`string`||!Sm.test(t))throw new H(`${i} id must be a valid local id`);if(typeof n!=`number`||!Number.isInteger(n)||n<=0)throw new H(`${i} version must be a positive integer`);if(!ih(r))throw new H(`${i} parse must be a function`);return{pluginId:e,id:t,version:n,parse:r}}function ih(e){return typeof e==`function`}function ah(e){return Object.freeze({capability:e.capability,key:ch(e.capability),value:e.value})}function oh(e,t){return e.token===t}function sh(e,t,n){try{return e.parse(t)}catch(e){throw new H(`${n} is invalid: ${bh(e)}`,{cause:e})}}function ch(e){return JSON.stringify([e.pluginId,e.id,e.version])}function V(e){return`${e.pluginId}/${e.id} v${String(e.version)}`}function lh(e,t){return Object.freeze({resolve(n){let r=nh(n,`Capability request from browser plugin ${e}`),i=ch(r);if(!t.has(i))throw Error(`Browser plugin ${e} did not declare required capability ${V(r)}`);return sh(r,t.get(i),`Required capability ${V(r)} for browser plugin ${e}`)}})}async function uh(e,t,n,r,i){let a=new AbortController,o=new vh(`Browser plugin ${e} ${t} timed out after ${String(n)}ms`),s=new Promise((e,t)=>{a.signal.addEventListener(`abort`,()=>{t(ph(a.signal))},{once:!0})}),c=globalThis.setTimeout(()=>{a.abort(o)},n),l=()=>{a.abort(ph(r))};r?.aborted===!0?l():r?.addEventListener(`abort`,l,{once:!0});try{let e=Promise.resolve().then(()=>{if(a.signal.aborted)throw ph(a.signal);return i(a.signal)});return await Promise.race([e,s])}finally{globalThis.clearTimeout(c),r?.removeEventListener(`abort`,l),a.signal.aborted||a.abort(new DOMException(`Browser plugin operation completed`,`AbortError`))}}function dh(e,t){e.signal.aborted||e.abort(t)}function fh(){return new DOMException(`Browser plugin host is shutting down`,`AbortError`)}function ph(e){let t=e?.reason;return t instanceof Error?t:Error(`Browser plugin operation aborted`,{cause:t})}function mh(e,t){return t===void 0?e:Error(`${bh(e)}; startup rollback failed: ${bh(t)}`,{cause:e})}function hh(e,t){return new _h(e,bh(t),{cause:t})}function gh(e,t){return e instanceof _h?e.phase:t}var _h=class extends Error{constructor(e,t,n){super(t,n),this.phase=e}},H=class extends Error{constructor(...e){super(...e),this.name=`BrowserPluginIncompatibleError`}},vh=class extends Error{constructor(...e){super(...e),this.name=`TimeoutError`}};function yh(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<=0)throw Error(`${n} must be a positive integer`);return r}function bh(e){return e instanceof Error?e.message:String(e)}function xh(e){return e instanceof At?[e]:e instanceof AggregateError?e.errors.flatMap(e=>xh(e)):[]}var Sh=[`actions`,`applicationPanels`,`workspacePanels`,`workspaceLabels`,`sessionLabels`,`stylesheets`,`themes`,`themePairs`,`contentRenderers`,`syntaxHighlighters`,`messageActions`,`uiPresentations`];function Ch(e){return wh(e)?Sh.every(t=>e[t]===void 0||Array.isArray(e[t])):!1}function wh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Th(e,t){if(t===5){if(e.themes?.some(e=>e.tokens!==void 0)===!0)throw new H(`Browser API v5 themes use stylesheets, not tokens`);return e}if(e.themes?.some(e=>!wh(e.tokens)||Object.values(e.tokens).some(e=>typeof e!=`string`))===!0)throw new H(`Browser API v4 themes require string palette tokens`);if(Reflect.get(e,`uiPresentations`)!==void 0||Reflect.get(e,`stylesheets`)!==void 0||Reflect.get(e,`syntaxHighlighters`)!==void 0||e.contentRenderers?.some(e=>Reflect.get(e,`title`)!==void 0||Reflect.get(e,`supports`)!==void 0)===!0||e.themes?.some(e=>Reflect.get(e,`stylesheets`)!==void 0)===!0)throw new H(`Stylesheet, syntax-highlighter and extended renderer contributions require browser API v5`);let n=e=>{let{entryId:t,role:n,text:r}=e.message;return{...e,message:{entryId:t,role:n,text:r}}};return{...e,...e.contentRenderers===void 0?{}:{contentRenderers:e.contentRenderers.map(e=>({...e,render:({text:t,signal:n,fail:r})=>e.render({text:t,signal:n,fail:r})}))},...e.messageActions===void 0?{}:{messageActions:e.messageActions.map(e=>{if(e.target===`display`)return e;let{visible:t,enabled:r,ariaLabel:i,run:a}=e;return{...e,...t===void 0?{}:{visible:e=>t(n(e))},...r===void 0?{}:{enabled:e=>r(n(e))},...i===void 0?{}:{ariaLabel:e=>i(n(e))},run:e=>a(n(e))}})}}}var Eh=Object.freeze({reason:`mutation`,resources:Object.freeze([`workspace.files`])});function Dh(e,t,n,r,i={}){let a=typeof r==`function`||r===void 0?i:r,o=typeof r==`function`?r:void 0,s=t.projectId,c=t.id,l=e.createWorkspaceDirectory?.bind(e),u=e.moveWorkspaceDirectory?.bind(e),d=e.deleteWorkspaceDirectory?.bind(e),f=a.workspaceFilePreviewUrl??rt,p=a.uploadWorkspaceFile??Ct,m=()=>{o?.(),a.onInvalidate?.(Eh)};return{capabilityVersion:1,defaultUploadFolder:a.defaultUploadFolder??``,maxInlinePreviewBytes:a.maxInlinePreviewBytes??10485760,...l===void 0?{}:{createDirectory:async e=>{let t=await l(s,c,e,n);return m(),t}},...u===void 0?{}:{moveDirectory:async(e,t)=>{let r=await u(s,c,e,t,n);return m(),r}},...d===void 0?{}:{deleteDirectory:async e=>{let t=await d(s,c,e,n);return m(),t}},readFile:(t,r)=>e.workspaceFile(s,c,t,n,r),listFiles:(t,r)=>e.workspaceTree(s,c,t,n,r),writeFile:async(t,r,i)=>{let a=await e.writeWorkspaceFile(s,c,t,r,i,n);return m(),a},deleteFile:async t=>{let r=await e.deleteWorkspaceFile(s,c,t,n);return m(),r},moveFile:async(t,r,i)=>{let a=await e.moveWorkspaceFile(s,c,t,r,i,n);return m(),a},previewUrl:(e,t)=>f(s,c,e,{machineId:n,...Oh(t)}),downloadUrl:(e,t)=>f(s,c,e,{machineId:n,download:!0,...Oh(t)}),uploadFile:(e,t)=>{let r=Ge(t?.destinationFolder??t?.folder??a.defaultUploadFolder??``,e.name),i=t?.signal;if(i?.aborted===!0)return{path:r,completed:Promise.reject(kh(new Re)),cancel:()=>{}};let o=p(s,c,{path:r,file:e},{machineId:n,createDirs:t?.createDirs??!0,overwrite:t?.overwrite??!1,...t?.onProgress===void 0?{}:{onProgress:t.onProgress}}),l=()=>{o.cancel()};return i?.addEventListener(`abort`,l,{once:!0}),{path:r,completed:o.promise.then(e=>(m(),e),e=>{throw kh(e)}).finally(()=>{i?.removeEventListener(`abort`,l)}),cancel:l}}}}function Oh(e){let t=e?.version??e?.modifiedAt;return t===void 0?{}:{modifiedAt:t}}function kh(e){if(!(e instanceof Re))return e;if(typeof DOMException<`u`)return new DOMException(e.message,`AbortError`);let t=Error(e.message);return t.name=`AbortError`,t}var Ah=me(`.ui-transcript-surface{box-sizing:border-box;background:var(--ui-transcript-bg,transparent);border:0;border-radius:0}.ui-transcript-activity{--ui-activity-tone:var(--pi-muted);--ui-transcript-bg:color-mix(in srgb, var(--ui-activity-tone) 6%, var(--pi-bg));--ui-transcript-heading-bg:color-mix(in srgb, var(--ui-activity-tone) 18%, var(--pi-bg));border-inline-start:var(--ui-activity-edge-width,3px) solid var(--ui-activity-tone);border-block-start:var(--ui-activity-separator-width,0px) solid color-mix(in srgb, var(--ui-activity-tone) 35%, var(--ui-transcript-heading-bg))}.ui-transcript-tool{--ui-activity-tone:var(--pi-tool,color-mix(in srgb, #238c86 70%, var(--pi-text) 30%))}.ui-transcript-activity>.ui-transcript-heading{box-sizing:border-box;background:var(--ui-transcript-heading-bg);min-height:32px;color:var(--pi-text);padding:6px 12px;line-height:20px}.ui-transcript-activity>summary.ui-transcript-heading:hover{background:color-mix(in srgb, var(--ui-activity-tone) 26%, var(--pi-bg))}.ui-transcript-disclosure{box-sizing:border-box;background:var(--ui-transcript-heading-bg,transparent);cursor:pointer;border:0;border-radius:0;align-items:center;gap:8px;min-height:32px;padding:6px 12px;line-height:20px;list-style:none;display:flex}.ui-transcript-disclosure::-webkit-details-marker{display:none}.ui-transcript-disclosure:before{content:"";border:4px solid #0000;border-inline-start:5px solid;border-inline-end-width:3px;flex:none;width:0;height:0}details[open]>.ui-transcript-disclosure:before{border:4px solid #0000;border-block-start:5px solid;border-block-end-width:3px}.ui-transcript-disclosure:hover{background:var(--pi-surface-hover)}.ui-transcript-disclosure:focus-visible{outline:2px solid var(--pi-accent);outline-offset:-2px}.ui-transcript-activity .ui-transcript-disclosure:focus-visible{outline-color:var(--pi-text)}`),jh=me(`.chat-jumps{gap:0;display:flex}.chat-jumps button{box-sizing:border-box;width:28px;height:28px;color:var(--pi-muted);font:14px/1 var(--pi-font,system-ui, sans-serif);cursor:pointer;background:0 0;border:0;border-radius:0;place-items:center;padding:0;display:inline-grid;position:relative}.chat-jumps button.following{color:var(--pi-accent)}.chat-jumps button.following:after{content:"";pointer-events:none;background:currentColor;border-radius:50%;width:3px;height:3px;position:absolute;bottom:3px;left:calc(50% - 1.5px)}.chat-jumps button:hover,.chat-jumps button:focus-visible{color:var(--pi-text-bright);background:var(--pi-selection-bg)}.chat-jumps button:focus-visible{outline:2px solid var(--pi-accent);outline-offset:-2px}.chat-follow-state{clip-path:inset(50%);white-space:nowrap;border:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}`),Mh=T`
|
|
136
|
+
></pi-web-content-rendering-boundary>`}),renderMarkdown:i}}var bm=/^[a-z][a-z0-9.:-]*$/u,xm=/^[a-z][a-z0-9.-]*$/u,Sm=/^[a-z][a-z0-9.-]*$/u,Cm=/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u,wm=new WeakMap,Tm=new WeakMap,Em=new WeakMap,Dm=new WeakMap,Om=new WeakMap,km=1e4,Am=class{promptChipMethods(e,t){let n=()=>{if(t===void 0)throw Error(`Select a ready, non-archived conversation to stage prompt chips`);if(!this.promptChipOwnerAvailable(e,t.machineId))throw Error(`Prompt chips unavailable for plugin ${e} on machine ${t.machineId}`);return t};return{setChip:t=>{this.promptChips.set(e,n(),t)},removeChip:t=>{this.promptChips.remove(e,n(),t)}}}promptChipOwnerAvailable(e,t){let n=this.declarationsById.get(e);return this.hasPlugin(e)&&n!==void 0&&this.isContributionActive(e,n.machineId,t,n.sourcePluginId)}get contentRendererVersion(){return this.contentRendererRevision}compareDiscoveryOrder(e,t){let n=[...this.declarationsById.keys()];return n.indexOf(e.pluginId)-n.indexOf(t.pluginId)}syntaxHighlightingRevision(e){let t=this.syntaxHighlighters.filter(t=>this.isContributionActive(t.pluginId,t.machineId,e,t.sourcePluginId)).sort((e,t)=>this.compareDiscoveryOrder(e,t)),n=this.syntaxHighlightingViews.get(e);return n?.length===t.length&&t.every((e,t)=>e===n[t])?n:(this.syntaxHighlightingViews.set(e,t),t)}getChatContentRendering(e){let t=this.activeContentRendererChoices(e),n=this.syntaxHighlightingRevision(e),r=this.chatContentRenderingViews.get(e);if(r?.grammars===n&&r.choices.length===t.length&&t.every((e,t)=>e.renderer===r.choices[t]?.renderer))return r.rendering;let i=ym(n=>n.machineId===e?t.filter(({renderer:e})=>Fd(e,n)):[],()=>n);return this.chatContentRenderingViews.set(e,{choices:t,grammars:n,rendering:i}),i}matchContentRenderers(e){return this.activeContentRendererChoices(e.machineId).filter(({renderer:t})=>Fd(t,e))}activeContentRendererChoices(e){return this.contentRenderers.filter(t=>this.isContributionActive(t.pluginId,t.machineId,e,t.sourcePluginId)).sort((e,t)=>this.compareDiscoveryOrder(e,t)).map(e=>({id:e.id,label:e.label,renderer:e}))}getMessageActions(e){let t=this.messageActions.filter(t=>this.isContributionActive(t.binding.registrationPluginId,t.machineId,e,t.binding.sourcePluginId));return(t.length!==this.messageActionView.length||t.some((e,t)=>e!==this.messageActionView[t]))&&(this.messageActionView=t),this.messageActionView}async runMessageAction(e,t,n){let r=En(this.getMessageActions(t.machine.id).filter(t=>t.id===e),t)[0];if(r?.enabled===!0&&r.action.target!==`display`)return r.action.run(n(r.action.binding))}async runDisplayedMessageAction(e,t,n){let r=Dn(this.getMessageActions(t.machine.id).filter(t=>t.id===e),t)[0];if(r?.enabled===!0&&r.action.target===`display`)return r.action.run(n(r.action.binding))}constructor(e={}){this.options=e,this.contentRenderers=[],this.syntaxHighlighters=[],this.syntaxHighlighting=Gd(e=>this.syntaxHighlightingRevision(e.machineId).filter(t=>Fd(t,{...e,text:``})).at(-1)),this.chatContentRendering=ym(e=>this.matchContentRenderers(e),e=>this.syntaxHighlightingRevision(e.machineId)),this.contentRendererRevision=0,this.syntaxHighlightingViews=new Map,this.chatContentRenderingViews=new Map,this.contentRendering=vm(e=>this.matchContentRenderers(e),e=>this.syntaxHighlightingRevision(e.machineId)),this.messageActions=[],this.messageActionView=[],this.actions=[],this.workspacePanels=[],this.applicationPanels=[],this.workspaceLabels=[],this.sessionLabels=[],this.stylesheets=[],this.themes=[],this.themePairs=[],this.pluginIds=new Set,this.warnedLegacyPluginIds=new Set,this.gatewayPluginIds=new Set,this.gatewayMachineSpecificPluginIds=new Set,this.gatewayPresentationPluginIds=new Set,this.remoteMachineSpecificPluginIds=new Map,this.contributionIds=new Set,this.declarationsById=new Map,this.activeCapabilitiesByRegistration=new Map,this.hostCapabilitySnapshotsByRegistration=new Map,this.hostCapabilitiesByKey=new Map,this.activatingLifetimes=new Set,this.activePlugins=[],this.stagedPlugins=[],this.registrationTail=Promise.resolve(),this.shuttingDown=!1,this.uiPresentation=new u((t,n)=>{e.onUiPresentationError===void 0?console.warn(`UI presentation failed for ${t}`,n):e.onUiPresentationError(t,n)}),this.promptChips=new ja(e.onPromptChipsChanged),this.selection=new Nd(e.getSelection??(()=>({}))),this.lifecycleTimeoutMs=yh(e.lifecycleTimeoutMs,km,`lifecycleTimeoutMs`);for(let t of eh([{capability:mm,value:this.contentRendering},{capability:Rd,value:this.syntaxHighlighting},{capability:se,value:v},{capability:le,value:c},...e.hostCapabilities??[]],void 0,`Browser host capability provisions`)){let e=ah(t);if(this.hostCapabilitiesByKey.has(e.key))throw new H(`Browser capability ${V(e.capability)} is provided more than once by the host`);this.hostCapabilitiesByKey.set(e.key,e)}}notifySelectionChanged(){this.selection.notifyChanged()}failUiPresentationStylesheetError(e){let t=!1;for(let n of xh(e)){let e=this.stylesheets.find(e=>e.id===n.contributionId&&e.url===n.url)?.pluginId??this.themes.find(e=>e.stylesheets?.some(e=>e.id===n.contributionId&&e.url===n.url)===!0)?.pluginId;e!==void 0&&this.gatewayPresentationPluginIds.has(e)&&(t=this.uiPresentation.failPlugin(e,n)||t)}return t}async register(e){let t=(await this.registerBatch([e])).failures.find(({declaration:t})=>t.id===e.id);if(t!==void 0)throw t.error}registerBatch(e,t={}){let n=[...e],r=[...t.declarations??e.map(Gm)],i=[...t.failures??[]],a=[...t.requiredCapabilities??[]],o=this.registrationTail.then(async()=>this.performRegistrationBatch(n,r,i,a));return this.registrationTail=o.then(()=>void 0,()=>void 0),o}beginShutdown(){if(this.shuttingDown)return;this.shuttingDown=!0,this.promptChips.clear();let e=new DOMException(`Browser plugin host is shutting down`,`AbortError`);for(let t of this.activatingLifetimes)dh(t,e);for(let t of[...this.activePlugins,...this.stagedPlugins])dh(t.lifetimeController,e)}dispose(){return this.disposePromise===void 0&&(this.beginShutdown(),this.disposePromise=this.performDispose()),this.disposePromise}async performDispose(){await this.registrationTail;let e=[...this.activePlugins,...this.stagedPlugins].reverse();this.activePlugins=[],this.stagedPlugins=[],this.activeCapabilitiesByRegistration.clear(),this.hostCapabilitySnapshotsByRegistration.clear(),this.pluginIds.clear(),this.actions.splice(0),(this.contentRenderers.length>0||this.syntaxHighlighters.length>0)&&(this.contentRendererRevision+=1),this.messageActions.splice(0),this.contentRenderers.splice(0),this.syntaxHighlighters.splice(0),this.syntaxHighlightingViews.clear(),this.chatContentRenderingViews.clear(),this.workspacePanels.splice(0),this.applicationPanels.splice(0),this.workspaceLabels.splice(0),this.sessionLabels.splice(0),this.stylesheets.splice(0),this.uiPresentation.clear(),this.gatewayPresentationPluginIds.clear(),this.themes.splice(0),this.themePairs.splice(0),this.contributionIds.clear();for(let t of e){let e=t.activation.dispose?.bind(t.activation);if(e!==void 0)try{await uh(t.registration.id,`dispose`,this.lifecycleTimeoutMs,void 0,t=>e(t))}catch(e){console.warn(`Failed to dispose PI WEB plugin ${t.registration.id}`,e)}}}resolveCapability(e,t){let n=nh(t,`Browser host capability request`),r=ch(n),i=this.activeCapabilitiesByRegistration.get(e)?.get(r);if(i===void 0)throw Error(`Browser capability ${V(n)} is not active for ${e}`);let a=this.hostCapabilitySnapshotsByRegistration.get(e)?.get(r);return a!==void 0&&oh(a,t)?a.value:sh(n,i.value,`Browser capability ${V(n)} for ${e}`)}async performRegistrationBatch(e,t,n,r){if(this.shuttingDown)throw Error(`Browser plugin registry is shutting down`);let i=[...n],a=new Set,o=new Set;for(let e of t)try{let t=this.normalizeDeclaration(e);if(o.has(t.id))throw Error(`Duplicate plugin id: ${t.id}`);o.add(t.id),this.recordDeclaration(t)&&a.add(t.id)}catch(t){i.push(Km(e,`validate`,t))}let s=new Map,c=new Set;for(let t of[...e].sort((e,t)=>e.id.localeCompare(t.id))){let e=Gm(t);if(!o.has(t.id))i.push(Km(e,`validate`,Error(`Plugin ${t.id} has no registration declaration`)));else if(a.has(t.id)){if(this.shutdownHasStarted())i.push(Km(e,`activate`,fh()));else try{if(c.has(t.id)||this.pluginIds.has(t.id))throw Error(`Duplicate plugin id: ${t.id}`);c.add(t.id);let n=this.declarationsById.get(t.id);if(n===void 0)throw Error(`Plugin ${t.id} has no valid registration declaration`);if(!Jm(n,this.normalizeDeclaration(e)))throw Error(`Plugin registration topology does not match its declaration: ${t.id}`);let r=await this.stageRegistration(t,n);s.set(t.id,r),this.stagedPlugins.push(r)}catch(t){i.push(Km(e,gh(t,`validate`),t))}}}let l=new Map(s);for(;l.size>0;){let e=!1,t=[...l.values()].sort((e,t)=>e.registration.id.localeCompare(t.registration.id));for(let n of t){let t=this.dependencyFailure(n,l,s);if(t!==void 0){l.delete(n.registration.id),i.push(await this.failBeforeStart(n,t)),e=!0;continue}if(this.waitingForDependencies(n,l,s))continue;l.delete(n.registration.id);let a=await this.startStagedPlugin(n,r);a!==void 0&&i.push(a),e=!0}if(e)continue;let n=this.findCapabilityCycle(l,s),a=n.length===0?[t[0]?.registration.id].filter(e=>e!==void 0):n;for(let e of a){let t=l.get(e);if(t===void 0)continue;l.delete(e);let n=Error(`Browser plugin ${e} has an unresolved capability dependency cycle`);i.push(await this.failBeforeStart(t,n))}}return Object.freeze({failures:Object.freeze(i)})}shutdownHasStarted(){return this.shuttingDown}async stageRegistration(e,t){let n=this.parseBackendRevision(e.id,e.backendRevision),r=this.parsePairedCapabilityVersion(e.id,`request`,e.pairedRequestVersion,n),i=this.parsePairedCapabilityVersion(e.id,`channel`,e.pairedChannelVersion,n),a=Xm(e.plugin,t.sourcePluginId);a.apiVersion===4&&!this.warnedLegacyPluginIds.has(t.sourcePluginId)&&(this.warnedLegacyPluginIds.add(t.sourcePluginId),console.warn(`Browser plugin ${t.sourcePluginId} uses deprecated API v4; migrate to API v5`));let o=new AbortController;this.activatingLifetimes.add(o);let s=`activate`,c;try{let l=await uh(e.id,s,this.lifecycleTimeoutMs,o.signal,n=>a.activate(Object.freeze({apiVersion:a.apiVersion,pluginId:t.sourcePluginId,runtimePluginId:e.id,html:E,svg:Bt,signal:n,lifetimeSignal:o.signal,translate:D,selection:this.selection.forPlugin(e.id,o.signal)})));c=Qm(l),s=`validate`;let u=Zm(l,e.id,t.sourcePluginId),d=(u.provides??[]).map(ah),f=Th(u.contributions,a.apiVersion);if((f.uiPresentations?.length??0)>0&&!a.requires.some(e=>e.pluginId===`pi-web`&&e.id===`ui-presentation`&&e.version===1))throw new H(`UI presentations require ui-presentation capability v1`);let p=this.prepareContributions(e,a.apiVersion===5?Ym(f,e,zm(e.id,t.sourcePluginId,n,r,i),o.signal):f,n,r,i,o.signal);if(this.shuttingDown)throw Error(`Browser plugin registry is shutting down`);return Object.freeze({registration:e,declaration:t,plugin:a,activation:u,lifetimeController:o,provisions:d,contributions:p})}catch(t){dh(o,new DOMException(`Browser plugin ${e.id} activation failed`,`AbortError`));let n=c===void 0?void 0:await this.runRollbackDispose(e.id,c);throw hh(s,mh(t,n))}finally{this.activatingLifetimes.delete(o)}}prepareContributions(e,t,n,r,i,a){let o=e.id,s=new Set,c=new Set,l=(t.uiPresentations??[]).map(t=>{if(e.machineId!==void 0||e.machineSpecific===!0)throw Error(`UI presentations are gateway-owned and cannot be machine-specific`);if(!wh(t)||!nt.includes(t.region)||typeof t.render!=`function`)throw Error(`Invalid UI presentation contribution`);let n=Reflect.get(t,`navigationLayout`);if(n!==void 0&&(t.region!==`navigation`||n!==`tree`))throw Error(`Invalid UI presentation navigation layout`);if(c.has(t.region)||this.uiPresentation.hasRegion(t.region)||this.stagedPlugins.some(e=>e.contributions.uiPresentations.some(e=>e.region===t.region)))throw Error(`UI presentation region ${t.region} already has an owner`);c.add(t.region);let r=t.render.bind(t);return Object.freeze({id:this.qualify(o,t.id,s),pluginId:o,region:t.region,render:r,...n===void 0?{}:{navigationLayout:n},active:()=>!a.aborted&&this.isContributionEnabled(o,void 0)})}),u=(t.contentRenderers??[]).map(t=>{let n=Id(t),r=n.supports?.bind(n);return{...n,id:this.qualify(o,t.id,s),pluginId:o,localId:t.id,label:n.title??`${e.sourcePluginId??o} / ${t.id}`,...r===void 0?{}:{supports:e=>!a.aborted&&r(e)},...e.machineId===void 0?{}:{machineId:e.machineId},...e.sourcePluginId===void 0?{}:{sourcePluginId:e.sourcePluginId},render:e=>{let t=AbortSignal.any([e.signal,a]);return n.render({...e,signal:t,fail:n=>{t.aborted||e.fail(n)}})}}}),d=(t.syntaxHighlighters??[]).map(t=>{let n=Ud(t),r=this.qualify(o,n.id,s);return Object.freeze({...n,id:r,pluginId:o,localId:n.id,label:`${e.sourcePluginId??o} / ${n.id}`,...e.machineId===void 0?{}:{machineId:e.machineId},...e.sourcePluginId===void 0?{}:{sourcePluginId:e.sourcePluginId},highlight:e=>Wd({...n,id:r},e.text,AbortSignal.any([e.signal,a]))})}),f=(t.messageActions??[]).map(t=>Object.freeze({...t,id:this.qualify(o,t.id,s),binding:zm(o,e.sourcePluginId,n,r,i),...e.machineId===void 0?{}:{machineId:e.machineId}})),p=(t.actions??[]).map(t=>this.qualifyAction(o,t,e.machineId,e.sourcePluginId,s)),m=(t.applicationPanels??[]).map(t=>this.qualifyApplicationPanel(o,t,e.machineId,e.sourcePluginId,s)),h=(t.workspacePanels??[]).map(t=>this.qualifyWorkspacePanel(o,t,e.machineId,e.sourcePluginId,n,r,i,s)),g=(t.workspaceLabels??[]).map(t=>this.qualifyWorkspaceLabelContribution(o,t,e.machineId,e.sourcePluginId,n,r,i,s)),ee=(t.sessionLabels??[]).map(t=>this.qualifySessionLabelContribution(o,t,e.machineId,e.sourcePluginId,n,r,i,s)),_=(t.stylesheets??[]).map(t=>({...this.qualifyStylesheet(o,t,s),...e.machineId===void 0?{}:{machineId:e.machineId},...e.sourcePluginId===void 0?{}:{sourcePluginId:e.sourcePluginId}})),te=e.machineId===void 0?(t.themes??[]).map(e=>this.qualifyTheme(o,e,s)):[],ne=e.machineId===void 0?(t.themePairs??[]).map(e=>this.qualifyThemePair(o,e,s)):[];return Object.freeze({ids:s,uiPresentations:l,contentRenderers:u,syntaxHighlighters:d,actions:p,messageActions:f,applicationPanels:m,workspacePanels:h,workspaceLabels:g,sessionLabels:ee,stylesheets:_,themes:te,themePairs:ne})}dependencyFailure(e,t,n){for(let r of e.plugin.requires){if(this.hostCapabilitiesByKey.has(ch(r)))continue;let i=this.providerDeclaration(e.declaration,r.pluginId);if(i===void 0)return Error(`Browser plugin ${e.registration.id} requires unavailable capability ${V(r)}`);let a=this.activeCapabilitiesByRegistration.get(i.id);if(a?.has(ch(r))===!0)continue;if(a!==void 0)return Error(`Browser plugin ${e.registration.id} requires unavailable capability ${V(r)} from ${i.id}`);let o=n.get(i.id);if(o!==void 0&&!o.provisions.some(({key:e})=>e===ch(r)))return Error(`Browser plugin ${e.registration.id} requires unavailable capability ${V(r)} from ${i.id}`);if(!t.has(i.id))return Error(`Browser plugin ${e.registration.id} requires ${V(r)}, but provider plugin ${i.id} did not start`)}}waitingForDependencies(e,t,n){return e.plugin.requires.some(r=>{if(this.hostCapabilitiesByKey.has(ch(r)))return!1;let i=this.providerDeclaration(e.declaration,r.pluginId);return i===void 0||this.activeCapabilitiesByRegistration.get(i.id)?.has(ch(r))===!0?!1:t.has(i.id)&&n.get(i.id)?.provisions.some(({key:e})=>e===ch(r))===!0})}async startStagedPlugin(e,t){try{let t=e.activation.start?.bind(e.activation);if(t!==void 0){let n=this.capabilityResolver(e);await uh(e.registration.id,`start`,this.lifecycleTimeoutMs,e.lifetimeController.signal,e=>t(Object.freeze({capabilities:n,signal:e})))}}catch(t){return await this.failBeforeStart(e,t,`start`)}let n=[];try{for(let r of t){if(r.registrationPluginId!==e.registration.id)continue;let t=nh(r.capability,`Host requirement for browser plugin ${e.registration.id}`),i=ch(t);if(n.some(e=>e.key===i))throw Error(`Host requires ${V(t)} from browser plugin ${e.registration.id} more than once`);let a=e.provisions.find(e=>e.key===i);if(a===void 0)throw Error(`Browser plugin ${e.registration.id} did not provide required capability ${V(t)}`);let o=sh(t,a.value,`Required host capability ${V(t)} from browser plugin ${e.registration.id}`);n.push(Object.freeze({token:r.capability,key:i,value:o}))}}catch(t){return await this.failBeforeStart(e,t,`validate`)}if(this.shuttingDown)return await this.failBeforeStart(e,fh(),`start`);this.publish(e,n)}capabilityResolver(e){let t=new Map;for(let n of e.plugin.requires){let r=ch(n),i=this.hostCapabilitiesByKey.get(r),a=i===void 0?this.providerDeclaration(e.declaration,n.pluginId):void 0,o=i??(a===void 0?void 0:this.activeCapabilitiesByRegistration.get(a.id)?.get(r));if(o===void 0)throw Error(`Browser plugin ${e.registration.id} requires inactive capability ${V(n)}`);sh(n,o.value,`Required capability ${V(n)} for browser plugin ${e.registration.id}`),t.set(r,o.value)}return lh(e.registration.id,t)}publish(e,t){this.removeStaged(e.registration.id),this.activePlugins.push(e),this.pluginIds.add(e.registration.id);for(let t of e.contributions.ids)this.contributionIds.add(t);this.contentRenderers.push(...e.contributions.contentRenderers),this.syntaxHighlighters.push(...e.contributions.syntaxHighlighters),(e.contributions.contentRenderers.length>0||e.contributions.syntaxHighlighters.length>0)&&(this.contentRendererRevision+=1),this.actions.push(...e.contributions.actions),this.messageActions.push(...e.contributions.messageActions),this.workspacePanels.push(...e.contributions.workspacePanels),this.applicationPanels.push(...e.contributions.applicationPanels),this.workspaceLabels.push(...e.contributions.workspaceLabels),this.sessionLabels.push(...e.contributions.sessionLabels),this.stylesheets.push(...e.contributions.stylesheets),e.contributions.uiPresentations.length>0&&this.gatewayPresentationPluginIds.add(e.registration.id),this.uiPresentation.register(e.contributions.uiPresentations),this.themes.push(...e.contributions.themes),this.themePairs.push(...e.contributions.themePairs),this.activeCapabilitiesByRegistration.set(e.registration.id,new Map(e.provisions.map(e=>[e.key,e]))),t.length>0&&this.hostCapabilitySnapshotsByRegistration.set(e.registration.id,new Map(t.map(e=>[e.key,e]))),e.declaration.machineId===void 0&&(this.gatewayPluginIds.add(e.registration.id),e.declaration.machineSpecific&&this.gatewayMachineSpecificPluginIds.add(e.registration.id))}async failBeforeStart(e,t,n=`start`){dh(e.lifetimeController,new DOMException(`Browser plugin ${e.registration.id} startup failed`,`AbortError`)),this.removeStaged(e.registration.id);let r=e.activation.dispose?.bind(e.activation),i=r===void 0?void 0:await this.runRollbackDispose(e.registration.id,r);return Km(Gm(e.registration),n,mh(t,i))}async runRollbackDispose(e,t){try{await uh(e,`dispose`,this.lifecycleTimeoutMs,void 0,e=>t(e));return}catch(e){return e}}removeStaged(e){this.stagedPlugins=this.stagedPlugins.filter(({registration:t})=>t.id!==e)}providerDeclaration(e,t){let n=[...this.declarationsById.values()].filter(e=>e.sourcePluginId===t);return e.machineId===void 0&&!e.machineSpecific?n.find(e=>e.machineId===void 0&&!e.machineSpecific):(e.machineId===void 0?n.find(e=>e.machineId===void 0&&e.machineSpecific):n.find(t=>t.machineId===e.machineId))??n.find(e=>e.machineId===void 0&&!e.machineSpecific)}findCapabilityCycle(e,t){let n=new Map,r=[],i=a=>{n.set(a,`visiting`),r.push(a);let o=e.get(a),s=(o?.plugin.requires??[]).flatMap(n=>{if(this.hostCapabilitiesByKey.has(ch(n))||o===void 0)return[];let r=this.providerDeclaration(o.declaration,n.pluginId);return r!==void 0&&e.has(r.id)&&t.get(r.id)?.provisions.some(({key:e})=>e===ch(n))===!0?[r.id]:[]}).sort((e,t)=>e.localeCompare(t));for(let e of s){if(n.get(e)===`visiting`)return r.slice(r.indexOf(e));if(n.get(e)!==`visited`){let t=i(e);if(t!==void 0)return t}}r.pop(),n.set(a,`visited`)};for(let t of[...e.keys()].sort((e,t)=>e.localeCompare(t))){if(n.has(t))continue;let e=i(t);if(e!==void 0)return e}return[]}normalizeDeclaration(e){this.validatePluginId(e.id);let t=e.sourcePluginId??e.id;this.validatePluginId(t);let n=this.parseMachineSpecific(e.id,e.machineSpecific);if(e.machineId!==void 0&&e.machineId===``)throw Error(`Invalid plugin machine id for ${e.id}`);return Object.freeze({id:e.id,sourcePluginId:t,...e.machineId===void 0?{}:{machineId:e.machineId},...e.manifestSource===void 0?{}:{manifestSource:e.manifestSource},...e.manifestScope===void 0?{}:{manifestScope:e.manifestScope},machineSpecific:n})}recordDeclaration(e){if(this.isRemoteDuplicateHiddenByGateway(e.sourcePluginId===e.id?void 0:e.sourcePluginId,e.machineId,e.machineSpecific))return!1;let t=this.declarationsById.get(e.id);if(t!==void 0&&!Jm(t,e))throw Error(`Plugin registration scope changed for ${e.id}; reload PI WEB before activating a replacement`);return this.declarationsById.set(e.id,e),e.machineId!==void 0&&e.machineSpecific&&Bm(this.remoteMachineSpecificPluginIds,e.sourcePluginId,e.machineId),!0}hasPlugin(e){return this.pluginIds.has(e)}shouldLoadRemotePlugin(e,t=!1){return!this.gatewayPluginIds.has(e)||this.gatewayMachineSpecificPluginIds.has(e)||t}getActions(e){let t=Wm(e);return this.actions.filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)).map(t=>{let n=jm(e,t.pluginId),r=t.enabled?.(n),i=r===!1?t.disabledReason?.(n):void 0,a={id:t.id,pluginId:t.pluginId,localId:t.localId,...t.machineId===void 0?{}:{machineId:t.machineId},title:t.title,run:()=>this.isContributionActive(t.pluginId,t.machineId,Wm(e),t.sourcePluginId)?t.run(jm(e,t.pluginId)):void 0};return t.description!==void 0&&(a.description=t.description),t.shortcut!==void 0&&(a.shortcut=t.shortcut),t.shortcutAliases!==void 0&&(a.shortcutAliases=[...t.shortcutAliases]),t.group!==void 0&&(a.group=t.group),r!==void 0&&(a.enabled=r),i!==void 0&&i!==``&&(a.disabledReason=i),a})}getApplicationPanels(){return[...this.applicationPanels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}getWorkspacePanels(){return[...this.workspacePanels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}resolveWorkspaceFileOpen(e,t){for(let n of this.getWorkspacePanels()){if(n.visible?.(e)===!1)continue;let r=n.fileOpenQuery?.(e,t);if(r!==void 0)return{contributionId:n.id,sourceContributionId:n.sourceContributionId,navigationAliases:n.navigationAliases,query:r}}}resolveWorkspacePanelRouteId(e,t){let n=[...this.workspacePanels,...this.applicationPanels].filter(e=>this.isContributionActive(e.pluginId,e.machineId,t,e.sourcePluginId)),r=n.find(t=>t.id===e);if(r!==void 0)return r.id;let i=n.filter(t=>t.sourceContributionId===e||t.routeAliases?.includes(e)===!0);if(i.length===1)return i[0]?.id;i.length>1&&console.warn(`Ambiguous PI WEB workspace panel source identity: ${e}`)}async invalidateWorkspacePanels(e,t){await this.invalidateMatchingWorkspacePanels(e,e=>t===void 0||e.id===t)}async invalidateWorkspaceResources(e,t){let n=new Set(t.resources);await this.invalidateMatchingWorkspacePanels(e,e=>e.invalidationResources?.some(e=>n.has(e))===!0,t)}async invalidateMatchingWorkspacePanels(e,t,n){await Promise.all(this.workspacePanels.map(async r=>{if(r.onInvalidate!==void 0&&t(r))try{n===void 0?await r.onInvalidate(e):await r.onInvalidate(e,n)}catch(e){console.warn(`Failed to invalidate PI WEB plugin panel ${r.id}`,e)}}))}getThemes(){return this.themes.filter(e=>this.isContributionEnabled(e.pluginId,void 0)).sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getThemePairs(){return this.themePairs.filter(e=>this.isContributionEnabled(e.pluginId,void 0)).sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.name.localeCompare(t.name))}getWorkspaceLabelItems(e){return[...this.workspaceLabels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.id.localeCompare(t.id)).flatMap(t=>t.visible?.(e)===!1?[]:t.items(e))}getSessionLabelItems(e){return[...this.sessionLabels].sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.id.localeCompare(t.id)).flatMap(t=>{let n=(n,r)=>{console.warn(`PI WEB plugin session label ${t.id} ${n} failed for session ${e.session.id} on machine ${e.machine.id}`,r)},r=`visible`;try{return t.visible?.(e)===!1?[]:(r=`items`,t.items(e).flatMap(e=>{if(e.type!==`render`)return[e];try{let t=e.render();return[{...e,render:()=>t}]}catch(e){return n(`render`,e),[]}}))}catch(e){return n(r,e),[]}})}qualifyAction(e,t,n,r,i){let a=this.qualify(e,t.id,i),o=`${r??e}:${t.id}`,s=this.parseShortcutAliases(a,t.shortcutAliases,o);return{...t,id:a,pluginId:e,localId:t.id,...s.length===0?{}:{shortcutAliases:s},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r}}}qualifyApplicationPanel(e,t,n,r,i){let a=this.qualify(e,t.id,i),o=this.parseRouteAliases(a,t.routeAliases,`${r??e}:${t.id}`),s=`${r??e}:${t.id}`,c=t=>Em.get(t)?.(e)??t;return{...t,id:a,sourceContributionId:s,pluginId:e,localId:t.id,...o.length===0?{}:{routeAliases:o},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r},visible:i=>this.isContributionActive(e,n,i.machine.id,r)&&(t.visible?.(c(i))??!0),...t.badge===void 0?{}:{badge:i=>this.isContributionActive(e,n,i.machine.id,r)?t.badge?.(c(i)):void 0},render:i=>this.isContributionActive(e,n,i.machine.id,r)?t.render(c(i)):E``}}qualifyWorkspacePanel(e,t,n,r,i,a,o,s){let c=this.qualify(e,t.id,s),l=t.fileOpenQuery,u=t.badge,d=t.visible,f=t.onInvalidate,p=zm(e,r,i,a,o),m=this.parseRouteAliases(c,t.routeAliases,`${r??e}:${t.id}`),h=this.parseNavigationAliases(c,t.navigationAliases,`${r??e}:${t.id}`),g=`${r??e}:${t.id}`,ee=this.parseInvalidationResources(c,t.invalidationResources),_=e=>Mm(e,p,c,h);return{...t,id:c,pluginId:e,localId:t.id,sourceContributionId:g,routeAliases:m,navigationAliases:h,...t.invalidationResources===void 0?{}:{invalidationResources:ee},...n===void 0?{}:{machineId:n},...r===void 0?{}:{sourcePluginId:r},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(d?.(_(t))??!0),...l===void 0?{}:{fileOpenQuery:(t,i)=>this.isContributionActive(e,n,t.machine.id,r)?l(_(t),i):void 0},...u===void 0?{}:{badge:t=>this.isContributionActive(e,n,t.machine.id,r)?u(_(t)):void 0},...f===void 0?{}:{onInvalidate:(t,i)=>{if(!this.isContributionActive(e,n,t.machine.id,r))return;let a=_(t);return i===void 0?f(a):f(a,i)}},render:i=>this.isContributionActive(e,n,i.machine.id,r)?t.render(_(i)):E``}}qualifyWorkspaceLabelContribution(e,t,n,r,i,a,o,s){let c=this.qualify(e,t.id,s),l=t.visible,u=t.items,d=zm(e,r,i,a,o);return{...t,id:c,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(l?.(Nm(t,d))??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?u(Nm(t,d)):[]}}qualifySessionLabelContribution(e,t,n,r,i,a,o,s){let c=this.qualify(e,t.id,s),l=t.visible,u=t.items,d=zm(e,r,i,a,o),f=e=>Om.get(e)?.(d)??e;return{...t,id:c,pluginId:e,localId:t.id,...n===void 0?{}:{machineId:n},visible:t=>this.isContributionActive(e,n,t.machine.id,r)&&(l?.(f(t))??!0),items:t=>this.isContributionActive(e,n,t.machine.id,r)?u(f(t)):[]}}qualifyTheme(e,t,n){let r=this.qualify(e,t.id,n),i=new Set,a=t.stylesheets?.map(n=>this.qualifyStylesheet(`${e}:${t.id}`,n,i));return{...t,id:r,pluginId:e,localId:t.id,...t.tokens===void 0?{}:{tokens:Object.freeze({...t.tokens})},...a===void 0?{}:{stylesheets:a}}}qualifyThemePair(e,t,n){let r=this.qualify(e,t.id,n);return{...t,id:r,pluginId:e,localId:t.id,light:this.qualifyReference(e,t.light),dark:this.qualifyReference(e,t.dark)}}qualify(e,t,n){this.validateLocalId(t);let r=`${e}:${t}`;if(this.contributionIds.has(r)||n.has(r))throw Error(`Duplicate contribution id: ${r}`);return n.add(r),r}qualifyReference(e,t){return this.validateLocalId(t),`${e}:${t}`}isContributionActive(e,t,n,r){return this.isContributionEnabled(e,t??n)?t===void 0?!this.isGatewayPluginHiddenForMachine(e,n):t===n&&!this.isRemotePluginHiddenByGateway(r,t):!1}isContributionEnabled(e,t){return!this.shuttingDown&&!this.uiPresentation.isFailed(e)&&(this.options.isContributionEnabled?.(e,t)??!0)}isRemoteDuplicateHiddenByGateway(e,t,n){return e!==void 0&&t!==void 0&&this.gatewayPluginIds.has(e)&&!this.gatewayMachineSpecificPluginIds.has(e)&&!n}isRemotePluginHiddenByGateway(e,t){return e===void 0||this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0?!1:this.gatewayPluginIds.has(e)}isGatewayPluginHiddenForMachine(e,t){return t!==`local`&&(this.gatewayMachineSpecificPluginIds.has(e)||this.remoteMachineSpecificPluginIds.get(e)?.has(t)===!0)}parseShortcutAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e),i=r.find(e=>!Hm(e));if(i!==void 0)throw Error(`Invalid shortcut alias for ${e}: ${i}`);return r.filter(Hm)}parseRouteAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e);for(let t of r)if(!bm.test(t))throw Error(`Invalid workspace panel route alias for ${e}: ${t}`);return r}parseNavigationAliases(e,t,n){let r=[...new Set([...t??[],n])].filter(t=>t!==e),i=r.find(e=>!Hm(e));if(i!==void 0)throw Error(`Invalid workspace panel navigation alias for ${e}: ${i}`);return r.filter(Hm)}parseInvalidationResources(e,t){if(t===void 0)return[];if(!Vm(t))throw Error(`Invalid workspace-panel invalidation resources for ${e}`);let n=[];for(let r of t){if(r!==`workspace.files`)throw Error(`Invalid workspace-panel invalidation resource for ${e}: ${Um(r)}`);n.includes(r)||n.push(r)}return n}validatePluginId(e){if(!xm.test(e))throw Error(`Invalid plugin id: ${e}`)}validateLocalId(e){if(!Sm.test(e))throw Error(`Invalid contribution id: ${e}`)}parseBackendRevision(e,t){if(t!==void 0)try{return Jt(t)}catch{throw Error(`Invalid plugin backend revision for ${e}`)}}parsePairedCapabilityVersion(e,t,n,r){if(n!==void 0){if(n!==1||r===void 0)throw Error(`Invalid plugin paired backend ${t} version for ${e}`);return n}}parseMachineSpecific(e,t){if(t===void 0)return!1;if(typeof t!=`boolean`)throw Error(`Invalid plugin machineSpecific value for ${e}: ${Um(t)}`);return t}getStylesheets(e){return this.stylesheets.filter(t=>this.gatewayPresentationPluginIds.has(t.pluginId)?this.isContributionEnabled(t.pluginId,void 0):this.isContributionActive(t.pluginId,t.machineId,e,t.sourcePluginId))}qualifyStylesheet(e,t,n){let r=this.qualify(e,t.id,n);if(typeof t.url!=`string`)throw Error(`Stylesheet ${r} requires a file URL`);let i=new URL(t.url);if(i.protocol!==`http:`&&i.protocol!==`https:`)throw Error(`Stylesheet ${r} requires an HTTP(S) file URL`);if(t.order!==void 0&&!Number.isFinite(t.order))throw Error(`Stylesheet ${r} order must be finite`);return Object.freeze({id:r,pluginId:e,url:i.href,...t.order===void 0?{}:{order:t.order}})}};function jm(e,t){return wm.get(e)?.(t)??e}function Mm(e,t,n,r){return Tm.get(e)?.(t,n,r)??e}function Nm(e,t){return Dm.get(e)?.(t)??e}function Pm(e,t){return wm.set(e,t),e}function Fm(e,t){return Em.set(e,t),e}function Im(e,t){return Tm.set(e,t),e}function Lm(e,t){return Dm.set(e,t),e}function Rm(e,t){return Om.set(e,t),e}function zm(e,t,n,r,i){return Object.freeze({registrationPluginId:e,sourcePluginId:t??e,...n===void 0?{}:{backendRevision:n},...r===void 0?{}:{pairedRequestVersion:r},...i===void 0?{}:{pairedChannelVersion:i}})}function Bm(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function Vm(e){return Array.isArray(e)}function Hm(e){return Cm.test(e)}function Um(e){if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||typeof e==`symbol`||typeof e==`function`||e==null)return String(e);try{return JSON.stringify(e)}catch{return Object.prototype.toString.call(e)}}function Wm(e){return e.state.selectedMachine?.id??`local`}function Gm(e){return Object.freeze({id:e.id,...e.machineId===void 0?{}:{machineId:e.machineId},...e.sourcePluginId===void 0?{}:{sourcePluginId:e.sourcePluginId},...e.manifestSource===void 0?{}:{manifestSource:e.manifestSource},...e.manifestScope===void 0?{}:{manifestScope:e.manifestScope},...e.machineSpecific===void 0?{}:{machineSpecific:e.machineSpecific}})}function Km(e,t,n){return Object.freeze({declaration:qm(e),phase:t,error:n})}function qm(e){return Object.freeze({id:e.id,...e.machineId===void 0?{}:{machineId:e.machineId},...e.sourcePluginId===void 0?{}:{sourcePluginId:e.sourcePluginId},...e.manifestSource===void 0?{}:{manifestSource:e.manifestSource},...e.manifestScope===void 0?{}:{manifestScope:e.manifestScope},...e.machineSpecific===void 0?{}:{machineSpecific:e.machineSpecific}})}function Jm(e,t){return e.id===t.id&&e.sourcePluginId===t.sourcePluginId&&e.machineId===t.machineId&&e.manifestSource===t.manifestSource&&e.manifestScope===t.manifestScope&&e.machineSpecific===t.machineSpecific}function Ym(e,t,n,r){let i=t.machineId??(t.machineSpecific===!0?`local`:void 0),a=e=>{let t=e.machine?.id??e.state?.selectedMachine?.id??`local`,a=i===t?jd(n,t,r):void 0;return{...e,catalog:kd(t,r),backend:a}},o=e=>(t,...n)=>e(a(t),...n);return{...e,...e.actions===void 0?{}:{actions:e.actions.map(({enabled:e,disabledReason:t,run:n,...r})=>({...r,...e===void 0?{}:{enabled:o(e)},...t===void 0?{}:{disabledReason:o(t)},run:o(n)}))},...e.applicationPanels===void 0?{}:{applicationPanels:e.applicationPanels.map(({visible:e,badge:t,render:n,...r})=>({...r,...e===void 0?{}:{visible:o(e)},...t===void 0?{}:{badge:o(t)},render:o(n)}))},...e.workspacePanels===void 0?{}:{workspacePanels:e.workspacePanels.map(({visible:e,fileOpenQuery:t,badge:n,onInvalidate:r,render:i,...a})=>({...a,...e===void 0?{}:{visible:o(e)},...t===void 0?{}:{fileOpenQuery:o(t)},...n===void 0?{}:{badge:o(n)},...r===void 0?{}:{onInvalidate:o(r)},render:o(i)}))},...e.workspaceLabels===void 0?{}:{workspaceLabels:e.workspaceLabels.map(({visible:e,items:t,...n})=>({...n,...e===void 0?{}:{visible:o(e)},items:o(t)}))},...e.sessionLabels===void 0?{}:{sessionLabels:e.sessionLabels.map(({visible:e,items:t,...n})=>({...n,...e===void 0?{}:{visible:o(e)},items:o(t)}))},...e.messageActions===void 0?{}:{messageActions:e.messageActions.map(e=>(e.target,{...e,run:o(e.run)}))}}}function Xm(e,t){if(!wh(e))throw new H(`Browser plugin ${t} must export an object`);let n=e.apiVersion;if(n!==4&&n!==5)throw new H(`Unsupported browser plugin API version for ${t}: ${String(n)} (expected 4 or 5)`);let r=e.name,i=e.activate;if(typeof r!=`string`||r===``)throw new H(`Browser plugin ${t} name must be a non-empty string`);if(typeof i!=`function`)throw new H(`Browser plugin ${t} activate must be a function`);let a=$m(e.requires,`Browser plugin ${t} requirements`);return Object.freeze({apiVersion:n,name:r,requires:a,activate(t){return Reflect.apply(i,e,[t])}})}function Zm(e,t,n){if(!wh(e))throw new H(`Browser plugin ${t} activation must be an object`);if(e.requiredTerminalFacade!==void 0)throw new H(`requiredTerminalFacade was removed in browser plugin API v4; use a typed capability provision`);let r=e.contributions;if(!Ch(r))throw new H(`Browser plugin ${t} contributions must contain contribution arrays`);for(let e of Object.keys(r))Sh.includes(e)||console.warn(`PI WEB plugin ${t} has unknown contribution: ${e}`);let i=eh(e.provides,n,`Browser plugin ${t} provisions`),a=e.start,o=e.dispose;if(a!==void 0&&typeof a!=`function`)throw new H(`Browser plugin ${t} start must be a function`);if(o!==void 0&&typeof o!=`function`)throw new H(`Browser plugin ${t} dispose must be a function`);return Object.freeze({contributions:r,...i.length===0?{}:{provides:i},...a===void 0?{}:{start:async t=>{await Reflect.apply(a,e,[t])}},...o===void 0?{}:{dispose:async t=>{await Reflect.apply(o,e,[t])}}})}function Qm(e){if(!wh(e)||typeof e.dispose!=`function`)return;let t=e.dispose;return async n=>{await Reflect.apply(t,e,[n])}}function $m(e,t){if(e===void 0)return Object.freeze([]);if(!Array.isArray(e))throw new H(`${t} must be an array`);let n=new Set,r=[];for(let i=0;i<e.length;i+=1){if(!Object.hasOwn(e,i))throw new H(`${t} must not be sparse`);let a=th(e[i],`${t}[${String(i)}]`),o=ch(a);if(n.has(o))throw new H(`${t} declares ${V(a)} more than once`);n.add(o),r.push(a)}return Object.freeze(r)}function eh(e,t,n){if(e===void 0)return Object.freeze([]);if(!Array.isArray(e))throw new H(`${n} must be an array`);let r=new Set,i=[];for(let a=0;a<e.length;a+=1){if(!Object.hasOwn(e,a))throw new H(`${n} must not be sparse`);let o=e[a];if(!wh(o))throw new H(`${n}[${String(a)}] must be an object`);let s=th(o.capability,`${n}[${String(a)}].capability`);if(t!==void 0&&s.pluginId!==t)throw new H(`Browser plugin ${t} cannot provide capability owned by ${s.pluginId}`);let c=ch(s);if(r.has(c))throw new H(`${n} publishes ${V(s)} more than once`);r.add(c);let l=sh(s,o.value,`Provided capability ${V(s)}`);i.push(Object.freeze({capability:s,value:l}))}return Object.freeze(i)}function th(e,t){if(!wh(e))throw new H(`${t} must be an object`);let n=rh(e.pluginId,e.id,e.version,e.parse,t);return Object.freeze({pluginId:n.pluginId,id:n.id,version:n.version,parse(t){return Reflect.apply(n.parse,e,[t])}})}function nh(e,t){return rh(e.pluginId,e.id,e.version,e.parse,t),Object.freeze({pluginId:e.pluginId,id:e.id,version:e.version,parse:t=>e.parse(t)})}function rh(e,t,n,r,i){if(typeof e!=`string`||!xm.test(e))throw new H(`${i} pluginId must be a valid plugin id`);if(typeof t!=`string`||!Sm.test(t))throw new H(`${i} id must be a valid local id`);if(typeof n!=`number`||!Number.isInteger(n)||n<=0)throw new H(`${i} version must be a positive integer`);if(!ih(r))throw new H(`${i} parse must be a function`);return{pluginId:e,id:t,version:n,parse:r}}function ih(e){return typeof e==`function`}function ah(e){return Object.freeze({capability:e.capability,key:ch(e.capability),value:e.value})}function oh(e,t){return e.token===t}function sh(e,t,n){try{return e.parse(t)}catch(e){throw new H(`${n} is invalid: ${bh(e)}`,{cause:e})}}function ch(e){return JSON.stringify([e.pluginId,e.id,e.version])}function V(e){return`${e.pluginId}/${e.id} v${String(e.version)}`}function lh(e,t){return Object.freeze({resolve(n){let r=nh(n,`Capability request from browser plugin ${e}`),i=ch(r);if(!t.has(i))throw Error(`Browser plugin ${e} did not declare required capability ${V(r)}`);return sh(r,t.get(i),`Required capability ${V(r)} for browser plugin ${e}`)}})}async function uh(e,t,n,r,i){let a=new AbortController,o=new vh(`Browser plugin ${e} ${t} timed out after ${String(n)}ms`),s=new Promise((e,t)=>{a.signal.addEventListener(`abort`,()=>{t(ph(a.signal))},{once:!0})}),c=globalThis.setTimeout(()=>{a.abort(o)},n),l=()=>{a.abort(ph(r))};r?.aborted===!0?l():r?.addEventListener(`abort`,l,{once:!0});try{let e=Promise.resolve().then(()=>{if(a.signal.aborted)throw ph(a.signal);return i(a.signal)});return await Promise.race([e,s])}finally{globalThis.clearTimeout(c),r?.removeEventListener(`abort`,l),a.signal.aborted||a.abort(new DOMException(`Browser plugin operation completed`,`AbortError`))}}function dh(e,t){e.signal.aborted||e.abort(t)}function fh(){return new DOMException(`Browser plugin host is shutting down`,`AbortError`)}function ph(e){let t=e?.reason;return t instanceof Error?t:Error(`Browser plugin operation aborted`,{cause:t})}function mh(e,t){return t===void 0?e:Error(`${bh(e)}; startup rollback failed: ${bh(t)}`,{cause:e})}function hh(e,t){return new _h(e,bh(t),{cause:t})}function gh(e,t){return e instanceof _h?e.phase:t}var _h=class extends Error{constructor(e,t,n){super(t,n),this.phase=e}},H=class extends Error{constructor(...e){super(...e),this.name=`BrowserPluginIncompatibleError`}},vh=class extends Error{constructor(...e){super(...e),this.name=`TimeoutError`}};function yh(e,t,n){let r=e??t;if(!Number.isInteger(r)||r<=0)throw Error(`${n} must be a positive integer`);return r}function bh(e){return e instanceof Error?e.message:String(e)}function xh(e){return e instanceof At?[e]:e instanceof AggregateError?e.errors.flatMap(e=>xh(e)):[]}var Sh=[`actions`,`applicationPanels`,`workspacePanels`,`workspaceLabels`,`sessionLabels`,`stylesheets`,`themes`,`themePairs`,`contentRenderers`,`syntaxHighlighters`,`messageActions`,`uiPresentations`];function Ch(e){return wh(e)?Sh.every(t=>e[t]===void 0||Array.isArray(e[t])):!1}function wh(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Th(e,t){if(t===5){if(e.themes?.some(e=>e.tokens!==void 0)===!0)throw new H(`Browser API v5 themes use stylesheets, not tokens`);return e}if(e.themes?.some(e=>!wh(e.tokens)||Object.values(e.tokens).some(e=>typeof e!=`string`))===!0)throw new H(`Browser API v4 themes require string palette tokens`);if(Reflect.get(e,`uiPresentations`)!==void 0||Reflect.get(e,`stylesheets`)!==void 0||Reflect.get(e,`syntaxHighlighters`)!==void 0||e.contentRenderers?.some(e=>Reflect.get(e,`title`)!==void 0||Reflect.get(e,`supports`)!==void 0)===!0||e.themes?.some(e=>Reflect.get(e,`stylesheets`)!==void 0)===!0)throw new H(`Stylesheet, syntax-highlighter and extended renderer contributions require browser API v5`);let n=e=>{let{entryId:t,role:n,text:r}=e.message;return{...e,message:{entryId:t,role:n,text:r}}};return{...e,...e.contentRenderers===void 0?{}:{contentRenderers:e.contentRenderers.map(e=>({...e,render:({text:t,signal:n,fail:r})=>e.render({text:t,signal:n,fail:r})}))},...e.messageActions===void 0?{}:{messageActions:e.messageActions.map(e=>{if(e.target===`display`)return e;let{visible:t,enabled:r,ariaLabel:i,run:a}=e;return{...e,...t===void 0?{}:{visible:e=>t(n(e))},...r===void 0?{}:{enabled:e=>r(n(e))},...i===void 0?{}:{ariaLabel:e=>i(n(e))},run:e=>a(n(e))}})}}}function Eh(e){if(typeof e!=`object`||!e||!(`available`in e))throw Error(`Invalid managed instructions status`);if(e.available===!1)return{available:!1};if(e.available!==!0||!(`pending`in e)||typeof e.pending!=`boolean`||!(`revision`in e)||typeof e.revision!=`string`||e.revision===``||!(`modifiedAt`in e)||e.modifiedAt!==null&&(typeof e.modifiedAt!=`string`||!Number.isFinite(Date.parse(e.modifiedAt)))||!(`templateModifiedAt`in e)||e.templateModifiedAt!==null&&(typeof e.templateModifiedAt!=`string`||!Number.isFinite(Date.parse(e.templateModifiedAt)))||!(`templateRevision`in e)||typeof e.templateRevision!=`string`)throw Error(`Invalid managed instructions status`);return{available:!0,pending:e.pending,revision:e.revision,modifiedAt:e.modifiedAt,templateModifiedAt:e.templateModifiedAt,templateRevision:e.templateRevision}}function Dh(e,t,n){return`api/machines/${encodeURIComponent(n)}/projects/${encodeURIComponent(e)}/workspaces/${encodeURIComponent(t)}/agents-instructions`}var Oh={status:(e,t,n,r)=>Ee(Dh(e,t,n),Eh,r),decide:(e,t,n,r)=>Ee(Dh(e,t,n),Eh,{method:`POST`,body:JSON.stringify(r)})},kh=Object.freeze({reason:`mutation`,resources:Object.freeze([`workspace.files`])});function Ah(e,t,n,r,i={}){let a=typeof r==`function`||r===void 0?i:r,o=typeof r==`function`?r:void 0,s=t.projectId,c=t.id,l=e.createWorkspaceDirectory?.bind(e),u=e.moveWorkspaceDirectory?.bind(e),d=e.deleteWorkspaceDirectory?.bind(e),f=e.optionalWorkspaceFile?.bind(e),p=a.workspaceFilePreviewUrl??rt,m=a.uploadWorkspaceFile??Ct,h=()=>{o?.(),a.onInvalidate?.(kh)},g=a.managementMode===!0?{status:e=>Oh.status(s,c,n,e),decide:async e=>{let t=await Oh.decide(s,c,n,e);return e.action===`overwrite`&&h(),t}}:void 0;return{capabilityVersion:1,...g===void 0?{}:{managedAgents:g},defaultUploadFolder:a.defaultUploadFolder??``,maxInlinePreviewBytes:a.maxInlinePreviewBytes??10485760,...l===void 0?{}:{createDirectory:async e=>{let t=await l(s,c,e,n);return h(),t}},...u===void 0?{}:{moveDirectory:async(e,t)=>{let r=await u(s,c,e,t,n);return h(),r}},...d===void 0?{}:{deleteDirectory:async e=>{let t=await d(s,c,e,n);return h(),t}},readFile:(t,r)=>e.workspaceFile(s,c,t,n,r),...f===void 0?{}:{readOptionalFile:(e,t)=>f(s,c,e,n,t)},listFiles:(t,r)=>e.workspaceTree(s,c,t,n,r),writeFile:async(t,r,i)=>{let a=await e.writeWorkspaceFile(s,c,t,r,i,n);return h(),a},deleteFile:async t=>{let r=await e.deleteWorkspaceFile(s,c,t,n);return h(),r},moveFile:async(t,r,i)=>{let a=await e.moveWorkspaceFile(s,c,t,r,i,n);return h(),a},previewUrl:(e,t)=>p(s,c,e,{machineId:n,...jh(t)}),downloadUrl:(e,t)=>p(s,c,e,{machineId:n,download:!0,...jh(t)}),uploadFile:(e,t)=>{let r=Ge(t?.destinationFolder??t?.folder??a.defaultUploadFolder??``,e.name),i=t?.signal;if(i?.aborted===!0)return{path:r,completed:Promise.reject(Mh(new Re)),cancel:()=>{}};let o=m(s,c,{path:r,file:e},{machineId:n,createDirs:t?.createDirs??!0,overwrite:t?.overwrite??!1,...t?.onProgress===void 0?{}:{onProgress:t.onProgress}}),l=()=>{o.cancel()};return i?.addEventListener(`abort`,l,{once:!0}),{path:r,completed:o.promise.then(e=>(h(),e),e=>{throw Mh(e)}).finally(()=>{i?.removeEventListener(`abort`,l)}),cancel:l}}}}function jh(e){let t=e?.version??e?.modifiedAt;return t===void 0?{}:{modifiedAt:t}}function Mh(e){if(!(e instanceof Re))return e;if(typeof DOMException<`u`)return new DOMException(e.message,`AbortError`);let t=Error(e.message);return t.name=`AbortError`,t}var Nh=me(`.ui-transcript-surface{box-sizing:border-box;background:var(--ui-transcript-bg,transparent);border:0;border-radius:0}.ui-transcript-activity{--ui-activity-tone:var(--pi-muted);--ui-transcript-bg:color-mix(in srgb, var(--ui-activity-tone) 6%, var(--pi-bg));--ui-transcript-heading-bg:color-mix(in srgb, var(--ui-activity-tone) 18%, var(--pi-bg));border-inline-start:var(--ui-activity-edge-width,3px) solid var(--ui-activity-tone);border-block-start:var(--ui-activity-separator-width,0px) solid color-mix(in srgb, var(--ui-activity-tone) 35%, var(--ui-transcript-heading-bg))}.ui-transcript-tool{--ui-activity-tone:var(--pi-tool,color-mix(in srgb, #238c86 70%, var(--pi-text) 30%))}.ui-transcript-activity>.ui-transcript-heading{box-sizing:border-box;background:var(--ui-transcript-heading-bg);min-height:32px;color:var(--pi-text);padding:6px 12px;line-height:20px}.ui-transcript-activity>summary.ui-transcript-heading:hover{background:color-mix(in srgb, var(--ui-activity-tone) 26%, var(--pi-bg))}.ui-transcript-disclosure{box-sizing:border-box;background:var(--ui-transcript-heading-bg,transparent);cursor:pointer;border:0;border-radius:0;align-items:center;gap:8px;min-height:32px;padding:6px 12px;line-height:20px;list-style:none;display:flex}.ui-transcript-disclosure::-webkit-details-marker{display:none}.ui-transcript-disclosure:before{content:"";border:4px solid #0000;border-inline-start:5px solid;border-inline-end-width:3px;flex:none;width:0;height:0}details[open]>.ui-transcript-disclosure:before{border:4px solid #0000;border-block-start:5px solid;border-block-end-width:3px}.ui-transcript-disclosure:hover{background:var(--pi-surface-hover)}.ui-transcript-disclosure:focus-visible{outline:2px solid var(--pi-accent);outline-offset:-2px}.ui-transcript-activity .ui-transcript-disclosure:focus-visible{outline-color:var(--pi-text)}`),Ph=me(`.chat-jumps{gap:0;display:flex}.chat-jumps button{box-sizing:border-box;width:28px;height:28px;color:var(--pi-muted);font:14px/1 var(--pi-font,system-ui, sans-serif);cursor:pointer;background:0 0;border:0;border-radius:0;place-items:center;padding:0;display:inline-grid;position:relative}.chat-jumps button.following{color:var(--pi-accent)}.chat-jumps button.following:after{content:"";pointer-events:none;background:currentColor;border-radius:50%;width:3px;height:3px;position:absolute;bottom:3px;left:calc(50% - 1.5px)}.chat-jumps button:hover,.chat-jumps button:focus-visible{color:var(--pi-text-bright);background:var(--pi-selection-bg)}.chat-jumps button:focus-visible{outline:2px solid var(--pi-accent);outline-offset:-2px}.chat-follow-state{clip-path:inset(50%);white-space:nowrap;border:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}`),Fh=T`
|
|
137
137
|
${de}
|
|
138
138
|
${ie}
|
|
139
|
-
${
|
|
140
|
-
${
|
|
139
|
+
${Nh}
|
|
140
|
+
${Ph}
|
|
141
141
|
@layer pi-web-base {
|
|
142
142
|
:host { position: relative; z-index: 0; display: flex; flex-direction: column; min-width: 0; min-height: 0; overflow: visible; color: var(--pi-text); font: 14px var(--pi-font, system-ui, sans-serif); }
|
|
143
143
|
.chat-wrap { --pi-chat-jump-size: 28px; position: relative; flex: 1 1 0; min-width: 0; min-height: 0; max-height: 100%; overflow: hidden; display: flex; flex-direction: column; }
|
|
@@ -302,7 +302,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
302
302
|
pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; direction: ltr; text-align: left; unicode-bidi: isolate; }
|
|
303
303
|
.shell-output { color: var(--pi-text); font: 13px var(--pi-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); line-height: 1.45; direction: ltr; text-align: left; unicode-bidi: isolate; }
|
|
304
304
|
}
|
|
305
|
-
`,
|
|
305
|
+
`,Ih=me(`:host{display:block}.formatted{white-space:normal;overflow-wrap:anywhere;text-align:start;unicode-bidi:plaintext;line-height:1.45}p,ul,ol,pre,blockquote,.table-scroll,.code-block-wrapper,.plain-code-block{margin:0 0 10px}:is(p,ul,ol,pre,blockquote,.table-scroll,.code-block-wrapper,.plain-code-block):last-child{margin-bottom:0}pre,blockquote,.table-scroll,.code-block-wrapper,.plain-code-block{clear:both}.plain-code-block{white-space:pre-wrap}ul,ol{padding-left:22px}li+li{margin-top:3px}code{background:var(--pi-surface-hover);font:13px var(--pi-mono,ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);text-align:left;direction:ltr;unicode-bidi:isolate;border:0;border-radius:3px;padding:1px 4px}.code-block-wrapper>:is(pre,.plain-code-block){background:0 0;border:0;border-radius:0 0 7px 7px;margin:0;padding:12px}pre{border:1px solid var(--pi-border);background:var(--pi-bg);white-space:pre-wrap;text-align:left;direction:ltr;unicode-bidi:isolate;border-radius:8px;padding:10px;overflow:visible}.code-blocks-scroll :is(pre,.plain-code-block){white-space:pre;overflow-wrap:normal;overflow:auto hidden}pre code{background:0 0;border:0;padding:0}blockquote{border-left:3px solid var(--formatted-muted-color,var(--pi-border));color:var(--formatted-muted-color,var(--pi-muted));padding-left:10px}img{max-width:100%;height:auto}a{color:var(--formatted-link-color,var(--pi-accent))}h1,h2,h3,h4{margin:14px 0 8px;line-height:1.2}h1:first-child,h2:first-child,h3:first-child,h4:first-child{margin-top:0}h1{font-size:20px}h2{font-size:17px}h3{font-size:15px}h4{font-size:14px}.table-scroll{overscroll-behavior-x:contain;-webkit-overflow-scrolling:touch;max-width:100%;overflow:auto hidden}.table-scroll:focus-visible{outline:1px solid var(--pi-accent);outline-offset:2px}table{--formatted-table-bg:color-mix(in srgb, var(--pi-text) 4%, var(--ui-transcript-bg,var(--pi-bg)));border-collapse:collapse;background:var(--formatted-table-bg);width:max-content;min-width:100%;max-width:none}th,td{border:1px solid var(--pi-border);overflow-wrap:anywhere;max-width:48ch;padding:4px 8px}th{background:color-mix(in srgb, var(--pi-text) 4%, var(--formatted-table-bg))}`),Lh=T`
|
|
306
306
|
.editor-input:has(.editor-chat-navigation) .cm-content { min-height: max(50px, 2.8em); padding-right: 66px; }
|
|
307
307
|
.markdown-editor .cm-editor { box-sizing: border-box; width: 100%; min-height: 54px; max-height: 220px; resize: none; overflow: hidden; border-radius: 0; border: 0; background: var(--pi-bg); color: var(--pi-text); font: var(--pi-control-font-size, 16px)/1.4 var(--pi-control-font-family, var(--pi-font, system-ui, sans-serif)); padding-block: 12px; }
|
|
308
308
|
.markdown-editor .cm-scroller { max-height: 196px; overflow-y: auto; font-family: var(--pi-control-font-family, var(--pi-font, system-ui, sans-serif)); line-height: 1.4; }
|
|
@@ -322,7 +322,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
322
322
|
.markdown-editor .cm-editor.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground { background: color-mix(in srgb, var(--pi-accent) 32%, transparent); }
|
|
323
323
|
.shell-mode .markdown-editor .cm-editor { background: var(--pi-success-bg); }
|
|
324
324
|
.markdown-editor-disabled .cm-editor { opacity: .5; cursor: not-allowed; }
|
|
325
|
-
`,
|
|
325
|
+
`,Rh=T`0 8px 18px -8px var(--pi-shadow-soft)`,zh=T`
|
|
326
326
|
@layer pi-web-base {
|
|
327
327
|
/* Mobile browsers already subtract browser controls from 100dvh; reserve bottom safe area only in standalone PWA modes. */
|
|
328
328
|
: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 var(--pi-font, system-ui, sans-serif); }
|
|
@@ -418,7 +418,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
418
418
|
.deprecation-notice .deprecation-notice-text { margin: 0; overflow-wrap: anywhere; }
|
|
419
419
|
.deprecation-notice .deprecation-notice-text + .deprecation-notice-text { margin-top: 4px; }
|
|
420
420
|
}
|
|
421
|
-
`,
|
|
421
|
+
`,Bh=T`
|
|
422
422
|
${de}
|
|
423
423
|
${ie}
|
|
424
424
|
${g}
|
|
@@ -454,7 +454,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
454
454
|
.workspace-label-link { color: var(--pi-accent); text-decoration: none; }
|
|
455
455
|
.workspace-label-link:hover, .workspace-label-link:focus { text-decoration: underline; }
|
|
456
456
|
}
|
|
457
|
-
`,
|
|
457
|
+
`,Vh=T`
|
|
458
458
|
${de}
|
|
459
459
|
${ie}
|
|
460
460
|
${f}
|
|
@@ -464,7 +464,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
464
464
|
section { box-sizing: border-box; flex: 1 1 auto; min-height: 0; display: flex; flex-direction: column; padding: 0; }
|
|
465
465
|
h2 { flex: 0 0 auto; margin: 0; color: var(--pi-muted); font-size: 12px; text-transform: uppercase; }
|
|
466
466
|
h2.ui-toolbar { border-bottom: 1px solid var(--pi-border-muted); }
|
|
467
|
-
section > h2 { position: relative; z-index: 3; background: var(--pi-bg); box-shadow: ${
|
|
467
|
+
section > h2 { position: relative; z-index: 3; background: var(--pi-bg); box-shadow: ${Rh}; }
|
|
468
468
|
.list-body { flex: 1 1 auto; min-height: 0; overflow: auto; }
|
|
469
469
|
.subheading { margin-top: 14px; }
|
|
470
470
|
.section-toggle { width: 100%; gap: 8px; }
|
|
@@ -523,7 +523,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
523
523
|
.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; }
|
|
524
524
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
525
525
|
}
|
|
526
|
-
`,
|
|
526
|
+
`,Hh=T`
|
|
527
527
|
@layer pi-web-base {
|
|
528
528
|
:host { display: block; color: var(--pi-muted); font: 12px var(--pi-font, system-ui, sans-serif); }
|
|
529
529
|
.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; }
|
|
@@ -538,7 +538,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
538
538
|
.muted { color: var(--pi-dim); }
|
|
539
539
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
540
540
|
}
|
|
541
|
-
`,
|
|
541
|
+
`,Uh=T`
|
|
542
542
|
@layer pi-web-base {
|
|
543
543
|
:host { display: block; }
|
|
544
544
|
.menu { overflow: auto; padding: 0; color: var(--pi-text); border: 1px solid var(--pi-border); border-radius: 8px; background: var(--pi-surface); box-shadow: 0 10px 30px var(--pi-shadow); }
|
|
@@ -550,11 +550,11 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
550
550
|
.detail { color: var(--pi-muted); font-size: 12px; }
|
|
551
551
|
small { grid-column: 1 / -1; color: var(--pi-muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
552
552
|
}
|
|
553
|
-
`,
|
|
553
|
+
`,Wh=T`
|
|
554
554
|
${de}
|
|
555
555
|
${f}
|
|
556
556
|
${ie}
|
|
557
|
-
${
|
|
557
|
+
${Ph}
|
|
558
558
|
@layer pi-web-base {
|
|
559
559
|
:host { position: relative; display: block; color: var(--pi-text); font: 14px var(--pi-font, system-ui, sans-serif); }
|
|
560
560
|
footer { display: grid; grid-template-columns: minmax(0, 1fr); gap: 0; padding: 0; border-top: 1px solid var(--pi-border); }
|
|
@@ -600,7 +600,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
600
600
|
.attachment-error { flex-basis: 100%; color: var(--pi-danger); font-size: 12px; }
|
|
601
601
|
textarea:disabled { opacity: .5; cursor: not-allowed; }
|
|
602
602
|
}
|
|
603
|
-
`,
|
|
603
|
+
`,Gh=T`${Wh}${Lh}`;function Kh(e,t){return e===`error`?Bt`
|
|
604
604
|
<svg class=${t} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
605
605
|
<circle cx="12" cy="12" r="10"></circle>
|
|
606
606
|
<path d="m15 9-6 6"></path>
|
|
@@ -618,7 +618,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
618
618
|
<path d="M12 9v4"></path>
|
|
619
619
|
<path d="M12 17h.01"></path>
|
|
620
620
|
</svg>
|
|
621
|
-
`}function Wh(e,t){if(!Yh(e))throw t();let n=e.status,r=Kh(e.exitCode),i=qh(e.startedAt),a=qh(e.completedAt);if(typeof e.id!=`string`||typeof e.origin!=`string`||typeof e.projectId!=`string`||typeof e.workspaceId!=`string`||typeof e.terminalId!=`string`||typeof e.title!=`string`||typeof e.command!=`string`||n!==`queued`&&n!==`running`&&n!==`succeeded`&&n!==`failed`||r===Gh||typeof e.createdAt!=`string`||i===Gh||a===Gh||!Jh(e.metadata))throw t();return{id:e.id,origin:e.origin,projectId:e.projectId,workspaceId:e.workspaceId,terminalId:e.terminalId,title:e.title,command:e.command,status:n,...r===void 0?{}:{exitCode:r},createdAt:e.createdAt,...i===void 0?{}:{startedAt:i},...a===void 0?{}:{completedAt:a},metadata:{...e.metadata}}}var Gh=Symbol(`invalid optional Terminal field`);function Kh(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:Gh}function qh(e){if(e!==void 0)return typeof e==`string`?e:Gh}function Jh(e){return Yh(e)&&Object.values(e).every(e=>typeof e==`string`)}function Yh(e){return typeof e==`object`&&!!e}var Xh=Object.freeze({pluginId:`pi-web.terminal`,id:`browser-facade`,version:1,parse:Qh}),Zh=class extends Error{constructor(...e){super(...e),this.name=`RequiredTerminalBrowserUnavailableError`}};function Qh(e){if(!rg(e)||e.version!==1)throw Error(`Required Terminal browser entry did not provide facade v1`);let t=e.createWorkspaceTerminal,n=e.listCommandRuns,r=e.parseCommandRun;if(typeof t!=`function`||typeof n!=`function`||typeof r!=`function`)throw Error(`Required Terminal browser entry did not provide facade v1`);let i={version:1,createWorkspaceTerminal(n){let r=Reflect.apply(t,e,[n]);if(!rg(r))throw Error(`Required Terminal browser facade returned an invalid workspace terminal`);let i=r.open,a=r.runCommand;if(typeof i!=`function`||typeof a!=`function`)throw Error(`Required Terminal browser facade returned an invalid workspace terminal`);return Object.freeze({open:e=>{Reflect.apply(i,r,[e])},runCommand:e=>Promise.resolve(Reflect.apply(a,r,[e])).then(eg)})},async listCommandRuns(t){let r=await Reflect.apply(n,e,[t]);if(!Array.isArray(r))throw Error(`Required Terminal browser facade returned an invalid command-run list`);return r.map(e=>i.parseCommandRun(e))},parseCommandRun(t){return tg(Reflect.apply(r,e,[t]))}};return Object.freeze(i)}function $h(e){return new Zh(e===`local`?D(`ui.main.9ff7a30a5924`,`Required Terminal plugin is unavailable. Open Settings for recovery guidance.`):D(`ui.main.cddadc4e8321`,`The required terminal plugin is unavailable on machine {arg0}. Open settings for recovery guidance.`,{arg0:e}))}function eg(e){if(!rg(e)||!(e.completed instanceof Promise))throw Error(`Required Terminal browser facade returned an invalid command-run handle`);return Object.freeze({run:tg(e.run),completed:e.completed.then(tg)})}function tg(e){return Wh(e,ng)}function ng(){return Error(`Required Terminal browser facade returned an invalid command run`)}function rg(e){return typeof e==`object`&&!!e}var ig=class{constructor(e,t,n=()=>!0){this.registerPlugins=e,this.shouldLoadRemotePlugin=t,this.shouldLoadGatewayPlugin=n,this.loadedMachineIds=new Set,this.machineLoads=new Map}ensureGatewayLoaded(){return this.gatewayLoad??=this.registerPlugins(D(`client.machinePluginLoadCoordinator.pi.web.plugins.54b78f`,`PI WEB plugins`),async()=>{let e=await ag();return Zt(`pi-web-plugins/manifest.json`,{...e===void 0?{}:{manifest:e},shouldLoadPlugin:e=>(!Gt()||e.id!==`pi-web.terminal`)&&this.shouldLoadGatewayPlugin(e.id,e.machineSpecific)})}).then(e=>(e||(this.gatewayLoad=void 0),e)),this.gatewayLoad}invalidateMachine(e){this.loadedMachineIds.delete(e)}async loadForMachine(e){if(await this.ensureGatewayLoaded(),e.kind!==`remote`||this.loadedMachineIds.has(e.id))return;let t=this.machineLoads.get(e.id);if(t!==void 0)return t;let n=this.registerPlugins(D(`client.machinePluginLoadCoordinator.pi.web.plugins.from.cf3236`,`PI WEB plugins from {value1}`,{value1:e.name}),()=>Zt(`api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.shouldLoadRemotePlugin(e.id,e.machineSpecific)}),e.id).then(t=>{t&&this.loadedMachineIds.add(e.id)}).finally(()=>{this.machineLoads.delete(e.id)});this.machineLoads.set(e.id,n),await n}};async function ag(){if(!Gt())return;let e=await kt.plugins();if(e.serverRuntime.status!==`available`)throw Error(e.serverRuntime.message??D(`ui.main.78c257936052`,`PI WEB plugin runtime unavailable`));let t=e.plugins.flatMap(e=>!e.enabled||e.module===void 0||e.server!==void 0&&(e.server.state!==`active`||e.server.staleRevision||e.server.health?.status===`unhealthy`)?[]:[{id:e.id,module:e.module,source:e.source,scope:e.scope,machineSpecific:e.machineSpecific,...e.backendRevision===void 0?{}:{backendRevision:e.backendRevision},...e.pairedRequestVersion===void 0?{}:{pairedRequestVersion:e.pairedRequestVersion},...e.pairedChannelVersion===void 0?{}:{pairedChannelVersion:e.pairedChannelVersion}}]);return{lifecycleVersion:e.lifecycleVersion,terminalMode:e.serverRuntime.terminalMode,plugins:t}}var og=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function sg(){return typeof window>`u`||!(`matchMedia`in window)?[]:og.map(e=>window.matchMedia(e))}function cg(e,t=lg()){return e.some(e=>e.matches)||ug(t)}function lg(){return typeof navigator>`u`?void 0:navigator}function ug(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var dg=class{constructor(e=fg()){this.scheduler=e}repair(e){e?(this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},250)):this.clear()}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);let e=this.scheduler.documentElement;e!==void 0&&(e.scrollTop=0);let t=this.scheduler.body;t!==void 0&&(t.scrollTop=0)}};function fg(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>`u`?void 0:document.documentElement},get body(){return typeof document>`u`?void 0:document.body}}}var pg=class{constructor(e,t={}){this.host=e,this.onDesktopSideBySideMediaChange=e=>{this.isDesktopSideBySideLayout!==e.matches&&(this.isDesktopSideBySideLayout=e.matches,this.host.requestUpdate())},this.onMobileNavigationMediaChange=e=>{this.isMobileNavigationLayout!==e.matches&&(this.isMobileNavigationLayout=e.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{let e=cg(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.desktopSideBySideMedia=t.desktopSideBySideMedia??mg(`(min-width: 1181px)`),this.isDesktopSideBySideLayout=this.desktopSideBySideMedia?.matches??!0,this.mobileNavigationMedia=t.mobileNavigationMedia??mg(`(max-width: 760px)`),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??sg(),this.viewportPositionRepairer=t.viewportPositionRepairer??new dg,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=cg(this.pwaDisplayModeMedia)}hostConnected(){this.desktopSideBySideMedia?.addEventListener(`change`,this.onDesktopSideBySideMediaChange),this.mobileNavigationMedia?.addEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.addEventListener(`change`,this.onPwaDisplayModeChange)}hostDisconnected(){this.desktopSideBySideMedia?.removeEventListener(`change`,this.onDesktopSideBySideMediaChange),this.mobileNavigationMedia?.removeEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.removeEventListener(`change`,this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.isMobileNavigationLayout?`navigation`:`chat`}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function mg(e){if(typeof window<`u`&&`matchMedia`in window)return window.matchMedia(e)}var hg=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new gr,this.connected=!1,this.connectionEpoch=0,this.onResume=()=>{this.handleResumeSignal()},this.windowTarget=t.windowTarget??gg(),this.documentTarget=t.documentTarget??_g(),this.isDocumentVisible=t.isDocumentVisible??vg,this.scheduleFrame=t.scheduleFrame??yg}connect(){if(!this.connected){this.connected=!0,this.connectionEpoch+=1,this.refreshes=new gr;for(let e of[`focus`,`pageshow`,`online`])this.windowTarget?.addEventListener(e,this.onResume);this.documentTarget?.addEventListener(`visibilitychange`,this.onResume)}}disconnect(){if(this.connected){this.connected=!1,this.connectionEpoch+=1;for(let e of[`focus`,`pageshow`,`online`])this.windowTarget?.removeEventListener(e,this.onResume);this.documentTarget?.removeEventListener(`visibilitychange`,this.onResume),this.scheduledRefresh?.cancel(),this.scheduledRefresh=void 0}}handleResumeSignal(){if(!this.connected||!this.isDocumentVisible()||(this.callbacks.onResumeSignal(),this.scheduledRefresh!==void 0))return;let e=this.connectionEpoch,t=this.refreshes,n=()=>this.connected&&e===this.connectionEpoch;this.scheduledRefresh=this.scheduleFrame(()=>{n()&&(this.scheduledRefresh=void 0,t.request(`browser-resume`,async()=>{n()&&this.isDocumentVisible()&&await this.callbacks.refreshAfterResume()}).catch(e=>{n()&&this.callbacks.onRefreshError(e)}))})}};function gg(){return typeof window>`u`?void 0:window}function _g(){return typeof document>`u`?void 0:document}function vg(){return typeof document>`u`||document.visibilityState===`visible`}function yg(e){if(typeof window<`u`&&typeof window.requestAnimationFrame==`function`){let t=window.requestAnimationFrame(()=>{e()});return{cancel:()=>{window.cancelAnimationFrame(t)}}}let t=globalThis.setTimeout(e,0);return{cancel:()=>{globalThis.clearTimeout(t)}}}var bg=[`machines`,`projects`,`workspaces`,`sessions`];function xg(e){return e.selectedProject===void 0?`projects`:e.selectedWorkspace===void 0&&e.workspaceSelectionVisible!==!1?`workspaces`:`sessions`}function Sg(e,t){if(e!==`none`)return e===`workspaces`&&t.workspaceSelectionVisible===!1?`sessions`:e??xg(t)}function Cg(e,t){return t.isMobileLayout?Sg(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function wg(e,t,n){return n.isMobileLayout?Sg(e,n.state)===t?`none`:t:e}function Tg(e,t,n){return n?t:e}function Eg(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),kg(n)}function Dg(e){return bg[bg.indexOf(e)+1]}var Og=class{hostConnected(){}constructor(e,t,n){this.host=e,this.getState=t,this.isMobileLayout=n,this.collapsedSections=[],e.addController(this)}expandedSection(){return Sg(this.expanded,this.getState())}isCollapsed(e){return Cg(e,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(e){this.isMobileLayout()?this.setExpanded(wg(this.expanded,e,{isMobileLayout:!0,state:this.getState()})):this.setCollapsedSections(Eg(this.collapsedSections,e))}expand(e){this.isMobileLayout()?this.setExpanded(Tg(this.expanded,e,!0)):this.setCollapsedSections(this.collapsedSections.filter(t=>t!==e))}advanceAfterSelection(e){if(!this.isMobileLayout())return;let t=e===`projects`&&this.getState().workspaceSelectionVisible===!1?`sessions`:Dg(e);t!==void 0&&this.expand(t)}open(e,t){this.isMobileLayout()&&(this.expand(e),t())}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}setCollapsedSections(e){Ag(this.collapsedSections,e)||(this.collapsedSections=e,this.host.requestUpdate())}};function kg(e){let t=new Set(e);return bg.filter(e=>t.has(e))}function Ag(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var jg=`pi-web:panel-collapse:v1`,Mg=class{hostConnected(){}constructor(e,t={}){this.host=e,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,e.addController(this),this.storage=t.storage??Pg();try{let e=this.storage?.getItem(jg);if(e==null||e===``)return;let t=JSON.parse(e);if(typeof t!=`object`||!t||!(`version`in t)||t.version!==1)return;this.navigationPanelCollapsed=`navigationPanelCollapsed`in t&&t.navigationPanelCollapsed===!0,this.workspacePanelCollapsed=`workspacePanelCollapsed`in t&&t.workspacePanelCollapsed===!0}catch(e){console.warn(`Could not restore panel collapse preferences`,e)}}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.persistAndUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.persistAndUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.persistAndUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.persistAndUpdate())}persistAndUpdate(){try{this.storage?.setItem(jg,JSON.stringify({version:1,navigationPanelCollapsed:this.navigationPanelCollapsed,workspacePanelCollapsed:this.workspacePanelCollapsed}))}catch(e){console.warn(`Could not save panel collapse preferences`,e)}this.host.requestUpdate()}shellClass(e){return[`shell`,Ng(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...this.workspacePanelCollapsed?[`workspace-panel-collapsed`]:[]].join(` `)}};function Ng(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}function Pg(){try{return typeof window>`u`?void 0:window.localStorage}catch(e){console.warn(`Panel collapse storage is unavailable`,e);return}}var Fg=`pi-web:panel-sizes:v1`,Ig={navigation:{minWidth:260,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},Lg=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??Zg(),this.panelSizes=Ug(this.storage)}hostConnected(){}constraints(e){return Rg(e)}panelWidth(e,t){return Hg(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=Hg(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=qg(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=Jg(this.panelSizes,e),t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(e={}){(this.panelSizes.navigationPanelWidth!==void 0||this.panelSizes.workspacePanelWidth!==void 0)&&(this.panelSizes={},e.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){Wg(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${Xg(Hg(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${Xg(Hg(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function Rg(e){return Ig[e]}function zg(e,t,n){return e===`navigation`?n-t:t-n}function Bg(e,t,n,r,i=Rg(e)){return Hg(e,t+zg(e,n,r),i)}function Vg(e,t,n,r={}){let i=r.constraints??Rg(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=Yg(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return Hg(e,t+a,i)}function Hg(e,t,n=Rg(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function Ug(e=Zg()){try{let t=e?.getItem(Fg);return t==null||t===``?{}:Gg(JSON.parse(t))}catch{return{}}}function Wg(e,t=Zg()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Fg);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=Hg(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=Hg(`workspace`,e.workspacePanelWidth)),t.setItem(Fg,JSON.stringify(n))}catch{}}function Gg(e){if(!Qg(e)||e.version!==1)return{};let t={},n=Kg(e.navigationPanelWidth),r=Kg(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=Hg(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=Hg(`workspace`,r)),t}function Kg(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function qg(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function Jg(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Yg(e,t,n){if(e===`navigation`)return t===`ArrowRight`?n:t===`ArrowLeft`?-n:void 0;if(t===`ArrowLeft`)return n;if(t===`ArrowRight`)return-n}function Xg(e){return`${String(Math.round(e))}px`}function Zg(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function Qg(e){return typeof e==`object`&&!!e}var $g=`pi-web:navigation-preferences`;function e_(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function t_(e=e_()){try{let t=JSON.parse(e?.getItem($g)??`null`);if(typeof t==`object`&&t){let e=`pinnedIds`in t?t.pinnedIds:void 0;return{pinnedIds:Array.isArray(e)?[...new Set(e.filter(e=>typeof e==`string`&&e.length>0))]:[],mobileCollapsed:`mobileCollapsed`in t&&t.mobileCollapsed===!0}}}catch{}return{pinnedIds:[],mobileCollapsed:!1}}function n_(e,t=e_()){try{t?.setItem($g,JSON.stringify(e))}catch{}}function r_(e,t){return t.length===0||t.includes(e)}function i_(e,t){return e.filter(e=>r_(e.id,t))}function a_(e,t,n){return n!==void 0&&e.some(e=>e.id===n)&&!t.some(e=>e.id===n)}function o_(e,t,n){let r=t.length===0?n:t;return r.includes(e)?r.filter(t=>t!==e):[...r,e]}function s_(){return l_(new URLSearchParams(window.location.search).get(`settings`))}function c_(e,t){let n=new URL(window.location.href);e===void 0?n.searchParams.delete(`settings`):n.searchParams.set(`settings`,e),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function l_(e){if(e===`general`)return`general`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`mcp`)return`mcp`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`}function u_(e,t){return t===void 0?e:e.map(e=>f_(e,t))}function d_(e,t){let n=new Set(pe(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return u_(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?p_(e):e)}function f_(t,n){let r=e(t,n);return r===void 0?t:r===null?p_(t):{...t,shortcut:r}}function p_(e){let t={...e};return delete t.shortcut,t}function m_(e,t){let n=t.api??Dt,r=t.pollIntervalMs??1e3,i=t.setTimeout??__(),a=t.clearTimeout??v_();return{async runCommand(o){let s=await n.runTerminalCommand(e,o);return o.open===!0&&t.openTerminal(o.workspace,{terminalId:s.terminalId}),{run:s,completed:h_(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function h_(e,t,n,r,i){return g_(e)?Promise.resolve(e):new Promise((a,o)=>{let s,c=!1,l=e=>{c||(c=!0,s!==void 0&&i(s),a(e))},u=e=>{c||(c=!0,s!==void 0&&i(s),o(e instanceof Error?e:Error(String(e))))},d=()=>{t.getCommandRun(e.id).then(e=>{e!==void 0&&g_(e)?l(e):s=r(d,n)}).catch(u)};s=r(d,n)})}function g_(e){return e.status===`succeeded`||e.status===`failed`}function __(){return(e,t)=>globalThis.setTimeout(e,t)}function v_(){return e=>{globalThis.clearTimeout(e)}}function y_(e,t=D(`ui.activityBadge.active`,`Active`),n){if(e===void 0)return n===void 0?void 0:E`<span class="activity-indicator unread" role="img" aria-label=${n} title=${n}></span>`;if(n===void 0)return E`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`;let r=`${n} · ${t}`;return E`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`activity-indicator ${e}`} aria-hidden="true"></span></span>`}function b_(e,t=D(`ui.activityBadge.active`,`Active`),n){let r=y_(e,t,n);if(r!==void 0)return E`<span class="action-activity">${r}</span>`}function x_(e){if(e!==void 0)return e[re.working]===!0?`session`:e[re.terminal]===!0?`terminal`:Object.entries(e).some(([e,t])=>t&&e!==re.unread)?`session`:void 0}function S_(e){return e?.[re.unread]===!0}var C_=[],w_=class{constructor(e,t){this.host=e,this.getPopup=t,this.cleanups=[],this.close=()=>{let e=this.current;e&&(this.stop(),e.onClose())},this.scheduleRefresh=()=>{this.frame??=requestAnimationFrame(this.onFrame)},this.onFrame=()=>{this.frame=void 0,this.refresh()},e.addController(this)}hostConnected(){this.host.requestUpdate()}hostUpdated(){let e=this.getPopup();(e?.panel!==this.current?.panel||e?.anchor!==this.current?.anchor)&&(this.stop(),e?.anchor.isConnected===!0&&e.panel.isConnected&&this.start(e)),this.refresh()}hostDisconnected(){this.close()}dismiss(){let e=this.current;e&&(this.stop(!1),e.onClose())}start(e){if(!St(e.anchor)){e.onClose();return}this.current=e;let{panel:t,anchor:n,options:r}=e;t.setAttribute(`popover`,`auto`),Object.assign(t.style,{position:`fixed`,inset:`auto`,margin:`0`,zIndex:`auto`,boxSizing:`border-box`,minWidth:`0`});let i=(e,t,n,r=!1)=>{e.addEventListener(t,n,r),this.cleanups.push(()=>{e.removeEventListener(t,n,r)})},a=e=>{`newState`in e&&e.newState===`closed`&&this.dismiss()};i(t,`beforetoggle`,a),i(t,`toggle`,a),i(window,`keydown`,e=>{e instanceof KeyboardEvent&&e.key===`Escape`&&!e.isComposing&&C_.at(-1)===this&&(e.preventDefault(),e.stopImmediatePropagation(),this.close(),r?.preserveFocus!==!0&&n.focus())},!0),i(window,`resize`,this.scheduleRefresh),i(window,`scroll`,this.scheduleRefresh,!0),window.visualViewport&&(i(window.visualViewport,`resize`,this.scheduleRefresh),i(window.visualViewport,`scroll`,this.scheduleRefresh));let o=typeof ResizeObserver>`u`?void 0:new ResizeObserver(this.scheduleRefresh);o&&(o.observe(n),o.observe(t),this.cleanups.push(()=>{o.disconnect()}));let s=n;for(;;){let e=s.getRootNode();if(!(e instanceof ShadowRoot))break;i(e,`scroll`,this.scheduleRefresh,!0),o?.observe(e.host),s=e.host}this.cleanups.push(We(n,this.close)),C_.push(this),this.refresh();let c=r?.preserveFocus===!0?n.getRootNode():void 0,l=c instanceof ShadowRoot?c.activeElement:document.activeElement;t.showPopover({source:n}),r?.preserveFocus===!0&&l instanceof HTMLElement&&l.focus({preventScroll:!0})}stop(e=!0){let t=this.current;this.current=void 0;for(let e of this.cleanups.splice(0))e();let n=C_.indexOf(this);n>=0&&C_.splice(n,1),this.frame!==void 0&&cancelAnimationFrame(this.frame),this.frame=void 0,t&&e&&t.panel.hidePopover()}refresh(){let e=this.current;if(!e)return;if(!St(e.anchor)||!e.panel.isConnected){this.close();return}let t=T_(e.anchor,e.options,e.panel);for(let[n,r]of Object.entries(t))e.panel.style.setProperty(n,r)}};function T_(e,t={},n){let r=e.getBoundingClientRect(),i=window.visualViewport,a=t.padding??0,o=(i?.offsetLeft??0)+a,s=(i?.offsetTop??0)+a,c=(i?.offsetLeft??0)+(i?.width??window.innerWidth)-a,l=(i?.offsetTop??0)+(i?.height??window.innerHeight)-a,u=t.gap??0,d=(e,t,n)=>Math.min(n,Math.max(t,e)),f=e=>`${String(Math.round(Math.max(0,e)))}px`,p=d(r.top,s,l),m=d(r.bottom,s,l),h=d(r.right,o,c),g=d(r.left,o,c),ee=t.placement??(n===void 0?void 0:window.getComputedStyle(n).getPropertyValue(`--ui-popup-placement`).trim()),_={top:`auto`,bottom:`auto`,left:`auto`,right:`auto`,width:`max-content`};if(ee===`left-end`){let e=Math.max(0,g-o-u);return _[`max-width`]=f(e),_[`min-width`]=f(Math.min(t.minWidth??0,e)),_[`max-height`]=f(l-s),_.right=f(window.innerWidth-g+u),_.top=f(d(r.bottom-(n?.getBoundingClientRect().height??0),s,l-(n?.getBoundingClientRect().height??0))),_}let te=Math.max(0,l-m-u),ne=Math.max(0,p-s-u),re=ee===`above-start`,ie=n?.scrollHeight??0,ae=Math.min(t.maxHeight??120,ie>0?ie:120),v=re?!(ne<ae&&te>ne):te<ae&&ne>te;_[v?`bottom`:`top`]=f(v?window.innerHeight-p+u:m+u),_[`max-height`]=f(Math.min(t.maxHeight??1/0,v?ne:te));let oe=ee===`below-start`||re,se=t.width===`anchor`?r.width:t.width;if(oe){let e=d(g,o,se===void 0?c:Math.max(o,c-se));_.left=f(e),_[`max-width`]=f(c-e),_[`min-width`]=f(Math.min(t.minWidth??0,c-e))}else _.right=f(window.innerWidth-h),_[`max-width`]=f(h-o),_[`min-width`]=f(Math.min(t.minWidth??0,h-o));return se!==void 0&&(_.width=f(Math.min(se,c-o))),_}var E_=class{constructor(e){this.host=e,this.menuStyle=``,e.addController(this),new w_(e,()=>{let t=e.shadowRoot?.querySelector(`.action-menu-panel`);return this.openId!==void 0&&this.anchor!==void 0&&t?{anchor:this.anchor,panel:t,onClose:()=>{this.close()},options:{minWidth:120}}:void 0})}hostDisconnected(){this.close()}isOpen(e){return this.openId===e}toggle(e,t){this.openId===e?this.close():(this.anchor=t instanceof HTMLElement?t:void 0,this.openId=e,this.host.requestUpdate())}close(){(this.openId!==void 0||this.menuStyle!==``)&&(this.openId=void 0,this.menuStyle=``,this.anchor=void 0,this.host.requestUpdate())}closeIfOpenIdMissing(e){this.openId!==void 0&&!e(this.openId)&&this.close()}closeIf(e){e&&this.close()}closeForEscape(e,t){return e.key!==`Escape`||this.openId!==t?!1:(e.preventDefault(),e.stopPropagation(),this.close(),!0)}},D_=`a[href],button,input,select,textarea,summary,[role='button'],[role='link'],[contenteditable='true']`;function O_(e){return e.composedPath().some(e=>k_(e,D_))}function k_(e,t){if(typeof Element<`u`&&e instanceof Element)return e.matches(t);if(!(`matches`in e))return!1;let{matches:n}=e;return typeof n==`function`&&n.call(e,t)===!0}function A_(e,t){O_(e)||t()}function j_(e,t){return O_(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?N_(e,()=>{P_(e.currentTarget,-1)}):e.key===`ArrowDown`?N_(e,()=>{P_(e.currentTarget,1)}):e.key===`Home`?N_(e,()=>{F_(e.currentTarget,0)}):e.key===`End`?N_(e,()=>{F_(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?N_(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?N_(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&N_(e,t.cancel)}function M_(e,t={}){let n=e.querySelector(`.action-row.selected`)??e.querySelector(`.action-row`)??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return n!=null&&(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}function N_(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function P_(e,t){let n=L_(e),r=z_(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||I_(n,i+t)}function F_(e,t){let n=L_(e);n.length!==0&&I_(n,t<0?n.length-1:t)}function I_(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function L_(e){let t=z_(e)?.getRootNode();return t===void 0||!R_(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function R_(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function z_(e){if(typeof HTMLElement<`u`&&e instanceof HTMLElement)return e.closest(`.action-row`)??void 0}var B_=me(`section>h2.ui-toolbar{background:var(--pi-surface);border-bottom-color:var(--pi-border);box-shadow:none}.list-body>.subheading:not(.ui-toolbar){padding-inline:10px}.action-row{border-bottom:1px solid var(--pi-border-muted);margin:0;padding:0}.action-row:last-child{border-bottom:0}.action-main{padding:10px 10px 10px calc(19px + var(--depth,0) * 16px)}.action-main,.workspace-row .action-main{background:0 0;border-color:#0000;border-radius:0}.action-row.selected{background:var(--pi-selection-bg);box-shadow:inset 3px 0 0 var(--pi-accent)}.action-row.selected .action-main{background:0 0;border-color:#0000}.action-row:not(.selected):hover{background:var(--pi-surface-hover)}.action-row:not(.selected):hover .action-main{background:0 0}.action-row:focus-visible{outline:2px solid var(--pi-accent);outline-offset:-2px;border-radius:0}`),V_=class extends O{constructor(){super(),this.machines=[],this.statuses={},this.activities={},this.unreadMachineIds=new Set,this.statusSnapshots={},this.collapsible=!1,this.collapsed=!1,this.menu=new E_(this),v.createController(this)}updated(e){e.has(`machines`)&&this.menu.closeIfOpenIdMissing(e=>this.machines.some(t=>t.id===e)),e.has(`collapsed`)&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,M_(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return E`
|
|
621
|
+
`}function qh(e,t){if(!Qh(e))throw t();let n=e.status,r=Yh(e.exitCode),i=Xh(e.startedAt),a=Xh(e.completedAt);if(typeof e.id!=`string`||typeof e.origin!=`string`||typeof e.projectId!=`string`||typeof e.workspaceId!=`string`||typeof e.terminalId!=`string`||typeof e.title!=`string`||typeof e.command!=`string`||n!==`queued`&&n!==`running`&&n!==`succeeded`&&n!==`failed`||r===Jh||typeof e.createdAt!=`string`||i===Jh||a===Jh||!Zh(e.metadata))throw t();return{id:e.id,origin:e.origin,projectId:e.projectId,workspaceId:e.workspaceId,terminalId:e.terminalId,title:e.title,command:e.command,status:n,...r===void 0?{}:{exitCode:r},createdAt:e.createdAt,...i===void 0?{}:{startedAt:i},...a===void 0?{}:{completedAt:a},metadata:{...e.metadata}}}var Jh=Symbol(`invalid optional Terminal field`);function Yh(e){if(e!==void 0)return typeof e==`number`&&Number.isFinite(e)?e:Jh}function Xh(e){if(e!==void 0)return typeof e==`string`?e:Jh}function Zh(e){return Qh(e)&&Object.values(e).every(e=>typeof e==`string`)}function Qh(e){return typeof e==`object`&&!!e}var $h=Object.freeze({pluginId:`pi-web.terminal`,id:`browser-facade`,version:1,parse:tg}),eg=class extends Error{constructor(...e){super(...e),this.name=`RequiredTerminalBrowserUnavailableError`}};function tg(e){if(!og(e)||e.version!==1)throw Error(`Required Terminal browser entry did not provide facade v1`);let t=e.createWorkspaceTerminal,n=e.listCommandRuns,r=e.parseCommandRun;if(typeof t!=`function`||typeof n!=`function`||typeof r!=`function`)throw Error(`Required Terminal browser entry did not provide facade v1`);let i={version:1,createWorkspaceTerminal(n){let r=Reflect.apply(t,e,[n]);if(!og(r))throw Error(`Required Terminal browser facade returned an invalid workspace terminal`);let i=r.open,a=r.runCommand;if(typeof i!=`function`||typeof a!=`function`)throw Error(`Required Terminal browser facade returned an invalid workspace terminal`);return Object.freeze({open:e=>{Reflect.apply(i,r,[e])},runCommand:e=>Promise.resolve(Reflect.apply(a,r,[e])).then(rg)})},async listCommandRuns(t){let r=await Reflect.apply(n,e,[t]);if(!Array.isArray(r))throw Error(`Required Terminal browser facade returned an invalid command-run list`);return r.map(e=>i.parseCommandRun(e))},parseCommandRun(t){return ig(Reflect.apply(r,e,[t]))}};return Object.freeze(i)}function ng(e){return new eg(e===`local`?D(`ui.main.9ff7a30a5924`,`Required Terminal plugin is unavailable. Open Settings for recovery guidance.`):D(`ui.main.cddadc4e8321`,`The required terminal plugin is unavailable on machine {arg0}. Open settings for recovery guidance.`,{arg0:e}))}function rg(e){if(!og(e)||!(e.completed instanceof Promise))throw Error(`Required Terminal browser facade returned an invalid command-run handle`);return Object.freeze({run:ig(e.run),completed:e.completed.then(ig)})}function ig(e){return qh(e,ag)}function ag(){return Error(`Required Terminal browser facade returned an invalid command run`)}function og(e){return typeof e==`object`&&!!e}var sg=class{constructor(e,t,n=()=>!0){this.registerPlugins=e,this.shouldLoadRemotePlugin=t,this.shouldLoadGatewayPlugin=n,this.loadedMachineIds=new Set,this.machineLoads=new Map}ensureGatewayLoaded(){return this.gatewayLoad??=this.registerPlugins(D(`client.machinePluginLoadCoordinator.pi.web.plugins.54b78f`,`PI WEB plugins`),async()=>{let e=await cg();return Zt(`pi-web-plugins/manifest.json`,{...e===void 0?{}:{manifest:e},shouldLoadPlugin:e=>(!Gt()||e.id!==`pi-web.terminal`)&&this.shouldLoadGatewayPlugin(e.id,e.machineSpecific)})}).then(e=>(e||(this.gatewayLoad=void 0),e)),this.gatewayLoad}invalidateMachine(e){this.loadedMachineIds.delete(e)}async loadForMachine(e){if(await this.ensureGatewayLoaded(),e.kind!==`remote`||this.loadedMachineIds.has(e.id))return;let t=this.machineLoads.get(e.id);if(t!==void 0)return t;let n=this.registerPlugins(D(`client.machinePluginLoadCoordinator.pi.web.plugins.from.cf3236`,`PI WEB plugins from {value1}`,{value1:e.name}),()=>Zt(`api/machines/${encodeURIComponent(e.id)}/pi-web-plugins/manifest.json`,{machineId:e.id,shouldLoadPlugin:e=>this.shouldLoadRemotePlugin(e.id,e.machineSpecific)}),e.id).then(t=>{t&&this.loadedMachineIds.add(e.id)}).finally(()=>{this.machineLoads.delete(e.id)});this.machineLoads.set(e.id,n),await n}};async function cg(){if(!Gt())return;let e=await kt.plugins();if(e.serverRuntime.status!==`available`)throw Error(e.serverRuntime.message??D(`ui.main.78c257936052`,`PI WEB plugin runtime unavailable`));let t=e.plugins.flatMap(e=>!e.enabled||e.module===void 0||e.server!==void 0&&(e.server.state!==`active`||e.server.staleRevision||e.server.health?.status===`unhealthy`)?[]:[{id:e.id,module:e.module,source:e.source,scope:e.scope,machineSpecific:e.machineSpecific,...e.backendRevision===void 0?{}:{backendRevision:e.backendRevision},...e.pairedRequestVersion===void 0?{}:{pairedRequestVersion:e.pairedRequestVersion},...e.pairedChannelVersion===void 0?{}:{pairedChannelVersion:e.pairedChannelVersion}}]);return{lifecycleVersion:e.lifecycleVersion,terminalMode:e.serverRuntime.terminalMode,plugins:t}}var lg=[`(display-mode: standalone)`,`(display-mode: fullscreen)`,`(display-mode: minimal-ui)`];function ug(){return typeof window>`u`||!(`matchMedia`in window)?[]:lg.map(e=>window.matchMedia(e))}function dg(e,t=fg()){return e.some(e=>e.matches)||pg(t)}function fg(){return typeof navigator>`u`?void 0:navigator}function pg(e){return e!==void 0&&`standalone`in e&&e.standalone===!0}var mg=class{constructor(e=hg()){this.scheduler=e}repair(e){e?(this.resetViewportScroll(),this.repairFrame!==void 0&&this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll(),this.repairFrame=this.scheduler.requestAnimationFrame(()=>{this.repairFrame=void 0,this.resetViewportScroll()})}),this.repairTimer!==void 0&&this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=this.scheduler.setTimeout(()=>{this.repairTimer=void 0,this.resetViewportScroll()},250)):this.clear()}clear(){this.repairFrame!==void 0&&(this.scheduler.cancelAnimationFrame(this.repairFrame),this.repairFrame=void 0),this.repairTimer!==void 0&&(this.scheduler.clearTimeout(this.repairTimer),this.repairTimer=void 0)}resetViewportScroll(){this.scheduler.scrollTo(0,0);let e=this.scheduler.documentElement;e!==void 0&&(e.scrollTop=0);let t=this.scheduler.body;t!==void 0&&(t.scrollTop=0)}};function hg(){return{requestAnimationFrame(e){return window.requestAnimationFrame(e)},cancelAnimationFrame(e){window.cancelAnimationFrame(e)},setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)},scrollTo(e,t){window.scrollTo(e,t)},get documentElement(){return typeof document>`u`?void 0:document.documentElement},get body(){return typeof document>`u`?void 0:document.body}}}var gg=class{constructor(e,t={}){this.host=e,this.onDesktopSideBySideMediaChange=e=>{this.isDesktopSideBySideLayout!==e.matches&&(this.isDesktopSideBySideLayout=e.matches,this.host.requestUpdate())},this.onMobileNavigationMediaChange=e=>{this.isMobileNavigationLayout!==e.matches&&(this.isMobileNavigationLayout=e.matches,this.host.requestUpdate())},this.onPwaDisplayModeChange=()=>{let e=dg(this.pwaDisplayModeMedia);this.isPwaDisplayMode!==e&&(this.isPwaDisplayMode=e,this.host.requestUpdate())},e.addController(this),this.desktopSideBySideMedia=t.desktopSideBySideMedia??_g(`(min-width: 1181px)`),this.isDesktopSideBySideLayout=this.desktopSideBySideMedia?.matches??!0,this.mobileNavigationMedia=t.mobileNavigationMedia??_g(`(max-width: 760px)`),this.pwaDisplayModeMedia=t.pwaDisplayModeMedia??ug(),this.viewportPositionRepairer=t.viewportPositionRepairer??new mg,this.isMobileNavigationLayout=this.mobileNavigationMedia?.matches??!1,this.isPwaDisplayMode=dg(this.pwaDisplayModeMedia)}hostConnected(){this.desktopSideBySideMedia?.addEventListener(`change`,this.onDesktopSideBySideMediaChange),this.mobileNavigationMedia?.addEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.addEventListener(`change`,this.onPwaDisplayModeChange)}hostDisconnected(){this.desktopSideBySideMedia?.removeEventListener(`change`,this.onDesktopSideBySideMediaChange),this.mobileNavigationMedia?.removeEventListener(`change`,this.onMobileNavigationMediaChange);for(let e of this.pwaDisplayModeMedia)e.removeEventListener(`change`,this.onPwaDisplayModeChange);this.viewportPositionRepairer.clear()}shouldAutoFocusPrompt(){return!this.isMobileNavigationLayout&&!this.isPwaDisplayMode}shouldShowAppRefreshInHeader(){return this.isPwaDisplayMode&&!this.isMobileNavigationLayout}shouldShowAppRefreshInContextBar(){return this.isPwaDisplayMode&&this.isMobileNavigationLayout}defaultRouteView(){return this.isMobileNavigationLayout?`navigation`:`chat`}repairViewportPosition(){this.viewportPositionRepairer.repair(this.shouldRepairViewportPosition())}shouldRepairViewportPosition(){return this.isMobileNavigationLayout||this.isPwaDisplayMode}};function _g(e){if(typeof window<`u`&&`matchMedia`in window)return window.matchMedia(e)}var vg=class{constructor(e,t={}){this.callbacks=e,this.refreshes=new gr,this.connected=!1,this.connectionEpoch=0,this.onResume=()=>{this.handleResumeSignal()},this.windowTarget=t.windowTarget??yg(),this.documentTarget=t.documentTarget??bg(),this.isDocumentVisible=t.isDocumentVisible??xg,this.scheduleFrame=t.scheduleFrame??Sg}connect(){if(!this.connected){this.connected=!0,this.connectionEpoch+=1,this.refreshes=new gr;for(let e of[`focus`,`pageshow`,`online`])this.windowTarget?.addEventListener(e,this.onResume);this.documentTarget?.addEventListener(`visibilitychange`,this.onResume)}}disconnect(){if(this.connected){this.connected=!1,this.connectionEpoch+=1;for(let e of[`focus`,`pageshow`,`online`])this.windowTarget?.removeEventListener(e,this.onResume);this.documentTarget?.removeEventListener(`visibilitychange`,this.onResume),this.scheduledRefresh?.cancel(),this.scheduledRefresh=void 0}}handleResumeSignal(){if(!this.connected||!this.isDocumentVisible()||(this.callbacks.onResumeSignal(),this.scheduledRefresh!==void 0))return;let e=this.connectionEpoch,t=this.refreshes,n=()=>this.connected&&e===this.connectionEpoch;this.scheduledRefresh=this.scheduleFrame(()=>{n()&&(this.scheduledRefresh=void 0,t.request(`browser-resume`,async()=>{n()&&this.isDocumentVisible()&&await this.callbacks.refreshAfterResume()}).catch(e=>{n()&&this.callbacks.onRefreshError(e)}))})}};function yg(){return typeof window>`u`?void 0:window}function bg(){return typeof document>`u`?void 0:document}function xg(){return typeof document>`u`||document.visibilityState===`visible`}function Sg(e){if(typeof window<`u`&&typeof window.requestAnimationFrame==`function`){let t=window.requestAnimationFrame(()=>{e()});return{cancel:()=>{window.cancelAnimationFrame(t)}}}let t=globalThis.setTimeout(e,0);return{cancel:()=>{globalThis.clearTimeout(t)}}}var Cg=[`machines`,`projects`,`workspaces`,`sessions`];function wg(e){return e.selectedProject===void 0?`projects`:e.selectedWorkspace===void 0&&e.workspaceSelectionVisible!==!1?`workspaces`:`sessions`}function Tg(e,t){if(e!==`none`)return e===`workspaces`&&t.workspaceSelectionVisible===!1?`sessions`:e??wg(t)}function Eg(e,t){return t.isMobileLayout?Tg(t.expanded,t.state)!==e:t.collapsedSections?.includes(e)??!1}function Dg(e,t,n){return n.isMobileLayout?Tg(e,n.state)===t?`none`:t:e}function Og(e,t,n){return n?t:e}function kg(e,t){let n=new Set(e);return n.has(t)?n.delete(t):n.add(t),Mg(n)}function Ag(e){return Cg[Cg.indexOf(e)+1]}var jg=class{hostConnected(){}constructor(e,t,n){this.host=e,this.getState=t,this.isMobileLayout=n,this.collapsedSections=[],e.addController(this)}expandedSection(){return Tg(this.expanded,this.getState())}isCollapsed(e){return Eg(e,{isMobileLayout:this.isMobileLayout(),expanded:this.expanded,state:this.getState(),collapsedSections:this.collapsedSections})}toggle(e){this.isMobileLayout()?this.setExpanded(Dg(this.expanded,e,{isMobileLayout:!0,state:this.getState()})):this.setCollapsedSections(kg(this.collapsedSections,e))}expand(e){this.isMobileLayout()?this.setExpanded(Og(this.expanded,e,!0)):this.setCollapsedSections(this.collapsedSections.filter(t=>t!==e))}advanceAfterSelection(e){if(!this.isMobileLayout())return;let t=e===`projects`&&this.getState().workspaceSelectionVisible===!1?`sessions`:Ag(e);t!==void 0&&this.expand(t)}open(e,t){this.isMobileLayout()&&(this.expand(e),t())}setExpanded(e){this.expanded!==e&&(this.expanded=e,this.host.requestUpdate())}setCollapsedSections(e){Ng(this.collapsedSections,e)||(this.collapsedSections=e,this.host.requestUpdate())}};function Mg(e){let t=new Set(e);return Cg.filter(e=>t.has(e))}function Ng(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}var Pg=`pi-web:panel-collapse:v1`,Fg=class{hostConnected(){}constructor(e,t={}){this.host=e,this.navigationPanelCollapsed=!1,this.workspacePanelCollapsed=!1,e.addController(this),this.storage=t.storage??Lg();try{let e=this.storage?.getItem(Pg);if(e==null||e===``)return;let t=JSON.parse(e);if(typeof t!=`object`||!t||!(`version`in t)||t.version!==1)return;this.navigationPanelCollapsed=`navigationPanelCollapsed`in t&&t.navigationPanelCollapsed===!0,this.workspacePanelCollapsed=`workspacePanelCollapsed`in t&&t.workspacePanelCollapsed===!0}catch(e){console.warn(`Could not restore panel collapse preferences`,e)}}toggleNavigationPanel(){this.navigationPanelCollapsed=!this.navigationPanelCollapsed,this.persistAndUpdate()}toggleWorkspacePanel(){this.workspacePanelCollapsed=!this.workspacePanelCollapsed,this.persistAndUpdate()}expandNavigationPanel(){this.navigationPanelCollapsed&&(this.navigationPanelCollapsed=!1,this.persistAndUpdate())}expandWorkspacePanel(){this.workspacePanelCollapsed&&(this.workspacePanelCollapsed=!1,this.persistAndUpdate())}persistAndUpdate(){try{this.storage?.setItem(Pg,JSON.stringify({version:1,navigationPanelCollapsed:this.navigationPanelCollapsed,workspacePanelCollapsed:this.workspacePanelCollapsed}))}catch(e){console.warn(`Could not save panel collapse preferences`,e)}this.host.requestUpdate()}shellClass(e){return[`shell`,Ig(e),...this.navigationPanelCollapsed?[`navigation-panel-collapsed`]:[],...this.workspacePanelCollapsed?[`workspace-panel-collapsed`]:[]].join(` `)}};function Ig(e){return e===`navigation`?`navigation-view`:e===`chat`?`chat-view`:`workspace-view`}function Lg(){try{return typeof window>`u`?void 0:window.localStorage}catch(e){console.warn(`Panel collapse storage is unavailable`,e);return}}var Rg=`pi-web:panel-sizes:v1`,zg={navigation:{minWidth:260,maxWidth:4096,defaultWidth:340,keyboardStep:24,largeKeyboardStep:72},workspace:{minWidth:240,maxWidth:4096,defaultWidth:480,keyboardStep:24,largeKeyboardStep:72}},Bg=class{constructor(e,t={}){this.host=e,e.addController(this),this.storage=t.storage??e_(),this.panelSizes=Kg(this.storage)}hostConnected(){}constraints(e){return Vg(e)}panelWidth(e,t){return Gg(e,t??this.storedPanelWidth(e)??this.constraints(e).defaultWidth)}resizePanel(e,t,n={}){let r=Gg(e,t);this.storedPanelWidth(e)!==r&&(this.panelSizes=Xg(this.panelSizes,e,r),n.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanel(e,t={}){this.storedPanelWidth(e)!==void 0&&(this.panelSizes=Zg(this.panelSizes,e),t.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}resetPanels(e={}){(this.panelSizes.navigationPanelWidth!==void 0||this.panelSizes.workspacePanelWidth!==void 0)&&(this.panelSizes={},e.persist!==!1&&this.persistPanelSizes(),this.host.requestUpdate())}persistPanelSizes(){qg(this.panelSizes,this.storage)}shellStyle(e={}){let t=[];return this.panelSizes.navigationPanelWidth!==void 0&&t.push(`--navigation-panel-size: ${$g(Gg(`navigation`,this.panelSizes.navigationPanelWidth,e.navigation))};`),this.panelSizes.workspacePanelWidth!==void 0&&t.push(`--workspace-panel-size: ${$g(Gg(`workspace`,this.panelSizes.workspacePanelWidth,e.workspace))};`),t.join(` `)}storedPanelWidth(e){return e===`navigation`?this.panelSizes.navigationPanelWidth:this.panelSizes.workspacePanelWidth}};function Vg(e){return zg[e]}function Hg(e,t,n){return e===`navigation`?n-t:t-n}function Ug(e,t,n,r,i=Vg(e)){return Gg(e,t+Hg(e,n,r),i)}function Wg(e,t,n,r={}){let i=r.constraints??Vg(e);if(n===`Home`)return i.minWidth;if(n===`End`)return i.maxWidth;let a=Qg(e,n,r.largeStep===!0?i.largeKeyboardStep:i.keyboardStep);if(a!==void 0)return Gg(e,t+a,i)}function Gg(e,t,n=Vg(e)){return Number.isFinite(t)?Math.round(Math.min(Math.max(t,n.minWidth),n.maxWidth)):n.defaultWidth}function Kg(e=e_()){try{let t=e?.getItem(Rg);return t==null||t===``?{}:Jg(JSON.parse(t))}catch{return{}}}function qg(e,t=e_()){if(t!==void 0)try{if(e.navigationPanelWidth===void 0&&e.workspacePanelWidth===void 0){t.removeItem(Rg);return}let n={version:1};e.navigationPanelWidth!==void 0&&(n.navigationPanelWidth=Gg(`navigation`,e.navigationPanelWidth)),e.workspacePanelWidth!==void 0&&(n.workspacePanelWidth=Gg(`workspace`,e.workspacePanelWidth)),t.setItem(Rg,JSON.stringify(n))}catch{}}function Jg(e){if(!t_(e)||e.version!==1)return{};let t={},n=Yg(e.navigationPanelWidth),r=Yg(e.workspacePanelWidth);return n!==void 0&&(t.navigationPanelWidth=Gg(`navigation`,n)),r!==void 0&&(t.workspacePanelWidth=Gg(`workspace`,r)),t}function Yg(e){return typeof e==`number`&&Number.isFinite(e)?e:void 0}function Xg(e,t,n){return t===`navigation`?{...e,navigationPanelWidth:n}:{...e,workspacePanelWidth:n}}function Zg(e,t){return t===`navigation`?e.workspacePanelWidth===void 0?{}:{workspacePanelWidth:e.workspacePanelWidth}:e.navigationPanelWidth===void 0?{}:{navigationPanelWidth:e.navigationPanelWidth}}function Qg(e,t,n){if(e===`navigation`)return t===`ArrowRight`?n:t===`ArrowLeft`?-n:void 0;if(t===`ArrowLeft`)return n;if(t===`ArrowRight`)return-n}function $g(e){return`${String(Math.round(e))}px`}function e_(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}function t_(e){return typeof e==`object`&&!!e}var n_=`pi-web:navigation-preferences`;function r_(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function i_(e=r_()){try{let t=JSON.parse(e?.getItem(n_)??`null`);if(typeof t==`object`&&t){let e=`pinnedIds`in t?t.pinnedIds:void 0;return{pinnedIds:Array.isArray(e)?[...new Set(e.filter(e=>typeof e==`string`&&e.length>0))]:[],mobileCollapsed:`mobileCollapsed`in t&&t.mobileCollapsed===!0}}}catch{}return{pinnedIds:[],mobileCollapsed:!1}}function a_(e,t=r_()){try{t?.setItem(n_,JSON.stringify(e))}catch{}}function o_(e,t){return t.length===0||t.includes(e)}function s_(e,t){return e.filter(e=>o_(e.id,t))}function c_(e,t,n){return n!==void 0&&e.some(e=>e.id===n)&&!t.some(e=>e.id===n)}function l_(e,t,n){let r=t.length===0?n:t;return r.includes(e)?r.filter(t=>t!==e):[...r,e]}function u_(){return f_(new URLSearchParams(window.location.search).get(`settings`))}function d_(e,t){let n=new URL(window.location.href);e===void 0?n.searchParams.delete(`settings`):n.searchParams.set(`settings`,e),`${n.pathname}${n.search}${n.hash}`!=`${window.location.pathname}${window.location.search}${window.location.hash}`&&(t?.replace===!0?window.history.replaceState({},``,n):window.history.pushState({},``,n))}function f_(e){if(e===`general`)return`general`;if(e===`sessiond`||e===`sessions`)return`sessiond`;if(e===`packages`||e===`pi-packages`)return`packages`;if(e===`plugins`)return`plugins`;if(e===`mcp`)return`mcp`;if(e===`shortcuts`||e===`keyboard`||e===`keyboard-shortcuts`)return`shortcuts`}function p_(e,t){return t===void 0?e:e.map(e=>h_(e,t))}function m_(e,t){let n=new Set(pe(e,t,{enabledOnly:!0}).filter(e=>e.active).map(e=>e.action.id));return p_(e,t).map(e=>e.shortcut!==void 0&&!n.has(e.id)?g_(e):e)}function h_(t,n){let r=e(t,n);return r===void 0?t:r===null?g_(t):{...t,shortcut:r}}function g_(e){let t={...e};return delete t.shortcut,t}function __(e,t){let n=t.api??Dt,r=t.pollIntervalMs??1e3,i=t.setTimeout??b_(),a=t.clearTimeout??x_();return{async runCommand(o){let s=await n.runTerminalCommand(e,o);return o.open===!0&&t.openTerminal(o.workspace,{terminalId:s.terminalId}),{run:s,completed:v_(s,n,r,i,a)}},listCommandRuns:e=>n.listCommandRuns(e),getCommandRun:e=>n.getCommandRun(e),open:e=>{t.openTerminal(void 0,e)}}}function v_(e,t,n,r,i){return y_(e)?Promise.resolve(e):new Promise((a,o)=>{let s,c=!1,l=e=>{c||(c=!0,s!==void 0&&i(s),a(e))},u=e=>{c||(c=!0,s!==void 0&&i(s),o(e instanceof Error?e:Error(String(e))))},d=()=>{t.getCommandRun(e.id).then(e=>{e!==void 0&&y_(e)?l(e):s=r(d,n)}).catch(u)};s=r(d,n)})}function y_(e){return e.status===`succeeded`||e.status===`failed`}function b_(){return(e,t)=>globalThis.setTimeout(e,t)}function x_(){return e=>{globalThis.clearTimeout(e)}}function S_(e,t=D(`ui.activityBadge.active`,`Active`),n){if(e===void 0)return n===void 0?void 0:E`<span class="activity-indicator unread" role="img" aria-label=${n} title=${n}></span>`;if(n===void 0)return E`<span class=${`activity-indicator ${e}`} role="img" aria-label=${t} title=${t}></span>`;let r=`${n} · ${t}`;return E`<span class="unread-ring" role="img" aria-label=${r} title=${r}><span class=${`activity-indicator ${e}`} aria-hidden="true"></span></span>`}function C_(e,t=D(`ui.activityBadge.active`,`Active`),n){let r=S_(e,t,n);if(r!==void 0)return E`<span class="action-activity">${r}</span>`}function w_(e){if(e!==void 0)return e[re.working]===!0?`session`:e[re.terminal]===!0?`terminal`:Object.entries(e).some(([e,t])=>t&&e!==re.unread)?`session`:void 0}function T_(e){return e?.[re.unread]===!0}var E_=[],D_=class{constructor(e,t){this.host=e,this.getPopup=t,this.cleanups=[],this.close=()=>{let e=this.current;e&&(this.stop(),e.onClose())},this.scheduleRefresh=()=>{this.frame??=requestAnimationFrame(this.onFrame)},this.onFrame=()=>{this.frame=void 0,this.refresh()},e.addController(this)}hostConnected(){this.host.requestUpdate()}hostUpdated(){let e=this.getPopup();(e?.panel!==this.current?.panel||e?.anchor!==this.current?.anchor)&&(this.stop(),e?.anchor.isConnected===!0&&e.panel.isConnected&&this.start(e)),this.refresh()}hostDisconnected(){this.close()}dismiss(){let e=this.current;e&&(this.stop(!1),e.onClose())}start(e){if(!St(e.anchor)){e.onClose();return}this.current=e;let{panel:t,anchor:n,options:r}=e;t.setAttribute(`popover`,`auto`),Object.assign(t.style,{position:`fixed`,inset:`auto`,margin:`0`,zIndex:`auto`,boxSizing:`border-box`,minWidth:`0`});let i=(e,t,n,r=!1)=>{e.addEventListener(t,n,r),this.cleanups.push(()=>{e.removeEventListener(t,n,r)})},a=e=>{`newState`in e&&e.newState===`closed`&&this.dismiss()};i(t,`beforetoggle`,a),i(t,`toggle`,a),i(window,`keydown`,e=>{e instanceof KeyboardEvent&&e.key===`Escape`&&!e.isComposing&&E_.at(-1)===this&&(e.preventDefault(),e.stopImmediatePropagation(),this.close(),r?.preserveFocus!==!0&&n.focus())},!0),i(window,`resize`,this.scheduleRefresh),i(window,`scroll`,this.scheduleRefresh,!0),window.visualViewport&&(i(window.visualViewport,`resize`,this.scheduleRefresh),i(window.visualViewport,`scroll`,this.scheduleRefresh));let o=typeof ResizeObserver>`u`?void 0:new ResizeObserver(this.scheduleRefresh);o&&(o.observe(n),o.observe(t),this.cleanups.push(()=>{o.disconnect()}));let s=n;for(;;){let e=s.getRootNode();if(!(e instanceof ShadowRoot))break;i(e,`scroll`,this.scheduleRefresh,!0),o?.observe(e.host),s=e.host}this.cleanups.push(We(n,this.close)),E_.push(this),this.refresh();let c=r?.preserveFocus===!0?n.getRootNode():void 0,l=c instanceof ShadowRoot?c.activeElement:document.activeElement;t.showPopover({source:n}),r?.preserveFocus===!0&&l instanceof HTMLElement&&l.focus({preventScroll:!0})}stop(e=!0){let t=this.current;this.current=void 0;for(let e of this.cleanups.splice(0))e();let n=E_.indexOf(this);n>=0&&E_.splice(n,1),this.frame!==void 0&&cancelAnimationFrame(this.frame),this.frame=void 0,t&&e&&t.panel.hidePopover()}refresh(){let e=this.current;if(!e)return;if(!St(e.anchor)||!e.panel.isConnected){this.close();return}let t=O_(e.anchor,e.options,e.panel);for(let[n,r]of Object.entries(t))e.panel.style.setProperty(n,r)}};function O_(e,t={},n){let r=e.getBoundingClientRect(),i=window.visualViewport,a=t.padding??0,o=(i?.offsetLeft??0)+a,s=(i?.offsetTop??0)+a,c=(i?.offsetLeft??0)+(i?.width??window.innerWidth)-a,l=(i?.offsetTop??0)+(i?.height??window.innerHeight)-a,u=t.gap??0,d=(e,t,n)=>Math.min(n,Math.max(t,e)),f=e=>`${String(Math.round(Math.max(0,e)))}px`,p=d(r.top,s,l),m=d(r.bottom,s,l),h=d(r.right,o,c),g=d(r.left,o,c),ee=t.placement??(n===void 0?void 0:window.getComputedStyle(n).getPropertyValue(`--ui-popup-placement`).trim()),_={top:`auto`,bottom:`auto`,left:`auto`,right:`auto`,width:`max-content`};if(ee===`left-end`){let e=Math.max(0,g-o-u);return _[`max-width`]=f(e),_[`min-width`]=f(Math.min(t.minWidth??0,e)),_[`max-height`]=f(l-s),_.right=f(window.innerWidth-g+u),_.top=f(d(r.bottom-(n?.getBoundingClientRect().height??0),s,l-(n?.getBoundingClientRect().height??0))),_}let te=Math.max(0,l-m-u),ne=Math.max(0,p-s-u),re=ee===`above-start`,ie=n?.scrollHeight??0,ae=Math.min(t.maxHeight??120,ie>0?ie:120),v=re?!(ne<ae&&te>ne):te<ae&&ne>te;_[v?`bottom`:`top`]=f(v?window.innerHeight-p+u:m+u),_[`max-height`]=f(Math.min(t.maxHeight??1/0,v?ne:te));let oe=ee===`below-start`||re,se=t.width===`anchor`?r.width:t.width;if(oe){let e=d(g,o,se===void 0?c:Math.max(o,c-se));_.left=f(e),_[`max-width`]=f(c-e),_[`min-width`]=f(Math.min(t.minWidth??0,c-e))}else _.right=f(window.innerWidth-h),_[`max-width`]=f(h-o),_[`min-width`]=f(Math.min(t.minWidth??0,h-o));return se!==void 0&&(_.width=f(Math.min(se,c-o))),_}var k_=class{constructor(e){this.host=e,this.menuStyle=``,e.addController(this),new D_(e,()=>{let t=e.shadowRoot?.querySelector(`.action-menu-panel`);return this.openId!==void 0&&this.anchor!==void 0&&t?{anchor:this.anchor,panel:t,onClose:()=>{this.close()},options:{minWidth:120}}:void 0})}hostDisconnected(){this.close()}isOpen(e){return this.openId===e}toggle(e,t){this.openId===e?this.close():(this.anchor=t instanceof HTMLElement?t:void 0,this.openId=e,this.host.requestUpdate())}close(){(this.openId!==void 0||this.menuStyle!==``)&&(this.openId=void 0,this.menuStyle=``,this.anchor=void 0,this.host.requestUpdate())}closeIfOpenIdMissing(e){this.openId!==void 0&&!e(this.openId)&&this.close()}closeIf(e){e&&this.close()}closeForEscape(e,t){return e.key!==`Escape`||this.openId!==t?!1:(e.preventDefault(),e.stopPropagation(),this.close(),!0)}},A_=`a[href],button,input,select,textarea,summary,[role='button'],[role='link'],[contenteditable='true']`;function j_(e){return e.composedPath().some(e=>M_(e,A_))}function M_(e,t){if(typeof Element<`u`&&e instanceof Element)return e.matches(t);if(!(`matches`in e))return!1;let{matches:n}=e;return typeof n==`function`&&n.call(e,t)===!0}function N_(e,t){j_(e)||t()}function P_(e,t){return j_(e)?!1:e.key===`Enter`||e.key===` `?(e.preventDefault(),t.activate(),!0):e.key===`ArrowUp`?I_(e,()=>{L_(e.currentTarget,-1)}):e.key===`ArrowDown`?I_(e,()=>{L_(e.currentTarget,1)}):e.key===`Home`?I_(e,()=>{R_(e.currentTarget,0)}):e.key===`End`?I_(e,()=>{R_(e.currentTarget,-1)}):e.key===`ArrowLeft`&&t.previousSection!==void 0?I_(e,t.previousSection):e.key===`ArrowRight`&&t.nextSection!==void 0?I_(e,t.nextSection):e.key===`Escape`&&t.cancel!==void 0&&I_(e,t.cancel)}function F_(e,t={}){let n=e.querySelector(`.action-row.selected`)??e.querySelector(`.action-row`)??(t.fallbackSelector===void 0?void 0:e.querySelector(t.fallbackSelector));return n!=null&&(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}function I_(e,t){return e.preventDefault(),e.stopPropagation?.(),t(),!0}function L_(e,t){let n=B_(e),r=H_(e);if(r===void 0||n.length===0)return;let i=n.indexOf(r);i<0||z_(n,i+t)}function R_(e,t){let n=B_(e);n.length!==0&&z_(n,t<0?n.length-1:t)}function z_(e,t){let n=e[Math.min(Math.max(t,0),e.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}function B_(e){let t=H_(e)?.getRootNode();return t===void 0||!V_(t)?[]:Array.from(t.querySelectorAll(`.action-row`))}function V_(e){return typeof Document<`u`&&e instanceof Document||typeof DocumentFragment<`u`&&e instanceof DocumentFragment}function H_(e){if(typeof HTMLElement<`u`&&e instanceof HTMLElement)return e.closest(`.action-row`)??void 0}var U_=me(`section>h2.ui-toolbar{background:var(--pi-surface);border-bottom-color:var(--pi-border);box-shadow:none}.list-body>.subheading:not(.ui-toolbar){padding-inline:10px}.action-row{border-bottom:1px solid var(--pi-border-muted);margin:0;padding:0}.action-row:last-child{border-bottom:0}.action-main{padding:10px 10px 10px calc(19px + var(--depth,0) * 16px)}.action-main,.workspace-row .action-main{background:0 0;border-color:#0000;border-radius:0}.action-row.selected{background:var(--pi-selection-bg);box-shadow:inset 3px 0 0 var(--pi-accent)}.action-row.selected .action-main{background:0 0;border-color:#0000}.action-row:not(.selected):hover{background:var(--pi-surface-hover)}.action-row:not(.selected):hover .action-main{background:0 0}.action-row:focus-visible{outline:2px solid var(--pi-accent);outline-offset:-2px;border-radius:0}`),W_=class extends O{constructor(){super(),this.machines=[],this.statuses={},this.activities={},this.unreadMachineIds=new Set,this.statusSnapshots={},this.collapsible=!1,this.collapsed=!1,this.menu=new k_(this),v.createController(this)}updated(e){e.has(`machines`)&&this.menu.closeIfOpenIdMissing(e=>this.machines.some(t=>t.id===e)),e.has(`collapsed`)&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,F_(this.renderRoot,{fallbackSelector:`.section-toggle`})}render(){return E`
|
|
622
622
|
<section>
|
|
623
623
|
<h2 class="ui-toolbar">${this.renderHeading()}</h2>
|
|
624
624
|
${this.collapsed?null:E`
|
|
@@ -627,13 +627,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
627
627
|
</div>
|
|
628
628
|
`}
|
|
629
629
|
</section>
|
|
630
|
-
`}renderMachine(e){let t=this.statuses[e.id]?.status??e.status??`unknown`,n=t===`online`?D(`ui.machineSwitcher.online`,`Online`):t===`offline`?D(`ui.machineSwitcher.offline`,`Offline`):t===`error`?D(`client.sessionNotifications.error.0bc1fb`,`Error`):D(`bundled.updates.unknown.4d8c1c`,`Unknown`),r=
|
|
630
|
+
`}renderMachine(e){let t=this.statuses[e.id]?.status??e.status??`unknown`,n=t===`online`?D(`ui.machineSwitcher.online`,`Online`):t===`offline`?D(`ui.machineSwitcher.offline`,`Offline`):t===`error`?D(`client.sessionNotifications.error.0bc1fb`,`Error`):D(`bundled.updates.unknown.4d8c1c`,`Unknown`),r=G_(e)&&this.onRemove!==void 0;return E`
|
|
631
631
|
<div
|
|
632
632
|
class=${`action-row machine-row ${this.selected?.id===e.id?`selected`:``} ${r?``:`no-actions`}`}
|
|
633
633
|
tabindex="0"
|
|
634
634
|
title=${e.baseUrl??e.name}
|
|
635
635
|
data-machine-id=${e.id}
|
|
636
|
-
@click=${t=>{
|
|
636
|
+
@click=${t=>{N_(t,()=>this.onSelect?.(e))}}
|
|
637
637
|
@keydown=${t=>{this.handleMachineKeydown(t,e)}}
|
|
638
638
|
>
|
|
639
639
|
<div class="action-main">
|
|
@@ -641,7 +641,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
641
641
|
</div>
|
|
642
642
|
${r?this.renderMachineMenu(e):null}
|
|
643
643
|
</div>
|
|
644
|
-
`}renderActivity(e){let t=this.statuses[e.id]?.status??e.status,n=this.statusSnapshots[e.id],r=n?.machine,i=t===`offline`||t===`error`?void 0:n===void 0?fr(this.activities[e.id]):
|
|
644
|
+
`}renderActivity(e){let t=this.statuses[e.id]?.status??e.status,n=this.statusSnapshots[e.id],r=n?.machine,i=t===`offline`||t===`error`?void 0:n===void 0?fr(this.activities[e.id]):w_(r),a=n===void 0?this.unreadMachineIds.has(e.id)?D(`ui.machineSwitcher.unreadSessionsOnThisMachine`,`Unread sessions on this machine`):void 0:T_(r)?D(`ui.machineSwitcher.unreadSessionsOnThisMachine`,`Unread sessions on this machine`):void 0;return C_(i,i===`terminal`?D(`ui.machineSwitcher.machineTerminalActive`,`Machine terminal active`):D(`ui.machineSwitcher.machineActive`,`Machine active`),a)}renderMachineMenu(e){let t=this.menu.isOpen(e.id),n=K_(e.id);return E`
|
|
645
645
|
<div class="action-menu">
|
|
646
646
|
<button
|
|
647
647
|
class="ui-button ui-button--icon action-menu-toggle"
|
|
@@ -657,13 +657,13 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
657
657
|
</div>
|
|
658
658
|
`:null}
|
|
659
659
|
</div>
|
|
660
|
-
`}renderHeading(){if(!this.collapsible)return D(`bundled.info.machine.ece969`,`Machine`);let e=this.selected?.name??D(`ui.machineList.noMachineSelected`,`No machine selected`),t=this.selected?.baseUrl??e;return E`<button class="ui-button ui-toolbar-title section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} ${D(`bundled.info.machine.ece969`,`Machine`)}</span>${this.collapsed?E`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}removeMachine(e){this.menu.close(),this.onRemove?.(e)}handleMachineKeydown(e,t){this.menu.closeForEscape(e,t.id)||
|
|
660
|
+
`}renderHeading(){if(!this.collapsible)return D(`bundled.info.machine.ece969`,`Machine`);let e=this.selected?.name??D(`ui.machineList.noMachineSelected`,`No machine selected`),t=this.selected?.baseUrl??e;return E`<button class="ui-button ui-toolbar-title section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} ${D(`bundled.info.machine.ece969`,`Machine`)}</span>${this.collapsed?E`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.machines.length}</small></button>`}removeMachine(e){this.menu.close(),this.onRemove?.(e)}handleMachineKeydown(e,t){this.menu.closeForEscape(e,t.id)||P_(e,{activate:()=>this.onSelect?.(t),nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}static{this.styles=[Vh,U_,T`
|
|
661
661
|
@layer pi-web-base {
|
|
662
662
|
.machine-primary { display: flex; align-items: baseline; gap: 6px; }
|
|
663
663
|
.machine-primary-label { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
|
664
664
|
|
|
665
665
|
}
|
|
666
|
-
`]}};w([y({attribute:!1})],
|
|
666
|
+
`]}};w([y({attribute:!1})],W_.prototype,`machines`,void 0),w([y({attribute:!1})],W_.prototype,`selected`,void 0),w([y({attribute:!1})],W_.prototype,`statuses`,void 0),w([y({attribute:!1})],W_.prototype,`activities`,void 0),w([y({attribute:!1})],W_.prototype,`unreadMachineIds`,void 0),w([y({attribute:!1})],W_.prototype,`statusSnapshots`,void 0),w([y({type:Boolean,reflect:!0})],W_.prototype,`collapsible`,void 0),w([y({type:Boolean,reflect:!0})],W_.prototype,`collapsed`,void 0),w([y({attribute:!1})],W_.prototype,`onSelect`,void 0),w([y({attribute:!1})],W_.prototype,`onRemove`,void 0),w([y({attribute:!1})],W_.prototype,`onToggleCollapsed`,void 0),w([y({attribute:!1})],W_.prototype,`onFocusNextSection`,void 0),w([y({attribute:!1})],W_.prototype,`onCancelKeyboardNavigation`,void 0),W_=w([b(`machine-list`)],W_);function G_(e){return e.kind===`remote`}function K_(e){return`machine-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}var q_=class extends O{constructor(){super(),this.machineId=`local`,this.busy=!1,this.generation=0,v.createController(this)}disconnectedCallback(){this.generation++,super.disconnectedCallback()}willUpdate(e){(e.has(`machineId`)||e.has(`project`))&&this.load()}async load(){let e=++this.generation,t=this.project,n=this.machineId;this.workspace=void 0,this.trusted=void 0,this.error=void 0,this.busy=!0;let r=()=>this.isConnected&&e===this.generation&&this.project===t&&this.machineId===n;if(t!==void 0)try{let e=await d.workspaceResolution(t.id,n);if(!r()||e.status!==`folder`)return;let i=e.workspaces[0];if(i===void 0)return;this.workspace=i;let a=await ye.workspaceTrust(t.id,i.id,n);r()&&(this.trusted=a.trusted)}catch(e){r()&&(this.error=e instanceof Error?e.message:String(e))}finally{r()&&(this.busy=!1)}}async setTrust(e){let t=this.workspace;if(t===void 0||this.busy||this.trusted===void 0)return;let n=this.generation,r=this.project,i=this.machineId,a=()=>this.isConnected&&n===this.generation&&this.project===r&&this.machineId===i;this.busy=!0,this.error=void 0;try{let n=await ye.setWorkspaceTrust(t.projectId,t.id,e,i);a()&&(this.trusted=n.trusted)}catch(e){a()&&(this.error=e instanceof Error?e.message:String(e))}finally{a()&&(this.busy=!1)}}render(){return E`
|
|
667
667
|
${this.workspace===void 0?null:E`
|
|
668
668
|
<label>
|
|
669
669
|
<input type="checkbox" .checked=${wt(this.trusted===!0)} ?disabled=${this.busy||this.trusted===void 0}
|
|
@@ -680,7 +680,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
680
680
|
input { margin: 0; cursor: pointer; }
|
|
681
681
|
a { display: block; padding: 0 9px 7px; color: var(--pi-accent); font-size: 12px; }
|
|
682
682
|
small { display: block; padding: 7px 9px; color: var(--pi-danger); overflow-wrap: anywhere; }
|
|
683
|
-
`}};w([y()],
|
|
683
|
+
`}};w([y()],q_.prototype,`machineId`,void 0),w([y({attribute:!1})],q_.prototype,`project`,void 0),w([C()],q_.prototype,`workspace`,void 0),w([C()],q_.prototype,`trusted`,void 0),w([C()],q_.prototype,`busy`,void 0),w([C()],q_.prototype,`error`,void 0),q_=w([b(`folder-project-trust`)],q_);var U=class extends O{constructor(){super(),this.projects=[],this.machineId=`local`,this.activities={},this.workspacesByProjectId={},this.unreadProjectIds=new Set,this.collapsible=!1,this.collapsed=!1,this.managementMode=!1,this.treeLayout=!1,this.menu=new k_(this),this.branchCollapsed=!1,v.createController(this)}willUpdate(e){e.has(`projects`)&&(this.focusAfterReorder=this.focusedControl),e.has(`treeLayout`)&&this.menu.close(),(e.has(`machineId`)||e.has(`selected`)&&(e.get(`selected`)?.id!==this.selected?.id||e.get(`selected`)?.path!==this.selected?.path))&&(this.branchCollapsed=!1)}updated(e){if(e.has(`projects`)&&this.focusAfterReorder?.isConnected===!0){let e=this.focusAfterReorder;(e instanceof HTMLButtonElement&&e.disabled?e.closest(`.action-menu-panel`)?.querySelector(`button[data-move]:not(:disabled)`):e)?.focus({preventScroll:!0})}this.focusAfterReorder=void 0,e.has(`projects`)&&this.menu.closeIfOpenIdMissing(e=>this.projects.some(t=>t.id===e)),e.has(`collapsed`)&&this.menu.closeIf(this.collapsed)}async focusSelectedOrFirst(){return await this.updateComplete,F_(this.renderRoot,{fallbackSelector:`.section-toggle`})}async revealSelectedBranch(){await this.updateComplete,this.treeLayout&&this.selected!==void 0&&(this.branchCollapsed=!1,await this.updateComplete)}render(){return E`
|
|
684
684
|
<section>
|
|
685
685
|
<h2 class="ui-toolbar">${this.renderHeading()}</h2>
|
|
686
686
|
${this.collapsed?null:E`
|
|
@@ -697,7 +697,7 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
697
697
|
@focusin=${e=>{this.focusedControl=e.target instanceof HTMLElement?e.target:void 0}}
|
|
698
698
|
@focusout=${()=>{this.focusedControl=void 0}}
|
|
699
699
|
title=${e.path}
|
|
700
|
-
@click=${t=>{
|
|
700
|
+
@click=${t=>{N_(t,()=>{this.selectProject(e)})}}
|
|
701
701
|
@keydown=${t=>{this.handleProjectKeydown(t,e)}}
|
|
702
702
|
>
|
|
703
703
|
<div class="action-main">
|
|
@@ -723,21 +723,21 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
|
|
|
723
723
|
</div>
|
|
724
724
|
`}
|
|
725
725
|
</section>
|
|
726
|
-
`}handleProjectKeydown(e,t){this.treeLayout&&e.target===e.currentTarget&&(e.key===`ArrowLeft`||e.key===`ArrowRight`)?(e.preventDefault(),e.stopPropagation(),e.key===`ArrowLeft`?this.isExpanded(t)?this.branchCollapsed=!0:this.onFocusPreviousSection?.():this.isExpanded(t)?this.onFocusNextSection?.():this.selected?.id===t.id?this.branchCollapsed=!1:this.onSelect?.(t)):
|
|
726
|
+
`}handleProjectKeydown(e,t){this.treeLayout&&e.target===e.currentTarget&&(e.key===`ArrowLeft`||e.key===`ArrowRight`)?(e.preventDefault(),e.stopPropagation(),e.key===`ArrowLeft`?this.isExpanded(t)?this.branchCollapsed=!0:this.onFocusPreviousSection?.():this.isExpanded(t)?this.onFocusNextSection?.():this.selected?.id===t.id?this.branchCollapsed=!1:this.onSelect?.(t)):P_(e,{activate:()=>{this.selectProject(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?.()}})}selectProject(e){this.treeLayout&&this.selected?.id===e.id?this.branchCollapsed=!this.branchCollapsed:this.onSelect?.(e)}isExpanded(e){return this.treeLayout&&this.selected?.id===e.id&&!this.branchCollapsed}renderHeading(){if(!this.collapsible)return D(`client.actions.project.79f326`,`Project`);let e=this.selected?.name??D(`ui.projectList.noProjectSelected`,`No project selected`),t=this.selected?.path??e;return E`<button class="ui-button ui-toolbar-title section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} ${D(`client.actions.project.79f326`,`Project`)}</span>${this.collapsed?E`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.projects.length}</small></button>`}renderActivity(e){let t=this.statusSnapshot?.projects[e.id],n=this.statusSnapshot===void 0?ur(e,this.workspacesByProjectId[e.id]??[],this.activities):w_(t),r=this.statusSnapshot===void 0?this.unreadProjectIds.has(e.id)?D(`ui.projectList.unreadSessionsInThisProject`,`Unread sessions in this project`):void 0:T_(t)?D(`ui.projectList.unreadSessionsInThisProject`,`Unread sessions in this project`):void 0;return C_(n,n===`terminal`?D(`ui.projectList.projectTerminalActive`,`Project terminal active`):D(`ui.projectList.projectActive`,`Project active`),r)}close(e){this.menu.close(),confirm(D(`ui.projectList.closeThisOnlyRemovesItFromPiWeb`,`Close {name}?
|
|
727
727
|
|
|
728
|
-
This only removes it from PI WEB. The project folder will not be changed.`,{name:e.name}))&&this.onClose?.(e)}static{this.styles=[
|
|
728
|
+
This only removes it from PI WEB. The project folder will not be changed.`,{name:e.name}))&&this.onClose?.(e)}static{this.styles=[Vh,U_]}};w([y({attribute:!1})],U.prototype,`projects`,void 0),w([y()],U.prototype,`machineId`,void 0),w([y({attribute:!1})],U.prototype,`selected`,void 0),w([y({attribute:!1})],U.prototype,`activities`,void 0),w([y({attribute:!1})],U.prototype,`workspacesByProjectId`,void 0),w([y({attribute:!1})],U.prototype,`unreadProjectIds`,void 0),w([y({attribute:!1})],U.prototype,`statusSnapshot`,void 0),w([y({type:Boolean,reflect:!0})],U.prototype,`collapsible`,void 0),w([y({type:Boolean,reflect:!0})],U.prototype,`collapsed`,void 0),w([y({type:Boolean})],U.prototype,`managementMode`,void 0),w([y({type:Boolean,reflect:!0,attribute:`tree-layout`})],U.prototype,`treeLayout`,void 0),w([y({attribute:!1})],U.prototype,`selectedChildren`,void 0),w([y({attribute:!1})],U.prototype,`onSelect`,void 0),w([y({attribute:!1})],U.prototype,`onClose`,void 0),w([y({attribute:!1})],U.prototype,`onMove`,void 0),w([y({attribute:!1})],U.prototype,`onToggleCollapsed`,void 0),w([y({attribute:!1})],U.prototype,`onFocusPreviousSection`,void 0),w([y({attribute:!1})],U.prototype,`onFocusNextSection`,void 0),w([y({attribute:!1})],U.prototype,`onCancelKeyboardNavigation`,void 0),w([C()],U.prototype,`branchCollapsed`,void 0),U=w([b(`project-list`)],U);function J_(e=[]){return e.map((e,t)=>E`${t===0?null:E`<span class="workspace-label-separator">·</span>`}${Y_(e)}`)}function Y_(e){if(e.type===`render`)return E`<span class="workspace-label-render">${e.render()}</span>`;if(e.type===`link`&&X_(e.href)){let t=e.target??`_blank`,n=t===`_blank`?`noopener noreferrer`:void 0;return E`<a class="workspace-label-item workspace-label-link" href=${e.href} title=${e.title??e.text} target=${t} rel=${n??void 0}>${e.text}</a>`}return E`<span class="workspace-label-item" title=${e.title??e.text}>${e.text}</span>`}function X_(e){let t=e.trim().toLowerCase();return t!==``&&!t.startsWith(`javascript:`)&&!t.startsWith(`data:`)}var W=class extends O{constructor(){super(),this.popup=new D_(this,()=>{let e=this.shadowRoot?.querySelector(`.action-menu-panel`);return e&&this.menuAnchor?{anchor:this.menuAnchor,panel:e,onClose:()=>{this.openMenuWorkspaceId=void 0},options:{minWidth:120}}:void 0}),this.workspaces=[],this.machineId=`local`,this.managementMode=!1,this.treeLayout=!1,this.collapsible=!1,this.collapsed=!1,this.workspaceLabelItems=()=>[],this.activities={},this.deletingWorkspaceIds=[],this.unreadWorkspaceIds=new Set,this.trustByWorkspaceId={},this.trustGeneration=0,this.branchCollapsed=!1,v.createController(this)}connectedCallback(){super.connectedCallback()}disconnectedCallback(){this.trustGeneration++,this.trustByWorkspaceId={},super.disconnectedCallback()}willUpdate(e){e.has(`workspaces`)&&(this.focusAfterReorder=this.focusedControl),e.has(`treeLayout`)&&(this.openMenuWorkspaceId=void 0),(e.has(`machineId`)||e.has(`selected`)&&(e.get(`selected`)?.id!==this.selected?.id||e.get(`selected`)?.projectId!==this.selected?.projectId||e.get(`selected`)?.path!==this.selected?.path))&&(this.branchCollapsed=!1)}updated(e){if(e.has(`workspaces`)&&this.focusAfterReorder?.isConnected===!0){let e=this.focusAfterReorder;(e instanceof HTMLButtonElement&&e.disabled?e.closest(`.action-menu-panel`)?.querySelector(`button[data-move]:not(:disabled)`):e)?.focus({preventScroll:!0})}this.focusAfterReorder=void 0;let t=e.get(`workspaces`)?.some(e=>!this.workspaces.some(t=>t.id===e.id&&t.projectId===e.projectId&&t.path===e.path))===!0;(e.has(`machineId`)||e.has(`managementMode`)||t)&&(this.trustGeneration++,this.trustByWorkspaceId={},this.openMenuWorkspaceId=void 0),e.has(`workspaces`)&&this.openMenuWorkspaceId!==void 0&&!this.workspaces.some(e=>e.id===this.openMenuWorkspaceId)&&(this.openMenuWorkspaceId=void 0),e.has(`collapsed`)&&this.collapsed&&(this.openMenuWorkspaceId=void 0),this.shouldRevealSelectedRow(e)&&this.scrollSelectedIntoView()}shouldRevealSelectedRow(e){return this.collapsed?!1:e.has(`collapsed`)?!0:e.has(`selected`)&&e.get(`selected`)?.id!==this.selected?.id}async focusSelectedOrFirst(){return await this.updateComplete,F_(this.renderRoot,{fallbackSelector:`.section-toggle`})}async revealSelectedBranch(){await this.updateComplete,this.treeLayout&&this.selected!==void 0&&(this.branchCollapsed=!1,await this.updateComplete)}render(){return E`
|
|
729
729
|
<section>
|
|
730
730
|
<h2 class="ui-toolbar">${this.renderHeading()}</h2>
|
|
731
731
|
${this.collapsed?null:E`
|
|
732
732
|
<div class="list-body">
|
|
733
|
-
${tm(this.workspaces,e=>e.id,e=>{let t=
|
|
733
|
+
${tm(this.workspaces,e=>e.id,e=>{let t=Z_(e),n=this.workspaceLabelItems(e),r=E`
|
|
734
734
|
<div
|
|
735
735
|
class=${`action-row workspace-row ${this.selected?.id===e.id?`selected`:``}`}
|
|
736
736
|
tabindex="0"
|
|
737
737
|
@focusin=${e=>{this.focusedControl=e.target instanceof HTMLElement?e.target:void 0}}
|
|
738
738
|
@focusout=${()=>{this.focusedControl=void 0}}
|
|
739
739
|
title=${t}
|
|
740
|
-
@click=${t=>{
|
|
740
|
+
@click=${t=>{N_(t,()=>{this.selectWorkspace(e)})}}
|
|
741
741
|
@keydown=${t=>{this.handleWorkspaceKeydown(t,e)}}
|
|
742
742
|
>
|
|
743
743
|
<div class="action-main">
|
|
@@ -750,18 +750,18 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
750
750
|
</div>
|
|
751
751
|
`}
|
|
752
752
|
</section>
|
|
753
|
-
`}renderHeading(){if(!this.collapsible)return E`<span>${D(`bundled.workspace-tasks.workspace.379798`,`Workspace`)}</span>`;let e=this.selected===void 0?D(`ui.workspaceList.noWorkspaceSelected`,`No workspace selected`):`${this.selected.label}${this.selected.isMain?` · main`:``} · ${this.selected.path}`,t=this.selected?.path??e;return E`<button class="ui-button ui-toolbar-title section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} ${D(`bundled.workspace-tasks.workspace.379798`,`Workspace`)}</span>${this.collapsed?E`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){let t=this.statusSnapshot?.workspaces[e.id],n=this.statusSnapshot===void 0?lr(cr(e,this.activities)):
|
|
753
|
+
`}renderHeading(){if(!this.collapsible)return E`<span>${D(`bundled.workspace-tasks.workspace.379798`,`Workspace`)}</span>`;let e=this.selected===void 0?D(`ui.workspaceList.noWorkspaceSelected`,`No workspace selected`):`${this.selected.label}${this.selected.isMain?` · main`:``} · ${this.selected.path}`,t=this.selected?.path??e;return E`<button class="ui-button ui-toolbar-title section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} ${D(`bundled.workspace-tasks.workspace.379798`,`Workspace`)}</span>${this.collapsed?E`<small class="section-selected" title=${t}>${e}</small>`:null}</span><small class="section-count">${this.workspaces.length}</small></button>`}renderActivity(e){let t=this.statusSnapshot?.workspaces[e.id],n=this.statusSnapshot===void 0?lr(cr(e,this.activities)):w_(t),r=this.statusSnapshot===void 0?this.unreadWorkspaceIds.has(e.id)?D(`ui.workspaceList.unreadSessionsInThisWorkspace`,`Unread sessions in this workspace`):void 0:T_(t)?D(`ui.workspaceList.unreadSessionsInThisWorkspace`,`Unread sessions in this workspace`):void 0;return C_(n,n===`terminal`?D(`ui.workspaceList.workspaceTerminalActive`,`Workspace terminal active`):D(`ui.workspaceList.workspaceActive`,`Workspace active`),r)}renderWorkspaceMain(e,t,n){return E`
|
|
754
754
|
<span class="workspace-primary">
|
|
755
755
|
<span class="workspace-primary-label">${e}</span>
|
|
756
756
|
${this.isDeleting(n)?E`<span class="workspace-status">${D(`ui.workspaceList.deleting`,`Deleting…`)}</span>`:null}
|
|
757
757
|
</span>
|
|
758
758
|
${t.length===0?null:E`
|
|
759
759
|
<small class="workspace-secondary">
|
|
760
|
-
<span class="workspace-label">${
|
|
760
|
+
<span class="workspace-label">${J_(t)}</span>
|
|
761
761
|
</small>
|
|
762
762
|
`}
|
|
763
763
|
${this.renderActivity(n)}
|
|
764
|
-
`}renderWorkspaceMenu(e,t,n){let r=this.openMenuWorkspaceId===n.id,i=
|
|
764
|
+
`}renderWorkspaceMenu(e,t,n){let r=this.openMenuWorkspaceId===n.id,i=Q_(n.id);return E`
|
|
765
765
|
<div class="action-menu">
|
|
766
766
|
<button
|
|
767
767
|
class="ui-button ui-button--icon action-menu-toggle"
|
|
@@ -787,7 +787,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
787
787
|
${this.renderTrustToggle(e)}
|
|
788
788
|
${zu(e)?E`<button class="ui-button ui-menu-item danger" title=${t?D(`ui.main.ebea1ecacc2f`,`Workspace removal in progress`):n} ?disabled=${t} @click=${()=>{this.delete(e)}}>${t?D(`ui.main.ce9fd54c50a3`,`Removing…`):n}</button>`:null}
|
|
789
789
|
</div>
|
|
790
|
-
`}renderTrustToggle(e){let t=this.trustByWorkspaceId[e.id],n=t?.loading===!0||t?.saving===!0,r=`${
|
|
790
|
+
`}renderTrustToggle(e){let t=this.trustByWorkspaceId[e.id],n=t?.loading===!0||t?.saving===!0,r=`${Q_(e.id)}-trusted`,i=`${r}-help`,a=`${r}-error`;return this.managementMode?E``:E`
|
|
791
791
|
<div class="workspace-menu-trust">
|
|
792
792
|
<div class="workspace-menu-trust-row">
|
|
793
793
|
<label for=${r}>
|
|
@@ -818,7 +818,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
818
818
|
${t.length===0?null:E`
|
|
819
819
|
<div class="workspace-detail-row">
|
|
820
820
|
<dt>${D(`ui.toolExecutionView.details`,`Details`)}</dt>
|
|
821
|
-
<dd><span class="workspace-label">${
|
|
821
|
+
<dd><span class="workspace-label">${J_(t)}</span></dd>
|
|
822
822
|
</div>
|
|
823
823
|
`}
|
|
824
824
|
</dl>
|
|
@@ -826,7 +826,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
826
826
|
<button type="button" class="ui-button ui-button--compact ui-button--icon detail-copy" title=${i} aria-label=${i} @click=${()=>{this.copyDetail(e,t)}}>
|
|
827
827
|
<span aria-hidden="true">${r?`✓`:`⧉`}</span>
|
|
828
828
|
</button>
|
|
829
|
-
`}async copyDetail(e,t){await rd(t)&&(this.copiedDetailKey=e,window.setTimeout(()=>{this.copiedDetailKey===e&&(this.copiedDetailKey=void 0)},1200))}delete(e){this.isDeleting(e)||(this.openMenuWorkspaceId=void 0,this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuAnchor=t instanceof HTMLElement?t:void 0,this.openMenuWorkspaceId=e;let n=this.workspaces.find(t=>t.id===e);!this.managementMode&&n!==void 0&&this.loadTrust(n)}handleWorkspaceKeydown(e,t){this.treeLayout&&e.target===e.currentTarget&&(e.key===`ArrowLeft`||e.key===`ArrowRight`)?(e.preventDefault(),e.stopPropagation(),e.key===`ArrowLeft`?this.isExpanded(t)?this.branchCollapsed=!0:this.onFocusPreviousSection?.():this.isExpanded(t)?this.onFocusNextSection?.():this.selected?.id===t.id?this.branchCollapsed=!1:this.onSelect?.(t)):e.key===`Escape`&&this.openMenuWorkspaceId===t.id?(e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0):
|
|
829
|
+
`}async copyDetail(e,t){await rd(t)&&(this.copiedDetailKey=e,window.setTimeout(()=>{this.copiedDetailKey===e&&(this.copiedDetailKey=void 0)},1200))}delete(e){this.isDeleting(e)||(this.openMenuWorkspaceId=void 0,this.onDelete?.(e))}isDeleting(e){return this.deletingWorkspaceIds.includes(e.id)}toggleMenu(e,t){if(this.openMenuWorkspaceId===e){this.openMenuWorkspaceId=void 0;return}this.menuAnchor=t instanceof HTMLElement?t:void 0,this.openMenuWorkspaceId=e;let n=this.workspaces.find(t=>t.id===e);!this.managementMode&&n!==void 0&&this.loadTrust(n)}handleWorkspaceKeydown(e,t){this.treeLayout&&e.target===e.currentTarget&&(e.key===`ArrowLeft`||e.key===`ArrowRight`)?(e.preventDefault(),e.stopPropagation(),e.key===`ArrowLeft`?this.isExpanded(t)?this.branchCollapsed=!0:this.onFocusPreviousSection?.():this.isExpanded(t)?this.onFocusNextSection?.():this.selected?.id===t.id?this.branchCollapsed=!1:this.onSelect?.(t)):e.key===`Escape`&&this.openMenuWorkspaceId===t.id?(e.preventDefault(),e.stopPropagation(),this.openMenuWorkspaceId=void 0):P_(e,{activate:()=>{this.selectWorkspace(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?.()}})}selectWorkspace(e){this.treeLayout&&this.selected?.id===e.id?this.branchCollapsed=!this.branchCollapsed:this.onSelect?.(e)}isExpanded(e){return this.treeLayout&&this.selected?.id===e.id&&!this.branchCollapsed}scrollSelectedIntoView(){this.renderRoot.querySelector(`.action-row.selected`)?.scrollIntoView({block:`nearest`})}static{this.styles=[Vh,U_,T`
|
|
830
830
|
@layer pi-web-base {
|
|
831
831
|
.workspace-menu-trust { display: flex; flex-direction: column; gap: 3px; padding: 4px 2px; }
|
|
832
832
|
.workspace-menu-trust-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
|
@@ -836,7 +836,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
836
836
|
.workspace-trust-error { color: var(--pi-danger, #c0392b); line-height: 1.3; }
|
|
837
837
|
|
|
838
838
|
}
|
|
839
|
-
`]}};w([y({attribute:!1})],W.prototype,`workspaces`,void 0),w([y()],W.prototype,`machineId`,void 0),w([y({type:Boolean})],W.prototype,`managementMode`,void 0),w([y({type:Boolean,reflect:!0,attribute:`tree-layout`})],W.prototype,`treeLayout`,void 0),w([y({attribute:!1})],W.prototype,`selectedChildren`,void 0),w([y({attribute:!1})],W.prototype,`selected`,void 0),w([y({type:Boolean,reflect:!0})],W.prototype,`collapsible`,void 0),w([y({type:Boolean,reflect:!0})],W.prototype,`collapsed`,void 0),w([y({attribute:!1})],W.prototype,`workspaceLabelItems`,void 0),w([y({attribute:!1})],W.prototype,`activities`,void 0),w([y({attribute:!1})],W.prototype,`deletingWorkspaceIds`,void 0),w([y({attribute:!1})],W.prototype,`unreadWorkspaceIds`,void 0),w([y({attribute:!1})],W.prototype,`statusSnapshot`,void 0),w([y({attribute:!1})],W.prototype,`onSelect`,void 0),w([y({attribute:!1})],W.prototype,`onDelete`,void 0),w([y({attribute:!1})],W.prototype,`onMove`,void 0),w([y({attribute:!1})],W.prototype,`onToggleCollapsed`,void 0),w([y({attribute:!1})],W.prototype,`onFocusPreviousSection`,void 0),w([y({attribute:!1})],W.prototype,`onFocusNextSection`,void 0),w([y({attribute:!1})],W.prototype,`onCancelKeyboardNavigation`,void 0),w([C()],W.prototype,`openMenuWorkspaceId`,void 0),w([C()],W.prototype,`copiedDetailKey`,void 0),w([C()],W.prototype,`trustByWorkspaceId`,void 0),w([C()],W.prototype,`branchCollapsed`,void 0),W=w([b(`workspace-list`)],W);function J_(e){return`${e.branch??e.label}${e.isMain?` · main`:``}`}function Y_(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}function X_(e){return e.slice(-8)}function Z_(e){return e.map((e,t)=>E`${t===0?null:E`<span class="session-label-separator" aria-hidden="true">·</span>`}${Q_(e)}`)}function Q_(e){if(e.type===`render`)return E`<span class="session-label-render">${e.render()}</span>`;if(e.type===`link`&&$_(e.href)){let t=e.target??`_blank`;return E`<a class="session-label-item" href=${e.href} title=${e.title??e.text} target=${t} rel=${t===`_blank`?`noopener noreferrer`:k}>${e.text}</a>`}return E`<span class="session-label-item" title=${e.title??e.text}>${e.text}</span>`}function $_(e){if(e.trim()===``)return!1;try{return[`http:`,`https:`,`mailto:`,`tel:`].includes(new URL(e,`https://pi-web.invalid/`).protocol)}catch{return!1}}function ev(e){return e.replace(/[/\\]+$/u,``)}function tv(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?X_(e.id):e.firstMessage}var nv=D(`client.parentSessionLocation.no.parent.session.available.in.this.workspace.cbd17a`,`No parent session available in this workspace`),rv=new Set([`onSelect`,`onSearch`,`onTogglePin`,`onStart`,`onToggleCollapsed`,`onArchivedCollapsed`,`onFocusPreviousSection`,`onFocusNextSection`,`onCancelKeyboardNavigation`,`onArchive`,`onArchiveWithDescendants`,`onArchiveMany`,`onRestore`,`onDelete`,`onDeleteArchived`,`onDeleteArchivedMany`,`onRename`,`onDetachParent`,`onMarkRead`,`onMarkReadMany`,`onReload`,`onCleanup`]),G=class extends O{constructor(){super(),this.popup=new w_(this,()=>{let e=this.shadowRoot?.querySelector(`.action-menu-panel`);return e&&this.menuAnchor?{anchor:this.menuAnchor,panel:e,onClose:()=>{this.openMenuSessionId=void 0},options:{minWidth:120}}:void 0}),this.scopeKey=``,this.sessions=[],this.pinnedSessionIds=[],this.pinnedRootIds=[],this.statuses={},this.activities={},this.sending={},this.unreadSessionIds=new Set,this.sessionLabelItems=()=>[],this.startingCount=0,this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.canCleanup=!1,this.authoritativeSessionPersistence=!1,this.archivedDeleteUnavailableMessage=D(`ui.appNavigationPanel.updateAndRestartPiWebOnThisMachine2`,`Update and restart Pi-Web on this machine before deleting archived sessions.`),this.cleanupUnavailableMessage=D(`ui.sessionCleanupDialog.updateAndRestartPiWebOnThisMachine`,`Update and restart Pi-Web on this machine before cleaning up sessions.`),this.collapsible=!1,this.collapsed=!1,this.externalScroll=!1,this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set,this.currentVisibleLimit=50,this.archivedVisibleLimit=50,this.expandedAgentParents=new Set,v.createController(this)}sessionTree(){if(this.treeCache?.sessions!==this.sessions||this.treeCache.pinnedSessionIds!==this.pinnedSessionIds){let e=wv(this.sessions,this.pinnedSessionIds),t=new Set(e.map(e=>e.session.id)),n=Tv(this.sessions.filter(e=>e.archived===!0&&!t.has(e.id)),this.pinnedSessionIds);this.treeCache={sessions:this.sessions,pinnedSessionIds:this.pinnedSessionIds,currentRows:e,currentAgentGroups:jv(e),archivedAgentGroups:jv(n),currentSelectableSessions:e.map(e=>e.session).filter(e=>sv(e)===`current`),archivedRows:n,archivedSessions:n.map(e=>e.session)}}return this.treeCache}visibleSessionTree(){let e=this.sessionTree();if(this.visibleTreeCache?.tree!==e||this.visibleTreeCache.expanded!==this.expandedAgentParents||this.visibleTreeCache.pins!==this.pinnedRootIds){let t=Dv(e.currentRows,this.pinnedSessionIds),n=[...this.pinnedRootIds.filter(e=>t.has(e)),...t],r=kv(Nv(e.currentRows,this.expandedAgentParents,e.currentAgentGroups),n),i=r.rows,a=Nv(e.archivedRows,this.expandedAgentParents,e.archivedAgentGroups);this.visibleTreeCache={tree:e,expanded:this.expandedAgentParents,pins:this.pinnedRootIds,pinnedRootIds:r.pinnedRootIds,pinnedRowCount:r.pinnedRowCount,currentRows:i,archivedRows:a,currentAgentOffsets:Av(i,e.currentAgentGroups),archivedAgentOffsets:Av(a,e.archivedAgentGroups),currentSelectableSessions:i.map(e=>e.session).filter(e=>sv(e)===`current`),archivedSessions:a.map(e=>e.session)}}return this.visibleTreeCache}automaticSessionCandidates(e){return Mv(e,{collapsed:this.collapsed,expandedAgentParents:this.expandedAgentParents,archivedExpanded:this.archivedExpanded})}agentGroupAttention(e,t){let n=this.agentAttentionCache;if(n?.rows===e&&n.statuses===this.statuses&&n.activities===this.activities&&n.sessionFlags===this.sessionFlags&&n.sending===this.sending&&n.unreadSessionIds===this.unreadSessionIds)return n.attention;let r=new Map;for(let n=e.length-1;n>=0;n--){let i=e[n];if(i===void 0)continue;let{session:a}=i,o=t.parentByAgentId.get(a.id);if(o===void 0)continue;let s=r.get(a.id),c=r.get(o),l=xv(a,this.statuses[a.id],this.activities[a.id],this.sending[a.id]===!0,this.sessionFlags),u=l===`sending`||s?.kind===`sending`||c?.kind===`sending`?`sending`:l??s?.kind??c?.kind,d=Sv(a,this.unreadSessionIds)||s?.unread===!0||c?.unread===!0;(u!==void 0||d)&&r.set(o,{kind:u,unread:d})}return this.agentAttentionCache={rows:e,statuses:this.statuses,activities:this.activities,sessionFlags:this.sessionFlags,sending:this.sending,unreadSessionIds:this.unreadSessionIds,attention:r},r}revealSelectedAgentRow(){if(this.selected===void 0)return!1;let e=this.sessionTree(),t=e.currentRows.some(e=>e.session.id===this.selected?.id)?e.currentAgentGroups:e.archivedAgentGroups,n=new Set(this.expandedAgentParents),r=new Set,i=this.selected.id;for(;i!==void 0&&!r.has(i);)r.add(i),i=t.parentByAgentId.get(i),i!==void 0&&n.add(i);return n.size!==this.expandedAgentParents.size&&(this.expandedAgentParents=n,!0)}toggleAgentParent(e){let t=new Set(this.expandedAgentParents);t.has(e)?t.delete(e):t.add(e),this.expandedAgentParents=t,t.has(e)||(this.selectedSessionIds=this.includeCollapsedChildren(this.selectedSessionIds)),this.openMenuSessionId=void 0}includeCollapsedChildren(e){if(e.size===0)return e;let t=this.sessionTree(),n=this.visibleSessionTree(),r=new Map(this.sessions.map(e=>[e.id,sv(e)])),i=new Set(e);for(let a of[`current`,`archived`]){let o=new Set([...e].filter(e=>r.get(e)===a));if(o.size!==0)for(let[e,r,s]of[[t.currentRows,n.currentRows,t.currentAgentGroups],[t.archivedRows,n.archivedRows,t.archivedAgentGroups]]){let t=new Set(r.map(e=>e.session.id));for(let{session:n}of e){let e=s.parentByAgentId.get(n.id);e!==void 0&&!t.has(n.id)&&o.has(e)&&(o.add(n.id),sv(n)===a&&i.add(n.id))}}}return i.size===e.size?e:i}connectedCallback(){super.connectedCallback()}disconnectedCallback(){this.loadMoreObserver?.disconnect(),this.loadMoreObserver=void 0,super.disconnectedCallback()}willUpdate(e){e.has(`pinnedRootIds`)&&(this.focusAfterPinReorder=this.focusedMenuControl),e.has(`scopeKey`)&&(this.currentVisibleLimit=50,this.archivedVisibleLimit=50,this.expandedAgentParents=new Set,this.selectionScopes=new Set,this.selectedSessionIds=new Set,this.openMenuSessionId=void 0),(e.has(`selected`)||e.has(`sessions`)||e.has(`pinnedSessionIds`))&&this.expandVisibleLimitForSelected()}shouldUpdate(e){for(let[t,n]of e)if(!rv.has(String(t))&&!(t===`sessions`&&uv(n,this.sessions))&&!(t===`selected`&&fv(n,this.selected))&&((t===`statuses`||t===`activities`)&&this.sessionTree().currentAgentGroups.parentByAgentId.size>0||!(t===`statuses`&&pv(n,this.statuses,this.activities,this.sending,this.sessions,this.authoritativeSessionPersistence,`status`))&&!(t===`activities`&&pv(n,this.activities,this.statuses,this.sending,this.sessions,this.authoritativeSessionPersistence,`activity`))))return!0;return!1}updated(e){if(e.has(`pinnedRootIds`)&&this.focusAfterPinReorder?.isConnected===!0){let e=this.focusAfterPinReorder;(e instanceof HTMLButtonElement&&e.disabled?e.closest(`.action-menu-panel`)?.querySelector(`button[data-pin-move]:not(:disabled)`):e)?.focus({preventScroll:!0})}this.focusAfterPinReorder=void 0,e.has(`sessions`)&&(this.openMenuSessionId!==void 0&&!this.sessions.some(e=>e.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),this.sessions.some(e=>e.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has(`collapsed`)&&this.collapsed&&(this.openMenuSessionId=void 0);let t=e.get(`selected`);e.has(`selected`)&&this.selected?.archived===!0&&(t?.id!==this.selected.id||t.archived!==!0)&&!this.archivedExpanded?(this.revealSelectedAgentRow(),this.expandVisibleLimitForSelected(),this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()})):(this.shouldRevealSelectedRow(e)&&(this.revealSelectedAgentRow()?(this.expandVisibleLimitForSelected(),this.updateComplete.then(()=>{this.scrollSelectedIntoView()})):this.scrollSelectedIntoView()),this.observeLoadMoreSentinels())}shouldRevealSelectedRow(e){if(this.collapsed)return!1;if(e.has(`scopeKey`)||e.has(`collapsed`))return!0;if(!e.has(`selected`))return!1;let t=e.get(`selected`);return t?.id!==this.selected?.id||t?.archived===!0&&this.selected?.archived!==!0}async focusSelectedOrFirst(){return await this.updateComplete,M_(this.renderRoot,{fallbackSelector:`.section-toggle, h2 button:not([disabled])`})}render(){let e=this.sessionTree(),{currentSelectableSessions:t}=e,{currentRows:n,archivedRows:r,currentAgentOffsets:i,archivedAgentOffsets:a,pinnedRowCount:o}=this.visibleSessionTree(),s=!this.collapsed&&e.currentAgentGroups.countByParentId.size>0&&n.some(({session:t})=>e.currentAgentGroups.countByParentId.has(t.id)&&!this.expandedAgentParents.has(t.id))?this.agentGroupAttention(e.currentRows,e.currentAgentGroups):void 0;this.collapsed||(e.descendantCounts??=lv(this.sessions));let c=iv(t,this.unreadSessionIds),l=n.slice(0,this.currentVisibleLimit),u=l.map(e=>e.session).filter(e=>sv(e)===`current`),d=r.slice(0,this.archivedVisibleLimit),f=d.map(e=>e.session);return E`
|
|
839
|
+
`]}};w([y({attribute:!1})],W.prototype,`workspaces`,void 0),w([y()],W.prototype,`machineId`,void 0),w([y({type:Boolean})],W.prototype,`managementMode`,void 0),w([y({type:Boolean,reflect:!0,attribute:`tree-layout`})],W.prototype,`treeLayout`,void 0),w([y({attribute:!1})],W.prototype,`selectedChildren`,void 0),w([y({attribute:!1})],W.prototype,`selected`,void 0),w([y({type:Boolean,reflect:!0})],W.prototype,`collapsible`,void 0),w([y({type:Boolean,reflect:!0})],W.prototype,`collapsed`,void 0),w([y({attribute:!1})],W.prototype,`workspaceLabelItems`,void 0),w([y({attribute:!1})],W.prototype,`activities`,void 0),w([y({attribute:!1})],W.prototype,`deletingWorkspaceIds`,void 0),w([y({attribute:!1})],W.prototype,`unreadWorkspaceIds`,void 0),w([y({attribute:!1})],W.prototype,`statusSnapshot`,void 0),w([y({attribute:!1})],W.prototype,`onSelect`,void 0),w([y({attribute:!1})],W.prototype,`onDelete`,void 0),w([y({attribute:!1})],W.prototype,`onMove`,void 0),w([y({attribute:!1})],W.prototype,`onToggleCollapsed`,void 0),w([y({attribute:!1})],W.prototype,`onFocusPreviousSection`,void 0),w([y({attribute:!1})],W.prototype,`onFocusNextSection`,void 0),w([y({attribute:!1})],W.prototype,`onCancelKeyboardNavigation`,void 0),w([C()],W.prototype,`openMenuWorkspaceId`,void 0),w([C()],W.prototype,`copiedDetailKey`,void 0),w([C()],W.prototype,`trustByWorkspaceId`,void 0),w([C()],W.prototype,`branchCollapsed`,void 0),W=w([b(`workspace-list`)],W);function Z_(e){return`${e.branch??e.label}${e.isMain?` · main`:``}`}function Q_(e){return`workspace-menu-${e.replace(/[^a-zA-Z0-9_-]/g,`-`)}`}function $_(e){return e.slice(-8)}function ev(e){return e.map((e,t)=>E`${t===0?null:E`<span class="session-label-separator" aria-hidden="true">·</span>`}${tv(e)}`)}function tv(e){if(e.type===`render`)return E`<span class="session-label-render">${e.render()}</span>`;if(e.type===`link`&&nv(e.href)){let t=e.target??`_blank`;return E`<a class="session-label-item" href=${e.href} title=${e.title??e.text} target=${t} rel=${t===`_blank`?`noopener noreferrer`:k}>${e.text}</a>`}return E`<span class="session-label-item" title=${e.title??e.text}>${e.text}</span>`}function nv(e){if(e.trim()===``)return!1;try{return[`http:`,`https:`,`mailto:`,`tel:`].includes(new URL(e,`https://pi-web.invalid/`).protocol)}catch{return!1}}function rv(e){return e.replace(/[/\\]+$/u,``)}function iv(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?$_(e.id):e.firstMessage}var av=D(`client.parentSessionLocation.no.parent.session.available.in.this.workspace.cbd17a`,`No parent session available in this workspace`),ov=new Set([`onSelect`,`onSearch`,`onTogglePin`,`onStart`,`onToggleCollapsed`,`onArchivedCollapsed`,`onFocusPreviousSection`,`onFocusNextSection`,`onCancelKeyboardNavigation`,`onArchive`,`onArchiveWithDescendants`,`onArchiveMany`,`onRestore`,`onDelete`,`onDeleteArchived`,`onDeleteArchivedMany`,`onRename`,`onDetachParent`,`onMarkRead`,`onMarkReadMany`,`onReload`,`onCleanup`]),G=class extends O{constructor(){super(),this.popup=new D_(this,()=>{let e=this.shadowRoot?.querySelector(`.action-menu-panel`);return e&&this.menuAnchor?{anchor:this.menuAnchor,panel:e,onClose:()=>{this.openMenuSessionId=void 0},options:{minWidth:120}}:void 0}),this.scopeKey=``,this.sessions=[],this.pinnedSessionIds=[],this.pinnedRootIds=[],this.statuses={},this.activities={},this.sending={},this.unreadSessionIds=new Set,this.sessionLabelItems=()=>[],this.startingCount=0,this.canStart=!1,this.canDeleteArchived=!1,this.canReload=!1,this.canCleanup=!1,this.authoritativeSessionPersistence=!1,this.archivedDeleteUnavailableMessage=D(`ui.appNavigationPanel.updateAndRestartPiWebOnThisMachine2`,`Update and restart Pi-Web on this machine before deleting archived sessions.`),this.cleanupUnavailableMessage=D(`ui.sessionCleanupDialog.updateAndRestartPiWebOnThisMachine`,`Update and restart Pi-Web on this machine before cleaning up sessions.`),this.collapsible=!1,this.collapsed=!1,this.externalScroll=!1,this.archivedExpanded=!1,this.selectionScopes=new Set,this.selectedSessionIds=new Set,this.currentVisibleLimit=50,this.archivedVisibleLimit=50,this.expandedAgentParents=new Set,v.createController(this)}sessionTree(){if(this.treeCache?.sessions!==this.sessions||this.treeCache.pinnedSessionIds!==this.pinnedSessionIds){let e=Dv(this.sessions,this.pinnedSessionIds),t=new Set(e.map(e=>e.session.id)),n=Ov(this.sessions.filter(e=>e.archived===!0&&!t.has(e.id)),this.pinnedSessionIds);this.treeCache={sessions:this.sessions,pinnedSessionIds:this.pinnedSessionIds,currentRows:e,currentAgentGroups:Pv(e),archivedAgentGroups:Pv(n),currentSelectableSessions:e.map(e=>e.session).filter(e=>uv(e)===`current`),archivedRows:n,archivedSessions:n.map(e=>e.session)}}return this.treeCache}visibleSessionTree(){let e=this.sessionTree();if(this.visibleTreeCache?.tree!==e||this.visibleTreeCache.expanded!==this.expandedAgentParents||this.visibleTreeCache.pins!==this.pinnedRootIds){let t=Av(e.currentRows,this.pinnedSessionIds),n=[...this.pinnedRootIds.filter(e=>t.has(e)),...t],r=Mv(Iv(e.currentRows,this.expandedAgentParents,e.currentAgentGroups),n),i=r.rows,a=Iv(e.archivedRows,this.expandedAgentParents,e.archivedAgentGroups);this.visibleTreeCache={tree:e,expanded:this.expandedAgentParents,pins:this.pinnedRootIds,pinnedRootIds:r.pinnedRootIds,pinnedRowCount:r.pinnedRowCount,currentRows:i,archivedRows:a,currentAgentOffsets:Nv(i,e.currentAgentGroups),archivedAgentOffsets:Nv(a,e.archivedAgentGroups),currentSelectableSessions:i.map(e=>e.session).filter(e=>uv(e)===`current`),archivedSessions:a.map(e=>e.session)}}return this.visibleTreeCache}automaticSessionCandidates(e){return Fv(e,{collapsed:this.collapsed,expandedAgentParents:this.expandedAgentParents,archivedExpanded:this.archivedExpanded})}agentGroupAttention(e,t){let n=this.agentAttentionCache;if(n?.rows===e&&n.statuses===this.statuses&&n.activities===this.activities&&n.sessionFlags===this.sessionFlags&&n.sending===this.sending&&n.unreadSessionIds===this.unreadSessionIds)return n.attention;let r=new Map;for(let n=e.length-1;n>=0;n--){let i=e[n];if(i===void 0)continue;let{session:a}=i,o=t.parentByAgentId.get(a.id);if(o===void 0)continue;let s=r.get(a.id),c=r.get(o),l=wv(a,this.statuses[a.id],this.activities[a.id],this.sending[a.id]===!0,this.sessionFlags),u=l===`sending`||s?.kind===`sending`||c?.kind===`sending`?`sending`:l??s?.kind??c?.kind,d=Tv(a,this.unreadSessionIds)||s?.unread===!0||c?.unread===!0;(u!==void 0||d)&&r.set(o,{kind:u,unread:d})}return this.agentAttentionCache={rows:e,statuses:this.statuses,activities:this.activities,sessionFlags:this.sessionFlags,sending:this.sending,unreadSessionIds:this.unreadSessionIds,attention:r},r}revealSelectedAgentRow(){if(this.selected===void 0)return!1;let e=this.sessionTree(),t=e.currentRows.some(e=>e.session.id===this.selected?.id)?e.currentAgentGroups:e.archivedAgentGroups,n=new Set(this.expandedAgentParents),r=new Set,i=this.selected.id;for(;i!==void 0&&!r.has(i);)r.add(i),i=t.parentByAgentId.get(i),i!==void 0&&n.add(i);return n.size!==this.expandedAgentParents.size&&(this.expandedAgentParents=n,!0)}toggleAgentParent(e){let t=new Set(this.expandedAgentParents);t.has(e)?t.delete(e):t.add(e),this.expandedAgentParents=t,t.has(e)||(this.selectedSessionIds=this.includeCollapsedChildren(this.selectedSessionIds)),this.openMenuSessionId=void 0}includeCollapsedChildren(e){if(e.size===0)return e;let t=this.sessionTree(),n=this.visibleSessionTree(),r=new Map(this.sessions.map(e=>[e.id,uv(e)])),i=new Set(e);for(let a of[`current`,`archived`]){let o=new Set([...e].filter(e=>r.get(e)===a));if(o.size!==0)for(let[e,r,s]of[[t.currentRows,n.currentRows,t.currentAgentGroups],[t.archivedRows,n.archivedRows,t.archivedAgentGroups]]){let t=new Set(r.map(e=>e.session.id));for(let{session:n}of e){let e=s.parentByAgentId.get(n.id);e!==void 0&&!t.has(n.id)&&o.has(e)&&(o.add(n.id),uv(n)===a&&i.add(n.id))}}}return i.size===e.size?e:i}connectedCallback(){super.connectedCallback()}disconnectedCallback(){this.loadMoreObserver?.disconnect(),this.loadMoreObserver=void 0,super.disconnectedCallback()}willUpdate(e){e.has(`pinnedRootIds`)&&(this.focusAfterPinReorder=this.focusedMenuControl),e.has(`scopeKey`)&&(this.currentVisibleLimit=50,this.archivedVisibleLimit=50,this.expandedAgentParents=new Set,this.selectionScopes=new Set,this.selectedSessionIds=new Set,this.openMenuSessionId=void 0),(e.has(`selected`)||e.has(`sessions`)||e.has(`pinnedSessionIds`))&&this.expandVisibleLimitForSelected()}shouldUpdate(e){for(let[t,n]of e)if(!ov.has(String(t))&&!(t===`sessions`&&pv(n,this.sessions))&&!(t===`selected`&&hv(n,this.selected))&&((t===`statuses`||t===`activities`)&&this.sessionTree().currentAgentGroups.parentByAgentId.size>0||!(t===`statuses`&&gv(n,this.statuses,this.activities,this.sending,this.sessions,this.authoritativeSessionPersistence,`status`))&&!(t===`activities`&&gv(n,this.activities,this.statuses,this.sending,this.sessions,this.authoritativeSessionPersistence,`activity`))))return!0;return!1}updated(e){if(e.has(`pinnedRootIds`)&&this.focusAfterPinReorder?.isConnected===!0){let e=this.focusAfterPinReorder;(e instanceof HTMLButtonElement&&e.disabled?e.closest(`.action-menu-panel`)?.querySelector(`button[data-pin-move]:not(:disabled)`):e)?.focus({preventScroll:!0})}this.focusAfterPinReorder=void 0,e.has(`sessions`)&&(this.openMenuSessionId!==void 0&&!this.sessions.some(e=>e.id===this.openMenuSessionId)&&(this.openMenuSessionId=void 0),this.sessions.some(e=>e.archived===!0)||(this.archivedExpanded=!1),this.pruneSelectedSessionIds()),e.has(`collapsed`)&&this.collapsed&&(this.openMenuSessionId=void 0);let t=e.get(`selected`);e.has(`selected`)&&this.selected?.archived===!0&&(t?.id!==this.selected.id||t.archived!==!0)&&!this.archivedExpanded?(this.revealSelectedAgentRow(),this.expandVisibleLimitForSelected(),this.archivedExpanded=!0,this.updateComplete.then(()=>{this.scrollSelectedIntoView()})):(this.shouldRevealSelectedRow(e)&&(this.revealSelectedAgentRow()?(this.expandVisibleLimitForSelected(),this.updateComplete.then(()=>{this.scrollSelectedIntoView()})):this.scrollSelectedIntoView()),this.observeLoadMoreSentinels())}shouldRevealSelectedRow(e){if(this.collapsed)return!1;if(e.has(`scopeKey`)||e.has(`collapsed`))return!0;if(!e.has(`selected`))return!1;let t=e.get(`selected`);return t?.id!==this.selected?.id||t?.archived===!0&&this.selected?.archived!==!0}async focusSelectedOrFirst(){return await this.updateComplete,F_(this.renderRoot,{fallbackSelector:`.section-toggle, h2 button:not([disabled])`})}render(){let e=this.sessionTree(),{currentSelectableSessions:t}=e,{currentRows:n,archivedRows:r,currentAgentOffsets:i,archivedAgentOffsets:a,pinnedRowCount:o}=this.visibleSessionTree(),s=!this.collapsed&&e.currentAgentGroups.countByParentId.size>0&&n.some(({session:t})=>e.currentAgentGroups.countByParentId.has(t.id)&&!this.expandedAgentParents.has(t.id))?this.agentGroupAttention(e.currentRows,e.currentAgentGroups):void 0;this.collapsed||(e.descendantCounts??=fv(this.sessions));let c=sv(t,this.unreadSessionIds),l=n.slice(0,this.currentVisibleLimit),u=l.map(e=>e.session).filter(e=>uv(e)===`current`),d=r.slice(0,this.archivedVisibleLimit),f=d.map(e=>e.session);return E`
|
|
840
840
|
<section>
|
|
841
841
|
${this.renderHeading(e.currentRows.length+e.archivedRows.length,t,c)}
|
|
842
842
|
${this.collapsed?null:E`
|
|
@@ -872,7 +872,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
872
872
|
${this.renderStartButton()}
|
|
873
873
|
</span>
|
|
874
874
|
</h2>
|
|
875
|
-
`;let r=this.selected===void 0?D(`ui.sessionList.noSessionSelected`,`No session selected`):
|
|
875
|
+
`;let r=this.selected===void 0?D(`ui.sessionList.noSessionSelected`,`No session selected`):iv(this.selected),i=this.selected?.path??r;return E`
|
|
876
876
|
<h2 class="ui-toolbar session-heading">
|
|
877
877
|
<button class="ui-button ui-toolbar-title section-toggle" aria-expanded=${String(!this.collapsed)} @click=${()=>{this.onToggleCollapsed?.()}}><span class="section-title"><span class="section-name">${this.collapsed?`▸`:`▾`} ${D(`ui.sessionSearchDialog.sessions`,`Sessions`)}</span>${this.collapsed?E`<small class="section-selected" dir="auto" title=${i}>${r}</small>`:null}</span></button>
|
|
878
878
|
${this.renderUnreadCount(n)}
|
|
@@ -912,19 +912,19 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
912
912
|
`}renderSelectionControls(e,t){let n=this.selectedSessions(e).length,r=t.filter(e=>this.selectedSessionIds.has(e.id)).length;return E`
|
|
913
913
|
${n===0?E`<button @click=${()=>{this.selectVisibleSessions(t)}}>${D(`ui.sessionList.selectVisible`,`Select visible`)}</button>`:E`<button @click=${()=>{this.clearSelection(e)}}>${D(`ui.sessionList.clearSelectedCount`,`Clear selected ({count})`,{count:n})}</button>`}
|
|
914
914
|
${r===n?null:E`<small>${D(`ui.main.fcafc66aea52`,` visible`)} ${r}</small>`}
|
|
915
|
-
`}renderSession(e,t,n=0,r=0,i){let{session:a}=e,o=r>0,s=Math.min(e.depth,2),c=
|
|
915
|
+
`}renderSession(e,t,n=0,r=0,i){let{session:a}=e,o=r>0,s=Math.min(e.depth,2),c=uv(a)===t,l=this.selectionScopes.has(t),u=l&&c,d=u&&this.selectedSessionIds.has(a.id),f=this.statuses[a.id],p=this.activities[a.id],m=wv(a,f,p,this.sending[a.id]===!0,this.sessionFlags),h=wv(a,f,p,!1,this.sessionFlags)===`session`,g=Tv(a,this.unreadSessionIds),ee=this.sessionPersistenceOptions(),_=zs(a,f,ee),te=lv(a,f,ee),ne=Bs(a,f,ee),re=_&&this.canReload,ie=this.pinnedSessionIds.includes(a.id),ae=a.persisted!==!1,v=this.openMenuSessionId===a.id?this.sessionTree().descendantCounts?.get(a.id)??0:0,oe=this.sessionLabelItems(a);return E`
|
|
916
916
|
<div
|
|
917
917
|
class="action-row ${this.selected?.id===a.id?`selected`:``} ${d?`bulk-selected`:``} ${a.archived===!0?`archived`:``} ${l?`selecting`:``} ${g?`unread`:``} ${ie?`pinned`:``} ${this.openMenuSessionId===a.id?`menu-open`:``} ${n>0?`has-agent-subsessions`:``} ${o?`linked-agent-child`:``}"
|
|
918
918
|
style=${`--depth:${String(s)};--agent-offset:${String(r)}px`}
|
|
919
919
|
tabindex="0"
|
|
920
920
|
title=${a.path}
|
|
921
|
-
@click=${e=>{
|
|
921
|
+
@click=${e=>{N_(e,()=>{this.activateSessionRow(a,t)})}}
|
|
922
922
|
@keydown=${e=>{this.handleSessionKeydown(e,a,t)}}
|
|
923
923
|
>
|
|
924
924
|
<div class="action-main ${l?`selecting`:``}">
|
|
925
|
-
${u?E`<input class="session-checkbox" type="checkbox" aria-label=${D(`ui.sessionList.select`,`Select {sessionLabelsession}`,{sessionLabelsession:
|
|
926
|
-
<span class="action-name-line"><span class="action-name" dir="auto" title=${
|
|
927
|
-
<small class="session-secondary"><span class="session-meta">${this.renderSessionMetaPrefix(a,f,p)}${String(a.messageCount)} ${D(`ui.sessionList.messages`,`messages`)}</span>${oe.length===0?null:E`<span class="session-label-separator" aria-hidden="true">·</span><span class="session-labels">${
|
|
925
|
+
${u?E`<input class="session-checkbox" type="checkbox" aria-label=${D(`ui.sessionList.select`,`Select {sessionLabelsession}`,{sessionLabelsession:iv(a)})} .checked=${d} @click=${e=>{e.stopPropagation()}} @change=${()=>{this.toggleSelected(a.id)}}>`:null}
|
|
926
|
+
<span class="action-name-line"><span class="action-name" dir="auto" title=${iv(a)}>${this.renderRowMarker(e)}${ie?E`<span class="pin-indicator" title="${D(`ui.sessionList.pinned`,`Pinned`)}" aria-label="${D(`ui.sessionList.pinned`,`Pinned`)}">★</span>`:null}${iv(a)}</span>${this.renderRowBadges(e)}</span>
|
|
927
|
+
<small class="session-secondary"><span class="session-meta">${this.renderSessionMetaPrefix(a,f,p)}${String(a.messageCount)} ${D(`ui.sessionList.messages`,`messages`)}</span>${oe.length===0?null:E`<span class="session-label-separator" aria-hidden="true">·</span><span class="session-labels">${ev(oe)}</span>`}</small>
|
|
928
928
|
${this.renderActivity(m,g)}
|
|
929
929
|
</div>
|
|
930
930
|
<div class="action-menu">
|
|
@@ -953,15 +953,15 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
953
953
|
`:null}
|
|
954
954
|
</div>
|
|
955
955
|
</div>
|
|
956
|
-
${n>0?E`<button class="agent-subsession-toggle" style=${`--depth:${String(s)};--agent-offset:${String(r)}px`} aria-expanded=${String(this.expandedAgentParents.has(a.id))} @click=${()=>{this.toggleAgentParent(a.id)}}><span class="agent-subsession-label">${this.expandedAgentParents.has(a.id)?`▾`:`▸`} ${D(`ui.navigation.agentSubsessions`,`Agent subsessions ({count})`,{count:n})}</span>${!this.expandedAgentParents.has(a.id)&&i!==void 0?
|
|
956
|
+
${n>0?E`<button class="agent-subsession-toggle" style=${`--depth:${String(s)};--agent-offset:${String(r)}px`} aria-expanded=${String(this.expandedAgentParents.has(a.id))} @click=${()=>{this.toggleAgentParent(a.id)}}><span class="agent-subsession-label">${this.expandedAgentParents.has(a.id)?`▾`:`▸`} ${D(`ui.navigation.agentSubsessions`,`Agent subsessions ({count})`,{count:n})}</span>${!this.expandedAgentParents.has(a.id)&&i!==void 0?C_(i.kind,i.kind===`sending`?D(`ui.navigation.sendingSubsessionMessage`,`Sending subsession message`):D(`ui.navigation.agentSubsessionsActive`,`Agent subsessions active`),i.unread?D(`ui.navigation.unreadSubsessionActivity`,`Unread subsession activity`):void 0):null}</button>`:null}
|
|
957
957
|
`}renderPinMoveActions(e){let t=this.visibleSessionTree().pinnedRootIds,n=t.indexOf(e.session.id);return this.onMovePin===void 0||n<0?null:E`
|
|
958
958
|
<button class="ui-button ui-menu-item" data-pin-move ?disabled=${n===0} @click=${()=>{this.onMovePin?.(e.session,-1)}}>${D(`ui.navigation.moveUp`,`Move up`)}</button>
|
|
959
959
|
<button class="ui-button ui-menu-item" data-pin-move ?disabled=${n===t.length-1} @click=${()=>{this.onMovePin?.(e.session,1)}}>${D(`ui.navigation.moveDown`,`Move down`)}</button>
|
|
960
|
-
`}renderRowMarker(e){return e.hasMissingParent?E`<span class="tree-marker orphan-marker" title=${
|
|
960
|
+
`}renderRowMarker(e){return e.hasMissingParent?E`<span class="tree-marker orphan-marker" title=${av} aria-label=${av}>↳</span>`:e.depth>0?E`<span class="tree-marker">↳</span>`:null}renderRowBadges(e){return e.depth<=2?null:E`<span class="row-badges"><span class="badge">depth ${e.depth}</span></span>`}handleSessionKeydown(e,t,n){P_(e,{activate:()=>{this.activateSessionRow(t,n)},previousSection:this.onFocusPreviousSection===void 0?void 0:()=>{this.onFocusPreviousSection?.()},nextSection:this.onFocusNextSection===void 0?void 0:()=>{this.onFocusNextSection?.()},cancel:this.onCancelKeyboardNavigation===void 0?void 0:()=>{this.onCancelKeyboardNavigation?.()}})}activateSessionRow(e,t){this.selectionScopes.has(t)&&uv(e)===t?this.toggleSelected(e.id):this.onSelect?.(e)}renameSession(e){this.openMenuSessionId=void 0;let t=cv(e);t!==void 0&&this.onRename?.(e,t)}confirmArchiveWithDescendants(e,t){confirm(D(`ui.sessionList.archiveAndItsDescendantSessions`,`Archive "{sessionLabelsession}" and its {descendantCount} descendant sessions?`,{sessionLabelsession:iv(e),descendantCount:String(t)}))&&this.onArchiveWithDescendants?.(e)}confirmDeleteArchived(e){this.canDeleteArchived&&confirm(D(`ui.sessionList.permanentlyDeleteArchivedSessionThisCannotBeUndone`,`Permanently delete archived session "{sessionLabelsession}"? This cannot be undone.`,{sessionLabelsession:iv(e)}))&&this.onDeleteArchived?.(e)}confirmDeleteSelectedArchived(){if(!this.canDeleteArchived)return;let e=this.selectedSessions(`archived`);e.length!==0&&confirm(D(`ui.sessionList.permanentlyDeleteSelectedArchivedSessionsThisCannotBe`,`Permanently delete {length} selected archived sessions? This cannot be undone.`,{length:String(e.length)}))&&(this.selectedSessionIds=dv(this.selectedSessionIds,e.map(e=>e.id)),this.onDeleteArchivedMany?.(e))}markSelectedCurrentRead(){let e=this.selectedSessions(`current`).filter(e=>this.unreadSessionIds.has(e.id));e.length!==0&&this.onMarkReadMany?.(e)}archiveSelectedCurrent(){let e=this.selectedSessions(`current`).filter(e=>zs(e,this.statuses[e.id],this.sessionPersistenceOptions()));this.selectedSessionIds=dv(this.selectedSessionIds,e.map(e=>e.id)),this.onArchiveMany?.(e)}toggleSelection(e,t){this.selectionScopes.has(e)?this.closeSelection(e):this.startSelection(e,t)}startSelection(e,t){this.selectionScopes=new Set([...this.selectionScopes,e]);let n=t.length===1?t[0]:void 0;n!==void 0&&(this.selectedSessionIds=this.includeCollapsedChildren(new Set([...this.selectedSessionIds,n.id])))}closeSelection(e){this.selectionScopes=new Set([...this.selectionScopes].filter(t=>t!==e)),this.clearSelection(e)}clearSelection(e){let t=this.sessions.filter(t=>uv(t)===e).map(e=>e.id);this.selectedSessionIds=dv(this.selectedSessionIds,t)}toggleSelected(e){let t=this.includeCollapsedChildren(new Set([e])),n=this.selectedSessionIds.has(e),r=new Set(this.selectedSessionIds);for(let e of t)n?r.delete(e):r.add(e);this.selectedSessionIds=r}selectVisibleSessions(e){this.selectedSessionIds=this.includeCollapsedChildren(new Set([...this.selectedSessionIds,...e.map(e=>e.id)]))}selectedSessions(e){return this.sessions.filter(t=>this.selectedSessionIds.has(t.id)&&uv(t)===e)}pruneSelectedSessionIds(){let e=new Set(this.sessions.map(e=>e.id)),t=new Set([...this.selectedSessionIds].filter(t=>e.has(t)));t.size!==this.selectedSessionIds.size&&(this.selectedSessionIds=t),this.selectedSessionIds=this.includeCollapsedChildren(this.selectedSessionIds),this.selectionScopes.has(`archived`)&&!this.sessions.some(e=>e.archived===!0)&&this.closeSelection(`archived`),this.selectionScopes.has(`current`)&&!this.sessions.some(e=>e.archived!==!0)&&this.closeSelection(`current`)}toggleMenu(e,t){this.openMenuSessionId===e?this.openMenuSessionId=void 0:(this.menuAnchor=t instanceof HTMLElement?t:void 0,this.openMenuSessionId=e)}toggleArchived(){this.archivedExpanded=!this.archivedExpanded,this.archivedExpanded||(this.openMenuSessionId=void 0,this.selectionScopes.has(`archived`)&&this.closeSelection(`archived`),this.onArchivedCollapsed?.())}renderLoadMoreSentinel(e,t,n){if(t>=n)return null;let r=n-t;return E`
|
|
961
961
|
<div class="session-load-more-sentinel">
|
|
962
962
|
<button class="ui-button" data-load-scope=${e} @click=${()=>{this.loadMore(e)}}>${D(`ui.sessionList.loadMoreCount`,`Load more ({count} remaining)`,{count:r})}</button>
|
|
963
963
|
</div>
|
|
964
|
-
`}loadMore(e){e===`current`?this.currentVisibleLimit+=50:this.archivedVisibleLimit+=50}observeLoadMoreSentinels(){if(this.loadMoreObserver?.disconnect(),this.loadMoreObserver=void 0,typeof IntersectionObserver>`u`||this.listBody===void 0)return;let e=new IntersectionObserver(t=>{if(this.loadMoreObserver===e&&this.isConnected)for(let e of t){if(!e.isIntersecting)continue;let t=e.target.getAttribute(`data-load-scope`);t===`current`?this.loadMore(`current`):t===`archived`&&!this.hasMoreCurrentRows()&&this.loadMore(`archived`)}},{root:this.externalScroll?null:this.listBody,rootMargin:`0px 0px 160px`});for(let t of this.renderRoot.querySelectorAll(`[data-load-scope]`))e.observe(t);this.loadMoreObserver=e}hasMoreCurrentRows(){return this.visibleSessionTree().currentRows.length>this.currentVisibleLimit}expandVisibleLimitForSelected(){let e=this.selected;if(e===void 0)return;let t=this.visibleSessionTree().currentRows,n=t.findIndex(t=>t.session.id===e.id);if(n>=0){this.currentVisibleLimit=Math.max(this.currentVisibleLimit,n+1);return}let r=new Set(t.map(e=>e.session.id)),i=
|
|
964
|
+
`}loadMore(e){e===`current`?this.currentVisibleLimit+=50:this.archivedVisibleLimit+=50}observeLoadMoreSentinels(){if(this.loadMoreObserver?.disconnect(),this.loadMoreObserver=void 0,typeof IntersectionObserver>`u`||this.listBody===void 0)return;let e=new IntersectionObserver(t=>{if(this.loadMoreObserver===e&&this.isConnected)for(let e of t){if(!e.isIntersecting)continue;let t=e.target.getAttribute(`data-load-scope`);t===`current`?this.loadMore(`current`):t===`archived`&&!this.hasMoreCurrentRows()&&this.loadMore(`archived`)}},{root:this.externalScroll?null:this.listBody,rootMargin:`0px 0px 160px`});for(let t of this.renderRoot.querySelectorAll(`[data-load-scope]`))e.observe(t);this.loadMoreObserver=e}hasMoreCurrentRows(){return this.visibleSessionTree().currentRows.length>this.currentVisibleLimit}expandVisibleLimitForSelected(){let e=this.selected;if(e===void 0)return;let t=this.visibleSessionTree().currentRows,n=t.findIndex(t=>t.session.id===e.id);if(n>=0){this.currentVisibleLimit=Math.max(this.currentVisibleLimit,n+1);return}let r=new Set(t.map(e=>e.session.id)),i=Ov(this.sessions.filter(e=>e.archived===!0&&!r.has(e.id)),this.pinnedSessionIds).findIndex(t=>t.session.id===e.id);i<0||(this.currentVisibleLimit=Math.max(this.currentVisibleLimit,t.length),this.archivedVisibleLimit=Math.max(this.archivedVisibleLimit,i+1))}scrollSelectedIntoView(){this.renderRoot.querySelector(`.action-row.selected`)?.scrollIntoView({block:`nearest`})}renderSessionMetaPrefix(e,t,n){return Bs(e,t,this.sessionPersistenceOptions())?n?.phase===`active`?D(`ui.sessionList.newSessionCreating`,`New session · Creating · `):n?.phase===`error`?D(`ui.sessionList.newSessionError`,`New session · Error · `):n?.phase===`idle`?D(`ui.sessionList.created`,`Created · `):D(`ui.sessionList.newSession`,`New session · `):e.archived===!0?D(`ui.sessionList.readOnly`,`Read-only · `):``}sessionPersistenceOptions(){return{authoritative:this.authoritativeSessionPersistence}}renderActivity(e,t){return C_(e,e===`sending`?D(`ui.sessionList.sendingMessage`,`Sending message`):D(`ui.sessionList.sessionActive`,`Session active`),t?D(`ui.sessionList.unreadSessionActivity`,`Unread session activity`):void 0)}static{this.styles=[Vh,U_,T`
|
|
965
965
|
@layer pi-web-base {
|
|
966
966
|
:host { container-type: inline-size; }
|
|
967
967
|
.list-body { isolation: isolate; }
|
|
@@ -1004,7 +1004,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1004
1004
|
/* Same glyph as a normal child marker, dimmed: the row is a child whose parent is not displayed here. */
|
|
1005
1005
|
.orphan-marker { color: var(--pi-dim); opacity: .65; }
|
|
1006
1006
|
.bulk-row .capability-hint { flex: 1 0 100%; color: var(--pi-warning); }
|
|
1007
|
-
.selection-toolbar { position: sticky; top: 0; z-index: 4; background: var(--pi-bg); border-bottom: 1px solid var(--pi-border-muted); box-shadow: ${
|
|
1007
|
+
.selection-toolbar { position: sticky; top: 0; z-index: 4; background: var(--pi-bg); border-bottom: 1px solid var(--pi-border-muted); box-shadow: ${Rh}; }
|
|
1008
1008
|
.action-row.has-agent-subsessions { margin-bottom: 0; border-bottom: 0; }
|
|
1009
1009
|
.action-row.has-agent-subsessions .action-main { padding-bottom: 6px; }
|
|
1010
1010
|
.agent-subsession-toggle { position: relative; display: flex; align-items: center; gap: 6px; box-sizing: border-box; width: 100%; min-height: 24px; margin: 0; padding-block: 2px; padding-inline: calc(35px + var(--agent-offset, 0px) + var(--depth, 0) * 16px) 16px; border: 0; border-radius: 0; background: transparent; font: 12px/20px var(--pi-font, system-ui, sans-serif); text-align: start; color: var(--pi-muted); overflow: hidden; }
|
|
@@ -1027,7 +1027,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1027
1027
|
.session-checkbox { position: absolute; top: 9px; inset-inline-start: calc(24px + var(--depth, 0) * 16px + var(--agent-offset, 0px)); z-index: 2; margin: 0; }
|
|
1028
1028
|
|
|
1029
1029
|
}
|
|
1030
|
-
`]}};w([y({attribute:!1})],G.prototype,`scopeKey`,void 0),w([y({attribute:!1})],G.prototype,`sessions`,void 0),w([y({attribute:!1})],G.prototype,`pinnedSessionIds`,void 0),w([y({attribute:!1})],G.prototype,`pinnedRootIds`,void 0),w([y({attribute:!1})],G.prototype,`onMovePin`,void 0),w([y({attribute:!1})],G.prototype,`statuses`,void 0),w([y({attribute:!1})],G.prototype,`activities`,void 0),w([y({attribute:!1})],G.prototype,`sessionFlags`,void 0),w([y({attribute:!1})],G.prototype,`sending`,void 0),w([y({attribute:!1})],G.prototype,`unreadSessionIds`,void 0),w([y({attribute:!1})],G.prototype,`selected`,void 0),w([y({attribute:!1})],G.prototype,`sessionLabelItems`,void 0),w([y({type:Number})],G.prototype,`startingCount`,void 0),w([y({type:Boolean})],G.prototype,`canStart`,void 0),w([y({type:Boolean})],G.prototype,`canDeleteArchived`,void 0),w([y({type:Boolean})],G.prototype,`canReload`,void 0),w([y({type:Boolean})],G.prototype,`canCleanup`,void 0),w([y({type:Boolean})],G.prototype,`authoritativeSessionPersistence`,void 0),w([y({type:String})],G.prototype,`archivedDeleteUnavailableMessage`,void 0),w([y({type:String})],G.prototype,`cleanupUnavailableMessage`,void 0),w([y({type:Boolean,reflect:!0})],G.prototype,`collapsible`,void 0),w([y({type:Boolean,reflect:!0})],G.prototype,`collapsed`,void 0),w([y({type:Boolean,attribute:`external-scroll`})],G.prototype,`externalScroll`,void 0),w([y({attribute:!1})],G.prototype,`onSelect`,void 0),w([y({attribute:!1})],G.prototype,`onSearch`,void 0),w([y({attribute:!1})],G.prototype,`onTogglePin`,void 0),w([y({attribute:!1})],G.prototype,`onStart`,void 0),w([y({attribute:!1})],G.prototype,`onToggleCollapsed`,void 0),w([y({attribute:!1})],G.prototype,`onArchivedCollapsed`,void 0),w([y({attribute:!1})],G.prototype,`onFocusPreviousSection`,void 0),w([y({attribute:!1})],G.prototype,`onFocusNextSection`,void 0),w([y({attribute:!1})],G.prototype,`onCancelKeyboardNavigation`,void 0),w([y({attribute:!1})],G.prototype,`onArchive`,void 0),w([y({attribute:!1})],G.prototype,`onArchiveWithDescendants`,void 0),w([y({attribute:!1})],G.prototype,`onArchiveMany`,void 0),w([y({attribute:!1})],G.prototype,`onRestore`,void 0),w([y({attribute:!1})],G.prototype,`onDelete`,void 0),w([y({attribute:!1})],G.prototype,`onDeleteArchived`,void 0),w([y({attribute:!1})],G.prototype,`onDeleteArchivedMany`,void 0),w([y({attribute:!1})],G.prototype,`onRename`,void 0),w([y({attribute:!1})],G.prototype,`onDetachParent`,void 0),w([y({attribute:!1})],G.prototype,`onMarkRead`,void 0),w([y({attribute:!1})],G.prototype,`onMarkReadMany`,void 0),w([y({attribute:!1})],G.prototype,`onReload`,void 0),w([y({attribute:!1})],G.prototype,`onCleanup`,void 0),w([C()],G.prototype,`openMenuSessionId`,void 0),w([C()],G.prototype,`archivedExpanded`,void 0),w([C()],G.prototype,`selectionScopes`,void 0),w([C()],G.prototype,`selectedSessionIds`,void 0),w([C()],G.prototype,`currentVisibleLimit`,void 0),w([C()],G.prototype,`archivedVisibleLimit`,void 0),w([S(`.list-body`)],G.prototype,`listBody`,void 0),w([C()],G.prototype,`expandedAgentParents`,void 0),G=w([b(`session-list`)],G);function
|
|
1030
|
+
`]}};w([y({attribute:!1})],G.prototype,`scopeKey`,void 0),w([y({attribute:!1})],G.prototype,`sessions`,void 0),w([y({attribute:!1})],G.prototype,`pinnedSessionIds`,void 0),w([y({attribute:!1})],G.prototype,`pinnedRootIds`,void 0),w([y({attribute:!1})],G.prototype,`onMovePin`,void 0),w([y({attribute:!1})],G.prototype,`statuses`,void 0),w([y({attribute:!1})],G.prototype,`activities`,void 0),w([y({attribute:!1})],G.prototype,`sessionFlags`,void 0),w([y({attribute:!1})],G.prototype,`sending`,void 0),w([y({attribute:!1})],G.prototype,`unreadSessionIds`,void 0),w([y({attribute:!1})],G.prototype,`selected`,void 0),w([y({attribute:!1})],G.prototype,`sessionLabelItems`,void 0),w([y({type:Number})],G.prototype,`startingCount`,void 0),w([y({type:Boolean})],G.prototype,`canStart`,void 0),w([y({type:Boolean})],G.prototype,`canDeleteArchived`,void 0),w([y({type:Boolean})],G.prototype,`canReload`,void 0),w([y({type:Boolean})],G.prototype,`canCleanup`,void 0),w([y({type:Boolean})],G.prototype,`authoritativeSessionPersistence`,void 0),w([y({type:String})],G.prototype,`archivedDeleteUnavailableMessage`,void 0),w([y({type:String})],G.prototype,`cleanupUnavailableMessage`,void 0),w([y({type:Boolean,reflect:!0})],G.prototype,`collapsible`,void 0),w([y({type:Boolean,reflect:!0})],G.prototype,`collapsed`,void 0),w([y({type:Boolean,attribute:`external-scroll`})],G.prototype,`externalScroll`,void 0),w([y({attribute:!1})],G.prototype,`onSelect`,void 0),w([y({attribute:!1})],G.prototype,`onSearch`,void 0),w([y({attribute:!1})],G.prototype,`onTogglePin`,void 0),w([y({attribute:!1})],G.prototype,`onStart`,void 0),w([y({attribute:!1})],G.prototype,`onToggleCollapsed`,void 0),w([y({attribute:!1})],G.prototype,`onArchivedCollapsed`,void 0),w([y({attribute:!1})],G.prototype,`onFocusPreviousSection`,void 0),w([y({attribute:!1})],G.prototype,`onFocusNextSection`,void 0),w([y({attribute:!1})],G.prototype,`onCancelKeyboardNavigation`,void 0),w([y({attribute:!1})],G.prototype,`onArchive`,void 0),w([y({attribute:!1})],G.prototype,`onArchiveWithDescendants`,void 0),w([y({attribute:!1})],G.prototype,`onArchiveMany`,void 0),w([y({attribute:!1})],G.prototype,`onRestore`,void 0),w([y({attribute:!1})],G.prototype,`onDelete`,void 0),w([y({attribute:!1})],G.prototype,`onDeleteArchived`,void 0),w([y({attribute:!1})],G.prototype,`onDeleteArchivedMany`,void 0),w([y({attribute:!1})],G.prototype,`onRename`,void 0),w([y({attribute:!1})],G.prototype,`onDetachParent`,void 0),w([y({attribute:!1})],G.prototype,`onMarkRead`,void 0),w([y({attribute:!1})],G.prototype,`onMarkReadMany`,void 0),w([y({attribute:!1})],G.prototype,`onReload`,void 0),w([y({attribute:!1})],G.prototype,`onCleanup`,void 0),w([C()],G.prototype,`openMenuSessionId`,void 0),w([C()],G.prototype,`archivedExpanded`,void 0),w([C()],G.prototype,`selectionScopes`,void 0),w([C()],G.prototype,`selectedSessionIds`,void 0),w([C()],G.prototype,`currentVisibleLimit`,void 0),w([C()],G.prototype,`archivedVisibleLimit`,void 0),w([S(`.list-body`)],G.prototype,`listBody`,void 0),w([C()],G.prototype,`expandedAgentParents`,void 0),G=w([b(`session-list`)],G);function sv(e,t){return t.size===0?0:e.filter(e=>Tv(e,t)).length}function cv(e){let t=globalThis.prompt(D(`ui.sessionList.renameSession`,`Rename session`),iv(e))?.trim();return t===void 0||t===``?void 0:t}function lv(e,t,n){return zs(e,t,n)}function uv(e){return e.archived===!0?`archived`:`current`}function dv(e,t){let n=new Set(t);return new Set([...e].filter(e=>!n.has(e)))}function fv(e){let t=new Map;for(let n of e){if(n.parentSessionPath===void 0)continue;let e=rv(n.parentSessionPath),r=t.get(e)??[];r.push(n),t.set(e,r)}let n=(e,r)=>{let i=rv(e.path);if(r.has(i))return 0;let a=new Set(r);a.add(i);let o=0;for(let e of t.get(i)??[])a.has(rv(e.path))||(e.archived!==!0&&(o+=1),o+=n(e,a));return o};return new Map(e.map(e=>[e.id,n(e,new Set)]))}function pv(e,t){return!Array.isArray(e)||e.length!==t.length?!1:t.every((t,n)=>mv(t)===mv(e[n]))}function mv(e){return vv(e)?JSON.stringify([e.id,e.path,e.cwd,e.name,e.firstMessage,e.messageCount,e.modified,e.archived,e.archivedAt,e.persisted,e.parentSessionPath,e.agentSubsession]):``}function hv(e,t){return e===void 0||t===void 0?e===t:mv(e)===mv(t)}function gv(e,t,n,r,i,a,o){if(!yv(e))return!1;for(let s of i){let i=bv(o===`status`?e:n,s.id),c=bv(o===`status`?t:n,s.id),l=xv(o===`activity`?e:n,s.id),u=xv(o===`activity`?t:n,s.id);if(_v(s,i,l,r[s.id]===!0,a)!==_v(s,c,u,r[s.id]===!0,a))return!1}return!0}function _v(e,t,n,r,i){return JSON.stringify([wv(e,t,n,r),n?.phase,Rs(e,t,{authoritative:i})])}function vv(e){return yv(e)&&typeof e.id==`string`&&typeof e.path==`string`}function yv(e){return typeof e==`object`&&!!e}function bv(e,t){if(!yv(e))return;let n=e[t];return Sv(n)?n:void 0}function xv(e,t){if(!yv(e))return;let n=e[t];return Cv(n)?n:void 0}function Sv(e){return yv(e)&&typeof e.sessionId==`string`&&typeof e.isStreaming==`boolean`&&typeof e.isCompacting==`boolean`&&typeof e.isBashRunning==`boolean`&&typeof e.pendingMessageCount==`number`&&Array.isArray(e.queuedMessages)&&yv(e.tokens)&&typeof e.cost==`number`}function Cv(e){return yv(e)&&typeof e.sessionId==`string`&&(e.phase===`active`||e.phase===`idle`||e.phase===`error`)&&typeof e.label==`string`&&typeof e.at==`string`}function wv(e,t,n,r,i){if(!($r(e)||e.archived===!0)){if(r)return`sending`;if(i===void 0?rr(t,n):i[e.id]?.[re.working]===!0)return`session`}}function Tv(e,t){return $r(e)||e.archived===!0?!1:t.has(e.id)}function Ev(e){return new Map(e.map(e=>[rv(e.path),e]))}function Dv(e,t=[]){let n=Ev(e),r=new Set;for(let t of e){if(t.archived===!0)continue;r.add(t.id);let e=t.parentSessionPath===void 0?void 0:rv(t.parentSessionPath),i=new Set([rv(t.path)]);for(;e!==void 0&&!i.has(e);){i.add(e);let t=n.get(e);if(t===void 0)break;r.add(t.id),e=t.parentSessionPath===void 0?void 0:rv(t.parentSessionPath)}}return Ov(e.filter(e=>r.has(e.id)),t)}function Ov(e,t=[]){let n=Ev(e),r=new Map,i=[];for(let t of e){let e=t.parentSessionPath,a=e===void 0?void 0:n.get(rv(e));if(a===void 0){i.push(t);continue}let o=rv(a.path),s=r.get(o)??[];s.push(t),r.set(o,s)}let a=new Set(t),o=new Map(e.map((e,t)=>[rv(e.path),t])),s=new Map,c=(e,t)=>{if(a.has(e.id))return!0;let n=rv(e.path),i=s.get(n);if(i!==void 0)return i;if(t.has(n))return!1;let o=new Set(t);o.add(n);let l=(r.get(n)??[]).some(e=>c(e,o));return s.set(n,l),l},l=(e,t)=>{let n=Number(c(t,new Set))-Number(c(e,new Set));if(n!==0)return n;let r=t.modified.localeCompare(e.modified);return r===0?(o.get(rv(e.path))??0)-(o.get(rv(t.path))??0):r},u=[],d=(e,t,i)=>{let a=rv(e.path);if(i.has(a))return;let o=e.parentSessionPath;u.push({session:e,depth:t,hasMissingParent:o!==void 0&&!n.has(rv(o))});let s=new Set(i);s.add(a);for(let e of[...r.get(a)??[]].sort((e,t)=>Number(t.agentSubsession===!0)-Number(e.agentSubsession===!0)||l(e,t)))d(e,t+1,s)};for(let e of i.sort(l))d(e,0,new Set);return u}function kv(e,t){let n=Dv([...e],t);return Mv(n,[...Av(n,t)]).pinnedRootIds}function Av(e,t){let n=new Set(t),r=new Set,i;for(let t of e)t.depth===0&&(i=t.session.id),i!==void 0&&n.has(t.session.id)&&r.add(i);return r}function jv(e){return e.depth===0&&!e.hasMissingParent&&e.session.parentSessionPath===void 0&&e.session.archived!==!0}function Mv(e,t){let n=[];for(let t of e)(t.depth===0||n.length===0)&&n.push([]),n[n.length-1]?.push(t);let r=new Map(n.flatMap(e=>{let t=e[0];return t!==void 0&&jv(t)?[[t.session.id,e]]:[]})),i=[...new Set(t)].filter(e=>r.has(e)),a=new Set(i),o=i.flatMap(e=>r.get(e)??[]);return{rows:[...o,...n.filter(e=>!a.has(e[0]?.session.id??``)).flat()],pinnedRootIds:i,pinnedRowCount:o.length}}function Nv(e,t){let n=new Map;for(let{session:r}of e){let e=t.parentByAgentId.get(r.id);e!==void 0&&n.set(r.id,(n.get(e)??0)+12)}return n}function Pv(e){let t=Ev(e.map(e=>e.session)),n=new Map,r=new Map;for(let{session:i}of e){if(i.agentSubsession!==!0||i.parentSessionPath===void 0)continue;let e=t.get(rv(i.parentSessionPath));e!==void 0&&e.id!==i.id&&(n.set(i.id,e.id),r.set(e.id,(r.get(e.id)??0)+1))}return{parentByAgentId:n,countByParentId:r}}function Fv(e,t={}){if(t.collapsed===!0)return[];let n=t.expandedAgentParents??new Set,r=Dv(e),i=new Set(Iv(r,n).map(e=>e.session.id));if(t.archivedExpanded===!0){let t=new Set(r.map(e=>e.session.id)),a=Ov(e.filter(e=>e.archived===!0&&!t.has(e.id)));for(let e of Iv(a,n))i.add(e.session.id)}return e.filter(e=>i.has(e.id))}function Iv(e,t,n=Pv(e)){let r=new Set;return e.filter(e=>{let i=n.parentByAgentId.get(e.session.id);return i===void 0||!r.has(i)&&t.has(i)?!0:(r.add(e.session.id),!1)})}var Lv=class extends O{constructor(){super(),this.canCleanup=!0,this.unavailableMessage=D(`ui.sessionCleanupDialog.updateAndRestartPiWebOnThisMachine`,`Update and restart Pi-Web on this machine before cleaning up sessions.`),this.loading=!1,this.running=!1,this.error=``,this.draft={...Bl},this.formError=``,v.createController(this)}willUpdate(e){e.has(`preview`)&&(this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd))}render(){let e=Vl(this.draft),t=this.selectedPreview(),n=this.canCleanup&&Ul({draft:this.draft,preview:t,previewRequest:this.previewRequest,loading:this.loading,running:this.running}),r=n?D(`ui.sessionCleanupDialog.runCleanup`,`Run cleanup`):t!==void 0&&!Gl(t)?D(`ui.sessionCleanupDialog.selectAtLeastOneProjectToRunCleanup2`,`Select at least one project to run cleanup`):D(`ui.sessionCleanupDialog.previewBeforeRunningCleanup2`,`Preview before running cleanup`);return E`
|
|
1031
1031
|
<modal-surface .onClose=${()=>{this.onClose?.()}} .busy=${this.running} .label=${D(`ui.sessionCleanupDialog.cleanUpSessions`,`Clean up sessions`)}>
|
|
1032
1032
|
<header>
|
|
1033
1033
|
<div>
|
|
@@ -1052,15 +1052,15 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1052
1052
|
`}renderForm(e){let t=this.loading||this.running,n=Vl(this.draft),r=this.preview!==void 0&&n.ok&&Hl(n.request)!==Hl(this.previewRequest)&&Gl(this.preview);return E`
|
|
1053
1053
|
<fieldset ?disabled=${t}>
|
|
1054
1054
|
<label class="toggle-row">
|
|
1055
|
-
<input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:
|
|
1055
|
+
<input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:Rv(e)})}}>
|
|
1056
1056
|
<span>${D(`ui.sessionCleanupDialog.archiveUnarchivedSessionsIdleForOver`,`Archive unarchived sessions idle for over`)}</span>
|
|
1057
|
-
<input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${t||!this.draft.archiveIdleEnabled} @input=${e=>{this.updateDraft({archiveIdleDays:
|
|
1057
|
+
<input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${t||!this.draft.archiveIdleEnabled} @input=${e=>{this.updateDraft({archiveIdleDays:zv(e)})}}>
|
|
1058
1058
|
<span>${D(`ui.sessionCleanupDialog.days2`,`days`)}</span>
|
|
1059
1059
|
</label>
|
|
1060
1060
|
<label class="toggle-row delete-row">
|
|
1061
|
-
<input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:
|
|
1061
|
+
<input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:Rv(e)})}}>
|
|
1062
1062
|
<span>${D(`ui.sessionCleanupDialog.deleteSessionsArchivedForOver`,`Delete sessions archived for over`)}</span>
|
|
1063
|
-
<input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${t||!this.draft.deleteArchivedEnabled} @input=${e=>{this.updateDraft({deleteArchivedDays:
|
|
1063
|
+
<input class="days" type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${t||!this.draft.deleteArchivedEnabled} @input=${e=>{this.updateDraft({deleteArchivedDays:zv(e)})}}>
|
|
1064
1064
|
<span>${D(`ui.sessionCleanupDialog.days`,`days`)}</span>
|
|
1065
1065
|
</label>
|
|
1066
1066
|
</fieldset>
|
|
@@ -1097,7 +1097,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1097
1097
|
${t.length===0?E`<p class="hint" role="status">${D(`ui.sessionCleanupDialog.selectAtLeastOneProjectToRunCleanup`,`Select at least one project to run cleanup.`)}</p>`:null}
|
|
1098
1098
|
`}renderProjectRow(e,t){return E`
|
|
1099
1099
|
<tr class=${t?``:`unselected`}>
|
|
1100
|
-
<td class="select-cell"><input type="checkbox" aria-label=${D(`ui.sessionCleanupDialog.cleanUp`,`Clean up {cwd}`,{cwd:e.cwd})} .checked=${t} ?disabled=${this.running} @change=${t=>{this.setProjectSelected(e.cwd,
|
|
1100
|
+
<td class="select-cell"><input type="checkbox" aria-label=${D(`ui.sessionCleanupDialog.cleanUp`,`Clean up {cwd}`,{cwd:e.cwd})} .checked=${t} ?disabled=${this.running} @change=${t=>{this.setProjectSelected(e.cwd,Rv(t))}}></td>
|
|
1101
1101
|
<th title=${e.cwd} dir="auto">${e.cwd}</th>
|
|
1102
1102
|
<td>${e.archiveCount}</td>
|
|
1103
1103
|
<td>${e.deleteCount}</td>
|
|
@@ -1158,7 +1158,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1158
1158
|
}
|
|
1159
1159
|
|
|
1160
1160
|
}
|
|
1161
|
-
`}};w([y({type:Boolean})],
|
|
1161
|
+
`}};w([y({type:Boolean})],Lv.prototype,`canCleanup`,void 0),w([y({type:String})],Lv.prototype,`unavailableMessage`,void 0),w([y({attribute:!1})],Lv.prototype,`preview`,void 0),w([y({attribute:!1})],Lv.prototype,`previewRequest`,void 0),w([y({attribute:!1})],Lv.prototype,`result`,void 0),w([y({type:Boolean})],Lv.prototype,`loading`,void 0),w([y({type:Boolean})],Lv.prototype,`running`,void 0),w([y({type:String})],Lv.prototype,`error`,void 0),w([y({attribute:!1})],Lv.prototype,`onPreview`,void 0),w([y({attribute:!1})],Lv.prototype,`onRun`,void 0),w([y({attribute:!1})],Lv.prototype,`onClose`,void 0),w([C()],Lv.prototype,`draft`,void 0),w([C()],Lv.prototype,`formError`,void 0),w([C()],Lv.prototype,`selectedProjectCwds`,void 0),Lv=w([b(`session-cleanup-dialog`)],Lv);function Rv(e){return e.target instanceof HTMLInputElement&&e.target.checked}function zv(e){return e.target instanceof HTMLInputElement?e.target.value:``}var Bv=class extends O{constructor(...e){super(...e),this.query=``,this.searching=!1,this.error=``}render(){let e=this.query.trim()!==``;return E`
|
|
1162
1162
|
<modal-surface .onClose=${()=>{this.onClose?.()}} .initialFocus=${`input`} .label=${D(`ui.sessionSearchDialog.searchSessionContent`,`Search session content`)}>
|
|
1163
1163
|
<header>
|
|
1164
1164
|
<div>
|
|
@@ -1170,7 +1170,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1170
1170
|
<div class="body">
|
|
1171
1171
|
<label class="search-field">
|
|
1172
1172
|
<span aria-hidden="true">⌕</span>
|
|
1173
|
-
<input type="search" aria-label=${D(`ui.sessionSearchDialog.searchUserQuestionsOrAiAnswers`,`Search user questions or AI answers`)} .value=${this.query} @input=${e=>{this.onSearch?.(
|
|
1173
|
+
<input type="search" aria-label=${D(`ui.sessionSearchDialog.searchUserQuestionsOrAiAnswers`,`Search user questions or AI answers`)} .value=${this.query} @input=${e=>{this.onSearch?.(Wv(e))}}>
|
|
1174
1174
|
${this.searching?E`<span class="spinner" aria-label=${D(`ui.sessionSearchDialog.searching`,`Searching`)}></span>`:null}
|
|
1175
1175
|
</label>
|
|
1176
1176
|
${this.renderStatus(e)}
|
|
@@ -1186,7 +1186,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1186
1186
|
${e.results.map(e=>E`
|
|
1187
1187
|
<section class="session-group">
|
|
1188
1188
|
<div class="session-heading">
|
|
1189
|
-
<strong dir="auto">${
|
|
1189
|
+
<strong dir="auto">${Uv(e.session)}</strong>
|
|
1190
1190
|
<span>${D(`ui.sessionSearchDialog.matchCount`,`{count} matches`,{count:e.matches.length})}</span>
|
|
1191
1191
|
</div>
|
|
1192
1192
|
${e.matches.map(t=>this.renderMatch(e.session,t))}
|
|
@@ -1197,7 +1197,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1197
1197
|
<button class="match-row" @click=${()=>{this.onSelect?.(e,t)}}>
|
|
1198
1198
|
<span class="match-meta"><span class=${`role ${t.role}`}>${n}</span></span>
|
|
1199
1199
|
<span class="excerpts" dir="auto">
|
|
1200
|
-
${t.excerpts.map(e=>E`<span class="excerpt">${
|
|
1200
|
+
${t.excerpts.map(e=>E`<span class="excerpt">${Vv(e)}</span>`)}
|
|
1201
1201
|
</span>
|
|
1202
1202
|
<span class="jump" aria-hidden="true">→</span>
|
|
1203
1203
|
</button>
|
|
@@ -1242,7 +1242,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1242
1242
|
.body { padding: 12px; }
|
|
1243
1243
|
.match-row { padding-left: 10px; }
|
|
1244
1244
|
}
|
|
1245
|
-
`}};w([y({type:String})],
|
|
1245
|
+
`}};w([y({type:String})],Bv.prototype,`query`,void 0),w([y({attribute:!1})],Bv.prototype,`response`,void 0),w([y({type:Boolean})],Bv.prototype,`searching`,void 0),w([y({type:String})],Bv.prototype,`error`,void 0),w([y({attribute:!1})],Bv.prototype,`onSearch`,void 0),w([y({attribute:!1})],Bv.prototype,`onSelect`,void 0),w([y({attribute:!1})],Bv.prototype,`onClose`,void 0),Bv=w([b(`session-search-dialog`)],Bv);function Vv(e){return E`${Hv(e).map(e=>e.highlighted?E`<mark>${e.text}</mark>`:e.text)}`}function Hv(e){let t=[...e.matchRanges].sort((e,t)=>e.start-t.start),n=[],r=0;for(let i of t){let t=Math.max(r,Math.min(e.text.length,i.start)),a=Math.max(t,Math.min(e.text.length,i.start+i.length));t>r&&n.push({text:e.text.slice(r,t),highlighted:!1}),a>t&&n.push({text:e.text.slice(t,a),highlighted:!0}),r=a}return r<e.text.length&&n.push({text:e.text.slice(r),highlighted:!1}),n}function Uv(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?$_(e.id):e.firstMessage}function Wv(e){return e.target instanceof HTMLInputElement?e.target.value:``}function Gv(e){let t=new Map,n=[];for(let r of e.nodes)t.has(r.id)||(t.set(r.id,r),n.push(r.id));let r=Zv(t,n),i=new Map;for(let e of n)i.set(e,[]);let a=[];for(let e of n){let t=r.get(e)??null;t===null?a.push(e):i.get(t)?.push(e)}let o=new Map,s=new Map,c=new Set,l=[...a].reverse().map(e=>({id:e,depth:0,branchDepth:0}));for(;l.length>0;){let e=l.pop();if(e===void 0||c.has(e.id))continue;c.add(e.id),o.set(e.id,e.depth),s.set(e.id,e.branchDepth);let t=i.get(e.id)??[],n=e.branchDepth+ +(t.length>1);for(let r=t.length-1;r>=0;--r){let i=t[r];i!==void 0&&l.push({id:i,depth:e.depth+1,branchDepth:n})}}for(let e of n)c.has(e)||(a.push(e),r.set(e,null),o.set(e,0),s.set(e,0));let u=new Map;for(let[e,t]of i)u.set(e,t);let d=e.activeLeafId!==null&&t.has(e.activeLeafId)?e.activeLeafId:null;return{nodesById:t,orderedIds:n,rootIds:a,parentById:r,childrenById:u,depthById:o,branchDepthById:s,activePathIds:d===null?new Set:Qv(d,r),activeLeafId:d}}function Kv(e,t){let n=[],r=new Set,i=[...e.rootIds].reverse();for(;i.length>0;){let a=i.pop();if(a===void 0||r.has(a))continue;let o=e.nodesById.get(a);if(o===void 0)continue;r.add(a);let s=e.childrenById.get(a)??[];if(n.push({node:o,depth:e.depthById.get(a)??0,branchDepth:e.branchDepthById.get(a)??0,parentId:e.parentById.get(a)??null,childIds:s,activePath:e.activePathIds.has(a),activeLeaf:e.activeLeafId===a}),!t.has(a))for(let e=s.length-1;e>=0;--e){let t=s[e];t!==void 0&&i.push(t)}}return n}function qv(e){return e.activeLeafId===null?e.orderedIds.at(-1):e.activeLeafId}function Jv(e,t,n){let r=Kv(e,t.foldedIds).map(e=>e.node.id),i=$v(r,t.selectedId),a=i===void 0?-1:r.indexOf(i),o=()=>({...t,selectedId:i,handled:!1}),s=e=>({...t,selectedId:e,handled:!0});switch(n){case`ArrowUp`:return s(a>0?r[a-1]:i);case`ArrowDown`:return s(a>=0&&a<r.length-1?r[a+1]:i);case`Home`:return s(r[0]);case`End`:return s(r.at(-1));case`ArrowLeft`:if(i===void 0)return s(void 0);if((e.childrenById.get(i)??[]).length>0&&!t.foldedIds.has(i)){let e=new Set(t.foldedIds);return e.add(i),{selectedId:i,foldedIds:e,handled:!0}}return s(e.parentById.get(i)??i);case`ArrowRight`:{if(i===void 0)return s(void 0);let n=e.childrenById.get(i)??[];if(n.length===0)return s(i);if(t.foldedIds.has(i)){let e=new Set(t.foldedIds);return e.delete(i),{selectedId:i,foldedIds:e,handled:!0}}return s(n[0])}case`Enter`:return{...t,selectedId:i,handled:!0,...i===void 0?{}:{action:`confirm`}};case`Escape`:return{...t,selectedId:i,handled:!0,action:`cancel`};default:return o()}}function Yv(e,t,n){if((e.childrenById.get(n)??[]).length===0)return{...t,selectedId:n};let r=new Set(t.foldedIds);return r.has(n)?r.delete(n):r.add(n),{selectedId:n,foldedIds:r}}function Xv(e,t){return e===`none`||e==="default"?{ok:!0,choice:{mode:e}}:t.trim()===``?{ok:!1,error:D(`client.sessionTreeModel.enter.custom.summary.focus.instructions.199988`,`Enter custom summary focus instructions.`)}:t.length>1e4?{ok:!1,error:D(`client.sessionTreeModel.custom.summary.focus.must.be.characters.or.fewer.26275e`,`Custom summary focus must be {value1} characters or fewer.`,{value1:String(Rt)})}:{ok:!0,choice:{mode:`custom`,instructions:t.trim()}}}function Zv(e,t){let n=new Map;for(let r of t){let t=e.get(r)?.parentId??null;n.set(r,t!==null&&t!==r&&e.has(t)?t:null)}let r=new Map;for(let e of t){if(r.has(e))continue;let t=[],i=e;for(;i!==null&&!r.has(i);)r.set(i,`visiting`),t.push(i),i=n.get(i)??null;if(i!==null&&r.get(i)===`visiting`){let e=t.at(-1);e!==void 0&&n.set(e,null)}for(let e of t)r.set(e,`visited`)}return n}function Qv(e,t){let n=new Set,r=e;for(;r!==null&&!n.has(r);)n.add(r),r=t.get(r)??null;return n}function $v(e,t){return t!==void 0&&e.includes(t)?t:e.at(-1)}var ey={nodes:[],activeLeafId:null,activePathIds:[]},ty=8,ny={user:{label:D(`ui.chatView.user`,`User`),tone:`user`,bookkeeping:!1},assistant:{label:D(`ui.chatView.assistant`,`Assistant`),tone:`assistant`,bookkeeping:!1},"tool-result":{label:D(`ui.sessionTreeNavigator.toolResult`,`Tool result`),tone:`tool`,bookkeeping:!1},bash:{label:D(`ui.toolExecutionView.command`,`Command`),tone:`shell`,bookkeeping:!1},"custom-message":{label:D(`ui.sessionTreeNavigator.customMessage`,`Custom message`),tone:`context`,bookkeeping:!1},compaction:{label:D(`ui.sessionTreeNavigator.contextCompaction`,`Context compaction`),tone:`context`,bookkeeping:!1},"branch-summary":{label:D(`ui.sessionTreeNavigator.branchSummary`,`Branch summary`),tone:`context`,bookkeeping:!1},"model-change":{label:D(`ui.sessionTreeNavigator.model`,`Model`),tone:`metadata`,bookkeeping:!0},"thinking-level-change":{label:D(`ui.sessionTreeNavigator.thinkingLevel`,`Thinking level`),tone:`metadata`,bookkeeping:!0},"session-info":{label:D(`ui.sessionTreeNavigator.sessionInformation`,`Session information`),tone:`metadata`,bookkeeping:!0},label:{label:D(`ui.sessionTreeNavigator.label`,`Label`),tone:`metadata`,bookkeeping:!0},custom:{label:D(`ui.main.custom`,`Custom`),tone:`metadata`,bookkeeping:!0},other:{label:D(`ui.settingsShortcutsPanel.other`,`Other`),tone:`metadata`,bookkeeping:!0}},K=class extends O{constructor(){super(),this.tree=ey,this.foldedIds=new Set,this.step=`tree`,this.operation=`continue`,this.summaryMode=`none`,this.customInstructions=``,this.busy=!1,this.aborting=!1,this.error=``,this.statusMessage=``,this.model=Gv(ey),this.operationGeneration=0,v.createController(this)}willUpdate(e){e.has(`tree`)&&this.resetTree()}updated(){let e=this.pendingFocus;e!==void 0&&(this.pendingFocus=void 0,e===`tree`?this.focusSelectedTreeItem():e===`custom`?this.renderRoot.querySelector(`#session-tree-custom-focus`)?.focus():e===`operation`?this.renderRoot.querySelector(`input[name='session-tree-operation']:checked`)?.focus():this.renderRoot.querySelector(`input[name='session-tree-summary']:checked`)?.focus())}render(){return E`
|
|
1246
1246
|
<modal-surface .onClose=${()=>{this.requestDismissal()}} .onBusyEscape=${()=>{this.requestBusyEscape()}} .busy=${this.busy} .initialFocus=${this.selectedId===void 0?`.close-button`:`[data-tree-node-id][tabindex='0']`} .label=${D(`ui.sessionTreeNavigator.browseSessionTree`,`Browse session tree`)}>
|
|
1247
1247
|
<header>
|
|
1248
1248
|
<div>
|
|
@@ -1254,7 +1254,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1254
1254
|
${this.step===`tree`?this.renderTreeStep():this.renderActionStep()}
|
|
1255
1255
|
${this.renderFooter()}
|
|
1256
1256
|
</modal-surface>
|
|
1257
|
-
`}renderTreeStep(){let e=
|
|
1257
|
+
`}renderTreeStep(){let e=Kv(this.model,this.foldedIds);return E`
|
|
1258
1258
|
<div class="body tree-step">
|
|
1259
1259
|
<div class="tree-intro">
|
|
1260
1260
|
<p>${D(`ui.main.accac83dc4d6`,`Select the history entry where you would like to continue.`)}</p>
|
|
@@ -1273,7 +1273,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1273
1273
|
</div>
|
|
1274
1274
|
`}
|
|
1275
1275
|
</div>
|
|
1276
|
-
`}renderTreeRow(e){let t=e.node.id===this.selectedId,n=e.childIds.length>0&&!this.foldedIds.has(e.node.id),r=
|
|
1276
|
+
`}renderTreeRow(e){let t=e.node.id===this.selectedId,n=e.childIds.length>0&&!this.foldedIds.has(e.node.id),r=ay(e.node.kind),i=[`tree-row`,t?`selected`:``,e.activePath?`active-path`:``,e.activeLeaf?`active-leaf`:``,r.bookkeeping?`bookkeeping`:``].filter(e=>e!==``).join(` `),a=ry(e.branchDepth);return E`
|
|
1277
1277
|
<div
|
|
1278
1278
|
class=${i}
|
|
1279
1279
|
style=${`--tree-indent: ${String(a*16)}px; --tree-indent-mobile: ${String(a*12)}px;`}
|
|
@@ -1306,7 +1306,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1306
1306
|
${e.node.timestamp===void 0?null:E`<time datetime=${e.node.timestamp}>${e.node.timestamp}</time>`}
|
|
1307
1307
|
</span>
|
|
1308
1308
|
</div>
|
|
1309
|
-
`}renderKindBadge(e){return E`<span class=${`kind kind-tone-${e.tone}`}>${e.label}</span>`}renderActionStep(){let e=this.selectedId===void 0?void 0:this.model.nodesById.get(this.selectedId),t=
|
|
1309
|
+
`}renderKindBadge(e){return E`<span class=${`kind kind-tone-${e.tone}`}>${e.label}</span>`}renderActionStep(){let e=this.selectedId===void 0?void 0:this.model.nodesById.get(this.selectedId),t=Xv(this.summaryMode,this.customInstructions);return E`
|
|
1310
1310
|
<div class="body confirmation-step">
|
|
1311
1311
|
<div class="confirmation-card">
|
|
1312
1312
|
<div>
|
|
@@ -1315,7 +1315,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1315
1315
|
</div>
|
|
1316
1316
|
${e===void 0?E`<div class="empty">${D(`ui.sessionTreeNavigator.theSelectedHistoryEntryIsNoLongerAvailable`,`The selected history entry is no longer available.`)}</div>`:E`
|
|
1317
1317
|
<div class="selected-entry">
|
|
1318
|
-
${this.renderKindBadge(
|
|
1318
|
+
${this.renderKindBadge(ay(e.kind))}
|
|
1319
1319
|
<strong dir="auto">${e.summary}</strong>
|
|
1320
1320
|
<p>${this.selectedEntryDescription(e.kind)}</p>
|
|
1321
1321
|
</div>
|
|
@@ -1354,7 +1354,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1354
1354
|
${this.error===``?null:E`<div class="dialog-error" role="alert">${this.error}</div>`}
|
|
1355
1355
|
</div>
|
|
1356
1356
|
</div>
|
|
1357
|
-
`}selectedEntryDescription(e){return this.operation===`fork`?e===`user`?D(`ui.main.31853eda65e0`,`The new session will branch before this user message, and its text will return to the prompt editor as the new session draft.`):D(`ui.main.51b8f85261ba`,`The new session will include this entry and all history leading to it.`):
|
|
1357
|
+
`}selectedEntryDescription(e){return this.operation===`fork`?e===`user`?D(`ui.main.31853eda65e0`,`The new session will branch before this user message, and its text will return to the prompt editor as the new session draft.`):D(`ui.main.51b8f85261ba`,`The new session will include this entry and all history leading to it.`):iy(e)?D(`ui.sessionTreeNavigator.thisMessageSTextReturnsToThePrompt`,`This message's text returns to the prompt editor for optional editing and resubmission.`):D(`ui.main.c3432d0efd76`,`The prompt editor will be empty after continuing from this entry in this session.`)}renderOperationOption(e,t,n){return E`
|
|
1358
1358
|
<label class=${`choice-option${this.operation===e?` selected`:``}`}>
|
|
1359
1359
|
<input
|
|
1360
1360
|
type="radio"
|
|
@@ -1393,7 +1393,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1393
1393
|
${this.primaryActionLabel()}
|
|
1394
1394
|
</button>
|
|
1395
1395
|
</footer>
|
|
1396
|
-
`}resetTree(){this.operationGeneration+=1,this.model=
|
|
1396
|
+
`}resetTree(){this.operationGeneration+=1,this.model=Gv(this.tree),this.selectedId=qv(this.model),this.foldedIds=new Set,this.step=`tree`,this.operation=`continue`,this.summaryMode=`none`,this.customInstructions=``,this.busy=!1,this.aborting=!1,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`}selectNode(e){this.model.nodesById.has(e)&&(this.selectedId=e,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`)}toggleNode(e,t){t.preventDefault(),t.stopPropagation();let n=Yv(this.model,{selectedId:this.selectedId,foldedIds:this.foldedIds},e);this.selectedId=n.selectedId,this.foldedIds=n.foldedIds,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`}handleTreeKeyDown(e){if(e.key===`Escape`)return;let t=Jv(this.model,{selectedId:this.selectedId,foldedIds:this.foldedIds},e.key);t.handled&&(e.preventDefault(),e.stopPropagation(),t.action===`confirm`?this.continueToAction():(this.selectedId=t.selectedId,this.foldedIds=t.foldedIds,this.pendingFocus=`tree`))}continueToAction(){!this.busy&&this.selectedId!==void 0&&this.model.nodesById.has(this.selectedId)&&(Xv(this.summaryMode,this.customInstructions).ok||(this.summaryMode=`none`,this.customInstructions=``),this.step=`action`,this.error=``,this.statusMessage=``,this.pendingFocus=`operation`)}selectOperation(e){this.busy||(this.operation=e,this.error=``,this.statusMessage=``,this.pendingFocus=`operation`)}returnToTree(){this.busy||(this.step=`tree`,this.error=``,this.statusMessage=``,this.pendingFocus=`tree`)}selectSummaryMode(e){this.busy||(this.summaryMode=e,this.error=``,this.statusMessage=``,this.pendingFocus=e===`custom`?`custom`:`summary`)}handleCustomInstructionsInput(e){e.currentTarget instanceof HTMLTextAreaElement&&(this.customInstructions=e.currentTarget.value,this.error=``,this.statusMessage=``)}primaryActionLabel(){return this.busy?this.operation===`fork`?D(`ui.main.a45a4265c22a`,`Forking…`):this.summaryMode===`none`?D(`ui.main.3f87d4e5ac2e`,`Continuing…`):D(`ui.sessionTreeNavigator.summarizing`,`Summarizing…`):this.operation===`continue`?D(`ui.main.ae07f9cb8a7e`,`Continue from here`):D(`ui.main.845e53aa3f7c`,`Fork into new session`)}submitSelectedOperation(){return this.operation===`continue`?this.submitNavigation():this.submitFork()}async submitNavigation(){if(this.busy||this.selectedId===void 0)return;let e=Xv(this.summaryMode,this.customInstructions);if(!e.ok){this.error=``,this.statusMessage=``,this.pendingFocus=`custom`,this.requestUpdate();return}let t=this.onNavigate;if(t===void 0){this.error=D(`ui.sessionTreeNavigator.sessionTreeNavigationIsUnavailableCloseAndReopen`,`Session tree navigation is unavailable. Close and reopen /tree, then retry.`);return}let n=this.selectedId,r=++this.operationGeneration;this.busy=!0,this.aborting=!1,this.error=``,this.statusMessage=``;try{let i=await t(n,e.choice);if(r!==this.operationGeneration||(this.busy=!1,this.aborting=!1,!i.cancelled))return;this.step=`tree`,this.statusMessage=i.aborted===!0?D(`ui.sessionTreeNavigator.summaryCancelledTheSelectedHistoryEntryIsUnchanged`,`Summary cancelled. The selected history entry is unchanged.`):D(`ui.sessionTreeNavigator.navigationCancelledTheSelectedHistoryEntryIsUnchanged`,`Navigation cancelled. The selected history entry is unchanged.`),this.pendingFocus=`tree`}catch(e){if(r!==this.operationGeneration)return;this.busy=!1,this.aborting=!1,this.statusMessage=``,this.error=D(`ui.sessionTreeNavigator.unableToNavigateSessionHistory`,`Unable to navigate session history: {errorMessageerror}`,{errorMessageerror:oy(e)})}}async submitFork(){if(this.busy||this.selectedId===void 0)return;let e=this.onFork;if(e===void 0){this.error=D(`ui.main.8c3057119b0c`,`Fork from the session tree is unavailable. Close and reopen /tree, then try again.`);return}let t=this.selectedId,n=++this.operationGeneration;this.busy=!0,this.error=``,this.statusMessage=``;try{let r=await e(t);if(n!==this.operationGeneration||(this.busy=!1,!r.cancelled))return;this.statusMessage=D(`ui.main.d38652912c3f`,`Fork cancelled. No new session was created; your selected history entry is unchanged.`),this.pendingFocus=`operation`}catch(e){if(n!==this.operationGeneration)return;this.busy=!1,this.statusMessage=``,this.error=D(`ui.main.390c887eead8`,`Could not fork session: {arg0}`,{arg0:oy(e)})}}async abortNavigation(){if(!this.busy||this.summaryMode===`none`||this.aborting)return;let e=this.onAbort;if(e===void 0){this.error=D(`ui.sessionTreeNavigator.unableToCancelTheSummaryFromThisClient`,`Unable to cancel the summary from this client.`);return}let t=this.operationGeneration;this.aborting=!0,this.error=``,this.statusMessage=D(`ui.sessionTreeNavigator.cancellingSummary`,`Cancelling summary…`);try{await e()}catch(e){if(t!==this.operationGeneration)return;this.aborting=!1,this.statusMessage=``,this.error=D(`ui.sessionTreeNavigator.unableToCancelSummary`,`Unable to cancel summary: {errorMessageerror}`,{errorMessageerror:oy(e)})}}requestDismissal(){this.step===`action`?this.returnToTree():this.onCancel?.()}requestBusyEscape(){this.operation===`continue`&&this.summaryMode!==`none`&&this.abortNavigation()}focusSelectedTreeItem(){let e=this.selectedId;if(e===void 0){this.renderRoot.querySelector(`.close-button`)?.focus();return}let t=this.renderRoot.querySelectorAll(`[data-tree-node-id]`);for(let n of t)if(n.dataset.treeNodeId===e){n.focus(),n.scrollIntoView({block:`nearest`});return}}static{this.styles=T`
|
|
1397
1397
|
@layer pi-web-base {
|
|
1398
1398
|
:host { position: fixed; inset: 0; color: var(--pi-text); font: 14px var(--pi-font, system-ui, sans-serif); }
|
|
1399
1399
|
header, footer, .confirmation-card { overflow-wrap: anywhere; }
|
|
@@ -1499,47 +1499,47 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1499
1499
|
}
|
|
1500
1500
|
|
|
1501
1501
|
}
|
|
1502
|
-
`}};w([y({attribute:!1})],K.prototype,`tree`,void 0),w([y({attribute:!1})],K.prototype,`onNavigate`,void 0),w([y({attribute:!1})],K.prototype,`onFork`,void 0),w([y({attribute:!1})],K.prototype,`onAbort`,void 0),w([y({attribute:!1})],K.prototype,`onCancel`,void 0),w([C()],K.prototype,`selectedId`,void 0),w([C()],K.prototype,`foldedIds`,void 0),w([C()],K.prototype,`step`,void 0),w([C()],K.prototype,`operation`,void 0),w([C()],K.prototype,`summaryMode`,void 0),w([C()],K.prototype,`customInstructions`,void 0),w([C()],K.prototype,`busy`,void 0),w([C()],K.prototype,`aborting`,void 0),w([C()],K.prototype,`error`,void 0),w([C()],K.prototype,`statusMessage`,void 0),K=w([b(`session-tree-navigator`)],K);function
|
|
1502
|
+
`}};w([y({attribute:!1})],K.prototype,`tree`,void 0),w([y({attribute:!1})],K.prototype,`onNavigate`,void 0),w([y({attribute:!1})],K.prototype,`onFork`,void 0),w([y({attribute:!1})],K.prototype,`onAbort`,void 0),w([y({attribute:!1})],K.prototype,`onCancel`,void 0),w([C()],K.prototype,`selectedId`,void 0),w([C()],K.prototype,`foldedIds`,void 0),w([C()],K.prototype,`step`,void 0),w([C()],K.prototype,`operation`,void 0),w([C()],K.prototype,`summaryMode`,void 0),w([C()],K.prototype,`customInstructions`,void 0),w([C()],K.prototype,`busy`,void 0),w([C()],K.prototype,`aborting`,void 0),w([C()],K.prototype,`error`,void 0),w([C()],K.prototype,`statusMessage`,void 0),K=w([b(`session-tree-navigator`)],K);function ry(e){return Math.min(Math.max(0,e),ty)}function iy(e){return e===`user`||e===`custom-message`}function ay(e){return ny[e]}function oy(e){return e instanceof Error?e.message:String(e)}function sy(){return E`<span aria-hidden="true">⧉</span>`}function cy(){return E`<svg aria-hidden="true" focusable="false" width="16" height="16" viewBox="-3 -3 30 30" fill="none" stroke="currentColor" stroke-width="0.85" stroke-linecap="round" stroke-linejoin="round"><path vector-effect="non-scaling-stroke" d="M4 5h11a6 6 0 0 1 0 12H4m5-5-5 5 5 5" /></svg>`}function ly(){return E`<svg aria-hidden="true" focusable="false" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18M9 6V4a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2M5 6l1 14a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1l1-14M10 10v7M14 10v7" /></svg>`}function uy(){return Bt`
|
|
1503
1503
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1504
1504
|
<rect x="3.5" y="3.5" width="17" height="17" rx="2.5"></rect>
|
|
1505
1505
|
<circle cx="9" cy="9" r="1.6"></circle>
|
|
1506
1506
|
<path d="m20.5 15.5-4.5-4.5L5.5 20.5"></path>
|
|
1507
1507
|
</svg>
|
|
1508
|
-
`}function
|
|
1508
|
+
`}function dy(){return Bt`
|
|
1509
1509
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1510
1510
|
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9.5a2 2 0 0 1 2-2h3.4l2-3h5.2l2 3H20a2 2 0 0 1 2 2Z"></path>
|
|
1511
1511
|
<circle cx="12" cy="13.5" r="3.6"></circle>
|
|
1512
1512
|
</svg>
|
|
1513
|
-
`}function
|
|
1513
|
+
`}function fy(){return Bt`
|
|
1514
1514
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1515
1515
|
<path d="M20 11.5 12.5 19a4 4 0 0 1-5.66-5.66l7.07-7.07a2.5 2.5 0 0 1 3.54 3.54l-7.07 7.07a1 1 0 0 1-1.42-1.42l6.37-6.36"></path>
|
|
1516
1516
|
</svg>
|
|
1517
|
-
`}function
|
|
1517
|
+
`}function py(){return Bt`
|
|
1518
1518
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1519
1519
|
<path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
|
|
1520
1520
|
<path d="M21 3 11.5 12.5"></path>
|
|
1521
1521
|
</svg>
|
|
1522
|
-
`}function
|
|
1522
|
+
`}function my(){return Bt`
|
|
1523
1523
|
<svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1524
1524
|
<path d="M4 7h11"></path>
|
|
1525
1525
|
<path d="M4 12h7"></path>
|
|
1526
1526
|
<path d="M4 17h7"></path>
|
|
1527
1527
|
<path d="m15 14 5 3-5 3z"></path>
|
|
1528
1528
|
</svg>
|
|
1529
|
-
`}function
|
|
1529
|
+
`}function hy(){return py()}function gy(){return Bt`
|
|
1530
1530
|
<svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1531
1531
|
<rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
|
|
1532
1532
|
</svg>
|
|
1533
|
-
`}function
|
|
1533
|
+
`}function _y(e){let t=Math.max(e.total,1),n=t>1?1.2:0,r=(18-n*(t-1))/t,i=Array.from({length:t},(i,a)=>{let o=3+a*(r+n),s=4+(a+1)/t*12,c=20-s,l=a<e.filled;return Bt`<rect class=${l?`gauge-bar gauge-bar-active`:`gauge-bar`} x=${o} y=${c} width=${r} height=${s} rx="1"></rect>`});return Bt`
|
|
1534
1534
|
<svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
1535
1535
|
${i}
|
|
1536
1536
|
</svg>
|
|
1537
|
-
`}function
|
|
1537
|
+
`}function vy(e,t){return[e.length===0?void 0:{source:`client`,heading:D(`ui.chatView.waitingForSessionStartup`,`Waiting for session startup`),detail:D(`ui.chatView.willSendAutomaticallyWhenTheBackendSessionIs`,`Will send automatically when the backend session is ready`),messages:e},t.length===0?void 0:{source:`server`,heading:D(`ui.chatView.queuedMessages`,`Queued messages`),detail:D(`ui.chatView.pending`,`{length} pending`,{length:String(t.length)}),messages:t}].filter(e=>e!==void 0)}function yy(e,t,n){return e.source===`server`&&t&&n}function by(e,t){let n=e.source===`server`?t.unavailable:void 0,r=n===void 0?void 0:n===``?D(`ui.queuedMessages.unavailable`,`Individual queue controls are unavailable with this runtime.`):n,i=t.pending||n!==void 0;return E`
|
|
1538
1538
|
<aside class="queued-messages ui-transcript-surface" aria-live="polite">
|
|
1539
1539
|
<div class="queued-header">
|
|
1540
1540
|
<div class="queued-heading"><strong>${e.heading}</strong><small>${e.detail}</small></div>
|
|
1541
|
-
${
|
|
1542
|
-
<button type="button" class="queued-clear-button ui-button ui-button--icon ui-button--compact" ?disabled=${t.pending} aria-label=${D(`ui.queuedMessages.clearQueue`,`Clear queue`)} title=${D(`ui.queuedMessages.clearTitle`,`Clear queued messages without stopping active work`)} @click=${t.onClear}>${
|
|
1541
|
+
${yy(e,t.canClearServerQueue,t.onClear!==void 0)?E`
|
|
1542
|
+
<button type="button" class="queued-clear-button ui-button ui-button--icon ui-button--compact" ?disabled=${t.pending} aria-label=${D(`ui.queuedMessages.clearQueue`,`Clear queue`)} title=${D(`ui.queuedMessages.clearTitle`,`Clear queued messages without stopping active work`)} @click=${t.onClear}>${ly()}</button>
|
|
1543
1543
|
`:k}
|
|
1544
1544
|
</div>
|
|
1545
1545
|
${r===void 0?k:E`<small role="status">${r}</small>`}
|
|
@@ -1548,14 +1548,14 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1548
1548
|
<div class="queued-message-header">
|
|
1549
1549
|
<div class="queued-message-meta">
|
|
1550
1550
|
<span class="queued-kind">${n.kind===`steer`?D(`ui.queuedMessages.steer`,`Steer`):D(`ui.queuedMessages.queue`,`Queue`)} ${String(e.messages.slice(0,a+1).filter(e=>e.kind===n.kind).length)}</span>
|
|
1551
|
-
${kn(n)===void 0?k:E`<span class="queued-attachments" title=${D(`ui.queuedMessages.attachmentsTitle`,`Attachments included with this queued message`)}><span aria-hidden="true">${
|
|
1551
|
+
${kn(n)===void 0?k:E`<span class="queued-attachments" title=${D(`ui.queuedMessages.attachmentsTitle`,`Attachments included with this queued message`)}><span aria-hidden="true">${fy()}</span> ${kn(n)}</span>`}
|
|
1552
1552
|
</div>
|
|
1553
1553
|
<div class="queued-message-actions ui-toolbar-group">
|
|
1554
|
-
<button type="button" class="queued-action ui-button ui-button--icon ui-button--compact" aria-label=${D(`ui.queuedMessages.copy`,`Copy queued message`)} title=${D(`ui.queuedMessages.copyTitle`,`Copy message`)} @click=${()=>{t.onCopy(n.text)}}>${
|
|
1554
|
+
<button type="button" class="queued-action ui-button ui-button--icon ui-button--compact" aria-label=${D(`ui.queuedMessages.copy`,`Copy queued message`)} title=${D(`ui.queuedMessages.copyTitle`,`Copy message`)} @click=${()=>{t.onCopy(n.text)}}>${sy()}</button>
|
|
1555
1555
|
${e.source!==`server`||!t.canMutate||t.onAction===void 0?k:E`
|
|
1556
|
-
<button type="button" class="queued-action ui-button ui-button--icon ui-button--compact" ?disabled=${i} title=${r??(n.kind===`steer`?D(`ui.queuedMessages.switchToQueueTitle`,`Move to the end of the follow-up queue`):D(`ui.queuedMessages.switchToSteerTitle`,`Move to the end of the steering queue`))} aria-label=${n.kind===`steer`?D(`ui.queuedMessages.switchToQueue`,`Switch to Queue`):D(`ui.queuedMessages.switchToSteer`,`Switch to Steer`)} @click=${()=>{t.onAction?.(`toggle`,a,e.messages)}}>${n.kind===`steer`?
|
|
1557
|
-
<button type="button" class="queued-action ui-button ui-button--icon ui-button--compact" ?disabled=${i} aria-label=${D(`ui.queuedMessages.recall`,`Recall queued message`)} title=${r??D(`ui.queuedMessages.recallTitle`,`Recall this message's text and clear later queued messages`)} @click=${()=>{t.onAction?.(`edit`,a,e.messages)}}>${
|
|
1558
|
-
<button type="button" class="queued-action ui-button ui-button--icon ui-button--compact" ?disabled=${i} aria-label=${D(`ui.queuedMessages.remove`,`Remove queued message`)} title=${r??D(`ui.queuedMessages.removeTitle`,`Remove only this message`)} @click=${()=>{t.onAction?.(`remove`,a,e.messages)}}>${
|
|
1556
|
+
<button type="button" class="queued-action ui-button ui-button--icon ui-button--compact" ?disabled=${i} title=${r??(n.kind===`steer`?D(`ui.queuedMessages.switchToQueueTitle`,`Move to the end of the follow-up queue`):D(`ui.queuedMessages.switchToSteerTitle`,`Move to the end of the steering queue`))} aria-label=${n.kind===`steer`?D(`ui.queuedMessages.switchToQueue`,`Switch to Queue`):D(`ui.queuedMessages.switchToSteer`,`Switch to Steer`)} @click=${()=>{t.onAction?.(`toggle`,a,e.messages)}}>${n.kind===`steer`?my():hy()}</button>
|
|
1557
|
+
<button type="button" class="queued-action ui-button ui-button--icon ui-button--compact" ?disabled=${i} aria-label=${D(`ui.queuedMessages.recall`,`Recall queued message`)} title=${r??D(`ui.queuedMessages.recallTitle`,`Recall this message's text and clear later queued messages`)} @click=${()=>{t.onAction?.(`edit`,a,e.messages)}}>${cy()}</button>
|
|
1558
|
+
<button type="button" class="queued-action ui-button ui-button--icon ui-button--compact" ?disabled=${i} aria-label=${D(`ui.queuedMessages.remove`,`Remove queued message`)} title=${r??D(`ui.queuedMessages.removeTitle`,`Remove only this message`)} @click=${()=>{t.onAction?.(`remove`,a,e.messages)}}>${ly()}</button>
|
|
1559
1559
|
`}
|
|
1560
1560
|
</div>
|
|
1561
1561
|
</div>
|
|
@@ -1563,7 +1563,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1563
1563
|
</div>
|
|
1564
1564
|
`)}
|
|
1565
1565
|
</aside>
|
|
1566
|
-
`}function
|
|
1566
|
+
`}function xy(e,t){let n=[],r=0;for(let i of e.matchAll(/(^|[\s([<'"`])https?:\/\/[^\s<>"'`\p{Cc}]+/giu)){let a=i.index+(i[1]??``).length,o=i.index+i[0].length;if(t&&o===e.length)continue;let s=e.slice(a,o).replace(/[.,!?:;]+$/u,``);for(let[e,t]of[[`(`,`)`],[`[`,`]`],[`{`,`}`]])for(;s.endsWith(t)&&s.split(t).length>s.split(e).length;)s=s.slice(0,-1).replace(/[.,!?:;]+$/u,``);try{let e=new URL(s);if(e.protocol!==`http:`&&e.protocol!==`https:`)continue}catch{continue}n.push(e.slice(r,a),E`<a href=${s} target="_blank" rel="noopener noreferrer">${s}</a>`),r=a+s.length}return n.push(e.slice(r)),n}var Sy=_t(class extends Qe{constructor(){super(...arguments),this.key=k}render(e,t){return this.key=e,t}update(e,[t,n]){return t!==this.key&&(ge(e),this.key=t),n}}),Cy=class{constructor(e,t){this.context=e,this.changed=t,this.availability=new On,this.entryPending=!1,this.displayPending=new Set,this.generation=0}available(e,t,n){let r=this.context();return r.availability===void 0?[]:this.availability.get(e,r.actions,r.availability,t,n).filter(({action:e})=>e.target===`display`?r.onDisplay!==void 0:r.onEntry!==void 0)}pending(e,t){return t.target===`display`?this.displayPending.has(this.pendingKey(e,t.id)):this.entryPending}presentation(e,t){return this.feedback!==void 0&&this.current(this.feedback)&&this.feedback.key===e&&this.feedback.actionId===t?this.feedback.presentation:void 0}errorMessage(e){return this.error!==void 0&&this.current(this.error)&&this.error.key===e?this.error.message:void 0}reset(){this.generation+=1,this.clearFeedback(),this.error=void 0,this.changed()}location(e){let{machineId:t,sessionId:n}=this.context();return{machineId:t,sessionId:n,generation:this.generation,key:e}}pendingKey(e,t){let n=this.location(e);return JSON.stringify([n.machineId,n.sessionId,n.generation,e,t])}current(e){let t=this.context();return t.connected&&e.generation===this.generation&&e.machineId===t.machineId&&e.sessionId===t.sessionId}async run(e,t,n,r){let i=this.context();if(i.availability===void 0||this.pending(n,r))return;let a=wn(e,t.role),{onEntry:o,onDisplay:s,availability:c}=i,l=r.target===`display`?s===void 0?void 0:()=>s({...c,message:Tn(t)},r.id):a===void 0||o===void 0?void 0:()=>o({...c,message:a},r.id);if(l===void 0)return;let u=this.location(n),d=this.pendingKey(n,r.id);r.target===`display`?this.displayPending.add(d):this.entryPending=!0,this.error=void 0,this.changed();try{let e=await l();e!==void 0&&this.current(u)&&(this.clearFeedback(),this.feedback={...u,actionId:r.id,presentation:e},this.feedbackTimer=setTimeout(()=>{this.clearFeedback(),this.changed()},1200))}catch(e){this.current(u)&&(this.error={...u,message:e instanceof Error?e.message:String(e)})}finally{r.target===`display`?this.displayPending.delete(d):this.entryPending=!1,this.changed()}}clearFeedback(){this.feedbackTimer!==void 0&&clearTimeout(this.feedbackTimer),this.feedbackTimer=void 0,this.feedback=void 0}},wy=class extends O{constructor(){super(),this.expanded=!1,this.popup=new D_(this,()=>this.expanded?{anchor:this.trigger,panel:this.panel,onClose:()=>{this.expanded=!1,this.removeAttribute(`open`)},options:{placement:`left-end`,padding:8}}:void 0),v.createController(this)}disconnectedCallback(){this.expanded=!1,this.removeAttribute(`open`),this.hasUpdated&&this.trigger.setAttribute(`aria-expanded`,`false`),super.disconnectedCallback()}close(){this.expanded&&(this.popup.close(),this.trigger.focus())}toggle(){this.expanded=!this.expanded,this.toggleAttribute(`open`,this.expanded)}render(){return E`
|
|
1567
1567
|
<button type="button" class="ui-button ui-button--small ui-button--icon"
|
|
1568
1568
|
aria-label=${D(`ui.chatView.messageActions`,`Message actions`)} aria-expanded=${String(this.expanded)} aria-controls="actions"
|
|
1569
1569
|
@click=${()=>{this.toggle()}}><span aria-hidden="true">⋯</span></button>
|
|
@@ -1590,22 +1590,22 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1590
1590
|
@media (prefers-reduced-motion: reduce) {
|
|
1591
1591
|
[popover] { transition: none; }
|
|
1592
1592
|
}
|
|
1593
|
-
`]}};w([S(`button`)],
|
|
1593
|
+
`]}};w([S(`button`)],wy.prototype,`trigger`,void 0),w([S(`[popover]`)],wy.prototype,`panel`,void 0),w([C()],wy.prototype,`expanded`,void 0),wy=w([b(`pi-message-actions-menu`)],wy);function Ty(e){return e===void 0||e===``?D(`ui.chatView.toolOutput`,`Tool output`):D(`ui.chatView.output`,`{toolName} output`,{toolName:e})}function Ey(e){return e?`msg event-group live`:`msg event-group`}function Dy(e){return e?D(`ui.chatView.liveEvent`,`Live event`):D(`ui.chatView.event`,`Event`)}var Oy=class{constructor(){this.slices=new WeakMap}group(e,t=0){return Ay(e,t,e=>{let t=this.slices.get(e);return t===void 0&&(t=jy(e),this.slices.set(e,t)),t})}};function ky(e){let t=[];for(let n of e){if(n.kind!==`tool-image`){t.push(n);continue}let e=t.at(-1);e?.kind===`tool-images`?e.outputs.push(n):t.push({kind:`tool-images`,outputs:[n]})}return t}function Ay(e,t,n){let r=[],i=[],a=(e,t)=>{i.push({message:e,index:t})},o=()=>{let e=i[0],t=i.at(-1);e!==void 0&&t!==void 0&&(r.push({kind:`group`,messages:i,startIndex:e.index,endIndex:t.index}),i=[])};return e.forEach((e,i)=>{let{readable:s,technical:c,toolName:l}=n(e),u=t+i;c!==void 0&&a(c,u),s!==void 0&&(o(),Fy(s)?r.push({kind:`tool-image`,message:s,index:u,...l===void 0?{}:{toolName:l}}):r.push({kind:`message`,message:s,index:u}))}),o(),r}function jy(e){let t=[],n=[];for(let r of e.parts)r.type!==`toolResultBoundary`&&r.type!==`empty`&&(Ly(e,r)?t:n).push(r);let r={...e.streamId===void 0?{}:{streamId:e.streamId},...e.entryId===void 0?{}:{entryId:e.entryId},...e.transcriptIndex===void 0?{}:{transcriptIndex:e.transcriptIndex},...e.source===void 0?{}:{source:e.source},...e.meta===void 0?{}:{meta:e.meta}};return{readable:t.length===0?void 0:{role:e.role,parts:t,...r},technical:n.length===0?void 0:{role:n.every(e=>e.type===`skillRead`)?`skill`:e.role,parts:n,...r},toolName:Iy(n)}}function My(e){return!(e.parts.length>0&&(e.role===`tool`&&e.parts.every(e=>e.type===`toolExecution`)||e.parts.every(e=>e.type===`askUserRecord`)))}function Ny(e){let t=new Map;for(let n of e)for(let e of n.kind===`group`?n.messages.map(e=>e.message):[n.message]){if(e.entryId===void 0||!My(e))continue;let r=e.role===`user`||e.role===`assistant`,i=n.kind!==`group`&&e.parts.some(e=>e.type===`text`||e.type===`image`),a=r?i?3:2:n.kind===`group`?0:1,o=t.get(e.entryId);(o===void 0||a>o.priority)&&t.set(e.entryId,{message:e,priority:a})}return new Set(Array.from(t.values(),({message:e})=>e))}function Py(e){if(e.every(e=>e.source===`compaction`))return D(`client.chatGroups.compaction.summaries.e2309c`,`{value1} compaction summaries`,{value1:String(e.length)});if(e.every(e=>e.source===`branch_summary`))return D(`client.chatGroups.branch.summaries.c232fa`,`{value1} branch summaries`,{value1:String(e.length)});let t=e.reduce((e,t)=>(e[t.role]=(e[t.role]??0)+1,e),{}),n={user:D(`client.chatGroups.user.0d0e1a`,`User`),assistant:D(`client.chatGroups.assistant.e5ce5f`,`Assistant`),tool:D(`client.chatGroups.tool.5ca673`,`Tool`),system:D(`client.chatGroups.system.5b50d7`,`System`),bash:D(`client.chatGroups.command.928f87`,`Command`),skill:D(`client.chatGroups.skill.99aea2`,`Skill`)},r=Object.entries(t).map(([e,t])=>`${String(t)} ${n[e]??e}`).join(` · `);return D(`client.chatGroups.events.12f406`,`{value1} events{value2}`,{value1:String(e.length),value2:r===``?``:` · ${r}`})}function Fy(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function Iy(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function Ly(e,t){return e.source===`compaction`||e.source===`branch_summary`?!1:t.type===`skillInvocation`||t.type===`image`||t.type===`askUserQuestion`||t.type===`askUserRecord`||t.type===`text`&&(e.role===`user`||e.role===`assistant`||e.role===`system`||e.role===`bash`)}function Ry(e,t,n,r){let i=By(t),a=My(t),o=i?`msg tool-execution-shell`:`msg ask-user-record-shell`,s=a&&(t.role===`user`||t.role===`assistant`)?` conversation-message conversation-layout`:``;return E`
|
|
1594
1594
|
<article class=${`${a?`msg ${t.role}${s}`:o} ui-transcript-surface`} data-index=${n} data-scroll-anchor-id=${e.anchors.message(n,t)??k}>
|
|
1595
1595
|
${s===``?E`
|
|
1596
|
-
${a?
|
|
1597
|
-
${t.parts.map((r,i)=>
|
|
1596
|
+
${a?Wy(e,t,String(n),n,r):null}
|
|
1597
|
+
${t.parts.map((r,i)=>Ky(e,r,t,n,i))}
|
|
1598
1598
|
`:E`
|
|
1599
1599
|
<div class="conversation-content">
|
|
1600
|
-
${
|
|
1601
|
-
<div class="conversation-body">${t.parts.map((r,i)=>
|
|
1600
|
+
${Wy(e,t,String(n),n,r,t.role,!0)}
|
|
1601
|
+
<div class="conversation-body">${t.parts.map((r,i)=>Ky(e,r,t,n,i))}</div>
|
|
1602
1602
|
</div>
|
|
1603
|
-
${
|
|
1603
|
+
${Gy(e,t,String(n))}
|
|
1604
1604
|
`}
|
|
1605
1605
|
</article>
|
|
1606
|
-
`}function
|
|
1606
|
+
`}function zy(e,t,n){let{outputs:r}=t,i=r[0],a=`image-sources:${JSON.stringify([e.machineId,e.sessionId,i.message.entryId??i.index])}`,o=e.disclosure.isOpen(a,!1),s=Ty(r.every(e=>e.toolName===i.toolName)?i.toolName:void 0),c=r.flatMap((t,n)=>t.message.parts.flatMap((r,i)=>r.type===`image`?[{part:r,output:t,anchor:n>0&&i===0?e.anchors.message(t.index,t.message):void 0}]:[])),l=c.map((e,t)=>({...e,description:D(`ui.chatView.toolImageDescription`,`{tool} image {index} of {count}`,{tool:Ty(e.output.toolName),index:t+1,count:c.length})}));return E`
|
|
1607
1607
|
<article class="msg tool-image-output conversation-message ui-transcript-surface" data-index=${i.index} data-scroll-anchor-id=${e.anchors.message(i.index,i.message)??k}>
|
|
1608
|
-
${r.length===1?
|
|
1608
|
+
${r.length===1?Wy(e,i.message,String(i.index),i.index,n,s):E`<div class="msg-header"><span class="label">${s}</span></div>`}
|
|
1609
1609
|
<div class="tool-image-thumbnails">
|
|
1610
1610
|
${l.map((t,n)=>E`
|
|
1611
1611
|
<pi-web-transcript-image .imagePart=${t.part} .thumbnail=${!0} .description=${t.description}
|
|
@@ -1619,43 +1619,43 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1619
1619
|
<details class="image-output-sources" ?open=${wt(o)} @toggle=${t=>{e.disclosure.toggle(a,t,!1)}}>
|
|
1620
1620
|
<summary class="ui-transcript-disclosure">${D(`ui.chatView.imageSources`,`Sources ({count})`,{count:r.length})}</summary>
|
|
1621
1621
|
${o?r.map((t,r)=>E`<section class="image-output-source" aria-label=${D(`ui.chatView.imageOutput`,`Output {index}`,{index:r+1})}>
|
|
1622
|
-
${
|
|
1622
|
+
${Wy(e,t.message,`image-source:${String(t.index)}`,t.index,n,`${Ty(t.toolName)} · ${String(r+1)}`)}
|
|
1623
1623
|
</section>`):k}
|
|
1624
1624
|
</details>
|
|
1625
1625
|
`}
|
|
1626
1626
|
</article>
|
|
1627
|
-
`}function
|
|
1628
|
-
<details class=${`${
|
|
1627
|
+
`}function By(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`toolExecution`)}function Vy(e,t,n,r,i){let{messages:a,startIndex:o}=t,{open:s,anchor:c,toggle:l}=i;return E`
|
|
1628
|
+
<details class=${`${Ey(n)} ui-transcript-surface ui-transcript-activity`} data-index=${o} data-scroll-anchor-id=${c??k} ?open=${s} @toggle=${l}>
|
|
1629
1629
|
<summary class="ui-transcript-disclosure ui-transcript-heading">
|
|
1630
|
-
<span class="label">${
|
|
1631
|
-
<span>${
|
|
1630
|
+
<span class="label">${Dy(n)}</span>
|
|
1631
|
+
<span>${Py(a.map(e=>e.message))}</span>
|
|
1632
1632
|
</summary>
|
|
1633
|
-
${Ae(s?
|
|
1633
|
+
${Ae(s?Hy(e,t,r):k)}
|
|
1634
1634
|
</details>
|
|
1635
|
-
`}function
|
|
1635
|
+
`}function Hy(e,{messages:t,startIndex:n},r=new Set){return E`
|
|
1636
1636
|
<div class="group-body">
|
|
1637
1637
|
${t.map(({message:t,index:i},a)=>E`
|
|
1638
1638
|
<section class=${`group-msg ${t.role} ui-transcript-surface`} data-index=${i} data-scroll-anchor-id=${e.anchors.event(i,t)??k}>
|
|
1639
|
-
${
|
|
1640
|
-
${
|
|
1639
|
+
${My(t)?E`<div class="transcript-content">${Wy(e,t,`${String(n)}:${String(a)}`,i,r)}</div>`:null}
|
|
1640
|
+
${Uy(e,t,i)}
|
|
1641
1641
|
</section>`)}
|
|
1642
1642
|
</div>
|
|
1643
|
-
`}function
|
|
1643
|
+
`}function Uy(e,t,n){let r=[];return t.parts.forEach((e,t)=>{if((e.type===`text`||e.type===`thinking`)&&(e.displayText??e.text)===``)return;let n=e.type===`thinking`||e.type===`toolCall`||e.type===`toolResult`||e.type===`toolExecution`||e.type===`askUserQuestion`||e.type===`askUserRecord`,i=r.at(-1);!n&&i!==void 0&&!i.section?i.parts.push({part:e,index:t}):r.push({section:n,parts:[{part:e,index:t}]})}),r.map(r=>E`
|
|
1644
1644
|
<div class=${r.section?`transcript-section`:`transcript-content`}>
|
|
1645
|
-
${r.parts.map(({part:r,index:i})=>
|
|
1645
|
+
${r.parts.map(({part:r,index:i})=>Ky(e,r,t,n,i))}
|
|
1646
1646
|
</div>
|
|
1647
|
-
`)}function
|
|
1647
|
+
`)}function Wy(e,t,n,r,i,a=t.role,o=!1){let s=e.metadata.label(t),c=e.metadata.expandedKey===n,l=`message-meta-${n}`,u=a===`user`||a===`assistant`,d={user:D(`ui.chatView.user`,`User`),assistant:D(`ui.chatView.assistant`,`Assistant`),tool:D(`ui.chatView.tool`,`Tool`),system:D(`ui.chatView.system`,`System`),bash:D(`ui.chatView.command`,`Command`),skill:D(`ui.chatView.skill`,`Skill`)},f=a===t.role?d[t.role]:a;return E`
|
|
1648
1648
|
<div class=${u?`msg-header conversation-header`:`msg-header`}>
|
|
1649
1649
|
<span class=${u?`visually-hidden`:`label`}>${f}</span>
|
|
1650
1650
|
<pi-message-actions-menu>
|
|
1651
1651
|
<div class="msg-actions-strip">
|
|
1652
|
-
${
|
|
1653
|
-
<button type="button" class="msg-meta ui-button ui-button--icon ui-button--small" title=${s} aria-label=${D(`ui.chatView.messageInformation`,`Message information`)} aria-controls=${l} aria-expanded=${String(c)} @click=${t=>{e.metadata.expand(c?void 0:n);let r=t.currentTarget instanceof HTMLElement?t.currentTarget.closest(`pi-message-actions-menu`):null;r instanceof
|
|
1652
|
+
${qy(e,t,n,e.messages[r-e.messageStart]??t,i.has(t))}
|
|
1653
|
+
<button type="button" class="msg-meta ui-button ui-button--icon ui-button--small" title=${s} aria-label=${D(`ui.chatView.messageInformation`,`Message information`)} aria-controls=${l} aria-expanded=${String(c)} @click=${t=>{e.metadata.expand(c?void 0:n);let r=t.currentTarget instanceof HTMLElement?t.currentTarget.closest(`pi-message-actions-menu`):null;r instanceof wy&&r.close()}}>${Kh(`info`,`msg-info-icon`)}</button>
|
|
1654
1654
|
</div>
|
|
1655
1655
|
</pi-message-actions-menu>
|
|
1656
1656
|
</div>
|
|
1657
|
-
${o?null:
|
|
1658
|
-
`}function
|
|
1657
|
+
${o?null:Gy(e,t,n)}
|
|
1658
|
+
`}function Gy(e,t,n){return E`<div id=${`message-meta-${n}`} class="msg-meta-details" ?hidden=${e.metadata.expandedKey!==n}>${e.metadata.label(t)}</div>`}function Ky(e,t,n,r,i){let a=JSON.stringify([e.machineId,e.sessionId,n.entryId??n.streamId??r,i]);if(t.type===`text`||t.type===`thinking`){let r=t.displayText??t.text;if(r===``)return null;if(t.type===`thinking`){let t=`thinking:${a}`,n=e.disclosure.isOpen(t,!0);return E`
|
|
1659
1659
|
<details class="part thinking ui-transcript-surface ui-transcript-activity" ?open=${wt(n)}
|
|
1660
1660
|
@toggle=${n=>{e.disclosure.toggle(t,n,!0)}}>
|
|
1661
1661
|
<summary class="ui-transcript-disclosure ui-transcript-heading"><svg class="thinking-icon" viewBox="0 0 20 20" aria-hidden="true"><path d="M6 14a5 5 0 1 1 8-1H9l-3 2v-1Z"/><circle cx="4" cy="17" r="1"/></svg>${D(`ui.chatView.thinking`,`Thinking`)}</summary>
|
|
@@ -1692,12 +1692,12 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1692
1692
|
<summary class="ui-transcript-disclosure ui-transcript-heading">${t.isError?`✖`:`✓`} ${D(`ui.chatView.toolResult`,`{toolName} result`,{toolName:t.toolName})}${t.isError?D(`ui.chatView.toolResultFailed`,` · Failed`):``}</summary>
|
|
1693
1693
|
${r?E`<formatted-text .imagesEnabled=${e.behaviors.loadImages} .codeBlocks=${e.behaviors.codeBlocks} .intentKey=${a} .contentRendering=${e.contentRendering} .contentRendererVersion=${e.contentRendererVersion} .machineId=${e.machineId} .workspaceContext=${e.workspaceContext} .text=${t.text}></formatted-text>`:k}
|
|
1694
1694
|
</details>
|
|
1695
|
-
`}return null}function
|
|
1695
|
+
`}return null}function qy(e,t,n,r,i){let a=e.actions.available(r,t,i);if(a.length===0)return null;let o=e.actions.errorMessage(n);return E`
|
|
1696
1696
|
<div class="msg-actions" aria-label=${D(`ui.chatView.messageActions`,`Message actions`)}>
|
|
1697
1697
|
${a.map(({action:i,enabled:a,ariaLabel:o})=>{let s=e.actions.presentation(n,i.id),c=s?.icon??i.icon;return E`<button type="button" class=${`msg-action ui-button ui-button--small ${c===void 0?``:`ui-button--icon`}`} title=${s?.title??i.title} aria-label=${s?.ariaLabel??s?.title??o} ?disabled=${!a||e.actions.pending(n,i)} @click=${a=>{a.stopPropagation(),e.actions.run(r,t,n,i)}}>${c??i.title}</button>`})}
|
|
1698
1698
|
${o===void 0?null:E`<span role="alert">${o}</span>`}
|
|
1699
1699
|
</div>
|
|
1700
|
-
`}var Gy=`pi-web:chat-groups:`,Ky={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(Jy(e));return t===null||t===``?void 0:Yy(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(Jy(e),JSON.stringify(t))}catch{}}},qy=class{constructor(e=Ky){this.storage=e,this.sessionId=``,this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(e){if(this.sessionId===e)return;this.sessionId=e;let t=e===``?void 0:this.storage.read(e);this.openGroupKeys=new Set(t?.open??[]),this.closedDefaultOpenGroupKeys=new Set(t?.closedDefaultOpen??[])}isOpen(e,t){return t?!this.closedDefaultOpenGroupKeys.has(e):this.openGroupKeys.has(e)}applyToggle(e,t,n){let r=this.isOpen(e,n),i=new Set(this.openGroupKeys),a=new Set(this.closedDefaultOpenGroupKeys);return n?(i.delete(e),t?a.delete(e):a.add(e)):(a.delete(e),t?i.add(e):i.delete(e)),(n?!a.has(e):i.has(e))===r&&Zy(i,this.openGroupKeys)&&Zy(a,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=i,this.closedDefaultOpenGroupKeys=a,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==``&&this.storage.write(this.sessionId,this.snapshot())}};function Jy(e){return`${Gy}${e}`}function Yy(e){if(Array.isArray(e))return{open:Xy(e),closedDefaultOpen:[]};if(Qy(e))return{open:Array.isArray(e.open)?Xy(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?Xy(e.closedDefaultOpen):[]}}function Xy(e){return e.filter(e=>typeof e==`string`)}function Zy(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function Qy(e){return typeof e==`object`&&!!e}function $y(e,t){if(!t.historyReady||!t.writable||t.messageEnd<t.messageTotal)return;let n=e.at(-1)?.parts.at(-1);return n?.type===`askUserQuestion`?n.ask:void 0}function eb(e){let t=new Map;for(let n of e)for(let e of n.parts){if(e.type!==`askUserRecord`)continue;let n=t.get(e.outcome.askId)??[];n.push(e.outcome),t.set(e.outcome.askId,n)}return t}var tb=`pi-web:chat-scroll:`,nb=180,rb=48,ib=2,ab={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)}},ob={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},sb=class{constructor(e=ab,t=ob){this.storage=e,this.scheduler=t}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(e,t,n=nb){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=ib){if(e===``||t===void 0||!ub(t))return`skipped`;try{if(fb(t,r))return this.storage.setItem(cb(e),JSON.stringify({mode:`bottom`})),`saved`;let i=mb(t,n);if(i===void 0)return`skipped`;let a=pb(t,i);return this.storage.setItem(cb(e),JSON.stringify(a)),`saved`}catch{return`skipped`}}restorePosition(e,t,n,r){let i=this.readPosition(e);return i===void 0?{status:`skipped`}:this.restoreExplicitPosition(i,t,n)}restoreExplicitPosition(e,t,n,r){if(e.mode===`bottom`)return this.scrollToBottom(t);if(t===void 0||!ub(t))return{status:`skipped`};let i=hb(n,e.anchorId);if(i===void 0)return{status:`missing`,position:e};let a=t.getBoundingClientRect().top,o=i.getBoundingClientRect().top-a;return t.scrollTop+=o-e.offset,{status:`restored`}}readPosition(e){if(e!==``)try{let t=this.storage.getItem(cb(e));if(t===null||t===``)return;let n=JSON.parse(t);return lb(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!ub(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function cb(e){return`${tb}${e}`}function lb(e){return typeof e!=`object`||!e||!(`mode`in e)?!1:e.mode===`bottom`||e.mode===`anchor`&&`anchorId`in e&&typeof e.anchorId==`string`&&e.anchorId!==``&&`offset`in e&&typeof e.offset==`number`}function ub(e){return e.clientHeight>0&&e.scrollHeight>0}function db(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function fb(e,t=rb){return db(e)<t}function pb(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:gb(t)??``,offset:t.getBoundingClientRect().top-n}}function mb(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0,s,c=1/0;for(let e of t){if(gb(e)===void 0)continue;let t=e.getBoundingClientRect();if(t.bottom<=t.top)continue;let l=t.top-n.top;t.bottom<n.top||t.top>n.bottom?Math.abs(l)<c&&(s=e,c=Math.abs(l)):l<=0&&l>i?(r=e,i=l):l>0&&l<o&&(a=e,o=l)}return r??a??s}function hb(e,t){return e.find(e=>{if(gb(e)!==t)return!1;let n=e.getBoundingClientRect();return n.bottom>n.top})}function gb(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}var _b={request:e=>requestAnimationFrame(e),cancel:e=>{cancelAnimationFrame(e)}};function vb(e){return e.hasMore()&&!e.isLoadingMore()&&e.canRequestEarlier()}var yb=2,bb=class{constructor(e,t){this.host=e,this.frames=t,this.following=!1,this.alignForm=!1,this.enabled=e.getBehaviors().followTail}get followingLive(){return this.following}configure(){let e=this.host.getBehaviors().followTail;e?this.enabled||this.syncFollowingAfterNavigation():this.pause(),this.enabled=e}syncFollowingAfterNavigation(){if(!this.host.getBehaviors().followTail)return;let e=this.readPosition();e!==void 0&&(this.lastPosition=e,this.setFollowing(e.maxTop-e.top<yb))}recordScrollBaseline(){this.host.getBehaviors().followTail&&(this.lastPosition=this.readPosition())}onScroll(){if(!this.host.getBehaviors().followTail)return;let e=this.readPosition({preserveOverscroll:!0});if(e===void 0)return;let t=this.lastPosition;if(this.lastPosition=e,t?.maxTop!==e.maxTop)return;let n=e.maxTop-e.top<yb,r=e.top>t.top&&n,i=e.overscrollBottom!==void 0||t.overscrollBottom!==void 0,a=e.top<t.top&&!n&&!i;r?this.setFollowing(!0):a&&this.pause()}pause(){this.setFollowing(!1),this.cancel()}startFollowing(){this.setFollowing(!0),this.recordScrollBaseline()}startup(){this.host.getBehaviors().followTail&&(this.startFollowing(),this.schedule(!0))}readPosition(e={}){let t=this.host.getScroller();if(t===void 0)return;let n=Math.max(0,t.scrollHeight-t.clientHeight),r=t.scrollTop,i=(e.preserveOverscroll===!0?this.lastPosition?.overscrollBottom:void 0)??(r>n?n:void 0);return{top:Math.max(0,Math.min(r,n)),maxTop:n,overscrollBottom:i!==void 0&&r>=i?i:void 0}}setFollowing(e){e&&=this.host.getBehaviors().followTail,this.following!==e&&(this.following=e,this.host.onFollowingChange?.(e))}schedule(e=!1){this.host.getBehaviors().followTail&&(this.lastPosition=this.readPosition({preserveOverscroll:!0}),this.following&&(e!==!1&&(this.alignForm=e),this.frame===void 0&&(this.frame=this.frames.request(()=>{this.frame=void 0;let e=this.alignForm;if(this.alignForm=!1,!this.host.getBehaviors().followTail||!this.following)return;let t=this.host.getScroller();if(t===void 0)return;let n=e===!1?void 0:this.host.getOpenForm(typeof e==`string`?e:void 0);n===void 0?t.scrollTop=t.scrollHeight:t.scrollTop+=n.getBoundingClientRect().top-t.getBoundingClientRect().top,n===void 0?this.recordScrollBaseline():this.syncFollowingAfterNavigation()}))))}cancel(){this.frame!==void 0&&this.frames.cancel(this.frame),this.frame=void 0,this.alignForm=!1}reset(){this.cancel(),this.lastPosition=void 0,this.setFollowing(!1)}},xb=class{constructor(e,t,n,r,i){this.host=e,this.frames=t,this.controller=n,this.onRestored=r,this.onMissing=i,this.requestedHistory=!1}get restoring(){return this.pending!==void 0}save(e=this.host.getSessionId()){this.host.getBehaviors().rememberPosition&&e!==``&&this.pending?.sessionId!==e&&this.controller.savePosition(e,this.host.getScroller(),this.host.getAnchors())}scheduleSave(){this.host.getBehaviors().rememberPosition&&!this.restoring&&this.controller.scheduleSave(this.host.getSessionId(),e=>{e===this.host.getSessionId()&&this.save(e)})}restore(){if(this.reset(),!this.host.getBehaviors().rememberPosition)return!1;let e=this.host.getSessionId(),t=this.controller.readPosition(e);return t!==void 0&&(this.pending={sessionId:e,position:t},this.retry(!1),!0)}retry(e){this.host.getBehaviors().rememberPosition&&this.pending!==void 0&&(e&&(this.requestedHistory=!1),this.frame===void 0&&(this.frame=this.frames.request(()=>{this.frame=void 0;let e=this.pending;if(!this.host.getBehaviors().rememberPosition||e?.sessionId!==this.host.getSessionId())return;let t=this.controller.restoreExplicitPosition(e.position,this.host.getScroller(),this.host.getAnchors());t.status===`restored`||t.status===`bottom`?(this.pending=void 0,this.onRestored()):t.status===`missing`&&(this.onMissing(),this.host.isHistoryReady()&&!this.host.hasMore()?this.pending=void 0:this.host.isHistoryReady()&&!this.requestedHistory&&vb(this.host)&&(this.requestedHistory=!0,this.host.requestEarlier()))})))}reset(){this.controller.clearScheduledSave(),this.frame!==void 0&&this.frames.cancel(this.frame),this.frame=void 0,this.pending=void 0,this.requestedHistory=!1}},Sb=class{constructor(e,t){this.host=e,this.frames=t,this.requestedAtTop=!1}schedule(){if(!this.host.getBehaviors().automaticHistory)return;let e=this.host.getScroller();e!==void 0&&(e.scrollTop>64?(this.requestedAtTop=!1,this.cancel()):!this.requestedAtTop&&this.frame===void 0&&vb(this.host)&&(this.frame=this.frames.request(()=>{if(this.frame=void 0,!this.host.getBehaviors().automaticHistory||!vb(this.host))return;let e=this.host.getScroller();e!==void 0&&e.scrollTop<=64&&(this.requestedAtTop=!0,this.host.requestEarlier())})))}reset(){this.cancel(),this.requestedAtTop=!1}cancel(){this.frame!==void 0&&this.frames.cancel(this.frame),this.frame=void 0}},Cb=class{constructor(e,t,n,r){this.host=e,this.frames=t,this.controller=n,this.onCorrected=r}get pending(){return this.snapshot!==void 0||this.frame!==void 0}capture(){if(!this.host.getBehaviors().anchorPrepends)return;this.cancel();let e=this.host.getScroller();if(e===void 0)return;let t=mb(e,this.host.getAnchors());t!==void 0&&(this.snapshot=pb(e,t))}apply(){if(!this.host.getBehaviors().anchorPrepends)return!1;if(this.frame!==void 0)return!0;let e=this.snapshot;return e!==void 0&&(this.snapshot=void 0,this.frame=this.frames.request(()=>{this.frame=void 0,this.host.getBehaviors().anchorPrepends&&this.controller.restoreExplicitPosition(e,this.host.getScroller(),this.host.getAnchors()).status===`restored`&&this.onCorrected()}),!0)}cancel(){this.frame!==void 0&&this.frames.cancel(this.frame),this.frame=void 0,this.snapshot=void 0}},wb=class{constructor(e,t=_b,n={}){this.host=e,this.started=!1,this.disposed=!1;let r=new sb(n.storage,n.saveScheduler);this.tail=new bb(e,t),this.position=new xb(e,t,r,()=>{this.tail.syncFollowingAfterNavigation()},()=>{this.tail.pause(),this.tail.recordScrollBaseline()}),this.history=new Sb(e,t),this.prepend=new Cb(e,t,r,()=>{this.tail.recordScrollBaseline(),this.history.schedule()})}get followingLive(){return this.tail.followingLive}beforeRender(e){this.disposed||(e.sessionChanged?(typeof e.previousSessionId==`string`&&this.position.save(e.previousSessionId),this.position.reset(),this.tail.reset(),this.history.reset(),this.prepend.cancel()):(e.prepend||e.loadingBoundaryChanged===!0)&&!this.position.restoring&&(this.history.cancel(),this.tail.cancel(),this.prepend.pending||this.prepend.capture()))}afterRender(e){this.disposed||(!this.started||e.sessionChanged?(this.started=!0,this.restorePosition()):this.position.restoring?(e.contentChanged||e.historyChanged)&&this.position.retry(e.historyChanged):!this.prepend.apply()&&(e.contentChanged||e.openedForm!==!1)&&this.tail.schedule(e.openedForm),!this.position.restoring&&!this.prepend.pending&&this.history.schedule())}onScroll(){this.disposed||(this.position.restoring||this.tail.onScroll(),this.position.scheduleSave(),!this.position.restoring&&!this.prepend.pending&&this.history.schedule())}onInteraction(){this.disposed||(this.position.restoring&&(this.position.reset(),this.tail.recordScrollBaseline()),this.prepend.cancel())}onUpIntent(){this.onInteraction(),!this.disposed&&this.host.getBehaviors().followTail&&this.tail.pause()}onContentLayoutChanged(){this.disposed||this.position.restoring||this.prepend.pending||this.tail.schedule()}onViewportResize(){this.disposed||(this.position.restoring?this.position.retry(!1):this.prepend.pending||(this.tail.schedule(),this.history.schedule()))}configure(){if(this.disposed)return;let e=this.host.getBehaviors();this.tail.configure(),e.rememberPosition||this.position.reset(),e.automaticHistory||this.history.reset(),e.anchorPrepends||this.prepend.cancel()}savePosition(e){this.disposed||this.position.save(e)}restorePosition(){this.disposed||(this.tail.cancel(),this.prepend.cancel(),this.history.cancel(),this.position.restore()?this.tail.pause():this.tail.startup())}jumpToEnd(){this.jump(!0)}jumpToTop(){this.jump(!1)}jump(e){if(this.disposed)return;this.position.reset(),this.tail.cancel(),this.prepend.cancel();let t=this.host.getScroller();t!==void 0&&(t.scrollTop=e?t.scrollHeight:0,e?this.tail.startFollowing():(this.tail.pause(),this.tail.recordScrollBaseline()),this.position.scheduleSave())}dispose(){this.disposed||(this.position.save(),this.disposed=!0,this.position.reset(),this.tail.cancel(),this.history.cancel(),this.prepend.cancel())}},Tb=class{constructor(){this.previous=[],this.sequence=0}reconcile(e,t){this.transcript!==e&&(this.transcript=e,this.previous=[],this.sequence=0);let n=new Map(this.previous.filter(e=>e.identity!==void 0).map(e=>[e.identity,e.key])),r=new Map(this.previous.filter(e=>e.streamIdentity!==void 0).map(e=>[e.streamIdentity,e.key])),i=new Map(this.previous.filter(e=>e.identity===void 0).map(e=>[e.slot,e.key]));return this.previous=t.map(e=>({...e,key:(e.identity===void 0?void 0:n.get(e.identity))??(e.streamIdentity===void 0?void 0:r.get(e.streamIdentity))??i.get(e.slot)??`render:${String(this.sequence++)}`})),this.previous.map(e=>e.key)}},Eb=me(`.ui-transcript-card-header{top:var(--pi-chat-sticky-top,0px);z-index:6;background:var(--pi-surface);justify-content:space-between;align-items:center;gap:12px;display:flex;position:sticky}.ui-transcript-card-header:not(.ui-transcript-disclosure){min-height:22px;padding:var(--ui-transcript-card-header-padding,8px 16px 7px)}.ui-transcript-card-header>h2{min-width:0;margin-inline-end:auto}.ui-transcript-card-status{color:var(--pi-muted);text-align:end;flex:0 auto;font-size:11px}.ui-transcript-card-status--success{color:var(--pi-success)}.ui-transcript-card-status--warning{color:var(--pi-warning)}`),Db=e=>e??k,Ob=class extends O{constructor(){super(),this.open=!1,this.outcomes=[],this.compact=!1,this.draftSessionId=``,this.answers={},this.confirmingPartialSubmit=!1,this.submitting=!1,v.createController(this)}willUpdate(e){if(!e.has(`ask`)&&!e.has(`outcome`)&&!e.has(`draftSessionId`))return;let t=this.currentModelIdentity();t!==this.modelIdentity&&(this.modelIdentity=t,this.answers=this.loadCurrentDraft(),this.confirmingPartialSubmit=!1,this.submitting=!1)}render(){return this.outcome===void 0?this.ask===void 0?null:this.open&&this.onSubmit!==void 0?this.renderOpenAsk(this.ask):this.renderClosedAsk(this.ask):this.renderRecord(this.outcome)}renderOpenAsk(e){let t=to(e.questions,this.answers),n=no(e.questions,this.answers);return E`
|
|
1700
|
+
`}var Jy=`pi-web:chat-groups:`,Yy={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(Zy(e));return t===null||t===``?void 0:Qy(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(Zy(e),JSON.stringify(t))}catch{}}},Xy=class{constructor(e=Yy){this.storage=e,this.sessionId=``,this.openGroupKeys=new Set,this.closedDefaultOpenGroupKeys=new Set}syncSession(e){if(this.sessionId===e)return;this.sessionId=e;let t=e===``?void 0:this.storage.read(e);this.openGroupKeys=new Set(t?.open??[]),this.closedDefaultOpenGroupKeys=new Set(t?.closedDefaultOpen??[])}isOpen(e,t){return t?!this.closedDefaultOpenGroupKeys.has(e):this.openGroupKeys.has(e)}applyToggle(e,t,n){let r=this.isOpen(e,n),i=new Set(this.openGroupKeys),a=new Set(this.closedDefaultOpenGroupKeys);return n?(i.delete(e),t?a.delete(e):a.add(e)):(a.delete(e),t?i.add(e):i.delete(e)),(n?!a.has(e):i.has(e))===r&&eb(i,this.openGroupKeys)&&eb(a,this.closedDefaultOpenGroupKeys)?!1:(this.openGroupKeys=i,this.closedDefaultOpenGroupKeys=a,this.persist(),!0)}snapshot(){return{open:[...this.openGroupKeys],closedDefaultOpen:[...this.closedDefaultOpenGroupKeys]}}persist(){this.sessionId!==``&&this.storage.write(this.sessionId,this.snapshot())}};function Zy(e){return`${Jy}${e}`}function Qy(e){if(Array.isArray(e))return{open:$y(e),closedDefaultOpen:[]};if(tb(e))return{open:Array.isArray(e.open)?$y(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?$y(e.closedDefaultOpen):[]}}function $y(e){return e.filter(e=>typeof e==`string`)}function eb(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function tb(e){return typeof e==`object`&&!!e}function nb(e,t){if(!t.historyReady||!t.writable||t.messageEnd<t.messageTotal)return;let n=e.at(-1)?.parts.at(-1);return n?.type===`askUserQuestion`?n.ask:void 0}function rb(e){let t=new Map;for(let n of e)for(let e of n.parts){if(e.type!==`askUserRecord`)continue;let n=t.get(e.outcome.askId)??[];n.push(e.outcome),t.set(e.outcome.askId,n)}return t}var ib=`pi-web:chat-scroll:`,ab=180,ob=48,sb=2,cb={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)}},lb={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},ub=class{constructor(e=cb,t=lb){this.storage=e,this.scheduler=t}dispose(){this.clearScheduledSave()}clearScheduledSave(){this.saveTimer!==void 0&&(this.scheduler.clearTimeout(this.saveTimer),this.saveTimer=void 0)}scheduleSave(e,t,n=ab){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=sb){if(e===``||t===void 0||!pb(t))return`skipped`;try{if(hb(t,r))return this.storage.setItem(db(e),JSON.stringify({mode:`bottom`})),`saved`;let i=_b(t,n);if(i===void 0)return`skipped`;let a=gb(t,i);return this.storage.setItem(db(e),JSON.stringify(a)),`saved`}catch{return`skipped`}}restorePosition(e,t,n,r){let i=this.readPosition(e);return i===void 0?{status:`skipped`}:this.restoreExplicitPosition(i,t,n)}restoreExplicitPosition(e,t,n,r){if(e.mode===`bottom`)return this.scrollToBottom(t);if(t===void 0||!pb(t))return{status:`skipped`};let i=vb(n,e.anchorId);if(i===void 0)return{status:`missing`,position:e};let a=t.getBoundingClientRect().top,o=i.getBoundingClientRect().top-a;return t.scrollTop+=o-e.offset,{status:`restored`}}readPosition(e){if(e!==``)try{let t=this.storage.getItem(db(e));if(t===null||t===``)return;let n=JSON.parse(t);return fb(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!pb(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function db(e){return`${ib}${e}`}function fb(e){return typeof e!=`object`||!e||!(`mode`in e)?!1:e.mode===`bottom`||e.mode===`anchor`&&`anchorId`in e&&typeof e.anchorId==`string`&&e.anchorId!==``&&`offset`in e&&typeof e.offset==`number`}function pb(e){return e.clientHeight>0&&e.scrollHeight>0}function mb(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function hb(e,t=ob){return mb(e)<t}function gb(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:yb(t)??``,offset:t.getBoundingClientRect().top-n}}function _b(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0,s,c=1/0;for(let e of t){if(yb(e)===void 0)continue;let t=e.getBoundingClientRect();if(t.bottom<=t.top)continue;let l=t.top-n.top;t.bottom<n.top||t.top>n.bottom?Math.abs(l)<c&&(s=e,c=Math.abs(l)):l<=0&&l>i?(r=e,i=l):l>0&&l<o&&(a=e,o=l)}return r??a??s}function vb(e,t){return e.find(e=>{if(yb(e)!==t)return!1;let n=e.getBoundingClientRect();return n.bottom>n.top})}function yb(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}var bb={request:e=>requestAnimationFrame(e),cancel:e=>{cancelAnimationFrame(e)}};function xb(e){return e.hasMore()&&!e.isLoadingMore()&&e.canRequestEarlier()}var Sb=2,Cb=class{constructor(e,t){this.host=e,this.frames=t,this.following=!1,this.alignForm=!1,this.enabled=e.getBehaviors().followTail}get followingLive(){return this.following}configure(){let e=this.host.getBehaviors().followTail;e?this.enabled||this.syncFollowingAfterNavigation():this.pause(),this.enabled=e}syncFollowingAfterNavigation(){if(!this.host.getBehaviors().followTail)return;let e=this.readPosition();e!==void 0&&(this.lastPosition=e,this.setFollowing(e.maxTop-e.top<Sb))}recordScrollBaseline(){this.host.getBehaviors().followTail&&(this.lastPosition=this.readPosition())}onScroll(){if(!this.host.getBehaviors().followTail)return;let e=this.readPosition({preserveOverscroll:!0});if(e===void 0)return;let t=this.lastPosition;if(this.lastPosition=e,t?.maxTop!==e.maxTop)return;let n=e.maxTop-e.top<Sb,r=e.top>t.top&&n,i=e.overscrollBottom!==void 0||t.overscrollBottom!==void 0,a=e.top<t.top&&!n&&!i;r?this.setFollowing(!0):a&&this.pause()}pause(){this.setFollowing(!1),this.cancel()}startFollowing(){this.setFollowing(!0),this.recordScrollBaseline()}startup(){this.host.getBehaviors().followTail&&(this.startFollowing(),this.schedule(!0))}readPosition(e={}){let t=this.host.getScroller();if(t===void 0)return;let n=Math.max(0,t.scrollHeight-t.clientHeight),r=t.scrollTop,i=(e.preserveOverscroll===!0?this.lastPosition?.overscrollBottom:void 0)??(r>n?n:void 0);return{top:Math.max(0,Math.min(r,n)),maxTop:n,overscrollBottom:i!==void 0&&r>=i?i:void 0}}setFollowing(e){e&&=this.host.getBehaviors().followTail,this.following!==e&&(this.following=e,this.host.onFollowingChange?.(e))}schedule(e=!1){this.host.getBehaviors().followTail&&(this.lastPosition=this.readPosition({preserveOverscroll:!0}),this.following&&(e!==!1&&(this.alignForm=e),this.frame===void 0&&(this.frame=this.frames.request(()=>{this.frame=void 0;let e=this.alignForm;if(this.alignForm=!1,!this.host.getBehaviors().followTail||!this.following)return;let t=this.host.getScroller();if(t===void 0)return;let n=e===!1?void 0:this.host.getOpenForm(typeof e==`string`?e:void 0);n===void 0?t.scrollTop=t.scrollHeight:t.scrollTop+=n.getBoundingClientRect().top-t.getBoundingClientRect().top,n===void 0?this.recordScrollBaseline():this.syncFollowingAfterNavigation()}))))}cancel(){this.frame!==void 0&&this.frames.cancel(this.frame),this.frame=void 0,this.alignForm=!1}reset(){this.cancel(),this.lastPosition=void 0,this.setFollowing(!1)}},wb=class{constructor(e,t,n,r,i){this.host=e,this.frames=t,this.controller=n,this.onRestored=r,this.onMissing=i,this.requestedHistory=!1}get restoring(){return this.pending!==void 0}save(e=this.host.getSessionId()){this.host.getBehaviors().rememberPosition&&e!==``&&this.pending?.sessionId!==e&&this.controller.savePosition(e,this.host.getScroller(),this.host.getAnchors())}scheduleSave(){this.host.getBehaviors().rememberPosition&&!this.restoring&&this.controller.scheduleSave(this.host.getSessionId(),e=>{e===this.host.getSessionId()&&this.save(e)})}restore(){if(this.reset(),!this.host.getBehaviors().rememberPosition)return!1;let e=this.host.getSessionId(),t=this.controller.readPosition(e);return t!==void 0&&(this.pending={sessionId:e,position:t},this.retry(!1),!0)}retry(e){this.host.getBehaviors().rememberPosition&&this.pending!==void 0&&(e&&(this.requestedHistory=!1),this.frame===void 0&&(this.frame=this.frames.request(()=>{this.frame=void 0;let e=this.pending;if(!this.host.getBehaviors().rememberPosition||e?.sessionId!==this.host.getSessionId())return;let t=this.controller.restoreExplicitPosition(e.position,this.host.getScroller(),this.host.getAnchors());t.status===`restored`||t.status===`bottom`?(this.pending=void 0,this.onRestored()):t.status===`missing`&&(this.onMissing(),this.host.isHistoryReady()&&!this.host.hasMore()?this.pending=void 0:this.host.isHistoryReady()&&!this.requestedHistory&&xb(this.host)&&(this.requestedHistory=!0,this.host.requestEarlier()))})))}reset(){this.controller.clearScheduledSave(),this.frame!==void 0&&this.frames.cancel(this.frame),this.frame=void 0,this.pending=void 0,this.requestedHistory=!1}},Tb=class{constructor(e,t){this.host=e,this.frames=t,this.requestedAtTop=!1}schedule(){if(!this.host.getBehaviors().automaticHistory)return;let e=this.host.getScroller();e!==void 0&&(e.scrollTop>64?(this.requestedAtTop=!1,this.cancel()):!this.requestedAtTop&&this.frame===void 0&&xb(this.host)&&(this.frame=this.frames.request(()=>{if(this.frame=void 0,!this.host.getBehaviors().automaticHistory||!xb(this.host))return;let e=this.host.getScroller();e!==void 0&&e.scrollTop<=64&&(this.requestedAtTop=!0,this.host.requestEarlier())})))}reset(){this.cancel(),this.requestedAtTop=!1}cancel(){this.frame!==void 0&&this.frames.cancel(this.frame),this.frame=void 0}},Eb=class{constructor(e,t,n,r){this.host=e,this.frames=t,this.controller=n,this.onCorrected=r}get pending(){return this.snapshot!==void 0||this.frame!==void 0}capture(){if(!this.host.getBehaviors().anchorPrepends)return;this.cancel();let e=this.host.getScroller();if(e===void 0)return;let t=_b(e,this.host.getAnchors());t!==void 0&&(this.snapshot=gb(e,t))}apply(){if(!this.host.getBehaviors().anchorPrepends)return!1;if(this.frame!==void 0)return!0;let e=this.snapshot;return e!==void 0&&(this.snapshot=void 0,this.frame=this.frames.request(()=>{this.frame=void 0,this.host.getBehaviors().anchorPrepends&&this.controller.restoreExplicitPosition(e,this.host.getScroller(),this.host.getAnchors()).status===`restored`&&this.onCorrected()}),!0)}cancel(){this.frame!==void 0&&this.frames.cancel(this.frame),this.frame=void 0,this.snapshot=void 0}},Db=class{constructor(e,t=bb,n={}){this.host=e,this.started=!1,this.disposed=!1;let r=new ub(n.storage,n.saveScheduler);this.tail=new Cb(e,t),this.position=new wb(e,t,r,()=>{this.tail.syncFollowingAfterNavigation()},()=>{this.tail.pause(),this.tail.recordScrollBaseline()}),this.history=new Tb(e,t),this.prepend=new Eb(e,t,r,()=>{this.tail.recordScrollBaseline(),this.history.schedule()})}get followingLive(){return this.tail.followingLive}beforeRender(e){this.disposed||(e.sessionChanged?(typeof e.previousSessionId==`string`&&this.position.save(e.previousSessionId),this.position.reset(),this.tail.reset(),this.history.reset(),this.prepend.cancel()):(e.prepend||e.loadingBoundaryChanged===!0)&&!this.position.restoring&&(this.history.cancel(),this.tail.cancel(),this.prepend.pending||this.prepend.capture()))}afterRender(e){this.disposed||(!this.started||e.sessionChanged?(this.started=!0,this.restorePosition()):this.position.restoring?(e.contentChanged||e.historyChanged)&&this.position.retry(e.historyChanged):!this.prepend.apply()&&(e.contentChanged||e.openedForm!==!1)&&this.tail.schedule(e.openedForm),!this.position.restoring&&!this.prepend.pending&&this.history.schedule())}onScroll(){this.disposed||(this.position.restoring||this.tail.onScroll(),this.position.scheduleSave(),!this.position.restoring&&!this.prepend.pending&&this.history.schedule())}onInteraction(){this.disposed||(this.position.restoring&&(this.position.reset(),this.tail.recordScrollBaseline()),this.prepend.cancel())}onUpIntent(){this.onInteraction(),!this.disposed&&this.host.getBehaviors().followTail&&this.tail.pause()}onContentLayoutChanged(){this.disposed||this.position.restoring||this.prepend.pending||this.tail.schedule()}onViewportResize(){this.disposed||(this.position.restoring?this.position.retry(!1):this.prepend.pending||(this.tail.schedule(),this.history.schedule()))}configure(){if(this.disposed)return;let e=this.host.getBehaviors();this.tail.configure(),e.rememberPosition||this.position.reset(),e.automaticHistory||this.history.reset(),e.anchorPrepends||this.prepend.cancel()}savePosition(e){this.disposed||this.position.save(e)}restorePosition(){this.disposed||(this.tail.cancel(),this.prepend.cancel(),this.history.cancel(),this.position.restore()?this.tail.pause():this.tail.startup())}jumpToEnd(){this.jump(!0)}jumpToTop(){this.jump(!1)}jump(e){if(this.disposed)return;this.position.reset(),this.tail.cancel(),this.prepend.cancel();let t=this.host.getScroller();t!==void 0&&(t.scrollTop=e?t.scrollHeight:0,e?this.tail.startFollowing():(this.tail.pause(),this.tail.recordScrollBaseline()),this.position.scheduleSave())}dispose(){this.disposed||(this.position.save(),this.disposed=!0,this.position.reset(),this.tail.cancel(),this.history.cancel(),this.prepend.cancel())}},Ob=class{constructor(){this.previous=[],this.sequence=0}reconcile(e,t){this.transcript!==e&&(this.transcript=e,this.previous=[],this.sequence=0);let n=new Map(this.previous.filter(e=>e.identity!==void 0).map(e=>[e.identity,e.key])),r=new Map(this.previous.filter(e=>e.streamIdentity!==void 0).map(e=>[e.streamIdentity,e.key])),i=new Map(this.previous.filter(e=>e.identity===void 0).map(e=>[e.slot,e.key]));return this.previous=t.map(e=>({...e,key:(e.identity===void 0?void 0:n.get(e.identity))??(e.streamIdentity===void 0?void 0:r.get(e.streamIdentity))??i.get(e.slot)??`render:${String(this.sequence++)}`})),this.previous.map(e=>e.key)}},kb=me(`.ui-transcript-card-header{top:var(--pi-chat-sticky-top,0px);z-index:6;background:var(--pi-surface);justify-content:space-between;align-items:center;gap:12px;display:flex;position:sticky}.ui-transcript-card-header:not(.ui-transcript-disclosure){min-height:22px;padding:var(--ui-transcript-card-header-padding,8px 16px 7px)}.ui-transcript-card-header>h2{min-width:0;margin-inline-end:auto}.ui-transcript-card-status{color:var(--pi-muted);text-align:end;flex:0 auto;font-size:11px}.ui-transcript-card-status--success{color:var(--pi-success)}.ui-transcript-card-status--warning{color:var(--pi-warning)}`),Ab=e=>e??k,jb=class extends O{constructor(){super(),this.open=!1,this.outcomes=[],this.compact=!1,this.draftSessionId=``,this.answers={},this.confirmingPartialSubmit=!1,this.submitting=!1,v.createController(this)}willUpdate(e){if(!e.has(`ask`)&&!e.has(`outcome`)&&!e.has(`draftSessionId`))return;let t=this.currentModelIdentity();t!==this.modelIdentity&&(this.modelIdentity=t,this.answers=this.loadCurrentDraft(),this.confirmingPartialSubmit=!1,this.submitting=!1)}render(){return this.outcome===void 0?this.ask===void 0?null:this.open&&this.onSubmit!==void 0?this.renderOpenAsk(this.ask):this.renderClosedAsk(this.ask):this.renderRecord(this.outcome)}renderOpenAsk(e){let t=to(e.questions,this.answers),n=no(e.questions,this.answers);return E`
|
|
1701
1701
|
<article class="ui-transcript-surface card open-card" aria-labelledby="ask-user-heading">
|
|
1702
1702
|
<header class="ui-transcript-card-header card-header">
|
|
1703
1703
|
<h2 id="ask-user-heading">${D(`ui.askUserCard.questions`,`Questions`)}</h2>
|
|
@@ -1724,7 +1724,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1724
1724
|
<fieldset
|
|
1725
1725
|
id=${this.questionFieldsetId(n)}
|
|
1726
1726
|
class=${`question${i?` answered`:``}`}
|
|
1727
|
-
aria-describedby=${
|
|
1727
|
+
aria-describedby=${Ab(a)}
|
|
1728
1728
|
tabindex="-1"
|
|
1729
1729
|
>
|
|
1730
1730
|
<legend>
|
|
@@ -1816,7 +1816,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1816
1816
|
<span class=${`ui-transcript-card-status header-status ${e.reason}`}>${t}</span>
|
|
1817
1817
|
</header>
|
|
1818
1818
|
<p class="record-summary">
|
|
1819
|
-
${e.reason===`superseded`?D(`ui.askUserCard.aNewerQuestionSetReplacedThisOneThe`,`A newer question set replaced this one. The draft answers below were not sent to the model.`):
|
|
1819
|
+
${e.reason===`superseded`?D(`ui.askUserCard.aNewerQuestionSetReplacedThisOneThe`,`A newer question set replaced this one. The draft answers below were not sent to the model.`):Mb(e)}
|
|
1820
1820
|
</p>
|
|
1821
1821
|
<div class="record-questions">
|
|
1822
1822
|
${e.questions.map((t,n)=>this.renderQuestionRecord(e,t,n))}
|
|
@@ -1840,7 +1840,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1840
1840
|
</ul>
|
|
1841
1841
|
${n.fromDraft?E`<p class="draft-note">${D(`ui.askUserCard.draftAnswerNotSent`,`Draft answer · Not sent`)}</p>`:null}
|
|
1842
1842
|
`}
|
|
1843
|
-
`}changeOption(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;if(e.multiple!==!0){r.checked&&this.setAnswer(e,{values:[t]});return}let i=this.answers[e.id],a=r.checked?[...new Set([...i?.values??[],t])]:(i?.values??[]).filter(e=>e!==t);this.setAnswer(e,{values:a,...i?.otherText===void 0?{}:{otherText:i.otherText}})}changeOther(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;let i=this.answers[e.id];e.multiple===!0?this.setAnswer(e,{values:[...i?.values??[]],...r.checked?{otherText:i?.otherText??``}:{}}):r.checked&&this.setAnswer(e,{values:[],otherText:this.isOtherSelected(e,i)?i?.otherText??``:``}),r.checked&&this.focusOtherInput(t)}changeOtherText(e,t){let n=t.currentTarget;if(!(n instanceof HTMLTextAreaElement))return;let r=this.answers[e.id];this.setAnswer(e,{values:[...r?.values??[]],otherText:n.value.slice(0,Mt)})}setAnswer(e,t){let n=t.values.length===0&&t.otherText===void 0?Object.fromEntries(Object.entries(this.answers).filter(([t])=>t!==e.id)):{...this.answers,[e.id]:t};this.answers=n,this.confirmingPartialSubmit=!1,this.ask!==void 0&&this.draftSessionId!==``&&Za(this.draftSessionId,this.ask.askId,n)}handleSubmit(e,t){e.preventDefault(),!this.submitting&&(no(t.questions,this.answers).length>0?this.showPartialSubmitConfirmation():this.submitAnswers(t))}submitAnswers(e,t=ro(e.questions,this.answers)){if(this.submitting||!this.open)return;this.submitting=!0;let n=this.onSubmit;if(n===void 0){this.submitting=!1;return}let r=e.askId;Promise.resolve().then(()=>n(r,t)).catch(()=>{}).finally(()=>{this.ask?.askId===r&&(this.submitting=!1)})}async showPartialSubmitConfirmation(){this.confirmingPartialSubmit=!0,await this.updateComplete,this.renderRoot.querySelector(`.send-anyway`)?.focus()}keepEditing(e,t){this.confirmingPartialSubmit=!1;let n=t[0];n!==void 0&&this.focusQuestion(e.questions.indexOf(n))}focusQuestion(e){e<0||this.updateComplete.then(()=>{let t=this.renderRoot.querySelector(`#${this.questionFieldsetId(e)}`);(t?.querySelector(`input, textarea`)??t)?.focus()})}async focusOtherInput(e){await this.updateComplete,this.renderRoot.querySelector(`#${this.otherInputId(e)}`)?.focus()}isOtherSelected(e,t){return t?.otherText===void 0?!1:e.multiple===!0||t.values.length===0}displayedRecordAnswer(e,t){if(t.answered)return{values:[...t.values],...t.otherText===void 0?{}:{otherText:t.otherText},fromDraft:!1};if(e!==void 0&&e.reason!==`superseded`)return;let n=ro([t.question],this.answers).answers[0];if(n!==void 0)return{values:[...n.values],...n.otherText===void 0?{}:{otherText:n.otherText},fromDraft:!0}}optionLabel(e,t){return e.options.find(e=>e.value===t)?.label??t}currentModelIdentity(){if(this.outcome!==void 0)return`record:${this.draftSessionId}:${this.outcome.askId}`;if(this.ask!==void 0)return`request:${this.draftSessionId}:${this.ask.askId}`}loadCurrentDraft(){let e=this.outcome?.askId??this.ask?.askId;return e===void 0||this.draftSessionId===``?{}:Xa(this.draftSessionId,e)}questionGroupName(e,t){return`ask-user:${e.askId}:${t.id}`}questionFieldsetId(e){return`ask-user-question-${String(e)}`}questionDetailId(e){return`ask-user-question-detail-${String(e)}`}otherInputId(e){return`ask-user-other-${String(e)}`}recordQuestionHeadingId(e){return`ask-user-record-question-${String(e)}`}static{this.styles=[de,Ke,
|
|
1843
|
+
`}changeOption(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;if(e.multiple!==!0){r.checked&&this.setAnswer(e,{values:[t]});return}let i=this.answers[e.id],a=r.checked?[...new Set([...i?.values??[],t])]:(i?.values??[]).filter(e=>e!==t);this.setAnswer(e,{values:a,...i?.otherText===void 0?{}:{otherText:i.otherText}})}changeOther(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;let i=this.answers[e.id];e.multiple===!0?this.setAnswer(e,{values:[...i?.values??[]],...r.checked?{otherText:i?.otherText??``}:{}}):r.checked&&this.setAnswer(e,{values:[],otherText:this.isOtherSelected(e,i)?i?.otherText??``:``}),r.checked&&this.focusOtherInput(t)}changeOtherText(e,t){let n=t.currentTarget;if(!(n instanceof HTMLTextAreaElement))return;let r=this.answers[e.id];this.setAnswer(e,{values:[...r?.values??[]],otherText:n.value.slice(0,Mt)})}setAnswer(e,t){let n=t.values.length===0&&t.otherText===void 0?Object.fromEntries(Object.entries(this.answers).filter(([t])=>t!==e.id)):{...this.answers,[e.id]:t};this.answers=n,this.confirmingPartialSubmit=!1,this.ask!==void 0&&this.draftSessionId!==``&&Za(this.draftSessionId,this.ask.askId,n)}handleSubmit(e,t){e.preventDefault(),!this.submitting&&(no(t.questions,this.answers).length>0?this.showPartialSubmitConfirmation():this.submitAnswers(t))}submitAnswers(e,t=ro(e.questions,this.answers)){if(this.submitting||!this.open)return;this.submitting=!0;let n=this.onSubmit;if(n===void 0){this.submitting=!1;return}let r=e.askId;Promise.resolve().then(()=>n(r,t)).catch(()=>{}).finally(()=>{this.ask?.askId===r&&(this.submitting=!1)})}async showPartialSubmitConfirmation(){this.confirmingPartialSubmit=!0,await this.updateComplete,this.renderRoot.querySelector(`.send-anyway`)?.focus()}keepEditing(e,t){this.confirmingPartialSubmit=!1;let n=t[0];n!==void 0&&this.focusQuestion(e.questions.indexOf(n))}focusQuestion(e){e<0||this.updateComplete.then(()=>{let t=this.renderRoot.querySelector(`#${this.questionFieldsetId(e)}`);(t?.querySelector(`input, textarea`)??t)?.focus()})}async focusOtherInput(e){await this.updateComplete,this.renderRoot.querySelector(`#${this.otherInputId(e)}`)?.focus()}isOtherSelected(e,t){return t?.otherText===void 0?!1:e.multiple===!0||t.values.length===0}displayedRecordAnswer(e,t){if(t.answered)return{values:[...t.values],...t.otherText===void 0?{}:{otherText:t.otherText},fromDraft:!1};if(e!==void 0&&e.reason!==`superseded`)return;let n=ro([t.question],this.answers).answers[0];if(n!==void 0)return{values:[...n.values],...n.otherText===void 0?{}:{otherText:n.otherText},fromDraft:!0}}optionLabel(e,t){return e.options.find(e=>e.value===t)?.label??t}currentModelIdentity(){if(this.outcome!==void 0)return`record:${this.draftSessionId}:${this.outcome.askId}`;if(this.ask!==void 0)return`request:${this.draftSessionId}:${this.ask.askId}`}loadCurrentDraft(){let e=this.outcome?.askId??this.ask?.askId;return e===void 0||this.draftSessionId===``?{}:Xa(this.draftSessionId,e)}questionGroupName(e,t){return`ask-user:${e.askId}:${t.id}`}questionFieldsetId(e){return`ask-user-question-${String(e)}`}questionDetailId(e){return`ask-user-question-detail-${String(e)}`}otherInputId(e){return`ask-user-other-${String(e)}`}recordQuestionHeadingId(e){return`ask-user-record-question-${String(e)}`}static{this.styles=[de,Ke,Nh,kb,T`
|
|
1844
1844
|
:host {
|
|
1845
1845
|
display: block;
|
|
1846
1846
|
box-sizing: border-box;
|
|
@@ -1978,7 +1978,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
1978
1978
|
.partial-confirmation { align-items: stretch; flex-direction: column; }
|
|
1979
1979
|
.confirmation-actions { justify-content: flex-end; }
|
|
1980
1980
|
}
|
|
1981
|
-
`]}};w([y({attribute:!1})],
|
|
1981
|
+
`]}};w([y({attribute:!1})],jb.prototype,`ask`,void 0),w([y({type:Boolean})],jb.prototype,`open`,void 0),w([y({attribute:!1})],jb.prototype,`outcomes`,void 0),w([y({attribute:!1})],jb.prototype,`outcome`,void 0),w([y({type:Boolean})],jb.prototype,`compact`,void 0),w([y({attribute:!1})],jb.prototype,`draftSessionId`,void 0),w([y({attribute:!1})],jb.prototype,`onSubmit`,void 0),w([C()],jb.prototype,`answers`,void 0),w([C()],jb.prototype,`confirmingPartialSubmit`,void 0),w([C()],jb.prototype,`submitting`,void 0),jb=w([b(`ask-user-card`)],jb);function Mb(e){let t=e.questions.length,n=D(`ui.main.e5972b436af4`,`Answered {arg0}/{arg1} questions`,{arg0:e.answeredCount.toString(),arg1:t.toString()});return e.unansweredIds.length===0?D(`ui.main.607a56ddb3a3`,`{arg0}; all questions answered`,{arg0:n}):D(`ui.main.507046aea4a4`,`{arg0}; unanswered: {arg1}`,{arg0:n,arg1:e.unansweredIds.join(`、`)})}var Nb=1e3;function Pb(e){switch(e){case`answered`:return D(`ui.extensionDialogCard.answered`,`Answered`);case`cancelled`:return D(`ui.extensionDialogCard.cancelled`,`Cancelled`);case`timeout`:return D(`ui.extensionDialogCard.timedOut`,`Timed out`);case`aborted`:return D(`ui.extensionDialogCard.aborted`,`Aborted`);case`session-ended`:return D(`ui.extensionDialogCard.sessionEnded`,`Session ended`)}}function Fb(e){switch(e.reason){case`answered`:{let t=e.answer;return t===void 0?D(`ui.extensionDialogCard.closedWithoutARecordedAnswer`,`Closed without a recorded answer.`):typeof t==`boolean`?D(`ui.extensionDialogCard.answer`,`Answer: {answer}`,{answer:t?D(`ui.extensionDialogCard.yes`,`Yes`):D(`ui.extensionDialogCard.no`,`No`)}):t===``?D(`ui.extensionDialogCard.answerWasEmpty`,`Answer was empty.`):D(`ui.extensionDialogCard.answer`,`Answer: {answer}`,{answer:t})}case`cancelled`:return D(`ui.extensionDialogCard.cancelledWithoutAnAnswer`,`Cancelled without an answer.`);case`timeout`:return D(`ui.extensionDialogCard.noAnswerReceivedBeforeTheDialogTimedOut`,`No answer received before the dialog timed out.`);case`aborted`:return D(`ui.extensionDialogCard.theTurnWasAbortedBeforeAnAnswer`,`The turn was aborted before an answer.`);case`session-ended`:return D(`ui.extensionDialogCard.theSessionEndedBeforeAnAnswer`,`The session ended before an answer.`)}}function Ib(e,t){if(e===void 0)return;let n=Date.parse(e);if(!Number.isFinite(n))return;let r=n-t;if(r<=0)return D(`ui.extensionDialogCard.autoCancellingSoon`,`Auto-cancelling soon`);let i=Math.ceil(r/1e3);if(i>=3600){let e=Math.floor(i/3600),t=Math.floor(i%3600/60);return D(`ui.extensionDialogCard.autoCancelsInHM`,`Auto-cancels in {hours}h {minutes}m`,{hours:String(e),minutes:String(t)})}if(i>=60){let e=Math.floor(i/60);return D(`ui.extensionDialogCard.autoCancelsInMS`,`Auto-cancels in {minutes}m {seconds60}s`,{minutes:String(e),seconds60:String(i%60)})}return D(`ui.extensionDialogCard.autoCancelsInS`,`Auto-cancels in {seconds}s`,{seconds:String(i)})}var Lb=class extends O{constructor(){super(),this.inputValue=``,this.closing=!1,this.countdownNow=0,v.createController(this)}connectedCallback(){super.connectedCallback(),this.syncCountdownTimer()}disconnectedCallback(){this.stopCountdownTimer(),super.disconnectedCallback()}willUpdate(e){if(!e.has(`dialog`)&&!e.has(`outcome`))return;let t=this.currentIdentity();t!==this.dialogIdentity&&(this.dialogIdentity=t,this.inputValue=``,this.closing=!1),this.syncCountdownTimer()}render(){return this.outcome===void 0?this.dialog===void 0?null:this.renderOpen(this.dialog):this.renderClosed(this.outcome)}renderOpen(e){let t=Ib(e.timeoutAt,this.countdownNow===0?Date.now():this.countdownNow);return E`
|
|
1982
1982
|
<article class="ui-transcript-surface card open-card" aria-labelledby="extension-dialog-heading">
|
|
1983
1983
|
<header class="ui-transcript-card-header card-header">
|
|
1984
1984
|
<h2 id="extension-dialog-heading">${e.title}</h2>
|
|
@@ -2009,7 +2009,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2009
2009
|
type="text"
|
|
2010
2010
|
name="dialog-answer"
|
|
2011
2011
|
aria-label=${D(`ui.extensionDialogCard.yourAnswer`,`Your answer`)}
|
|
2012
|
-
placeholder=${
|
|
2012
|
+
placeholder=${Ab(e.placeholder)}
|
|
2013
2013
|
maxlength=${String(Wt)}
|
|
2014
2014
|
.value=${this.inputValue}
|
|
2015
2015
|
?disabled=${this.closing}
|
|
@@ -2024,14 +2024,14 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2024
2024
|
<article class="ui-transcript-surface card closed-card" aria-labelledby="extension-dialog-closed-heading">
|
|
2025
2025
|
<header class="ui-transcript-card-header card-header">
|
|
2026
2026
|
<h2 id="extension-dialog-closed-heading">${e.dialog.title}</h2>
|
|
2027
|
-
<span class=${`ui-transcript-card-status header-status ${e.reason}`}>${
|
|
2027
|
+
<span class=${`ui-transcript-card-status header-status ${e.reason}`}>${Pb(e.reason)}</span>
|
|
2028
2028
|
</header>
|
|
2029
|
-
<p class="closed-summary">${
|
|
2029
|
+
<p class="closed-summary">${Fb(e)}</p>
|
|
2030
2030
|
<footer class="dialog-footer">
|
|
2031
2031
|
<button class="ui-button ui-button--compact secondary-action" type="button" @click=${()=>{this.dismissClosed(e)}}>${D(`ui.extensionDialogCard.close`,`Close`)}</button>
|
|
2032
2032
|
</footer>
|
|
2033
2033
|
</article>
|
|
2034
|
-
`}answerDialog(e,t){this.closeWith(e,()=>this.onAnswer?.(e.dialogId,t))}cancelDialog(e){this.closeWith(e,()=>this.onCancel?.(e.dialogId))}submitInput(e,t){e.preventDefault(),this.answerDialog(t,this.inputValue)}closeWith(e,t){if(this.closing)return;this.closing=!0;let n=e.dialogId;Promise.resolve().then(t).catch(()=>{}).finally(()=>{this.dialog?.dialogId===n&&(this.closing=!1)})}changeInput(e){let t=e.currentTarget;t instanceof HTMLInputElement&&(this.inputValue=t.value)}dismissClosed(e){this.onDismiss?.(e.dialog.dialogId)}currentIdentity(){if(this.outcome!==void 0)return`closed:${this.outcome.dialog.dialogId}`;if(this.dialog!==void 0)return`open:${this.dialog.dialogId}`}syncCountdownTimer(){let e=this.isConnected&&this.outcome===void 0&&this.dialog?.timeoutAt!==void 0;e&&this.countdownTimer===void 0?(this.countdownNow=Date.now(),this.countdownTimer=window.setInterval(()=>{this.countdownNow=Date.now()},
|
|
2034
|
+
`}answerDialog(e,t){this.closeWith(e,()=>this.onAnswer?.(e.dialogId,t))}cancelDialog(e){this.closeWith(e,()=>this.onCancel?.(e.dialogId))}submitInput(e,t){e.preventDefault(),this.answerDialog(t,this.inputValue)}closeWith(e,t){if(this.closing)return;this.closing=!0;let n=e.dialogId;Promise.resolve().then(t).catch(()=>{}).finally(()=>{this.dialog?.dialogId===n&&(this.closing=!1)})}changeInput(e){let t=e.currentTarget;t instanceof HTMLInputElement&&(this.inputValue=t.value)}dismissClosed(e){this.onDismiss?.(e.dialog.dialogId)}currentIdentity(){if(this.outcome!==void 0)return`closed:${this.outcome.dialog.dialogId}`;if(this.dialog!==void 0)return`open:${this.dialog.dialogId}`}syncCountdownTimer(){let e=this.isConnected&&this.outcome===void 0&&this.dialog?.timeoutAt!==void 0;e&&this.countdownTimer===void 0?(this.countdownNow=Date.now(),this.countdownTimer=window.setInterval(()=>{this.countdownNow=Date.now()},Nb)):e||this.stopCountdownTimer()}stopCountdownTimer(){this.countdownTimer!==void 0&&(window.clearInterval(this.countdownTimer),this.countdownTimer=void 0)}static{this.styles=[de,Ke,Nh,kb,T`
|
|
2035
2035
|
:host {
|
|
2036
2036
|
display: block;
|
|
2037
2037
|
box-sizing: border-box;
|
|
@@ -2091,7 +2091,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2091
2091
|
white-space: pre-wrap;
|
|
2092
2092
|
overflow-wrap: anywhere;
|
|
2093
2093
|
}
|
|
2094
|
-
`]}};w([y({attribute:!1})],
|
|
2094
|
+
`]}};w([y({attribute:!1})],Lb.prototype,`dialog`,void 0),w([y({attribute:!1})],Lb.prototype,`outcome`,void 0),w([y({attribute:!1})],Lb.prototype,`onAnswer`,void 0),w([y({attribute:!1})],Lb.prototype,`onCancel`,void 0),w([y({attribute:!1})],Lb.prototype,`onDismiss`,void 0),w([C()],Lb.prototype,`inputValue`,void 0),w([C()],Lb.prototype,`closing`,void 0),w([C()],Lb.prototype,`countdownNow`,void 0),Lb=w([b(`extension-dialog-card`)],Lb);var Rb=class extends O{constructor(){super(),this.close=()=>{this.swipe=void 0,this.navigationFocus=void 0,this.gallery!==void 0&&(this.gallery=void 0)},this.onKeyDown=e=>{if(e.key===`Tab`){let t=[...this.dialog?.querySelectorAll(`button:not(:disabled)`)??[]],n=t.findIndex(e=>e===ft(this.ownerDocument));(n===-1||(e.shiftKey?n===0:n===t.length-1))&&(e.preventDefault(),(e.shiftKey?t.at(-1):t[0])?.focus())}else e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.key!==`ArrowLeft`&&e.key!==`ArrowRight`||(e.preventDefault(),e.stopPropagation(),this.move(e.key===`ArrowLeft`?-1:1))},this.onPointerDown=e=>{e.pointerType===`touch`&&(e.isPrimary?(this.swipe={pointerId:e.pointerId,x:e.clientX,y:e.clientY},e.currentTarget instanceof HTMLElement&&e.currentTarget.setPointerCapture(e.pointerId)):this.swipe=void 0)},this.onPointerUp=e=>{let t=this.swipe;if(t?.pointerId!==e.pointerId)return;this.swipe=void 0;let n=e.clientX-t.x,r=e.clientY-t.y;Math.abs(n)>=48&&Math.abs(n)>Math.abs(r)*1.5&&this.move(n>0?-1:1)},this.onDialogClick=e=>{e.target===this.dialog&&this.close()},v.createController(this)}show(e,t=0){e[t]!==void 0&&(this.swipe=void 0,this.navigationFocus=void 0,this.gallery={images:e,index:t})}disconnectedCallback(){this.close(),this.dialog?.open===!0&&this.dialog.close(),this.releaseModal(),super.disconnectedCallback()}updated(){this.syncDialog()}syncDialog(){let e=this.dialog;if(e!==void 0){if(this.gallery!==void 0&&this.isConnected){if(this.modalRegistration===void 0){let t=qe({element:e,focus:()=>{(this.renderRoot.querySelector(`.image-zoom-close`)??e).focus()}});this.modalRegistration=t;try{e.open||e.showModal(),t.focus()}catch(e){throw this.modalRegistration=void 0,t.unregister(),e}}let t=this.navigationFocus;this.navigationFocus=void 0,t!==void 0&&e.querySelector(`[data-direction="${t}"]`)?.focus()}else e.open&&e.close(),this.releaseModal()}}releaseModal(){let e=this.modalRegistration;this.modalRegistration=void 0,e?.unregister()}move(e){let t=this.gallery;if(t===void 0)return;let n=t.index+e;if(n<0||n>=t.images.length)return;let r=ft(this.ownerDocument);n===0&&r===this.dialog?.querySelector(`[data-direction="previous"]`)?this.navigationFocus=`next`:n===t.images.length-1&&r===this.dialog?.querySelector(`[data-direction="next"]`)&&(this.navigationFocus=`previous`),this.gallery={...t,index:n}}render(){let e=this.gallery,t=e?.images[e.index];return E`
|
|
2095
2095
|
<dialog class="image-zoom" aria-label=${D(`images.preview`,`Image preview`)} aria-describedby="image-gallery-position"
|
|
2096
2096
|
@keydown=${this.onKeyDown} @click=${this.onDialogClick} @close=${this.close} @cancel=${this.close}>
|
|
2097
2097
|
${e===void 0||t===void 0?null:E`
|
|
@@ -2120,7 +2120,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2120
2120
|
.image-zoom-full { display: block; width: 100%; height: 100%; min-width: 0; min-height: 0; object-fit: contain; }
|
|
2121
2121
|
.image-gallery-navigation { border-top: 1px solid var(--pi-border); }
|
|
2122
2122
|
.image-gallery-navigation .ui-button { flex: 1 1 0; min-width: 0; white-space: normal; overflow-wrap: anywhere; }
|
|
2123
|
-
`]}};w([S(`dialog`)],
|
|
2123
|
+
`]}};w([S(`dialog`)],Rb.prototype,`dialog`,void 0),w([C()],Rb.prototype,`gallery`,void 0),Rb=w([b(`pi-web-image-gallery-dialog`)],Rb);var zb=`pi-web:markdown-image-dimensions:v1`;function Bb(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function Vb(e,t=Bb()){if(Wb(e))return;let n=Ub(t).find(t=>t.source===e);return n===void 0?void 0:{width:n.width,height:n.height}}function Hb(e,t,n=Bb()){if(Wb(e))return;let r=tt(t.width,t.height);if(e===``||r===void 0)return;let i=Ub(n).filter(t=>t.source!==e);i.push({source:e,...r});try{n?.setItem(zb,JSON.stringify(i.slice(-128)))}catch{}}function Ub(e){try{let t=e?.getItem(zb);if(t==null)return[];let n=JSON.parse(t);if(!Array.isArray(n))return[];let r=new Map;for(let e of n){let t=Gb(e);t===void 0||Wb(t.source)||(r.delete(t.source),r.set(t.source,t))}return[...r.values()].slice(-128)}catch{return[]}}function Wb(e){let t=e.indexOf(`?`);if(t===-1)return!1;let n=new URLSearchParams(e.slice(t+1).split(`#`,1)[0]);return n.get(`embed`)===`management`||n.has(`token`)}function Gb(e){if(typeof e!=`object`||!e||Array.isArray(e)||!(`source`in e)||typeof e.source!=`string`||e.source===``||!(`width`in e)||!(`height`in e))return;let t=tt(e.width,e.height);return t===void 0?void 0:{source:e.source,...t}}var Kb=`important`,qb=` !`+Kb,Jb=_t(class extends Qe{constructor(e){if(super(e),e.type!==Ne.ATTRIBUTE||e.name!==`style`||e.strings?.length>2)throw Error("The `styleMap` directive must be used in the `style` attribute and must be the only part in the attribute.")}render(e){return Object.keys(e).reduce((t,n)=>{let r=e[n];return r==null?t:t+`${n=n.includes(`-`)?n:n.replace(/(?:^(webkit|moz|ms|o)|)(?=[A-Z])/g,`-$&`).toLowerCase()}:${r};`},``)}update(e,[t]){let{style:n}=e.element;if(this.ft===void 0)return this.ft=new Set(Object.keys(t)),this.render(t);for(let e of this.ft)t[e]??(this.ft.delete(e),e.includes(`-`)?n.removeProperty(e):n[e]=null);for(let e in t){let r=t[e];if(r!=null){this.ft.add(e);let t=typeof r==`string`&&r.endsWith(qb);e.includes(`-`)||t?n.setProperty(e,t?r.slice(0,-11):r,t?Kb:``):n[e]=r}}return It}}),Yb=class extends O{constructor(){super(),this.thumbnail=!1,this.description=``,this.label=``,this.requestDisabled=!1,this.pendingLabel=D(`images.show`,`Show image`),v.createController(this)}requestImage(e){this.requestDisabled||(e.preventDefault(),e.stopPropagation(),this.dispatchEvent(new Event(`image-request`,{bubbles:!0,composed:!0})))}reportIntrinsicDimensions(e){let t=e.currentTarget,n=this.source;if(this.onIntrinsicDimensions===void 0||!(t instanceof HTMLImageElement)||n===void 0||n===``||t.getAttribute(`src`)!==n||!t.complete)return;let r=tt(t.naturalWidth,t.naturalHeight);r!==void 0&&this.onIntrinsicDimensions(n,r)}open(e){e.preventDefault(),e.stopPropagation(),this.source!==void 0&&this.source!==``&&this.dispatchEvent(new CustomEvent(`image-open`,{detail:{src:this.source,alt:this.description},bubbles:!0,composed:!0}))}render(){let e=this.source===void 0||this.source===``,t=this.dimensions;return E`
|
|
2124
2124
|
<div class="frame">
|
|
2125
2125
|
<button class="placeholder ui-button" type="button" ?hidden=${!e} ?disabled=${this.requestDisabled}
|
|
2126
2126
|
@click=${e=>{this.requestImage(e)}}>
|
|
@@ -2133,7 +2133,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2133
2133
|
<img loading="lazy" decoding="async" src=${e?k:this.source} alt=${this.description}
|
|
2134
2134
|
@load=${e=>{this.reportIntrinsicDimensions(e)}}
|
|
2135
2135
|
width=${t?.width??k} height=${t?.height??k}
|
|
2136
|
-
style=${
|
|
2136
|
+
style=${Jb(t===void 0?{}:{"--image-width":`${String(t.width)}px`,"--image-height":`${String(t.height)}px`,"--image-ratio":String(t.width/t.height)})} />
|
|
2137
2137
|
</button>
|
|
2138
2138
|
</div>
|
|
2139
2139
|
`}static{this.styles=[de,T`
|
|
@@ -2156,7 +2156,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2156
2156
|
:host([thumbnail]) .placeholder code { display: none; }
|
|
2157
2157
|
:host([thumbnail]) img { width: 100%; height: 100%; max-height: none; border-radius: 0; }
|
|
2158
2158
|
}
|
|
2159
|
-
`]}};w([y({attribute:!1})],
|
|
2159
|
+
`]}};w([y({attribute:!1})],Yb.prototype,`source`,void 0),w([y({type:Boolean,reflect:!0})],Yb.prototype,`thumbnail`,void 0),w([y({attribute:!1})],Yb.prototype,`dimensions`,void 0),w([y({attribute:!1})],Yb.prototype,`onIntrinsicDimensions`,void 0),w([y()],Yb.prototype,`description`,void 0),w([y()],Yb.prototype,`label`,void 0),w([y({type:Boolean})],Yb.prototype,`requestDisabled`,void 0),w([y()],Yb.prototype,`pendingLabel`,void 0),Yb=w([b(`pi-web-image-presentation`)],Yb);var Xb=new nm,Zb=class extends O{constructor(){super(),this.previewUrl=``,this.path=``,this.description=``,this.outside=!1,this.loadingDisabled=!1,this.approved=!1,this.rememberDimensions=(e,t)=>{e!==this.previewUrl||this.loadingDisabled||this.outside&&!this.approved||(Hb(e,t),(this.dimensions?.width!==t.width||this.dimensions.height!==t.height)&&(this.dimensions=t))},v.createController(this)}willUpdate(e){e.has(`previewUrl`)&&(this.dimensions=Vb(this.previewUrl)),(e.has(`previewUrl`)||e.has(`intentKey`)||e.has(`outside`))&&(this.approved=this.outside&&this.intentKey!==void 0&&Xb.read(this.intentKey,this.previewUrl)===!0)}showImage(){!this.loadingDisabled&&this.outside&&this.previewUrl!==``&&(this.approved=!0,this.intentKey!==void 0&&Xb.choose(this.intentKey,this.previewUrl,!0))}render(){return E`<pi-web-image-presentation
|
|
2160
2160
|
.source=${!this.loadingDisabled&&this.previewUrl!==``&&(!this.outside||this.approved)?this.previewUrl:void 0}
|
|
2161
2161
|
.dimensions=${this.dimensions} .onIntrinsicDimensions=${this.rememberDimensions}
|
|
2162
2162
|
.requestDisabled=${this.loadingDisabled||!this.outside||this.previewUrl===``}
|
|
@@ -2165,23 +2165,23 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2165
2165
|
@image-request=${()=>{this.showImage()}}
|
|
2166
2166
|
></pi-web-image-presentation>`}static{this.styles=T`
|
|
2167
2167
|
:host { display: inline-block; max-width: 100%; vertical-align: middle; }
|
|
2168
|
-
`}};w([y({attribute:`preview-url`})],
|
|
2168
|
+
`}};w([y({attribute:`preview-url`})],Zb.prototype,`previewUrl`,void 0),w([y()],Zb.prototype,`path`,void 0),w([y()],Zb.prototype,`description`,void 0),w([y({attribute:`intent-key`})],Zb.prototype,`intentKey`,void 0),w([y({type:Boolean})],Zb.prototype,`outside`,void 0),w([y({type:Boolean,attribute:`loading-disabled`})],Zb.prototype,`loadingDisabled`,void 0),w([C()],Zb.prototype,`approved`,void 0),w([C()],Zb.prototype,`dimensions`,void 0),Zb=w([b(`pi-web-markdown-image`)],Zb);function Qb(e,t){let n=/^(?:[a-z]:[\\/]|\\\\|\/\/)/iu.test(t),r=n?t.replaceAll(`\\`,`/`):t,i=n&&/^[a-z]:\//iu.test(e);if(e===``||/^[#?]/u.test(e)||e.startsWith(`//`)||/^[a-z][a-z\d+.-]*:/iu.test(e)&&!i)return;let a;try{a=decodeURIComponent(e.split(/[?#]/u,1)[0]??``)}catch{return}if(a===``||/[\\\u0000-\u001f\u007f]/u.test(a))return;if(a.startsWith(`~/`))return{path:a,outside:!0};let o=n?/^(?:[a-z]:|\/\/[^/]+\/[^/]+)/iu.exec(r)?.[0]??``:``,s=n?/^[a-z]:\//iu.exec(a)?.[0].slice(0,2):void 0,c=s===void 0?a.startsWith(`/`)?a:`${r.slice(o.length)}/${a}`:a.slice(2),l=[];for(let e of c.split(`/`))e===`..`?l.pop():e!==``&&e!==`.`&&l.push(e);let u=`${s??o}/${l.join(`/`)}`,d=`${r.replace(/\/+$/u,``)}/`;return(n?u.toLowerCase().startsWith(d.toLowerCase()):u.startsWith(d))?{path:u.slice(d.length),outside:!1}:{path:u,outside:!0}}function $b(e,t,n){e.querySelectorAll(`img[src]`).forEach((e,r)=>{let i=Qb(e.getAttribute(`src`)??``,t.root);if(i===void 0)return;let a=document.createElement(`pi-web-markdown-image`);a.setAttribute(`path`,i.path),a.setAttribute(`description`,e.getAttribute(`alt`)??``),n!==void 0&&a.setAttribute(`intent-key`,JSON.stringify([t.machineId,t.projectId,t.workspaceId,t.root,n,r])),a.setAttribute(`preview-url`,rt(t.projectId,t.workspaceId,i.path,{machineId:t.machineId})),i.outside&&a.setAttribute(`outside`,``),e.replaceWith(a)})}var ex=new z.Renderer;function tx(e){let t=new z.Renderer;return t.html=({text:e})=>ax(e),t.code=t=>{let n=e.presentation===`code`?ex.code(t):`<div class="plain-code-block">${ax(t.text)}\n</div>\n`;if(e.presentation===`plain`&&!e.copy)return n;let r=t.lang?.trim().split(/\s/u)[0]??``,i=r===``?``:`<span class="code-block-label">${ax(r)}</span>`,a=e.copy?`<button type="button" class="code-copy-button code-block-copy ui-button ui-button--icon ui-button--compact" title="${ax(D(`images.code.copy`,`Copy code block`))}" aria-label="${ax(D(`images.code.copy`,`Copy code block`))}"><span aria-hidden="true">⧉</span></button>`:``;return`<div class="code-block-wrapper code-block-frame">${i===``&&a===``?``:`<div class="code-block-header" role="group" aria-label="${ax(D(`images.code.controls`,`Code block controls`))}">${i}${a}</div>`}${n}</div>\n`},t}var nx=300,rx=new Map;function ix(e,t,n,r=!0,i=jn){let a=JSON.stringify([e,r,i.presentation,i.copy,t===void 0?null:[t.machineId,t.projectId,t.workspaceId,t.root,Ht(zt(``)),n]]),o=rx.get(a);if(o!==void 0)return o;let s=sx(z.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:tx(i)}),t,n,r);if(rx.set(a,s),rx.size>nx){let e=rx.keys().next().value;e!==void 0&&rx.delete(e)}return s}function ax(e){return e.replaceAll(`&`,`&`).replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`)}var ox=`table-scroll`;function sx(e,t,n,r){let i=document.createElement(`template`);return i.innerHTML=e,t!==void 0&&$b(i.content,t,n),i.content.querySelectorAll(`script, style, iframe, object, embed`).forEach(e=>{e.remove()}),i.content.querySelectorAll(`*`).forEach(e=>{let n=e.tagName===`A`?e.getAttribute(`href`):null;if(n!==null&&t!==void 0){let r=Rl(n,t);r!==void 0&&(e.setAttribute(`href`,rt(t.projectId,t.workspaceId,r,{machineId:t.machineId,download:!0})),e.setAttribute(`data-workspace-file`,r))}for(let t of[...e.attributes]){let n=t.name.toLowerCase();n.startsWith(`on`)&&e.removeAttribute(t.name),n!==`href`&&n!==`src`||lx(t.value)||e.removeAttribute(t.name)}e.tagName===`A`&&(e.setAttribute(`target`,e.hasAttribute(`data-workspace-file`)?`_self`:`_blank`),e.setAttribute(`rel`,`noreferrer noopener`))}),i.content.querySelectorAll(`img`).forEach(e=>{e.setAttribute(`loading`,`lazy`),e.setAttribute(`decoding`,`async`),r||e.removeAttribute(`src`)}),r||i.content.querySelectorAll(`pi-web-markdown-image`).forEach(e=>{e.setAttribute(`loading-disabled`,``)}),cx(i.content),i.innerHTML}function cx(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(ox)===!0)return;let t=document.createElement(`div`);t.className=ox,t.setAttribute(`role`,`region`),t.setAttribute(`aria-label`,D(`bundled.relays.table.22d9e7`,`Table`)),t.setAttribute(`tabindex`,`0`),e.before(t),t.append(e)})}function lx(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}function ux(e){if((e.getAttribute(`src`)??``).trim()===``)return;let t=e.src;return/^https?:\/\//u.test(t)?t:void 0}function dx(e,t){return e.complete&&e.currentSrc===t?tt(e.naturalWidth,e.naturalHeight):void 0}function fx(e,t){e.setAttribute(`width`,String(t.width)),e.setAttribute(`height`,String(t.height))}function px(e){e.querySelectorAll(`img[src]`).forEach(e=>{if(!(e instanceof HTMLImageElement))return;let t=ux(e);if(t===void 0)return;let n=dx(e,t)??Vb(t);n!==void 0&&fx(e,n)})}function mx(e){let t=ux(e);if(t===void 0)return;let n=dx(e,t);n!==void 0&&(Hb(t,n),fx(e,n))}var hx=class extends O{constructor(){super(),this.text=``,this.highlight=``,this.imagesEnabled=!0,this.codeBlocks=jn,this.contentRendererVersion=0,this.machineId=`local`,this.enhancement=new um(this),this.phase=`markdown`,this.scheduled=!1,this.displayedText=``,this.replacing=!1,this.layoutChanged=!1,this.onImageLoad={capture:!0,handleEvent:e=>{e.target instanceof HTMLImageElement&&mx(e.target)}},this.onFormattedClick=e=>{if(!(e.target instanceof Element))return;let t=e.target.closest(`a[data-workspace-file]`);if(t instanceof HTMLAnchorElement&&this.workspaceContext!==void 0&&!e.defaultPrevented&&e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey&&(!t.target||t.target===`_self`)){let n=t.getAttribute(`data-workspace-file`);if(n!==null){let t=new CustomEvent(`workspace-file-open`,{detail:{...this.workspaceContext,path:n},bubbles:!0,composed:!0,cancelable:!0});this.dispatchEvent(t)||e.preventDefault()}return}let n=e.target.closest(`.code-copy-button`);if(!(n instanceof HTMLButtonElement))return;let r=n.closest(`.code-block-wrapper`);if(!(r instanceof HTMLElement))return;let i=r.querySelector(`pre code, .plain-code-block`);i instanceof HTMLElement&&this.copyCode(i.textContent,n)},v.createController(this)}willUpdate(e){[`text`,`intentKey`,`imagesEnabled`,`codeBlocks`,`contentRendering`,`contentRendererVersion`,`machineId`,`workspaceContext`].some(t=>e.has(t))&&(this.phase=`markdown`,this.markup=void 0,this.replacing=!this.text.startsWith(this.displayedText)||e.has(`intentKey`)||e.has(`machineId`)||e.has(`workspaceContext`),this.replacing&&(this.content=void 0))}connectedCallback(){super.connectedCallback(),this.requestUpdate()}disconnectedCallback(){super.disconnectedCallback(),this.scheduled=!1}render(){let e=this.codeBlocks.overflow===`scroll`?`formatted code-blocks-scroll`:`formatted`,t=this.replacing||this.content===void 0;return E`<div class=${e} dir="auto" @load=${this.onImageLoad} @click=${this.onFormattedClick}><div class="enhanced-content" ?hidden=${this.replacing}>${this.content}</div><span class="pending-source" ?hidden=${!t}>${t?this.text:``}</span></div>`}updated(){this.phase!==`done`&&!this.scheduled&&(this.scheduled=!0,this.enhancement.request(()=>{this.scheduled=!1,this.phase===`markdown`?this.formatMarkdown():this.phase===`preview`&&this.enhanceMarkdown(),this.requestUpdate()})),px(this.renderRoot),this.applyHighlight(),this.layoutChanged&&(this.layoutChanged=!1,this.dispatchEvent(new CustomEvent(`content-layout-changed`,{bubbles:!0,composed:!0})))}applyHighlight(){let e=this.renderRoot.querySelector(`.enhanced-content`);if(!(e instanceof HTMLElement))return;e.querySelectorAll(`mark[data-search-highlight]`).forEach(e=>{e.replaceWith(document.createTextNode(e.textContent))}),e.normalize();let t=this.highlight.trim();if(t===``)return;let n=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),r=[];for(let e=n.nextNode();e!==null;e=n.nextNode())e instanceof Text&&e.parentElement?.closest(`.code-copy-button`)===null&&r.push(e);for(let e of r)gx(e,t)}formatMarkdown(){try{this.markup=ix(this.text,this.workspaceContext,this.intentKey,this.imagesEnabled,this.codeBlocks),this.codeBlocks.previews&&this.contentRendering!==void 0?(this.phase=`preview`,this.content===void 0?this.showMarkdown():this.enhanceMarkdown()):(this.showMarkdown(),this.phase=`done`)}catch{console.warn(`Chat Markdown formatting failed; source remains available`),this.replacing=!0,this.phase=`done`}}showMarkdown(){this.layoutChanged=!0,this.content=E`${cf(this.markup)}`,this.displayedText=this.text,this.replacing=!1}enhanceMarkdown(){try{this.layoutChanged=!0,this.content=this.contentRendering?.renderMarkdown({text:this.text,machineId:this.workspaceContext?.machineId??this.machineId,toSafeHtml:e=>e===this.text&&this.markup!==void 0?this.markup:ix(e,this.workspaceContext,this.intentKey,this.imagesEnabled,this.codeBlocks)},this.intentKey,this.codeBlocks),this.displayedText=this.text,this.replacing=!1}catch{console.warn(`Chat content enhancement failed; Markdown remains available`),this.showMarkdown()}this.phase=`done`}async copyCode(e,t){let n=await rd(e);this.setCopyButtonState(t,n?`copied`:`failed`),window.setTimeout(()=>{this.setCopyButtonState(t,`idle`)},1200)}setCopyButtonState(e,t){let n=e.querySelector(`span`);n!==null&&(n.textContent=t===`copied`?`✓`:`⧉`);let r=t===`copied`?D(`ui.formattedText.codeBlockCopied`,`Code block copied`):t===`failed`?D(`ui.formattedText.failedToCopyCodeBlock`,`Failed to copy code block`):D(`ui.formattedText.copyCodeBlock`,`Copy code block`);e.title=r,e.setAttribute(`aria-label`,r)}static{this.styles=[Ih,im,T`
|
|
2169
2169
|
.pending-source { white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
2170
2170
|
.enhanced-content { display: contents; }
|
|
2171
2171
|
.enhanced-content[hidden] { display: none; }
|
|
2172
2172
|
mark[data-search-highlight] { border-radius: 3px; background: color-mix(in srgb, var(--pi-warning) 42%, var(--pi-warning-surface)); color: var(--pi-text-bright, inherit); padding: 0 1px; box-shadow: 0 0 0 1px var(--pi-warning-border); }
|
|
2173
|
-
`]}};w([y()],
|
|
2173
|
+
`]}};w([y()],hx.prototype,`text`,void 0),w([y()],hx.prototype,`highlight`,void 0),w([y()],hx.prototype,`intentKey`,void 0),w([y({type:Boolean})],hx.prototype,`imagesEnabled`,void 0),w([y({attribute:!1})],hx.prototype,`codeBlocks`,void 0),w([y({attribute:!1})],hx.prototype,`contentRendering`,void 0),w([y({type:Number})],hx.prototype,`contentRendererVersion`,void 0),w([y()],hx.prototype,`machineId`,void 0),w([y({attribute:!1})],hx.prototype,`workspaceContext`,void 0),hx=w([b(`formatted-text`)],hx);function gx(e,t){let n=e.data,r=[...n.matchAll(new RegExp(_x(t),`giu`))];if(r.length===0)return;let i=0,a=document.createDocumentFragment();for(let e of r){let t=e.index;t>i&&a.append(n.slice(i,t));let r=document.createElement(`mark`);r.dataset.searchHighlight=``,r.textContent=e[0],a.append(r),i=t+e[0].length}i<n.length&&a.append(n.slice(i)),e.replaceWith(a)}function _x(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}var vx=180,yx=class extends O{constructor(){super(),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0,v.createController(this)}willUpdate(e){let t=e.get(`execution`);e.has(`execution`)&&this.execution?.status===`error`&&t?.status!==`error`&&(this.textOpen=!0)}render(){let e=this.execution;if(e===void 0)return null;let t=xx(e.args),n=Cx(e.details),r=e.preview,i=n??r?.diff;i!==this.countedDiff&&(this.countedDiff=i,this.diffStats=i===void 0?void 0:wx(i));let a=this.diffStats,o=n!==void 0&&r?.diff!==void 0&&n!==r.diff,s=e.status===`error`?e.resultText:r?.error,c=i===void 0?e.resultText:void 0,l=bx(e,t);return E`
|
|
2174
2174
|
<section class=${`tool-card ui-transcript-surface ui-transcript-activity ui-transcript-tool ${e.status}`}>
|
|
2175
2175
|
<div class="tool-header ui-transcript-heading">
|
|
2176
2176
|
<div class="tool-title">
|
|
2177
|
-
<span class="status-icon" aria-hidden="true">${
|
|
2177
|
+
<span class="status-icon" aria-hidden="true">${Ox(e.status)}</span>
|
|
2178
2178
|
<strong>${e.toolName}</strong>
|
|
2179
2179
|
${this.renderHeaderTarget(l)}
|
|
2180
2180
|
</div>
|
|
2181
2181
|
<div class="tool-meta">
|
|
2182
|
-
${
|
|
2182
|
+
${Sx(e)===void 0?null:E`<span>${Sx(e)}</span>`}
|
|
2183
2183
|
${a===void 0?null:E`<span class="diff-stats"><b class="added">+${a.added}</b><span>/</span><b class="removed">-${a.removed}</b></span>`}
|
|
2184
|
-
<span class="status-label">${
|
|
2184
|
+
<span class="status-label">${kx(e.status)}</span>
|
|
2185
2185
|
</div>
|
|
2186
2186
|
</div>
|
|
2187
2187
|
|
|
@@ -2214,19 +2214,19 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2214
2214
|
${this.diffOpen?this.renderDiffContent(e,t,n):null}
|
|
2215
2215
|
</details>
|
|
2216
2216
|
`}renderDiffContent(e,t,n){let r=e.split(`
|
|
2217
|
-
`),i=!this.showFullDiff&&r.length>
|
|
2217
|
+
`),i=!this.showFullDiff&&r.length>vx,a=i?r.slice(0,vx):r;return E`
|
|
2218
2218
|
${this.renderExpandedTarget(n)}
|
|
2219
2219
|
<div class="diff-toolbar">
|
|
2220
2220
|
<span>${i?D(`ui.toolExecutionView.showingLines`,`Showing {length} / {value2} lines`,{length:String(a.length),value2:String(r.length)}):D(`ui.toolExecutionView.fullDiff`,`Full diff`)}</span>
|
|
2221
2221
|
<button class="ui-button ui-button--compact" type="button" @click=${()=>{this.copyDiff(e)}}>${this.copied?D(`ui.toolExecutionView.copied`,`Copied`):D(`ui.toolExecutionView.copyDiff`,`Copy diff`)}</button>
|
|
2222
2222
|
</div>
|
|
2223
|
-
<pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>E`<span class=${
|
|
2223
|
+
<pre class="diff" aria-label=${t}><code class="diff-content">${a.map(e=>E`<span class=${Tx(e)}>${e}</span>`)}</code></pre>
|
|
2224
2224
|
${i?E`
|
|
2225
2225
|
<button class="show-more ui-button ui-button--compact" type="button" @click=${()=>{this.showFullDiff=!0}}>
|
|
2226
2226
|
${D(`ui.toolExecutionView.showAllDiffLines`,`Show all {count} diff lines`,{count:r.length})}
|
|
2227
2227
|
</button>
|
|
2228
2228
|
`:null}
|
|
2229
|
-
`}onDiffToggle(e){let t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){await rd(e)?(this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)):this.copied=!1}static{this.styles=[de,
|
|
2229
|
+
`}onDiffToggle(e){let t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){await rd(e)?(this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)):this.copied=!1}static{this.styles=[de,Nh,T`
|
|
2230
2230
|
:host { display: block; width: 100%; max-width: 100%; min-width: 0; color: var(--pi-text); }
|
|
2231
2231
|
.tool-card { display: grid; width: 100%; max-width: 100%; min-width: 0; overflow: hidden; padding: 0; color: var(--pi-text); }
|
|
2232
2232
|
.tool-card.running, .tool-card.pending { --ui-activity-tone: var(--pi-warning); }
|
|
@@ -2272,22 +2272,22 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2272
2272
|
.diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
|
|
2273
2273
|
.diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
|
|
2274
2274
|
.show-more { justify-self: start; margin-inline: 12px; }
|
|
2275
|
-
`]}};w([y({attribute:!1})],
|
|
2276
|
-
`);for(let e of r)
|
|
2275
|
+
`]}};w([y({attribute:!1})],yx.prototype,`execution`,void 0),w([C()],yx.prototype,`showFullDiff`,void 0),w([C()],yx.prototype,`copied`,void 0),w([C()],yx.prototype,`diffOpen`,void 0),w([C()],yx.prototype,`textOpen`,void 0),yx=w([b(`tool-execution-view`)],yx);function bx(e,t){if(t!==void 0&&t!==``)return{label:D(`ui.toolExecutionView.file`,`File`),text:t};let n=Mx(e.args,`command`);if(n!==void 0&&n!==``)return{label:D(`ui.toolExecutionView.command`,`Command`),text:n};if(e.summary!==``)return{label:D(`ui.toolExecutionView.input`,`Input`),text:e.summary}}function xx(e){return Mx(e,`path`)??Mx(e,`file_path`)}function Sx(e){if(e.toolName!==`edit`)return;let t=jx(e.args,`edits`);if(Array.isArray(t))return D(`ui.toolExecutionView.edits`,`{length} edits`,{length:String(t.length)});if(typeof jx(e.args,`oldText`)==`string`&&typeof jx(e.args,`newText`)==`string`)return D(`ui.toolExecutionView.1Edit`,`1 edit`)}function Cx(e){return Mx(e,`diff`)}function wx(e){let t=0,n=0,r=e.split(`
|
|
2276
|
+
`);for(let e of r)Ex(e)?t++:Dx(e)&&n++;return{added:t,removed:n,lines:r.length}}function Tx(e){return Ex(e)?`added`:Dx(e)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`+++`)||e.startsWith(`---`)?`file`:e.startsWith(`diff `)||e.startsWith(`index `)?`meta`:`context`}function Ex(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)}function Dx(e){return e.startsWith(`-`)&&!e.startsWith(`---`)}function Ox(e){return e===`success`?`✓`:e===`error`?`✖`:e===`running`?`●`:`○`}function kx(e){return e===`success`?D(`ui.toolExecutionView.done`,`Done`):e===`error`?D(`ui.toolExecutionView.failed`,`Failed`):e===`running`?D(`ui.toolExecutionView.running`,`Running`):D(`ui.toolExecutionView.pending`,`Pending`)}function Ax(e){return typeof e==`object`&&!!e}function jx(e,t){return Ax(e)?e[t]:void 0}function Mx(e,t){let n=jx(e,t);return typeof n==`string`?n:void 0}function Nx(e,t,n=`local`){return e.mediaId===void 0?{src:`data:${e.mimeType};base64,${e.data}`,alt:D(`images.attached`,`attached image`)}:t===void 0||!r(e.mediaId)?void 0:{src:ue(t,e.mediaId,n),alt:D(`images.attached`,`attached image`)}}var Px=class extends O{constructor(){super(),this.machineId=`local`,this.loadingDisabled=!1,this.thumbnail=!1,this.description=D(`images.attached`,`attached image`),v.createController(this)}render(){let e=this.loadingDisabled||this.imagePart===void 0?void 0:Nx(this.imagePart,this.session,this.machineId)?.src;return E`<pi-web-image-presentation
|
|
2277
2277
|
.source=${e} .requestDisabled=${!0} .thumbnail=${this.thumbnail}
|
|
2278
2278
|
.dimensions=${tt(this.imagePart?.width,this.imagePart?.height)}
|
|
2279
2279
|
.pendingLabel=${this.loadingDisabled?D(`images.loadingDisabled`,`Image loading disabled`):D(`images.unavailable`,`Image unavailable`)}
|
|
2280
2280
|
.description=${this.description} .label=${this.description}
|
|
2281
|
-
></pi-web-image-presentation>`}static{this.styles=T`:host { display: block; max-width: 100%; min-width: 0; }`}};w([y({attribute:!1})],
|
|
2281
|
+
></pi-web-image-presentation>`}static{this.styles=T`:host { display: block; max-width: 100%; min-width: 0; }`}};w([y({attribute:!1})],Px.prototype,`imagePart`,void 0),w([y({attribute:!1})],Px.prototype,`session`,void 0),w([y()],Px.prototype,`machineId`,void 0),w([y({type:Boolean})],Px.prototype,`loadingDisabled`,void 0),w([y({type:Boolean,reflect:!0})],Px.prototype,`thumbnail`,void 0),w([y()],Px.prototype,`description`,void 0),Px=w([b(`pi-web-transcript-image`)],Px);function Fx(e,t){if(t===void 0||e!==`idle`&&t.phase===`idle`)return Ix(e);let n=t.label;return t.detail!==void 0&&t.detail!==``?D(`ui.chatView.activityDetail`,`{label}: {detail}`,{label:n,detail:t.detail}):n}function Ix(e,t){return t===`idle`?D(`activity.idle`,`Idle`):t===void 0?{"agent running":D(`ui.chatView.agentRunning`,`Agent running`),"bash complete":D(`ui.chatView.commandCompleted`,`Command completed`),"bash failed":D(`ui.chatView.commandFailed`,`Command failed`),"branch summary aborted":D(`ui.chatView.branchSummaryAborted`,`Branch summary aborted`),compacting:D(`ui.chatView.compactingContext`,`Compacting context`),"compaction complete":D(`ui.chatView.contextCompactionCompleted`,`Context compaction completed`),"compaction failed":D(`ui.chatView.contextCompactionFailed`,`Context compaction failed`),"duplicate queued message ignored":D(`ui.chatView.duplicateQueuedMessageIgnored`,`Duplicate queued message ignored`),error:D(`ui.chatView.anErrorOccurred`,`An error occurred`),"extension error":D(`ui.chatView.extensionError`,`Extension error`),idle:D(`ui.chatView.idle`,`Idle`),"message complete":D(`ui.chatView.messageCompleted`,`Message completed`),"message queued":D(`ui.chatView.messageQueued`,`Message queued`),"message queued during compaction":D(`ui.chatView.messageQueuedDuringCompaction`,`Message queued during compaction`),"message started":D(`ui.chatView.messageStarted`,`Message started`),"navigating session tree":D(`ui.chatView.navigatingSessionTree`,`Navigating session tree`),"prompt accepted":D(`ui.chatView.messageReceived`,`Message received`),"receiving response":D(`ui.chatView.receivingResponse`,`Receiving response`),"reload failed":D(`ui.chatView.reloadFailed`,`Reload failed`),"reloading resources":D(`ui.chatView.reloadingResources`,`Reloading resources`),"resources reloaded":D(`ui.chatView.resourcesReloaded`,`Resources reloaded`),running:D(`ui.chatView.running`,`Running`),"running bash":D(`ui.chatView.runningCommand`,`Running command`),"running tool":D(`ui.chatView.runningTool`,`Running tool`),"session tree navigated":D(`ui.chatView.sessionTreeUpdated`,`Session tree updated`),"steering queued":D(`ui.chatView.steeringMessageQueued`,`Steering message queued`),"stop failed":D(`ui.chatView.stopFailed`,`Stop failed`),stopped:D(`ui.chatView.stopped`,`Stopped`),"summarizing branch":D(`ui.chatView.summarizingBranch`,`Summarizing branch`),"tool complete":D(`ui.chatView.toolCompleted`,`Tool completed`),"tool failed":D(`ui.chatView.toolFailed`,`Tool failed`),"tree navigation cancelled":D(`ui.chatView.sessionTreeNavigationCancelled`,`Session tree navigation cancelled`),"turn complete":D(`ui.chatView.turnCompleted`,`Turn completed`),"updating session":D(`ui.chatView.updatingSession`,`Updating session`),queued:D(`ui.chatView.queueing`,`Queueing`)}[e]??e:Ix(e)}var Lx=zx({dateStyle:`medium`,timeStyle:`medium`}),Rx=zx({timeStyle:`short`});function zx(e){let t=Ft(),n=new Intl.DateTimeFormat(t,e);return{format(r){return t!==Ft()&&(t=Ft(),n=new Intl.DateTimeFormat(t,e)),n.format(r)}}}function Bx(e){return E`
|
|
2282
2282
|
<svg class=${`notification-icon notification-disclosure-icon${e?``:` expanded`}`} viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2283
2283
|
<path d="m9 18 6-6-6-6"></path>
|
|
2284
2284
|
</svg>
|
|
2285
|
-
`}function
|
|
2285
|
+
`}function Vx(){return E`
|
|
2286
2286
|
<svg class="notification-icon notification-close-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2287
2287
|
<path d="M6 6l12 12"></path>
|
|
2288
2288
|
<path d="M18 6 6 18"></path>
|
|
2289
2289
|
</svg>
|
|
2290
|
-
`}function
|
|
2290
|
+
`}function Hx(e){return typeof e==`object`&&!!e&&typeof Reflect.get(e,`machineId`)==`string`&&typeof Reflect.get(e,`cwd`)==`string`&&typeof Reflect.get(e,`sessionId`)==`string`}function Ux(e){return(e?.warnings??[]).map(e=>({severity:e.severity,severityClass:`session-warning ${e.severity}`,message:e.message,...e.source===void 0?{}:{source:e.source},...e.path===void 0?{}:{path:e.path},...e.dismiss===void 0?{}:{dismissId:e.dismiss.id}}))}function Wx(e){let t=e.meta?.timestamp,n=t===void 0?void 0:Gx(t),r=Kx(e),i=e.meta?.thinkingLevel,a=[n,r,i===void 0||i===``?void 0:ct(i,D)].filter(e=>e!==void 0&&e!==``);return a.length===0?D(`ui.chatView.noPiMessageMetadataAvailable`,`No Pi message metadata available`):a.join(` · `)}function Gx(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return Lx.format(t)}function Kx(e){let t=e.meta?.model;if(t===void 0)return;let n=t.responseId??t.id;return n===void 0||n===``?t.provider:t.provider!==void 0&&t.provider!==``?`${t.provider}/${n}`:n}function qx(e,t){return Jx(t)??String(e)}function Jx(e){if(e?.entryId===void 0||e.entryId===``)return;let t=e.parts.some(e=>e.type===`skillInvocation`)?`skill-invocation`:`message`;return JSON.stringify([e.entryId,e.role,t])}function Yx(e,t){let n=Jx(t);return n===void 0?void 0:`m:${n}`}function Xx(e,t){let n=Jx(t);return n===void 0?void 0:`e:${n}`}var q=class extends O{constructor(){super(),this.messages=[],this.sessionId=``,this.sessionCwd=``,this.machineId=`local`,this.messageActions=[],this.messageActionController=new Cy(()=>({machineId:this.machineId,sessionId:this.sessionId,connected:this.isConnected,actions:this.messageActions,availability:this.messageActionContext,onEntry:this.onMessageAction,onDisplay:this.onDisplayedMessageAction}),()=>{this.requestUpdate()}),this.messageActionIdentity=``,this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.hasMore=!1,this.historyReady=!0,this.loadingMore=!1,this.isSendingPrompt=!1,this.isCompacting=!1,this.pendingMessageCount=0,this.clientQueuedMessages=[],this.askDraftSessionId=``,this.pendingDialogs=[],this.closedDialogs=[],this.canMutateQueuedMessages=!1,this.queuedMessageActionPending=!1,this.queuedCopyFeedback=``,this.queuedCopyGeneration=0,this.warningsVisible=!0,this.behaviors=Nn,this.followingLive=!1,this.disclosures=new Xy,this.transientDisclosures=new Map,this.scrollFlows=new Db({getScroller:()=>this.chat??void 0,onFollowingChange:e=>{this.followingLive=e},getAnchors:()=>this.scrollAnchorElements(),getSessionId:()=>j(this.machineId,this.sessionId),getBehaviors:()=>this.behaviors,hasMore:()=>this.hasMore,isHistoryReady:()=>this.historyReady,isLoadingMore:()=>this.loadingMore||this.loadMoreRequested,canRequestEarlier:()=>this.onLoadMore!==void 0,requestEarlier:()=>{this.requestLoadMore()},getOpenForm:e=>this.renderRoot.querySelector(e===`dialog`?`.chat > extension-dialog-card.open-dialog-card`:e===`ask`?`.chat ask-user-card.open-question-card`:`.chat ask-user-card.open-question-card, .chat > extension-dialog-card.open-dialog-card`)??void 0}),this.questionOutcomes=rb([]),this.questionIds=new Set,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageGrouper=new Oy,this.messageMetaCache=new WeakMap,this.loadMoreRequested=!1,this.onViewportResize=()=>{this.scrollFlows.onViewportResize()},this.onContentLayoutChanged=()=>{this.scrollFlows.onViewportResize()},this.handleScroll=()=>{this.scrollFlows.onScroll()},this.handleDisclosureToggle={capture:!0,handleEvent:e=>{e.target instanceof HTMLDetailsElement&&this.scrollFlows.onContentLayoutChanged()}},this.handleWheel=e=>{e.deltaY!==0&&this.scrollFlows.onInteraction(),e.deltaY<0&&this.scrollFlows.onUpIntent()},this.handleTouchStart=e=>{this.touchY=e.touches[0]?.clientY,this.scrollFlows.onInteraction()},this.handleTouchMove=e=>{let t=e.touches[0]?.clientY;this.touchY!==void 0&&t!==void 0&&t>this.touchY&&this.scrollFlows.onUpIntent(),this.touchY=t},this.handleTouchEnd=()=>{this.touchY=void 0},this.handleJumpTop=()=>{this.scrollFlows.jumpToTop()},this.handleJumpEnd=()=>{this.scrollFlows.jumpToEnd()},this.openImageZoom=(e,t)=>{this.behaviors.loadImages&&this.imageGalleryDialog?.show([{src:e,alt:t}])},this.onPageHide=()=>{this.saveScrollPosition()},this.handleClearServerQueue=()=>{this.onClearServerQueue?.()},this.handleToggleWarnings=()=>{this.onToggleWarnings?.()},this.renderKeys=new Ob,this.collapsedNotificationTargetKeys=new Set,this.canClearServerQueue=!1,this.contentRendererVersion=0,v.createController(this)}openToolImageGallery(e,t){if(!this.behaviors.loadImages)return;let n=e.flatMap((e,t)=>{let n=Nx(e.part,this.transcriptSession(),this.machineId);return n===void 0?[]:[{src:n.src,alt:e.description,partIndex:t}]}),r=n.findIndex(e=>e.partIndex===t);r>=0&&this.imageGalleryDialog?.show(n,r)}connectedCallback(){super.connectedCallback(),window.addEventListener(`resize`,this.onViewportResize),window.addEventListener(`pagehide`,this.onPageHide),window.visualViewport?.addEventListener(`resize`,this.onViewportResize)}disconnectedCallback(){this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0,this.scrollFlows.dispose(),this.messageActionController.reset(),this.queuedCopyGeneration+=1,this.queuedCopyFeedback=``,window.removeEventListener(`resize`,this.onViewportResize),window.removeEventListener(`pagehide`,this.onPageHide),window.visualViewport?.removeEventListener(`resize`,this.onViewportResize),super.disconnectedCallback()}prepareSessionUiState(){this.behaviors.rememberDisclosures&&this.disclosures.syncSession(j(this.machineId,this.sessionId)),this.loadMoreRequested=!1,this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0}willUpdate(e){e.has(`messages`)&&(this.questionOutcomes=rb(this.messages),this.questionIds=new Set(this.messages.flatMap(e=>e.parts.flatMap(e=>e.type===`askUserQuestion`?[e.ask.askId]:[])))),(e.has(`sessionId`)||e.has(`machineId`)||e.has(`behaviors`)&&!this.behaviors.loadImages)&&this.imageGalleryDialog?.close(),(e.has(`sessionId`)||e.has(`machineId`))&&(this.transientDisclosures.clear(),this.lastOpenQuestionId=void 0);let t=JSON.stringify([this.machineId,this.sessionId,this.sessionCwd,this.workspaceContext?.machineId,this.workspaceContext?.projectId,this.workspaceContext?.workspaceId,this.workspaceContext?.root]);t!==this.messageActionIdentity&&(this.queuedCopyGeneration+=1,this.queuedCopyFeedback=``,this.messageActionIdentity=t,this.messageActionController.reset()),(e.has(`sessionId`)||e.has(`machineId`))&&this.prepareSessionUiState(),e.has(`notificationInbox`)&&this.notificationTargetChanged(e.get(`notificationInbox`))&&(this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0),e.has(`behaviors`)&&(this.scrollFlows.configure(),this.behaviors.rememberDisclosures&&this.disclosures.syncSession(j(this.machineId,this.sessionId)))}update(e){let t=e.get(`messageStart`),n=e.get(`machineId`),r=e.get(`sessionId`);this.scrollFlows.beforeRender({sessionChanged:e.has(`sessionId`)||e.has(`machineId`),previousSessionId:j(typeof n==`string`?n:this.machineId,typeof r==`string`?r:this.sessionId),prepend:typeof t==`number`&&this.messageStart<t,loadingBoundaryChanged:e.has(`loadingMore`)}),super.update(e)}updated(e){e.has(`loadingMore`)&&!this.loadingMore&&(this.loadMoreRequested=!1),e.has(`hasMore`)&&!this.hasMore&&(this.loadMoreRequested=!1);let t=this.openQuestion()?.askId;this.scrollFlows.afterRender({sessionChanged:e.has(`sessionId`)||e.has(`machineId`),contentChanged:this.scrollContentChanged(e),historyChanged:e.has(`messages`)||e.has(`messageStart`)||e.has(`hasMore`)||e.has(`loadingMore`)||e.has(`historyReady`),openedForm:e.has(`pendingDialogs`)&&this.isNewOpenDialog(e.get(`pendingDialogs`))?`dialog`:t!==void 0&&t!==this.lastOpenQuestionId&&`ask`}),e.has(`notificationInbox`)&&this.pendingNotificationFocus!==void 0&&this.focusPendingNotificationTarget(),this.onTranscriptRendered!==void 0&&this.reportRenderedTranscript(),this.lastOpenQuestionId=t,(e.has(`followingLive`)||e.has(`behaviors`)||e.has(`onNavigationChange`))&&this.onNavigationChange?.(this.renderNavigation())}render(){let e=this.groupedMessages(),t=Ny(e),n=ky(e),r=this.transcriptRenderContext(),i=j(this.machineId,this.sessionId),a=this.renderKeys.reconcile(i,n.map(e=>{let t=e.kind===`tool-images`?e.outputs[0]:e,n=t.kind===`group`?t.startIndex:t.index,r=t.kind===`group`?t.messages[0]?.message:t.message,i=Jx(r);return{slot:JSON.stringify([e.kind,n,r?.role]),...r?.streamId===void 0?{}:{streamIdentity:JSON.stringify([e.kind,r.role,r.streamId])},...i===void 0?{}:{identity:JSON.stringify([e.kind,i])}}}));return E`
|
|
2291
2291
|
${this.renderTopNotices()}
|
|
2292
2292
|
${this.renderNotificationLiveRegions()}
|
|
2293
2293
|
<div class=${this.behaviors.visualEffects?`chat-wrap`:`chat-wrap plain`}>
|
|
@@ -2301,7 +2301,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2301
2301
|
@touchend=${this.handlesScrollIntent?this.handleTouchEnd:void 0}
|
|
2302
2302
|
@touchcancel=${this.handlesScrollIntent?this.handleTouchEnd:void 0}>
|
|
2303
2303
|
${this.renderHistoryBoundary()}
|
|
2304
|
-
${
|
|
2304
|
+
${Sy(i,tm(n,(e,t)=>a[t],(e,i)=>e.kind===`group`?this.renderMessageGroup(r,e,this.isLiveTailGroup(n,i),t):e.kind===`tool-images`?zy(r,e,t):Ry(r,e.message,e.index,t)))}
|
|
2305
2305
|
${this.renderQueuedMessages()}
|
|
2306
2306
|
${this.renderSessionActivity()}
|
|
2307
2307
|
${this.renderSuggestedInput()}
|
|
@@ -2316,7 +2316,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2316
2316
|
title=${this.behaviors.followTail?e?D(`ui.chatView.followingLiveJumpToEnd`,`Following live - jump to end`):D(`ui.chatView.jumpToEndAndFollowLive`,`Jump to end and follow live`):D(`ui.chatView.jumpToEnd`,`Jump to end`)}
|
|
2317
2317
|
aria-label=${D(`ui.chatView.jumpToEnd`,`Jump to end`)} aria-describedby="chat-follow-state" @click=${this.handleJumpEnd}>↓</button>
|
|
2318
2318
|
<span id="chat-follow-state" class="chat-follow-state">${this.behaviors.followTail?e?D(`ui.chatView.followingLive`,`Following live`):D(`ui.chatView.followingPaused`,`Live following paused`):D(`ui.chatView.followingDisabled`,`Automatic following disabled`)}</span>
|
|
2319
|
-
</nav>`}renderTopNotices(){let e=this.renderWarnings(),t=this.renderNotificationTray();return e===null&&t===null?null:E`<div class="top-notices">${e}${t}</div>`}renderWarnings(){let e=
|
|
2319
|
+
</nav>`}renderTopNotices(){let e=this.renderWarnings(),t=this.renderNotificationTray();return e===null&&t===null?null:E`<div class="top-notices">${e}${t}</div>`}renderWarnings(){let e=Ux(this.status);return!this.warningsVisible||e.length===0?null:E`
|
|
2320
2320
|
<aside class="session-warnings" role="alert" aria-live="polite">
|
|
2321
2321
|
${this.onToggleWarnings===void 0?null:E`
|
|
2322
2322
|
<div class="session-warnings-controls">
|
|
@@ -2337,7 +2337,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2337
2337
|
${e.map(e=>{let t=e.dismissId;return E`
|
|
2338
2338
|
<div class=${e.severityClass}>
|
|
2339
2339
|
<div class="session-warning-head">
|
|
2340
|
-
${
|
|
2340
|
+
${Kh(e.severity,`session-warning-icon`)}
|
|
2341
2341
|
${e.source===void 0?null:E`<span class="session-warning-source">${e.source}</span>`}
|
|
2342
2342
|
</div>
|
|
2343
2343
|
<div class="session-warning-body">
|
|
@@ -2356,8 +2356,8 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2356
2356
|
</div>
|
|
2357
2357
|
`})}
|
|
2358
2358
|
</aside>
|
|
2359
|
-
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart||(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=this.messageGrouper.group(this.messages,this.messageStart)),this.groupedMessagesCache}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase===`active`}renderQueuedMessages(){let e=this.status?.queuedMessages??[];return E`${
|
|
2360
|
-
${this.queuedCopyFeedback===``?k:E`<small role="status">${this.queuedCopyFeedback}</small>`}`}renderQueuedMessageList(e){let t={machineId:this.machineId,sessionId:this.sessionId,cwd:this.sessionCwd};return
|
|
2359
|
+
`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart||(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedMessagesCache=this.messageGrouper.group(this.messages,this.messageStart)),this.groupedMessagesCache}isLiveTailGroup(e,t){return t===e.length-1&&this.isSessionLive()}isSessionLive(){return this.isSendingPrompt||this.status?.isStreaming===!0||this.status?.isCompacting===!0||this.status?.isBashRunning===!0||this.activity?.phase===`active`}renderQueuedMessages(){let e=this.status?.queuedMessages??[];return E`${vy(this.clientQueuedMessages,e).map(e=>this.renderQueuedMessageList(e))}
|
|
2360
|
+
${this.queuedCopyFeedback===``?k:E`<small role="status">${this.queuedCopyFeedback}</small>`}`}renderQueuedMessageList(e){let t={machineId:this.machineId,sessionId:this.sessionId,cwd:this.sessionCwd};return by(e,{machineId:this.machineId,sessionId:this.sessionId,behaviors:this.behaviors,contentRendering:this.contentRendering,contentRendererVersion:this.contentRendererVersion,workspaceContext:this.workspaceContext,pending:this.queuedMessageActionPending,canMutate:this.canMutateQueuedMessages,canClearServerQueue:this.canClearServerQueue,unavailable:this.status?.queueMessageActionsUnavailable,onClear:this.onClearServerQueue===void 0?void 0:this.handleClearServerQueue,onCopy:e=>{this.copyQueuedMessage(e)},onAction:this.onQueuedMessageAction===void 0?void 0:(e,n,r)=>{this.actOnQueuedMessage({...t,action:e,index:n,expectedQueue:r.map(e=>({...e}))})}})}async copyQueuedMessage(e){let t=this.queuedCopyGeneration,n=await rd(e);this.isConnected&&t===this.queuedCopyGeneration&&(this.queuedCopyFeedback=n?``:D(`ui.queuedMessages.copyFailed`,`Could not copy message`))}actOnQueuedMessage(e){this.canMutateQueuedMessages&&!this.queuedMessageActionPending&&this.status?.queueMessageActionsUnavailable===void 0&&e.machineId===this.machineId&&e.sessionId===this.sessionId&&e.cwd===this.sessionCwd&&this.onQueuedMessageAction?.(e)}renderExtensionDialogs(){let e=this.pendingDialogs[0];if(e===void 0&&this.closedDialogs.length===0)return null;let t=this.pendingDialogs.length-1;return E`
|
|
2361
2361
|
${tm(this.closedDialogs,e=>e.dialog.dialogId,e=>E`
|
|
2362
2362
|
<extension-dialog-card
|
|
2363
2363
|
class="closed-dialog-card"
|
|
@@ -2386,7 +2386,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2386
2386
|
<span>${D(`ui.chatView.scrollUpToLoadEarlierMessages`,`Scroll up to load earlier messages`)}</span>
|
|
2387
2387
|
${e}
|
|
2388
2388
|
</div>
|
|
2389
|
-
`:this.messages.length?E`<div class="history-boundary"><span>${D(`ui.chatView.startOfSession`,`Start of session`)}</span>${e}</div>`:null}historyRangeLabel(){if(!this.messages.length||this.messageTotal<=0)return null;let e=this.messageStart+1,t=this.loadedRawMessageEnd(),n=Math.max(this.messageTotal,t);return E`<small>${D(`ui.main.f99875eec53e`,`Showing messages`)} ${e}–${t}${D(`ui.main.c66df59d637e`,` of `)}${n} ${D(`ui.main.bce2ef61514a`,` messages`)}</small>`}loadedRawMessageEnd(){return Math.max(this.messageEnd,this.messageStart+this.messages.length)}transcriptRenderContext(){return{machineId:this.machineId,sessionId:this.sessionId,session:this.transcriptSession(),messages:this.messages,messageStart:this.messageStart,behaviors:this.behaviors,contentRendering:this.contentRendering,contentRendererVersion:this.contentRendererVersion,workspaceContext:this.workspaceContext,anchors:{message:
|
|
2389
|
+
`:this.messages.length?E`<div class="history-boundary"><span>${D(`ui.chatView.startOfSession`,`Start of session`)}</span>${e}</div>`:null}historyRangeLabel(){if(!this.messages.length||this.messageTotal<=0)return null;let e=this.messageStart+1,t=this.loadedRawMessageEnd(),n=Math.max(this.messageTotal,t);return E`<small>${D(`ui.main.f99875eec53e`,`Showing messages`)} ${e}–${t}${D(`ui.main.c66df59d637e`,` of `)}${n} ${D(`ui.main.bce2ef61514a`,` messages`)}</small>`}loadedRawMessageEnd(){return Math.max(this.messageEnd,this.messageStart+this.messages.length)}transcriptRenderContext(){return{machineId:this.machineId,sessionId:this.sessionId,session:this.transcriptSession(),messages:this.messages,messageStart:this.messageStart,behaviors:this.behaviors,contentRendering:this.contentRendering,contentRendererVersion:this.contentRendererVersion,workspaceContext:this.workspaceContext,anchors:{message:Yx,event:Xx},disclosure:{isOpen:(e,t)=>this.isDisclosureOpen(e,t),toggle:(e,t,n)=>{this.onDisclosureToggle(e,t,n)}},metadata:{expandedKey:this.expandedMetaKey,label:e=>this.messageMetaLabel(e),expand:e=>{this.expandedMetaKey=e}},actions:this.messageActionController,openQuestionId:()=>this.openQuestion()?.askId,questionOutcomes:this.questionOutcomes,questionIds:this.questionIds,askDraftSessionId:this.askDraftSessionId,onSubmitAsk:this.onSubmitAsk,openImageGallery:(e,t)=>{this.openToolImageGallery(e,t)}}}renderMessageGroup(e,t,n,r=new Set){let i=this.groupDisclosureKey(t,n);return Vy(e,t,n,r,{open:this.isDisclosureOpen(i,n),anchor:this.groupAnchorKey(t,n),toggle:e=>{this.onDisclosureToggle(i,e,n)}})}messageMetaLabel(e){let t=this.messageMetaCache.get(e);if(t!==void 0)return t;let n=Wx(e);return this.messageMetaCache.set(e,n),n}transcriptSession(){return(this.imageSession?.id!==this.sessionId||this.imageSession.cwd!==this.sessionCwd)&&(this.imageSession={id:this.sessionId,cwd:this.sessionCwd}),this.imageSession}isDisclosureOpen(e,t){return this.behaviors.rememberDisclosures?this.disclosures.isOpen(e,t):this.transientDisclosures.get(e)??t}onDisclosureToggle(e,t,n){let r=t.currentTarget;if(!(r instanceof HTMLDetailsElement))return;let i=this.isDisclosureOpen(e,n)!==r.open;this.behaviors.rememberDisclosures?this.disclosures.applyToggle(e,r.open,n):this.transientDisclosures.set(e,r.open),i&&this.requestUpdate()}get handlesScrollIntent(){return this.behaviors.followTail||this.behaviors.rememberPosition}scrollContentChanged(e){return e.has(`messages`)||e.has(`historyReady`)||e.has(`messageEnd`)||e.has(`messageTotal`)||e.has(`onSubmitAsk`)||e.has(`pendingDialogs`)||e.has(`closedDialogs`)}requestLoadMore(){this.loadMoreRequested||!this.hasMore||this.loadingMore||this.onLoadMore===void 0||(this.loadMoreRequested=!0,this.onLoadMore())}openQuestion(){return nb(this.messages,{historyReady:this.historyReady,messageEnd:this.messageEnd,messageTotal:this.messageTotal,writable:this.onSubmitAsk!==void 0})}isNewOpenDialog(e){let t=this.pendingDialogs[0];if(t===void 0)return!1;if(!Array.isArray(e))return!0;let n=e[0];return typeof n!=`object`||!n||Reflect.get(n,`dialogId`)!==t.dialogId}restoreScrollPosition(){this.scrollFlows.restorePosition()}saveScrollPosition(e=this.sessionId){this.scrollFlows.savePosition(j(this.machineId,e))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll(`[data-scroll-anchor-id]`))}groupDisclosureKey(e,t){return t?`${j(this.machineId,this.sessionId)}:live:${qx(e.startIndex,e.messages[0]?.message)}`:`${j(this.machineId,this.sessionId)}:${qx(e.endIndex,e.messages.at(-1)?.message)}`}groupAnchorKey(e,t){let n=e.messages.map(({message:e})=>Jx(e)).filter(e=>e!==void 0),r=t?n[0]:n.at(-1);if(r!==void 0)return t?`g:${r}`:`g-end:${r}`}static{this.styles=Fh}notificationTargetChanged(e){let t=this.notificationInbox;return!Hx(e)||t===void 0?e!==t:qc(e)!==qc(t)}renderNotificationTray(){let e=this.notificationInbox;if(e?.sessionId!==this.sessionId)return null;let t=qc(e),n=e.pendingDismissedIds.size>0||e.dismissAllPending,r=this.retainedEmptyNotificationTrayTargetKey===t,i=Uc(e);if(i===0&&!n&&!r)return null;let a=Jc(this.collapsedNotificationTargetKeys,e),o=a?D(`ui.chatView.expandNotifications`,`Expand notifications`):D(`ui.chatView.collapseNotifications`,`Collapse notifications`);return E`
|
|
2390
2390
|
<section class=${`notification-tray${a?` collapsed`:``}`} role="region" aria-labelledby="session-notifications-heading" @focusout=${e=>{this.releaseEmptyNotificationTray(e)}}>
|
|
2391
2391
|
<header class="notification-header" data-notification-focus="header" tabindex="-1">
|
|
2392
2392
|
<strong class="notification-heading" id="session-notifications-heading">${Wc(e)}</strong>
|
|
@@ -2407,7 +2407,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2407
2407
|
aria-expanded=${String(!a)}
|
|
2408
2408
|
aria-controls="session-notification-list"
|
|
2409
2409
|
@click=${()=>{this.toggleNotificationTray(e,a)}}
|
|
2410
|
-
>${
|
|
2410
|
+
>${Bx(a)}</button>
|
|
2411
2411
|
</div>
|
|
2412
2412
|
</header>
|
|
2413
2413
|
<div class="notification-list" id="session-notification-list" ?hidden=${a}>
|
|
@@ -2419,9 +2419,9 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2419
2419
|
<div class="notification-metadata">
|
|
2420
2420
|
<strong class="notification-severity">${n}</strong>
|
|
2421
2421
|
<span aria-hidden="true">·</span>
|
|
2422
|
-
<time datetime=${t.receivedAt}>${
|
|
2422
|
+
<time datetime=${t.receivedAt}>${Rx.format(new Date(t.receivedAt))}</time>
|
|
2423
2423
|
</div>
|
|
2424
|
-
<p class="notification-message" dir="auto">${
|
|
2424
|
+
<p class="notification-message" dir="auto">${xy(t.message,t.truncated)}</p>
|
|
2425
2425
|
${r===void 0?null:E`<p class="notification-truncated">${r}</p>`}
|
|
2426
2426
|
<button
|
|
2427
2427
|
type="button"
|
|
@@ -2430,7 +2430,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2430
2430
|
title="${D(`ui.chatView.dismissNotification`,`Dismiss notification`)}"
|
|
2431
2431
|
?disabled=${e.pendingDismissedIds.has(t.id)||e.dismissAllPending||this.onDismissNotification===void 0}
|
|
2432
2432
|
@click=${()=>{this.dismissNotification(t.id)}}
|
|
2433
|
-
>${
|
|
2433
|
+
>${Vx()}</button>
|
|
2434
2434
|
</article>
|
|
2435
2435
|
`})}
|
|
2436
2436
|
</div>
|
|
@@ -2445,7 +2445,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2445
2445
|
<small>${D(`ui.chatView.suggestedInputHint`,`Replaces your current draft. Nothing is sent.`)}</small>
|
|
2446
2446
|
<button type="button" class="ui-button" @click=${()=>{this.onUseSuggestedInput?.(this.machineId,this.sessionId)}}>${D(`ui.chatView.useSuggestedInput`,`Use suggested input`)}</button>
|
|
2447
2447
|
</aside>
|
|
2448
|
-
`}async reportRenderedTranscript(){let e=this.machineId,t=this.sessionCwd,n={sessionId:this.sessionId,messages:this.messages,start:this.messageStart,end:this.messageEnd};await this.updateComplete,this.isConnected&&e===this.machineId&&t===this.sessionCwd&&n.sessionId===this.sessionId&&n.messages===this.messages&&n.start===this.messageStart&&n.end===this.messageEnd&&this.onTranscriptRendered?.(n)}};w([y({attribute:!1})],q.prototype,`messages`,void 0),w([y()],q.prototype,`sessionId`,void 0),w([y({attribute:!1})],q.prototype,`onNavigationChange`,void 0),w([y()],q.prototype,`sessionCwd`,void 0),w([y({attribute:!1})],q.prototype,`workspaceContext`,void 0),w([y({attribute:!1})],q.prototype,`contentRendering`,void 0),w([y()],q.prototype,`machineId`,void 0),w([y({attribute:!1})],q.prototype,`messageActions`,void 0),w([y({attribute:!1})],q.prototype,`messageActionContext`,void 0),w([y({attribute:!1})],q.prototype,`onMessageAction`,void 0),w([y({attribute:!1})],q.prototype,`onDisplayedMessageAction`,void 0),w([y({type:Number})],q.prototype,`messageStart`,void 0),w([y({type:Number})],q.prototype,`messageEnd`,void 0),w([y({type:Number})],q.prototype,`messageTotal`,void 0),w([y({type:Boolean})],q.prototype,`hasMore`,void 0),w([y({type:Boolean})],q.prototype,`historyReady`,void 0),w([y({type:Boolean})],q.prototype,`loadingMore`,void 0),w([y({type:Boolean})],q.prototype,`isSendingPrompt`,void 0),w([y({type:Boolean})],q.prototype,`isCompacting`,void 0),w([y({type:Number})],q.prototype,`pendingMessageCount`,void 0),w([y({attribute:!1})],q.prototype,`clientQueuedMessages`,void 0),w([y({attribute:!1})],q.prototype,`status`,void 0),w([y({attribute:!1})],q.prototype,`activity`,void 0),w([y({attribute:!1})],q.prototype,`askDraftSessionId`,void 0),w([y({attribute:!1})],q.prototype,`onSubmitAsk`,void 0),w([y({attribute:!1})],q.prototype,`pendingDialogs`,void 0),w([y({attribute:!1})],q.prototype,`closedDialogs`,void 0),w([y({attribute:!1})],q.prototype,`onAnswerDialog`,void 0),w([y({attribute:!1})],q.prototype,`onCancelDialog`,void 0),w([y({attribute:!1})],q.prototype,`onDismissClosedDialog`,void 0),w([y({attribute:!1})],q.prototype,`notificationInbox`,void 0),w([y({attribute:!1})],q.prototype,`onClearServerQueue`,void 0),w([y({attribute:!1})],q.prototype,`onQueuedMessageAction`,void 0),w([y({type:Boolean})],q.prototype,`canMutateQueuedMessages`,void 0),w([y({type:Boolean})],q.prototype,`queuedMessageActionPending`,void 0),w([C()],q.prototype,`queuedCopyFeedback`,void 0),w([y({attribute:!1})],q.prototype,`onDismissWarning`,void 0),w([y({attribute:!1})],q.prototype,`onDismissNotification`,void 0),w([y({attribute:!1})],q.prototype,`onDismissAllNotifications`,void 0),w([y({type:Boolean})],q.prototype,`warningsVisible`,void 0),w([y({attribute:!1})],q.prototype,`onToggleWarnings`,void 0),w([y({attribute:!1})],q.prototype,`onLoadMore`,void 0),w([y({attribute:!1})],q.prototype,`behaviors`,void 0),w([S(`.chat`)],q.prototype,`chat`,void 0),w([S(`pi-web-image-gallery-dialog`)],q.prototype,`imageGalleryDialog`,void 0),w([C()],q.prototype,`followingLive`,void 0),w([C()],q.prototype,`expandedMetaKey`,void 0),w([C()],q.prototype,`collapsedNotificationTargetKeys`,void 0),w([C()],q.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),w([y({attribute:!1})],q.prototype,`onTranscriptRendered`,void 0),w([y({type:Boolean})],q.prototype,`canClearServerQueue`,void 0),w([y({attribute:!1})],q.prototype,`onUseSuggestedInput`,void 0),w([y({type:Number})],q.prototype,`contentRendererVersion`,void 0),q=w([b(`chat-view`)],q);var
|
|
2448
|
+
`}async reportRenderedTranscript(){let e=this.machineId,t=this.sessionCwd,n={sessionId:this.sessionId,messages:this.messages,start:this.messageStart,end:this.messageEnd};await this.updateComplete,this.isConnected&&e===this.machineId&&t===this.sessionCwd&&n.sessionId===this.sessionId&&n.messages===this.messages&&n.start===this.messageStart&&n.end===this.messageEnd&&this.onTranscriptRendered?.(n)}};w([y({attribute:!1})],q.prototype,`messages`,void 0),w([y()],q.prototype,`sessionId`,void 0),w([y({attribute:!1})],q.prototype,`onNavigationChange`,void 0),w([y()],q.prototype,`sessionCwd`,void 0),w([y({attribute:!1})],q.prototype,`workspaceContext`,void 0),w([y({attribute:!1})],q.prototype,`contentRendering`,void 0),w([y()],q.prototype,`machineId`,void 0),w([y({attribute:!1})],q.prototype,`messageActions`,void 0),w([y({attribute:!1})],q.prototype,`messageActionContext`,void 0),w([y({attribute:!1})],q.prototype,`onMessageAction`,void 0),w([y({attribute:!1})],q.prototype,`onDisplayedMessageAction`,void 0),w([y({type:Number})],q.prototype,`messageStart`,void 0),w([y({type:Number})],q.prototype,`messageEnd`,void 0),w([y({type:Number})],q.prototype,`messageTotal`,void 0),w([y({type:Boolean})],q.prototype,`hasMore`,void 0),w([y({type:Boolean})],q.prototype,`historyReady`,void 0),w([y({type:Boolean})],q.prototype,`loadingMore`,void 0),w([y({type:Boolean})],q.prototype,`isSendingPrompt`,void 0),w([y({type:Boolean})],q.prototype,`isCompacting`,void 0),w([y({type:Number})],q.prototype,`pendingMessageCount`,void 0),w([y({attribute:!1})],q.prototype,`clientQueuedMessages`,void 0),w([y({attribute:!1})],q.prototype,`status`,void 0),w([y({attribute:!1})],q.prototype,`activity`,void 0),w([y({attribute:!1})],q.prototype,`askDraftSessionId`,void 0),w([y({attribute:!1})],q.prototype,`onSubmitAsk`,void 0),w([y({attribute:!1})],q.prototype,`pendingDialogs`,void 0),w([y({attribute:!1})],q.prototype,`closedDialogs`,void 0),w([y({attribute:!1})],q.prototype,`onAnswerDialog`,void 0),w([y({attribute:!1})],q.prototype,`onCancelDialog`,void 0),w([y({attribute:!1})],q.prototype,`onDismissClosedDialog`,void 0),w([y({attribute:!1})],q.prototype,`notificationInbox`,void 0),w([y({attribute:!1})],q.prototype,`onClearServerQueue`,void 0),w([y({attribute:!1})],q.prototype,`onQueuedMessageAction`,void 0),w([y({type:Boolean})],q.prototype,`canMutateQueuedMessages`,void 0),w([y({type:Boolean})],q.prototype,`queuedMessageActionPending`,void 0),w([C()],q.prototype,`queuedCopyFeedback`,void 0),w([y({attribute:!1})],q.prototype,`onDismissWarning`,void 0),w([y({attribute:!1})],q.prototype,`onDismissNotification`,void 0),w([y({attribute:!1})],q.prototype,`onDismissAllNotifications`,void 0),w([y({type:Boolean})],q.prototype,`warningsVisible`,void 0),w([y({attribute:!1})],q.prototype,`onToggleWarnings`,void 0),w([y({attribute:!1})],q.prototype,`onLoadMore`,void 0),w([y({attribute:!1})],q.prototype,`behaviors`,void 0),w([S(`.chat`)],q.prototype,`chat`,void 0),w([S(`pi-web-image-gallery-dialog`)],q.prototype,`imageGalleryDialog`,void 0),w([C()],q.prototype,`followingLive`,void 0),w([C()],q.prototype,`expandedMetaKey`,void 0),w([C()],q.prototype,`collapsedNotificationTargetKeys`,void 0),w([C()],q.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),w([y({attribute:!1})],q.prototype,`onTranscriptRendered`,void 0),w([y({type:Boolean})],q.prototype,`canClearServerQueue`,void 0),w([y({attribute:!1})],q.prototype,`onUseSuggestedInput`,void 0),w([y({type:Number})],q.prototype,`contentRendererVersion`,void 0),q=w([b(`chat-view`)],q);var Zx=T`
|
|
2449
2449
|
@layer pi-web-base {
|
|
2450
2450
|
:host { display: flex; flex-direction: column; flex: 1 1 auto; min-width: 0; min-height: 0; isolation: isolate; }
|
|
2451
2451
|
:host([hidden]) { display: none; }
|
|
@@ -2463,7 +2463,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2463
2463
|
@media (prefers-reduced-motion: reduce) { .dot { animation: none; } }
|
|
2464
2464
|
@keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
|
|
2465
2465
|
}
|
|
2466
|
-
`;function
|
|
2466
|
+
`;function Qx(e,t,n){if(n)return D(`ui.chatView.sendingYourMessage`,`Sending your message…`);let r=e===void 0?t?.label:e.isCompacting?`compacting`:e.isBashRunning?`bash`:e.isStreaming?`running`:e.pendingMessageCount>0?`queued`:`idle`;if(!(r===void 0||r===`idle`&&t?.phase!==`active`))return Fx(r,t)}var $x=class extends O{constructor(){super(),this.sending=!1,this.visualEffects=!0,this.presentationContext={mode:`normal`},v.createController(this)}render(){let e=Qx(this.status,this.activity,this.sending);return E`
|
|
2467
2467
|
<pi-web-ui-presentation region="chat-chrome" .runtime=${this.presentationRuntime} .context=${this.presentationContext}>
|
|
2468
2468
|
<div class="transcript" slot="transcript"><slot></slot></div>
|
|
2469
2469
|
<div class="composer-boundary" slot="composer">
|
|
@@ -2474,7 +2474,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2474
2474
|
</div>
|
|
2475
2475
|
</pi-web-ui-presentation>
|
|
2476
2476
|
<slot name="status"></slot>
|
|
2477
|
-
`}static{this.styles=
|
|
2477
|
+
`}static{this.styles=Zx}};w([y({attribute:!1})],$x.prototype,`status`,void 0),w([y({attribute:!1})],$x.prototype,`activity`,void 0),w([y({type:Boolean})],$x.prototype,`sending`,void 0),w([y({type:Boolean})],$x.prototype,`visualEffects`,void 0),w([y({attribute:!1})],$x.prototype,`presentationRuntime`,void 0),w([y({attribute:!1})],$x.prototype,`presentationContext`,void 0),$x=w([b(`conversation-layout`)],$x);var eS=hn.define(),tS=vn.define({create:()=>null,update(e,t){for(let e of t.effects)if(e.is(eS))return e.value;return t.docChanged||t.selection!==void 0?null:e}}),nS=class extends nn{constructor(e){super(),this.text=e}eq(e){return e.text===this.text}toDOM(){let e=document.createElement(`span`);return e.className=`cm-argument-hint`,e.textContent=this.text,e}},rS=[tS,_n.decorations.compute([tS],e=>{let t=e.field(tS);return t===null?rn.none:rn.set([rn.widget({widget:new nS(t.text),side:1}).range(t.pos)])})],iS=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function aS(e){return typeof e==`string`&&iS.has(e)}function oS(e){switch(e){case`image/jpeg`:return`jpg`;case`image/png`:return`png`;case`image/gif`:return`gif`;case`image/webp`:return`webp`;default:return`bin`}}var sS=`application/octet-stream`,cS=D(`client.promptAttachmentCapture.failed.to.read.an.attachment.aa0fe0`,`Failed to read an attachment.`);async function lS(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(pS(i,e))}catch{r=cS}return{attachments:n,...r===void 0?{}:{error:r}}}function uS(e){return e.kind===`image`&&aS(e.mimeType)}function dS(e){return e.every(e=>uS(e))}function fS(e,t){return dS(t)?e:`folder`}function pS(e,t){return aS(e.type)?{kind:`image`,name:hS(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:hS(e),mimeType:mS(e),data:t,size:e.size}}function mS(e){let t=e.type.trim();return t===``?sS:t}function hS(e){return e.name===``?aS(e.type)?`pasted-image.${oS(e.type)}`:`pasted-file.bin`:e.name}var gS=`pi-web:attachment-delivery`;function _S(e=Gr()){try{return e?.getItem(gS)===`folder`?`folder`:`inline`}catch{return`inline`}}function vS(e,t=Gr()){try{t?.setItem(gS,e)}catch{}}var yS=class extends O{constructor(){super(),this.popup=new D_(this,()=>{let e=this.renderRoot.querySelector(`.menu`);return e?{anchor:this.anchor??this.parentElement??this,panel:e,onClose:()=>{this.items=[],this.onClose?.()},options:{placement:`above-start`,gap:6,width:`anchor`,maxHeight:260,preserveFocus:!0}}:void 0}),this.items=[],this.selectedIndex=0,v.createController(this)}render(){return this.items.length?E`
|
|
2478
2478
|
<div class="menu" popover="auto">
|
|
2479
2479
|
${this.items.map((e,t)=>E`
|
|
2480
2480
|
<button class=${t===this.selectedIndex?`selected`:``} ${yt(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
|
|
@@ -2484,8 +2484,8 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2484
2484
|
</button>
|
|
2485
2485
|
`)}
|
|
2486
2486
|
</div>
|
|
2487
|
-
`:null}static{this.styles=
|
|
2488
|
-
<footer class=${t?`shell-mode`:``} @paste=${e=>{this.handlePaste(e)}} @dragover=${e=>{this.handleDragOver(e)}} @drop=${e=>{this.handleDrop(e)}}>
|
|
2487
|
+
`:null}static{this.styles=Uh}};w([y({attribute:!1})],yS.prototype,`anchor`,void 0),w([y({attribute:!1})],yS.prototype,`onClose`,void 0),w([y({attribute:!1})],yS.prototype,`items`,void 0),w([y({type:Number})],yS.prototype,`selectedIndex`,void 0),w([y({attribute:!1})],yS.prototype,`onPick`,void 0),yS=w([b(`autocomplete-menu`)],yS);function bS(){return D(`ui.promptEditor.messagePiForCommandsForTrackedFilesSpace`,`Message pi... Use / for commands, @ for tracked files, @ space for all files, # for models`)}var xS=`(pointer: coarse)`;function SS(){return typeof window<`u`&&`matchMedia`in window?window.matchMedia(xS):void 0}function CS(){let e=document.createElement(`span`);return e.className=`prompt-placeholder`,e.dataset.placeholder=bS(),e}var J=class extends O{constructor(){super(),this.defaultStreamingBehavior=`steer`,this.disabled=!1,this.machineId=`local`,this.attachmentsFolder=$e,this.workspaceScopedFileSuggestions=!1,this.canSteer=!1,this.isCompacting=!1,this.canStop=!1,this.sending=!1,this.shortcutConfig={},this.promptChips=[],this.availableThinkingLevels=[],this.draft=``,this.currentInputMode={kind:`normal`},this.completions=[],this.selectedIndex=0,this.attachments=[],this.attachmentDelivery=_S(),this.attachmentError=void 0,this.chipSendingKey=void 0,this.chipError=void 0,this.attachSourceOpen=!1,this.attachPopup=new D_(this,()=>{if(this.attachSourceOpen&&this.attachButton&&this.attachSourcePanel)return{anchor:this.attachButton,panel:this.attachSourcePanel,onClose:()=>{this.attachSourceOpen=!1},options:{minWidth:210}}}),this.attachmentSeq=0,this.attachmentContextGeneration=0,this.requestVersion=0,this.editableCompartment=new on,this.readOnlyCompartment=new on,this.mobilePromptEnterMedia=Ue(),this.explicitShiftKeyActive=!1,v.createController(this)}willUpdate(e){if((this.busy||e.has(`sessionId`)||e.has(`machineId`)||e.has(`cwd`))&&(this.attachSourceOpen=!1),(e.has(`sessionId`)||e.has(`machineId`)||e.has(`cwd`))&&(this.attachmentContextGeneration+=1),[`cwd`,`projectId`,`workspaceId`,`machineId`,`sessionId`].some(t=>e.has(t))&&this.cancelFileCompletion(),!e.has(`sessionId`)&&!e.has(`machineId`))return;let t=e.has(`sessionId`)?e.get(`sessionId`):this.sessionId,n=TS(e.has(`machineId`)?e.get(`machineId`):this.machineId,t);n!==void 0&&za(n,this.draft);let r=TS(this.machineId,this.sessionId);this.draft=r===void 0?``:Ra(r),this.attachments=r===void 0?[]:Wa(r),this.attachmentError=void 0,this.chipError=void 0,this.currentInputMode=Cs(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return e.has(`status`)&&e.size===1?!wS(e.get(`status`),this.status):!0}firstUpdated(){this.createEditor()}get busy(){return this.disabled||this.sending||this.chipSendingKey===this.composerKey()}updated(e){e.has(`disabled`)&&this.updateEditorDisabledState(),(e.has(`sessionId`)||e.has(`machineId`))&&this.syncEditorDoc()}disconnectedCallback(){this.attachSourceOpen=!1,this.attachmentContextGeneration+=1,this.cancelFileCompletion(),this.editor?.destroy(),this.editor=void 0,super.disconnectedCallback()}render(){let e=this.promptChips.length===0&&this.currentInputMode.kind===`shell`?this.currentInputMode:void 0,t=e!==void 0,n=this.canSteer||this.isCompacting,r=this.defaultSendBehavior()===`steer`,i=this.busy,a=SS()?.matches===!0;return E`
|
|
2488
|
+
<footer class=${t?`shell-mode`:``} ?data-active-work=${this.canStop} @paste=${e=>{this.handlePaste(e)}} @dragover=${e=>{this.handleDragOver(e)}} @drop=${e=>{this.handleDrop(e)}}>
|
|
2489
2489
|
<div class="editor-wrap">
|
|
2490
2490
|
<div class="editor-input">
|
|
2491
2491
|
<div class=${`markdown-editor${this.disabled?` markdown-editor-disabled`:``}`} aria-label=${D(`ui.promptEditor.messagePi`,`Message pi`)} aria-disabled=${this.disabled?`true`:`false`}></div>
|
|
@@ -2493,11 +2493,11 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2493
2493
|
<input class="attachment-input" type="file" multiple hidden @change=${e=>{this.handleFileInput(e)}} />
|
|
2494
2494
|
<input class="attachment-image-input" type="file" multiple accept="image/*" hidden @change=${e=>{this.handleFileInput(e)}} />
|
|
2495
2495
|
<input class="attachment-camera-input" type="file" accept="image/*" capture="environment" hidden @change=${e=>{this.handleFileInput(e)}} />
|
|
2496
|
-
<button type="button" class="editor-attach icon-button ui-button ui-button--icon" ?disabled=${i} title=${D(`ui.promptEditor.attachFiles`,`Attach files`)} aria-label=${D(`ui.promptEditor.attachFiles`,`Attach files`)} aria-controls=${a?`attach-source-panel`:k} aria-expanded=${a?String(this.attachSourceOpen):k} @click=${()=>{this.handleAttachClick()}}>${
|
|
2496
|
+
<button type="button" class="editor-attach icon-button ui-button ui-button--icon" ?disabled=${i} title=${D(`ui.promptEditor.attachFiles`,`Attach files`)} aria-label=${D(`ui.promptEditor.attachFiles`,`Attach files`)} aria-controls=${a?`attach-source-panel`:k} aria-expanded=${a?String(this.attachSourceOpen):k} @click=${()=>{this.handleAttachClick()}}>${fy()}</button>
|
|
2497
2497
|
<div id="attach-source-panel" class="attach-source-panel ui-menu" popover="auto" role="group" aria-label=${D(`ui.promptEditor.attachmentSource`,`Attachment source`)}>
|
|
2498
|
-
<button type="button" class="ui-button ui-menu-item" ?disabled=${i} title=${D(`ui.promptEditor.chooseFromPhotoLibrary`,`Choose from your photo library`)} @click=${()=>{this.openAttachmentPicker(this.attachmentImageInput)}}><span class="attach-source-icon" aria-hidden="true">${
|
|
2499
|
-
<button type="button" class="ui-button ui-menu-item" ?disabled=${i} title=${D(`ui.promptEditor.takePhoto`,`Take a new photo`)} @click=${()=>{this.openAttachmentPicker(this.attachmentCameraInput)}}><span class="attach-source-icon" aria-hidden="true">${
|
|
2500
|
-
<button type="button" class="ui-button ui-menu-item" ?disabled=${i} title=${D(`ui.promptEditor.browseFiles`,`Browse documents and other files`)} @click=${()=>{this.openAttachmentPicker(this.attachmentInput)}}><span class="attach-source-icon" aria-hidden="true">${
|
|
2498
|
+
<button type="button" class="ui-button ui-menu-item" ?disabled=${i} title=${D(`ui.promptEditor.chooseFromPhotoLibrary`,`Choose from your photo library`)} @click=${()=>{this.openAttachmentPicker(this.attachmentImageInput)}}><span class="attach-source-icon" aria-hidden="true">${uy()}</span><span class="attach-source-label">${D(`ui.promptEditor.photos`,`Photos`)}</span></button>
|
|
2499
|
+
<button type="button" class="ui-button ui-menu-item" ?disabled=${i} title=${D(`ui.promptEditor.takePhoto`,`Take a new photo`)} @click=${()=>{this.openAttachmentPicker(this.attachmentCameraInput)}}><span class="attach-source-icon" aria-hidden="true">${dy()}</span><span class="attach-source-label">${D(`ui.promptEditor.camera`,`Camera`)}</span></button>
|
|
2500
|
+
<button type="button" class="ui-button ui-menu-item" ?disabled=${i} title=${D(`ui.promptEditor.browseFiles`,`Browse documents and other files`)} @click=${()=>{this.openAttachmentPicker(this.attachmentInput)}}><span class="attach-source-icon" aria-hidden="true">${fy()}</span><span class="attach-source-label">${D(`ui.promptEditor.files`,`Files`)}</span></button>
|
|
2501
2501
|
</div>
|
|
2502
2502
|
${t?E`<div class="mode-hint">${D(`ui.promptEditor.shellCommand`,`Shell command`)}${e.excludeFromContext?D(`ui.promptEditor.excludedFromContext`,` · Excluded from context`):``}</div>`:null}
|
|
2503
2503
|
${this.isCompacting&&!t?E`<div class="mode-hint">${D(`ui.promptEditor.compactingHistoryMessagesWillQueue`,`Compacting history · Messages will queue`)}</div>`:null}
|
|
@@ -2509,16 +2509,16 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2509
2509
|
<div class="actions ui-toolbar ui-toolbar--primary">
|
|
2510
2510
|
${this.renderCompactStatus()}
|
|
2511
2511
|
<div class="ui-toolbar-group">
|
|
2512
|
-
<button class="ui-button ui-button--icon icon-button send-button ${r?``:`default-send-action`}" ?disabled=${i} title=${n?D(`ui.promptEditor.queueAfterCurrentActivity`,`Queue until the current activity finishes`):D(`ui.promptEditor.sendMessage`,`Send message`)} aria-label=${n?D(`ui.promptEditor.queueMessage`,`Queue message`):D(`ui.promptEditor.sendMessage`,`Send message`)} @click=${()=>{this.send(`followUp`)}}>${n?
|
|
2513
|
-
${this.canSteer&&!this.isCompacting?E`<button class="ui-button ui-button--icon icon-button steer-button ${r?`default-send-action`:``}" ?disabled=${i} title=${D(`ui.promptEditor.steerTheCurrentResponseBeforeTheNextModel`,`Steer the current response before the next model call`)} aria-label=${D(`ui.promptEditor.steerCurrentResponse`,`Steer current response`)} @click=${()=>{this.send(`steer`)}}>${
|
|
2514
|
-
<button class="ui-button ui-button--icon icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?D(`ui.promptEditor.stopCurrentWorkAndClearQueuedMessages`,`Stop current work and clear queued messages`):D(`ui.promptEditor.noTaskIsRunning`,`Nothing running`)} aria-label=${D(`ui.promptEditor.stop`,`Stop current work`)} @click=${()=>this.onStop?.()}>${
|
|
2512
|
+
<button class="ui-button ui-button--icon icon-button send-button ${r?``:`default-send-action`}" ?disabled=${i} title=${n?D(`ui.promptEditor.queueAfterCurrentActivity`,`Queue until the current activity finishes`):D(`ui.promptEditor.sendMessage`,`Send message`)} aria-label=${n?D(`ui.promptEditor.queueMessage`,`Queue message`):D(`ui.promptEditor.sendMessage`,`Send message`)} @click=${()=>{this.send(`followUp`)}}>${n?my():py()}</button>
|
|
2513
|
+
${this.canSteer&&!this.isCompacting?E`<button class="ui-button ui-button--icon icon-button steer-button ${r?`default-send-action`:``}" ?disabled=${i} title=${D(`ui.promptEditor.steerTheCurrentResponseBeforeTheNextModel`,`Steer the current response before the next model call`)} aria-label=${D(`ui.promptEditor.steerCurrentResponse`,`Steer current response`)} @click=${()=>{this.send(`steer`)}}>${hy()}</button>`:null}
|
|
2514
|
+
<button class="ui-button ui-button--icon icon-button stop-button" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?D(`ui.promptEditor.stopCurrentWorkAndClearQueuedMessages`,`Stop current work and clear queued messages`):D(`ui.promptEditor.noTaskIsRunning`,`Nothing running`)} aria-label=${D(`ui.promptEditor.stop`,`Stop current work`)} @click=${()=>this.onStop?.()}>${gy()}</button>
|
|
2515
2515
|
</div>
|
|
2516
2516
|
</div>
|
|
2517
2517
|
</footer>
|
|
2518
|
-
`}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=
|
|
2518
|
+
`}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=TS(this.machineId,this.sessionId);t!==void 0&&za(t,e);let n=this.editor;if(n!==void 0){let t=n.state.doc.toString();n.dispatch({...t===e?{}:{changes:{from:0,to:t.length,insert:e}},selection:en.cursor(e.length)})}this.cancelFileCompletion(),this.currentInputMode=Cs(e),this.completions=[],this.selectedIndex=0}get view(){return this.editor}renderCompactStatus(){let e=this.status;if(e===void 0)return null;let t=e.model?.id??D(`ui.promptEditor.noModel`,`No model`),n=e.model?.provider!==void 0&&e.model.provider!==``?`${e.model.provider}/`:``;return E`
|
|
2519
2519
|
<div class="compact-status" aria-label="${D(`ui.promptEditor.sessionStatus`,`Session status`)}">
|
|
2520
2520
|
<button class="ui-button select-model" title="${D(`client.actions.choose.model.1afed6`,`Choose model`)}" @click=${()=>this.onSelectModel?.()}>${n}${t}</button>
|
|
2521
|
-
<button class="ui-button ui-button--icon select-thinking icon-button" title=${D(`ui.promptEditor.thinkingLevel`,`Thinking level: {thinkingLevel}`,{thinkingLevel:ct(e.thinkingLevel,D)})} aria-label=${D(`ui.promptEditor.thinkingLevel`,`Thinking level: {thinkingLevel}`,{thinkingLevel:ct(e.thinkingLevel,D)})} @click=${()=>this.onSelectThinking?.()}>${
|
|
2521
|
+
<button class="ui-button ui-button--icon select-thinking icon-button" title=${D(`ui.promptEditor.thinkingLevel`,`Thinking level: {thinkingLevel}`,{thinkingLevel:ct(e.thinkingLevel,D)})} aria-label=${D(`ui.promptEditor.thinkingLevel`,`Thinking level: {thinkingLevel}`,{thinkingLevel:ct(e.thinkingLevel,D)})} @click=${()=>this.onSelectThinking?.()}>${_y(He(e.thinkingLevel,this.availableThinkingLevels))}</button>
|
|
2522
2522
|
</div>
|
|
2523
2523
|
`}renderPromptChips(){return this.promptChips.length===0&&this.chipError===void 0?null:E`
|
|
2524
2524
|
<div class="prompt-chips" aria-label=${D(`ui.promptEditor.pendingPluginContext`,`Pending plugin context`)}>
|
|
@@ -2530,10 +2530,10 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2530
2530
|
`)}
|
|
2531
2531
|
${this.chipError===void 0?null:E`<div class="chip-error" role="alert">${this.chipError}</div>`}
|
|
2532
2532
|
</div>
|
|
2533
|
-
`}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=
|
|
2533
|
+
`}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=dS(this.attachments),t=this.effectiveAttachmentDelivery();return E`
|
|
2534
2534
|
<div class="attachments" aria-label="${D(`ui.promptEditor.pendingAttachments`,`Pending attachments`)}">
|
|
2535
2535
|
${this.attachments.map(e=>E`
|
|
2536
|
-
<div class=${`attachment-chip ${
|
|
2536
|
+
<div class=${`attachment-chip ${uS(e)?`attachment-chip-image`:`attachment-chip-file`}`} title=${e.name}>
|
|
2537
2537
|
${this.renderAttachmentPreview(e)}
|
|
2538
2538
|
<button type="button" class="attachment-remove ui-button ui-button--compact ui-button--icon" title="${D(`ui.promptEditor.removeAttachment`,`Remove attachment`)}" aria-label=${D(`ui.promptEditor.remove`,`Remove {name}`,{name:e.name})} @click=${()=>{this.removeAttachment(e.id)}}>×</button>
|
|
2539
2539
|
</div>
|
|
@@ -2542,16 +2542,16 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2542
2542
|
<label class="attachment-delivery" title=${e?D(`ui.promptEditor.howAttachmentsAreSentToTheAgent`,`How attachments are sent to the agent`):D(`ui.promptEditor.regularFilesAreSavedToTheWorkspaceAnd`,`Regular files are saved to the workspace and referenced`)}>
|
|
2543
2543
|
<select class="ui-select" aria-label=${D(`ui.promptEditor.attachmentDelivery`,`Attachment delivery`)} .value=${t} @change=${e=>{this.changeDelivery(e)}}>
|
|
2544
2544
|
<option value="inline" ?disabled=${!e}>${D(`ui.promptEditor.attachToMessage`,`Attach to message`)}${e?``:D(`ui.promptEditor.imagesOnly`,` (images only)`)}</option>
|
|
2545
|
-
<option value="folder">${
|
|
2545
|
+
<option value="folder">${MS(this.attachmentsFolder)}</option>
|
|
2546
2546
|
</select>
|
|
2547
2547
|
</label>
|
|
2548
2548
|
`:null}
|
|
2549
2549
|
${this.attachmentError===void 0?null:E`<div class="attachment-error">${this.attachmentError}</div>`}
|
|
2550
2550
|
</div>
|
|
2551
|
-
`}renderAttachmentPreview(e){return
|
|
2552
|
-
<div class="attachment-file-preview" aria-hidden="true">${
|
|
2551
|
+
`}renderAttachmentPreview(e){return uS(e)?E`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:E`
|
|
2552
|
+
<div class="attachment-file-preview" aria-hidden="true">${NS(e.name)}</div>
|
|
2553
2553
|
<span class="attachment-file-name">${e.name}</span>
|
|
2554
|
-
`}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;t===`inline`&&!cS(this.attachments)?e.target.value=`folder`:(this.attachmentDelivery=t,hS(this.attachmentDelivery))}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e);let t=SS(this.machineId,this.sessionId);t!==void 0&&Ga(t,this.attachments)}async handlePaste(e){let t=ES(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&DS(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=ES(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleAttachClick(){this.busy||(yS()?.matches===!0?this.attachSourceOpen=!this.attachSourceOpen:this.attachmentInput?.click())}openAttachmentPicker(e){this.busy||(this.attachPopup.close(),this.attachButton?.focus(),e?.click())}defaultSendBehavior(){return this.isCompacting?`followUp`:this.canSteer?this.defaultStreamingBehavior:void 0}async handleFileInput(e){if(!(e.target instanceof HTMLInputElement)||e.target.files===null)return;let t=Array.from(e.target.files);e.target.value=``,await this.addAttachmentFiles(t)}async addAttachmentFiles(e){let t=this.composerKey(),n=this.attachmentContextGeneration;this.attachmentError=void 0;let{attachments:r,error:i}=await oS(e,jS);if(!this.isConnected||t!==this.composerKey()||n!==this.attachmentContextGeneration)console.warn(`Attachment selection ignored after conversation changed`);else{if(r.length>0){this.attachments=[...this.attachments,...r.map(e=>({id:`attachment-${String(++this.attachmentSeq)}`,...e}))];let e=SS(this.machineId,this.sessionId);e!==void 0&&Ga(e,this.attachments)}i!==void 0&&(this.attachmentError=i)}}currentAttachments(){return this.attachments.map(e=>OS(e))}effectiveAttachmentDelivery(){return lS(this.attachmentDelivery,this.attachments)}createEditor(){this.editorHost&&this.editor===void 0&&(this.editor=new _n({parent:this.editorHost,state:dn.create({doc:this.draft,extensions:[yn(),eS,Sn(),pn(),tn.of(` `),an(bn,{fallback:!0}),_n.lineWrapping,cn(),_n.contentAttributes.of(e=>PS(e.state.sliceDoc(0,e.state.selection.main.head))),_n.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),ln(bS),_n.contentAttributes.of({"aria-placeholder":_S()}),this.editableCompartment.of(_n.editable.of(!this.disabled)),this.readOnlyCompartment.of(dn.readOnly.of(this.disabled)),_n.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),sn.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:`ArrowDown`,run:()=>this.moveCompletion(1)},{key:`ArrowUp`,run:()=>this.moveCompletion(-1)},{key:`Escape`,run:()=>this.closeCompletions()},{key:`Tab`,run:e=>this.handleEditorTab(e)},{key:`Shift-Tab`,run:e=>fn.shift?.(e)??!1},{key:`Backspace`,run:e=>Cn(e)},...un,...mn])]})}))}syncEditorDoc(){let e=this.editor;if(!e)return;let t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:en.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(_n.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(dn.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;let t=SS(this.machineId,this.sessionId);t!==void 0&&za(t,this.draft);let n=Cs(this.draft);Ts(n,this.currentInputMode)||(this.currentInputMode=n),this.cancelFileCompletion(),this.currentTrigger()?.kind===`file`?(this.completions=[],this.fileCompletionTimer=setTimeout(()=>{this.refreshCompletions()},150)):this.refreshCompletions()}cancelFileCompletion(){clearTimeout(this.fileCompletionTimer),this.fileCompletionTimer=void 0,this.fileCompletionAbort?.abort(),this.fileCompletionAbort=void 0,this.requestVersion+=1}async refreshCompletions(){this.cancelFileCompletion();let e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0)this.completions=[];else if(e.kind===`command`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await x.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(CS);if(t!==this.requestVersion)return;this.completions=n.filter(t=>t.name.toLowerCase().includes(e.query.toLowerCase())).map(t=>({kind:`command`,replaceFrom:e.from,replaceTo:e.to,insertText:`/${t.name}`,detail:fs(t.source),...t.description===void 0?{}:{description:t.description},...t.argumentHint===void 0?{}:{argumentHint:t.argumentHint}}))}else if(e.kind===`file`&&this.projectId!==void 0&&this.workspaceId!==void 0){this.fileCompletionAbort=new AbortController;let n=await x.files(e.query,{signal:this.fileCompletionAbort.signal,scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId}).catch(wS);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=vs(t.path,e.quoted===!0,t.path.endsWith(`/`)?e.allPrefix:void 0);return{kind:`file`,replaceFrom:e.from,replaceTo:e.to,insertText:n,detail:t.kind,...t.path.endsWith(`/`)&&n.endsWith(`"`)?{cursorOffset:n.length-1}:{}}})}else if(e.kind===`model`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await x.models({id:this.sessionId,cwd:this.cwd},this.machineId).then(e=>e.models).catch(TS);if(t!==this.requestVersion)return;this.completions=hs(n,e.query).map(t=>({kind:`model`,replaceFrom:e.from,replaceTo:e.to,...t}))}}currentTrigger(){return ps(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.requestVersion+=1,this.completions.length?(this.completions=[],!0):!1}ownsKeyboardEvent(e){return this.editor===void 0||!e.composedPath().includes(this.editor.contentDOM)?!1:e.isComposing||this.editor.composing||e.key===`Enter`&&!e.ctrlKey&&!e.metaKey&&!e.altKey||this.matchesSendShortcut(e)}matchesSendShortcut(e){let t=e.key===`Enter`?at(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia):e.shiftKey;return ze({key:e.key,ctrlKey:e.ctrlKey,metaKey:e.metaKey,altKey:e.altKey,shiftKey:t,isComposing:e.isComposing,target:e.target},Le(this.shortcuts??this.shortcutConfig,this.mobilePromptEnterMedia))}handleEditorKeyDown(e,t){if(e.key===`Shift`)return this.explicitShiftKeyActive=!0,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;let n=this.matchesSendShortcut(e),r=e.key===`Enter`&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&!at(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);if(this.explicitShiftKeyActive=!1,r&&this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return n?(this.send(this.defaultSendBehavior()),!0):e.key===`Enter`&&!e.ctrlKey&&!e.metaKey&&!e.altKey?xn(t)||gn(t):!1}handleEditorKeyUp(e){return e.key===`Shift`&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorTab(e){if(this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.currentTrigger()?.kind===`file`?(this.refreshCompletions(),!0):fn.run?.(e)??!1}pick(e){let t=this.editor;if(!t)return;let n=e.kind===`file`&&(e.insertText.endsWith(`/`)||e.cursorOffset!==void 0)?``:` `,r=e.replaceFrom+(e.cursorOffset??e.insertText.length)+n.length,i=e.insertText.endsWith(`"`)&&this.draft.slice(e.replaceTo).startsWith(`"`)?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:i,insert:`${e.insertText}${n}`},selection:en.cursor(r),effects:e.argumentHint===void 0||e.argumentHint===``?[]:Zx.of({pos:r,text:e.argumentHint}),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending||this.chipSendingKey===this.composerKey())return;let t=this.draft.trim(),n=this.attachments,r=this.promptChips;if(t===``&&n.length===0&&r.length===0)return;let i=this.canSteer||this.isCompacting?e:void 0,a=n.length>0?this.currentAttachments():void 0,o=this.effectiveAttachmentDelivery(),s=a!==void 0&&o===`folder`?this.attachmentsFolder:void 0;r.length>0?this.sendWithChips(t,i,a,a===void 0?void 0:o,s,r):(this.resetComposer(),this.onSend?.(t,i,a,a===void 0?void 0:o,s))}composerKey(){return JSON.stringify([this.machineId,this.cwd,this.sessionId])}async sendWithChips(e,t,n,r,i,a){let o=this.composerKey(),s=this.draft,c=this.attachments;this.chipSendingKey=o,this.chipError=void 0;try{let l=await this.onSend?.(e,t,n,r,i,a);if(o!==this.composerKey()||!this.isConnected)return;l===!0?s===this.draft&&c===this.attachments&&this.resetComposer():this.chipError=D(`ui.promptEditor.contextKeptForRetry`,`Message not submitted. Context kept for retry.`)}catch(e){o===this.composerKey()&&(this.chipError=D(`ui.promptEditor.messageNotSubmitted`,`Message not submitted: {error}`,{error:String(e)}))}finally{this.chipSendingKey===o&&(this.chipSendingKey=void 0)}}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=SS(this.machineId,this.sessionId);e!==void 0&&(Ba(e),Ka(e)),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=Hh}};w([y()],J.prototype,`defaultStreamingBehavior`,void 0),w([y({attribute:!1})],J.prototype,`chatNavigation`,void 0),w([y({type:Boolean})],J.prototype,`disabled`,void 0),w([y()],J.prototype,`sessionId`,void 0),w([y()],J.prototype,`cwd`,void 0),w([y()],J.prototype,`machineId`,void 0),w([y()],J.prototype,`projectId`,void 0),w([y()],J.prototype,`workspaceId`,void 0),w([y()],J.prototype,`attachmentsFolder`,void 0),w([y({type:Boolean})],J.prototype,`workspaceScopedFileSuggestions`,void 0),w([y({type:Boolean})],J.prototype,`canSteer`,void 0),w([y({type:Boolean})],J.prototype,`isCompacting`,void 0),w([y({type:Boolean})],J.prototype,`canStop`,void 0),w([y({attribute:!1})],J.prototype,`status`,void 0),w([y({type:Boolean})],J.prototype,`sending`,void 0),w([y({attribute:!1})],J.prototype,`shortcutConfig`,void 0),w([y({attribute:!1})],J.prototype,`shortcuts`,void 0),w([y({attribute:!1})],J.prototype,`promptChips`,void 0),w([y({attribute:!1})],J.prototype,`onRemoveChip`,void 0),w([y({attribute:!1})],J.prototype,`onSend`,void 0),w([y({attribute:!1})],J.prototype,`onStop`,void 0),w([y({attribute:!1})],J.prototype,`onSelectModel`,void 0),w([y({attribute:!1})],J.prototype,`onSelectThinking`,void 0),w([y({attribute:!1})],J.prototype,`availableThinkingLevels`,void 0),w([S(`.markdown-editor`)],J.prototype,`editorHost`,void 0),w([S(`.attachment-input`)],J.prototype,`attachmentInput`,void 0),w([S(`.attachment-image-input`)],J.prototype,`attachmentImageInput`,void 0),w([S(`.attachment-camera-input`)],J.prototype,`attachmentCameraInput`,void 0),w([S(`.attach-source-panel`)],J.prototype,`attachSourcePanel`,void 0),w([S(`.editor-attach`)],J.prototype,`attachButton`,void 0),w([C()],J.prototype,`currentInputMode`,void 0),w([C()],J.prototype,`completions`,void 0),w([C()],J.prototype,`selectedIndex`,void 0),w([C()],J.prototype,`attachments`,void 0),w([C()],J.prototype,`attachmentDelivery`,void 0),w([C()],J.prototype,`attachmentError`,void 0),w([C()],J.prototype,`chipSendingKey`,void 0),w([C()],J.prototype,`chipError`,void 0),w([C()],J.prototype,`attachSourceOpen`,void 0),J=w([b(`prompt-editor`)],J);function xS(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.model?.id===t.model?.id&&e.model?.provider===t.model?.provider&&e.thinkingLevel===t.thinkingLevel}function SS(e,t){if(typeof e==`string`&&e!==``&&typeof t==`string`&&t!==``)return j(e,t)}function CS(){return[]}function wS(){return[]}function TS(){return[]}function ES(e){return e===null?[]:Array.from(e.files)}function DS(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function OS(e){return e.kind===`image`?{kind:`image`,mimeType:e.mimeType,data:e.data,name:e.name}:{kind:`file`,mimeType:e.mimeType,data:e.data,name:e.name}}function kS(e){return D(`ui.main.bbbb5df3357e`,`Save to {arg0}`,{arg0:e})}function AS(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():D(`ui.toolExecutionView.file`,`File`)}function jS(e){return new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>{n(r.error??Error(D(`ui.promptEditor.failedToReadFile`,`Failed to read file`)))},r.onload=()=>{let e=r.result;if(typeof e!=`string`){n(Error(D(`ui.promptEditor.unexpectedFileReadResult`,`Unexpected file read result`)));return}let i=e.indexOf(`,`);t(i===-1?e:e.slice(i+1))},r.readAsDataURL(e)})}var MS={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},NS={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function PS(e){return Cs(e).kind===`normal`?MS:NS}function FS(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 IS(e){return!Number.isFinite(e)||e===0?`$0`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function LS(e,t){if(!Number.isInteger(e)||e<=0)return;let n=D(`ui.statusBar.warnings`,`{count} warnings`,{count:String(e)});return{countText:String(e),accessibleLabel:t?D(`ui.statusBar.minimize`,`Minimize {warningText}`,{warningText:n}):D(`ui.statusBar.showInTheWarningArea`,`Show {warningText} in the warning area`,{warningText:n})}}var RS=class extends O{constructor(){super(),this.warningCount=0,this.warningsExpanded=!1,this.handleToggleWarnings=()=>{this.onToggleWarnings?.()},v.createController(this)}render(){let e=this.status;if(e===void 0)return E`<div class="bar muted">${D(`ui.statusBar.noSessionStatusYet`,`No session status yet`)}</div>`;let t=e.contextUsage,n=t?t.percent==null?D(`ui.statusBar.context`,`Context {contextWindow}`,{contextWindow:FS(t.contextWindow)}):`${t.percent.toFixed(1)}%/${FS(t.contextWindow)}`:D(`ui.statusBar.contextUnknown`,`Context unknown`),r=e.tokens,i=LS(this.warningCount,this.warningsExpanded);return E`
|
|
2554
|
+
`}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;t===`inline`&&!dS(this.attachments)?e.target.value=`folder`:(this.attachmentDelivery=t,vS(this.attachmentDelivery))}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e);let t=TS(this.machineId,this.sessionId);t!==void 0&&Ga(t,this.attachments)}async handlePaste(e){let t=kS(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&AS(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=kS(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleAttachClick(){this.busy||(SS()?.matches===!0?this.attachSourceOpen=!this.attachSourceOpen:this.attachmentInput?.click())}openAttachmentPicker(e){this.busy||(this.attachPopup.close(),this.attachButton?.focus(),e?.click())}defaultSendBehavior(){return this.isCompacting?`followUp`:this.canSteer?this.defaultStreamingBehavior:void 0}async handleFileInput(e){if(!(e.target instanceof HTMLInputElement)||e.target.files===null)return;let t=Array.from(e.target.files);e.target.value=``,await this.addAttachmentFiles(t)}async addAttachmentFiles(e){let t=this.composerKey(),n=this.attachmentContextGeneration;this.attachmentError=void 0;let{attachments:r,error:i}=await lS(e,PS);if(!this.isConnected||t!==this.composerKey()||n!==this.attachmentContextGeneration)console.warn(`Attachment selection ignored after conversation changed`);else{if(r.length>0){this.attachments=[...this.attachments,...r.map(e=>({id:`attachment-${String(++this.attachmentSeq)}`,...e}))];let e=TS(this.machineId,this.sessionId);e!==void 0&&Ga(e,this.attachments)}i!==void 0&&(this.attachmentError=i)}}currentAttachments(){return this.attachments.map(e=>jS(e))}effectiveAttachmentDelivery(){return fS(this.attachmentDelivery,this.attachments)}createEditor(){this.editorHost&&this.editor===void 0&&(this.editor=new _n({parent:this.editorHost,state:dn.create({doc:this.draft,extensions:[yn(),rS,Sn(),pn(),tn.of(` `),an(bn,{fallback:!0}),_n.lineWrapping,cn(),_n.contentAttributes.of(e=>LS(e.state.sliceDoc(0,e.state.selection.main.head))),_n.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),ln(CS),_n.contentAttributes.of({"aria-placeholder":bS()}),this.editableCompartment.of(_n.editable.of(!this.disabled)),this.readOnlyCompartment.of(dn.readOnly.of(this.disabled)),_n.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),sn.of([{any:(e,t)=>this.handleEditorKeyDown(t,e)},{key:`ArrowDown`,run:()=>this.moveCompletion(1)},{key:`ArrowUp`,run:()=>this.moveCompletion(-1)},{key:`Escape`,run:()=>this.closeCompletions()},{key:`Tab`,run:e=>this.handleEditorTab(e)},{key:`Shift-Tab`,run:e=>fn.shift?.(e)??!1},{key:`Backspace`,run:e=>Cn(e)},...un,...mn])]})}))}syncEditorDoc(){let e=this.editor;if(!e)return;let t=e.state.doc.toString();t!==this.draft&&e.dispatch({changes:{from:0,to:t.length,insert:this.draft},selection:en.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(_n.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(dn.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;let t=TS(this.machineId,this.sessionId);t!==void 0&&za(t,this.draft);let n=Cs(this.draft);Ts(n,this.currentInputMode)||(this.currentInputMode=n),this.cancelFileCompletion(),this.currentTrigger()?.kind===`file`?(this.completions=[],this.fileCompletionTimer=setTimeout(()=>{this.refreshCompletions()},150)):this.refreshCompletions()}cancelFileCompletion(){clearTimeout(this.fileCompletionTimer),this.fileCompletionTimer=void 0,this.fileCompletionAbort?.abort(),this.fileCompletionAbort=void 0,this.requestVersion+=1}async refreshCompletions(){this.cancelFileCompletion();let e=this.currentTrigger(),t=++this.requestVersion;if(this.selectedIndex=0,e===void 0)this.completions=[];else if(e.kind===`command`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await x.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(ES);if(t!==this.requestVersion)return;this.completions=n.filter(t=>t.name.toLowerCase().includes(e.query.toLowerCase())).map(t=>({kind:`command`,replaceFrom:e.from,replaceTo:e.to,insertText:`/${t.name}`,detail:fs(t.source),...t.description===void 0?{}:{description:t.description},...t.argumentHint===void 0?{}:{argumentHint:t.argumentHint}}))}else if(e.kind===`file`&&this.projectId!==void 0&&this.workspaceId!==void 0){this.fileCompletionAbort=new AbortController;let n=await x.files(e.query,{signal:this.fileCompletionAbort.signal,scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId}).catch(DS);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=vs(t.path,e.quoted===!0,t.path.endsWith(`/`)?e.allPrefix:void 0);return{kind:`file`,replaceFrom:e.from,replaceTo:e.to,insertText:n,detail:t.kind,...t.path.endsWith(`/`)&&n.endsWith(`"`)?{cursorOffset:n.length-1}:{}}})}else if(e.kind===`model`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await x.models({id:this.sessionId,cwd:this.cwd},this.machineId).then(e=>e.models).catch(OS);if(t!==this.requestVersion)return;this.completions=hs(n,e.query).map(t=>({kind:`model`,replaceFrom:e.from,replaceTo:e.to,...t}))}}currentTrigger(){return ps(this.draft,this.editor?.state.selection.main.head??this.draft.length)}moveCompletion(e){return this.completions.length?(this.selectedIndex=(this.selectedIndex+e+this.completions.length)%this.completions.length,!0):!1}closeCompletions(){return this.requestVersion+=1,this.completions.length?(this.completions=[],!0):!1}ownsKeyboardEvent(e){return this.editor===void 0||!e.composedPath().includes(this.editor.contentDOM)?!1:e.isComposing||this.editor.composing||e.key===`Enter`&&!e.ctrlKey&&!e.metaKey&&!e.altKey||this.matchesSendShortcut(e)}matchesSendShortcut(e){let t=e.key===`Enter`?at(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia):e.shiftKey;return ze({key:e.key,ctrlKey:e.ctrlKey,metaKey:e.metaKey,altKey:e.altKey,shiftKey:t,isComposing:e.isComposing,target:e.target},Le(this.shortcuts??this.shortcutConfig,this.mobilePromptEnterMedia))}handleEditorKeyDown(e,t){if(e.key===`Shift`)return this.explicitShiftKeyActive=!0,!1;if(e.defaultPrevented||e.isComposing||t.composing)return!1;let n=this.matchesSendShortcut(e),r=e.key===`Enter`&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&!at(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia);if(this.explicitShiftKeyActive=!1,r&&this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return n?(this.send(this.defaultSendBehavior()),!0):e.key===`Enter`&&!e.ctrlKey&&!e.metaKey&&!e.altKey?xn(t)||gn(t):!1}handleEditorKeyUp(e){return e.key===`Shift`&&(this.explicitShiftKeyActive=!1),!1}resetEditorModifierState(){return this.explicitShiftKeyActive=!1,!1}handleEditorTab(e){if(this.completions.length){let e=this.completions[this.selectedIndex];return e!==void 0&&this.pick(e),!0}return this.currentTrigger()?.kind===`file`?(this.refreshCompletions(),!0):fn.run?.(e)??!1}pick(e){let t=this.editor;if(!t)return;let n=e.kind===`file`&&(e.insertText.endsWith(`/`)||e.cursorOffset!==void 0)?``:` `,r=e.replaceFrom+(e.cursorOffset??e.insertText.length)+n.length,i=e.insertText.endsWith(`"`)&&this.draft.slice(e.replaceTo).startsWith(`"`)?e.replaceTo+1:e.replaceTo;t.dispatch({changes:{from:e.replaceFrom,to:i,insert:`${e.insertText}${n}`},selection:en.cursor(r),effects:e.argumentHint===void 0||e.argumentHint===``?[]:eS.of({pos:r,text:e.argumentHint}),scrollIntoView:!0}),this.completions=[]}send(e){if(this.disabled||this.sending||this.chipSendingKey===this.composerKey())return;let t=this.draft.trim(),n=this.attachments,r=this.promptChips;if(t===``&&n.length===0&&r.length===0)return;let i=this.canSteer||this.isCompacting?e:void 0,a=n.length>0?this.currentAttachments():void 0,o=this.effectiveAttachmentDelivery(),s=a!==void 0&&o===`folder`?this.attachmentsFolder:void 0;r.length>0?this.sendWithChips(t,i,a,a===void 0?void 0:o,s,r):(this.resetComposer(),this.onSend?.(t,i,a,a===void 0?void 0:o,s))}composerKey(){return JSON.stringify([this.machineId,this.cwd,this.sessionId])}async sendWithChips(e,t,n,r,i,a){let o=this.composerKey(),s=this.draft,c=this.attachments;this.chipSendingKey=o,this.chipError=void 0;try{let l=await this.onSend?.(e,t,n,r,i,a);if(o!==this.composerKey()||!this.isConnected)return;l===!0?s===this.draft&&c===this.attachments&&this.resetComposer():this.chipError=D(`ui.promptEditor.contextKeptForRetry`,`Message not submitted. Context kept for retry.`)}catch(e){o===this.composerKey()&&(this.chipError=D(`ui.promptEditor.messageNotSubmitted`,`Message not submitted: {error}`,{error:String(e)}))}finally{this.chipSendingKey===o&&(this.chipSendingKey=void 0)}}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=TS(this.machineId,this.sessionId);e!==void 0&&(Ba(e),Ka(e)),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=Gh}};w([y()],J.prototype,`defaultStreamingBehavior`,void 0),w([y({attribute:!1})],J.prototype,`chatNavigation`,void 0),w([y({type:Boolean})],J.prototype,`disabled`,void 0),w([y()],J.prototype,`sessionId`,void 0),w([y()],J.prototype,`cwd`,void 0),w([y()],J.prototype,`machineId`,void 0),w([y()],J.prototype,`projectId`,void 0),w([y()],J.prototype,`workspaceId`,void 0),w([y()],J.prototype,`attachmentsFolder`,void 0),w([y({type:Boolean})],J.prototype,`workspaceScopedFileSuggestions`,void 0),w([y({type:Boolean})],J.prototype,`canSteer`,void 0),w([y({type:Boolean})],J.prototype,`isCompacting`,void 0),w([y({type:Boolean})],J.prototype,`canStop`,void 0),w([y({attribute:!1})],J.prototype,`status`,void 0),w([y({type:Boolean})],J.prototype,`sending`,void 0),w([y({attribute:!1})],J.prototype,`shortcutConfig`,void 0),w([y({attribute:!1})],J.prototype,`shortcuts`,void 0),w([y({attribute:!1})],J.prototype,`promptChips`,void 0),w([y({attribute:!1})],J.prototype,`onRemoveChip`,void 0),w([y({attribute:!1})],J.prototype,`onSend`,void 0),w([y({attribute:!1})],J.prototype,`onStop`,void 0),w([y({attribute:!1})],J.prototype,`onSelectModel`,void 0),w([y({attribute:!1})],J.prototype,`onSelectThinking`,void 0),w([y({attribute:!1})],J.prototype,`availableThinkingLevels`,void 0),w([S(`.markdown-editor`)],J.prototype,`editorHost`,void 0),w([S(`.attachment-input`)],J.prototype,`attachmentInput`,void 0),w([S(`.attachment-image-input`)],J.prototype,`attachmentImageInput`,void 0),w([S(`.attachment-camera-input`)],J.prototype,`attachmentCameraInput`,void 0),w([S(`.attach-source-panel`)],J.prototype,`attachSourcePanel`,void 0),w([S(`.editor-attach`)],J.prototype,`attachButton`,void 0),w([C()],J.prototype,`currentInputMode`,void 0),w([C()],J.prototype,`completions`,void 0),w([C()],J.prototype,`selectedIndex`,void 0),w([C()],J.prototype,`attachments`,void 0),w([C()],J.prototype,`attachmentDelivery`,void 0),w([C()],J.prototype,`attachmentError`,void 0),w([C()],J.prototype,`chipSendingKey`,void 0),w([C()],J.prototype,`chipError`,void 0),w([C()],J.prototype,`attachSourceOpen`,void 0),J=w([b(`prompt-editor`)],J);function wS(e,t){return e===t?!0:e===void 0||t===void 0?!1:e.model?.id===t.model?.id&&e.model?.provider===t.model?.provider&&e.thinkingLevel===t.thinkingLevel}function TS(e,t){if(typeof e==`string`&&e!==``&&typeof t==`string`&&t!==``)return j(e,t)}function ES(){return[]}function DS(){return[]}function OS(){return[]}function kS(e){return e===null?[]:Array.from(e.files)}function AS(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function jS(e){return e.kind===`image`?{kind:`image`,mimeType:e.mimeType,data:e.data,name:e.name}:{kind:`file`,mimeType:e.mimeType,data:e.data,name:e.name}}function MS(e){return D(`ui.main.bbbb5df3357e`,`Save to {arg0}`,{arg0:e})}function NS(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():D(`ui.toolExecutionView.file`,`File`)}function PS(e){return new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>{n(r.error??Error(D(`ui.promptEditor.failedToReadFile`,`Failed to read file`)))},r.onload=()=>{let e=r.result;if(typeof e!=`string`){n(Error(D(`ui.promptEditor.unexpectedFileReadResult`,`Unexpected file read result`)));return}let i=e.indexOf(`,`);t(i===-1?e:e.slice(i+1))},r.readAsDataURL(e)})}var FS={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},IS={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function LS(e){return Cs(e).kind===`normal`?FS:IS}function RS(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 zS(e){return!Number.isFinite(e)||e===0?`$0`:e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function BS(e,t){if(!Number.isInteger(e)||e<=0)return;let n=D(`ui.statusBar.warnings`,`{count} warnings`,{count:String(e)});return{countText:String(e),accessibleLabel:t?D(`ui.statusBar.minimize`,`Minimize {warningText}`,{warningText:n}):D(`ui.statusBar.showInTheWarningArea`,`Show {warningText} in the warning area`,{warningText:n})}}var VS=class extends O{constructor(){super(),this.warningCount=0,this.warningsExpanded=!1,this.handleToggleWarnings=()=>{this.onToggleWarnings?.()},v.createController(this)}render(){let e=this.status;if(e===void 0)return E`<div class="bar muted">${D(`ui.statusBar.noSessionStatusYet`,`No session status yet`)}</div>`;let t=e.contextUsage,n=t?t.percent==null?D(`ui.statusBar.context`,`Context {contextWindow}`,{contextWindow:RS(t.contextWindow)}):`${t.percent.toFixed(1)}%/${RS(t.contextWindow)}`:D(`ui.statusBar.contextUnknown`,`Context unknown`),r=e.tokens,i=BS(this.warningCount,this.warningsExpanded);return E`
|
|
2555
2555
|
<div class="bar">
|
|
2556
2556
|
${i===void 0||this.onToggleWarnings===void 0?null:E`
|
|
2557
2557
|
<button
|
|
@@ -2562,17 +2562,17 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2562
2562
|
aria-expanded=${String(this.warningsExpanded)}
|
|
2563
2563
|
@click=${this.handleToggleWarnings}
|
|
2564
2564
|
>
|
|
2565
|
-
${
|
|
2565
|
+
${Kh(`warning`,`warning-toggle-icon`)}
|
|
2566
2566
|
<span>${i.countText}</span>
|
|
2567
2567
|
</button>
|
|
2568
2568
|
`}
|
|
2569
|
-
<span>↑${
|
|
2570
|
-
<span>↓${
|
|
2571
|
-
<span class="context">${n}</span>
|
|
2572
|
-
<span>${
|
|
2569
|
+
<span class="token-input">↑${RS(r.input)}</span>
|
|
2570
|
+
<span class="token-output">↓${RS(r.output)}</span>
|
|
2571
|
+
<span class="context" title=${D(`ui.statusBar.contextUsage`,`Context usage`)}>${n}</span>
|
|
2572
|
+
<span class="cost" title=${D(`ui.statusBar.sessionCost`,`Session cost`)}>${zS(e.cost)}</span>
|
|
2573
2573
|
${e.pendingMessageCount>0?E`<span>${D(`ui.statusBar.queuedCount`,`{count} queued`,{count:e.pendingMessageCount})}</span>`:null}
|
|
2574
2574
|
</div>
|
|
2575
|
-
`}static{this.styles=
|
|
2575
|
+
`}static{this.styles=Hh}};w([y({attribute:!1})],VS.prototype,`status`,void 0),w([y({type:Number})],VS.prototype,`warningCount`,void 0),w([y({type:Boolean})],VS.prototype,`warningsExpanded`,void 0),w([y({attribute:!1})],VS.prototype,`onToggleWarnings`,void 0),VS=w([b(`status-bar`)],VS);function HS(e){return`${e.provider}/${e.id}`}function US(e,t){let n=t.trim().toLowerCase();return n===``?[...e]:e.filter(e=>`${e.label} ${e.description??``} ${e.value}`.toLowerCase().includes(n))}function WS(e){return e.every(e=>e.catalogIndex!==void 0)?[...e].sort((e,t)=>(e.catalogIndex??0)-(t.catalogIndex??0)):[...e]}function GS(e,t,n){let r=WS(e),i=new Map(r.map(e=>[HS(e),e])),a=new Set,o=n===void 0?r:[...n.flatMap(e=>{let t=i.get(e);return t===void 0||a.has(e)?[]:(a.add(e),[t])}),...r.filter(e=>!a.has(HS(e)))],s=t.trim().toLowerCase();return{rows:s===``?o:o.filter(e=>`${e.provider} ${e.id} ${e.name??``}`.toLowerCase().includes(s))}}function KS(e,t){let n=e.filter(e=>e.enabled),r=t===void 0?void 0:e.find(e=>HS(e)===t),i=r?.enabled===!0&&n.length===1,a=n.length===0||i?`all`:`current`;return{mode:a,canApply:a===`all`||r!==void 0,hasChanges:a===`all`?n.length<e.length:r!==void 0&&(!r.enabled||n.some(e=>e!==r))}}var Y=class extends O{constructor(){super(),this.title=D(`client.actions.choose.model.1afed6`,`Choose model`),this.options=[],this.catalog=[],this.defaultsLoading=!1,this.mode=`enabled`,this.defaultPending=!1,this.selectedIndex=0,this.query=``,this.pendingToggles=new Set,this.toggleAllPending=!1,this.catalogOrder=[],v.createController(this)}render(){let e=this.visibleRows();return E`
|
|
2576
2576
|
<modal-surface .onClose=${()=>this.onCancel?.()} .initialFocus=${`input.search`} .label=${this.title} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
2577
2577
|
<header class="ui-dialog-header"><strong class="ui-dialog-title">${this.title}</strong><button class="ui-button ui-button--icon" aria-label="${D(`ui.common.close`,`Close`)}" @click=${()=>this.onCancel?.()}>×</button></header>
|
|
2578
2578
|
<div class="scope-toggle ui-toolbar" role="group" aria-label="${D(`ui.main.24575c56a20e`,`Model scope`)}">
|
|
@@ -2595,15 +2595,15 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2595
2595
|
${e.length===0?E`<div class="empty ui-dialog-empty">${D(`ui.commandPicker.noMatchingOptions`,`No matching options`)}</div>`:null}
|
|
2596
2596
|
</div>
|
|
2597
2597
|
</modal-surface>
|
|
2598
|
-
`}firstUpdated(){this.anchorSelectionToSelectedValue()}willUpdate(e){if(!e.has(`catalog`)||(this.mode===`all`&&(this.catalogScrollTopBeforeUpdate=this.shadowRoot?.querySelector(`.options`)?.scrollTop),this.rememberCatalogOrder(),this.mode!==`all`))return;let t=e.get(`catalog`);if(t===void 0)return;let n=
|
|
2598
|
+
`}firstUpdated(){this.anchorSelectionToSelectedValue()}willUpdate(e){if(!e.has(`catalog`)||(this.mode===`all`&&(this.catalogScrollTopBeforeUpdate=this.shadowRoot?.querySelector(`.options`)?.scrollTop),this.rememberCatalogOrder(),this.mode!==`all`))return;let t=e.get(`catalog`);if(t===void 0)return;let n=GS(t,this.query,this.catalogOrder).rows[this.selectedIndex],r=GS(this.catalog,this.query,this.catalogOrder).rows,i=n===void 0?void 0:HS(n),a=i===void 0?-1:r.findIndex(e=>HS(e)===i);this.selectedIndex=a>=0?a:Math.min(this.selectedIndex,Math.max(r.length-1,0))}updated(e){if(!e.has(`catalog`)||this.catalogScrollTopBeforeUpdate===void 0)return;let t=this.shadowRoot?.querySelector(`.options`);t!=null&&(t.scrollTop=this.catalogScrollTopBeforeUpdate),this.catalogScrollTopBeforeUpdate=void 0}get membershipChangePending(){return this.toggleAllPending||this.pendingToggles.size>0}get modelScopeEditable(){return this.catalog.every(e=>e.editable!==!1)}renderScopeToggleButton(e,t){return E`<button class="ui-button" ?disabled=${this.membershipChangePending} aria-pressed=${this.mode===e?`true`:`false`} @click=${()=>{this.selectMode(e)}}>${t}</button>`}renderToggleAllButton(){let e=KS(this.catalog,this.selectedValue),t=e.mode===`all`?D(`ui.sessionCleanupDialog.selectAll`,`Select all`):D(`ui.main.2d6cec165a76`,`Deselect all`);return E`
|
|
2599
2599
|
<button class="toggle-all ui-button" ?disabled=${!this.modelScopeEditable||!e.canApply||!e.hasChanges||this.toggleAllPending||this.pendingToggles.size>0} aria-describedby="model-scope-status" title=${this.modelScopeEditable?e.canApply?k:D(`ui.main.46b71cd9c032`,`The current model is unavailable`):D(`ui.main.7bd492497eee`,`Workspace settings control model availability`)} @click=${()=>{this.requestToggleAll()}}>${t}</button>
|
|
2600
2600
|
<span id="model-scope-status" class="scope-status" aria-live="polite">${this.membershipChangePending?D(`ui.main.6fa086f67183`,`Updating model availability`):this.modelScopeEditable?e.canApply?k:D(`ui.main.46b71cd9c032`,`The current model is unavailable`):D(`ui.main.7bd492497eee`,`Workspace settings control model availability`)}</span>
|
|
2601
|
-
`}rememberCatalogOrder(){let e=new Set(this.catalogOrder);for(let t of
|
|
2601
|
+
`}rememberCatalogOrder(){let e=new Set(this.catalogOrder);for(let t of GS(this.catalog,``).rows){let n=HS(t);e.has(n)||(e.add(n),this.catalogOrder.push(n))}}renderEnabledList(){return US(this.options,this.query).map((e,t)=>{let n=E`
|
|
2602
2602
|
<button class=${t===this.selectedIndex?`ui-button ui-selection-option selected`:`ui-button ui-selection-option`} ?disabled=${this.membershipChangePending} aria-current=${t===this.selectedIndex?`true`:k} ${yt(t===this.selectedIndex,e.value)} @focus=${()=>{this.selectedIndex=t}} @click=${()=>this.onPick?.(e.value)}>
|
|
2603
2603
|
<span>${e.label}</span>
|
|
2604
2604
|
${e.description!==void 0&&e.description!==``?E`<small class="ui-selection-detail">${e.description}</small>`:null}
|
|
2605
2605
|
</button>
|
|
2606
|
-
`;return this.onSetDefault===void 0?n:E`<div class="default-row ui-selection-row">${n}${gt(e.label,e.value===this.defaultValue,this.defaultsLoading||this.defaultPending||this.membershipChangePending||this.catalog.find(t=>
|
|
2606
|
+
`;return this.onSetDefault===void 0?n:E`<div class="default-row ui-selection-row">${n}${gt(e.label,e.value===this.defaultValue,this.defaultsLoading||this.defaultPending||this.membershipChangePending||this.catalog.find(t=>HS(t)===e.value)?.enabled===!1,()=>{this.setDefault(e.value)})}</div>`})}renderCatalogList(){let e=GS(this.catalog,this.query,this.catalogOrder).rows;return E`${tm(e,HS,(e,t)=>this.renderCatalogRow(e,t))}`}renderDefaultPin(e,t,n){return this.onSetDefault?gt(t,e===this.defaultValue,!n||this.defaultsLoading||this.defaultPending||this.membershipChangePending,()=>{this.setDefault(e)}):k}async setDefault(e){if(!(this.onSetDefault===void 0||this.defaultsLoading||this.defaultPending||this.membershipChangePending)&&this.catalog.find(t=>HS(t)===e)?.enabled!==!1){this.defaultPending=!0;try{await this.onSetDefault(e)}catch(e){console.warn(`Failed to set default model`,e)}finally{this.defaultPending=!1}}}renderCatalogRow(e,t){let n=HS(e),r=t===this.selectedIndex,i=n===this.selectedValue&&e.enabled,a=!this.modelScopeEditable||this.membershipChangePending||i,o=this.modelScopeEditable?i?D(`ui.main.613b6d756a13`,`Cannot deselect the current model {arg0}`,{arg0:n}):`${e.enabled?D(`ui.main.be70be5a2e12`,`Disable`):D(`ui.settingsSessiondPanel.enable`,`Enable`)} ${n}`:D(`ui.main.d05c48dbb58b`,`Availability of {arg0} is controlled by workspace settings`,{arg0:n});return E`
|
|
2607
2607
|
<div class="catalog-row ui-selection-row ${r?`selected`:``}" data-model-value=${n} ${yt(r,n)}>
|
|
2608
2608
|
<label class="membership-checkbox">
|
|
2609
2609
|
<input type="checkbox" .checked=${e.enabled} ?disabled=${a} aria-label=${o} title=${this.modelScopeEditable?i?D(`ui.main.c22854b56cf8`,`The current model must remain enabled`):k:D(`ui.main.7bd492497eee`,`Workspace settings control model availability`)} @focus=${()=>{this.selectedIndex=t}} @click=${t=>{this.handleEnableToggleClick(e,t)}} />
|
|
@@ -2613,7 +2613,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2613
2613
|
</button>
|
|
2614
2614
|
${this.renderDefaultPin(n,e.name??e.id,e.enabled)}
|
|
2615
2615
|
</div>
|
|
2616
|
-
`}visibleRows(){return this.mode===`all`?
|
|
2616
|
+
`}visibleRows(){return this.mode===`all`?GS(this.catalog,this.query,this.catalogOrder).rows.map(e=>({value:HS(e),entry:e})):US(this.options,this.query).map(e=>({value:e.value}))}anchorSelectionToSelectedValue(){if(this.selectedValue===void 0){this.selectedIndex=0;return}let e=this.visibleRows().findIndex(e=>e.value===this.selectedValue);this.selectedIndex=e>=0?e:0}selectMode(e){e!==this.mode&&(this.mode=e,this.anchorSelectionToSelectedValue())}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}handleKeyDown(e){let t=e.composedPath().find(e=>e instanceof HTMLInputElement&&e.type===`checkbox`);if(t!==void 0){e.key===`Enter`&&(e.preventDefault(),t.click());return}if(ut(e))return;if(this.membershipChangePending&&(e.key===`Enter`||e.key===` `)){e.preventDefault();return}let n=this.visibleRows();if(e.key===`ArrowDown`)e.preventDefault(),n.length>0&&(this.selectedIndex=(this.selectedIndex+1)%n.length);else if(e.key===`ArrowUp`)e.preventDefault(),n.length>0&&(this.selectedIndex=(this.selectedIndex-1+n.length)%n.length);else if(e.key===`Enter`){e.preventDefault();let t=n[this.selectedIndex];t?.entry===void 0?t!==void 0&&this.onPick?.(t.value):this.requestEnabledToggle(t.entry)}else if(e.key===` `&&this.mode===`all`){if(e.composedPath().some(e=>e instanceof HTMLInputElement))return;let t=n[this.selectedIndex];if(t?.entry===void 0)return;e.preventDefault(),this.requestEnabledToggle(t.entry)}}handleEnableToggleClick(e,t){t.preventDefault();let n=t.currentTarget instanceof HTMLInputElement?t.currentTarget:void 0;n!==void 0&&(n.checked=e.enabled),this.requestEnabledToggle(e,n)}requestEnabledToggle(e,t){let n=HS(e);if(!this.modelScopeEditable||n===this.selectedValue&&e.enabled||this.membershipChangePending)return;t!==void 0&&this.shadowRoot?.activeElement===t&&(this.focusAfterToggle=t);let r=new Set(this.pendingToggles);r.add(n),this.pendingToggles=r,this.settleEnabledToggle(n,e)}requestToggleAll(){if(!this.modelScopeEditable||this.toggleAllPending||this.pendingToggles.size>0)return;let e=KS(this.catalog,this.selectedValue);e.canApply&&e.hasChanges&&(this.toggleAllPending=!0,this.settleToggleAll(e.mode))}async settleToggleAll(e){try{await this.onSetScope?.(e)}catch(t){console.warn(`Failed to ${e===`all`?`enable all models`:`keep only the current model`}`,t)}finally{this.toggleAllPending=!1}}async settleEnabledToggle(e,t){try{await this.onToggleEnabled?.(t.provider,t.id,!t.enabled)}catch(t){console.warn(`Failed to toggle model ${e}`,t)}finally{let t=new Set(this.pendingToggles);t.delete(e),this.pendingToggles=t;let n=this.focusAfterToggle;this.focusAfterToggle=void 0,await this.updateComplete,n?.isConnected===!0&&this.shadowRoot?.activeElement===null&&n.focus({preventScroll:!0})}}static{this.styles=[bt,st,ie,Me,T`
|
|
2617
2617
|
@layer pi-web-base {
|
|
2618
2618
|
.scope-toggle { border-bottom: 1px solid var(--pi-border-muted); }
|
|
2619
2619
|
.scope-toggle button { flex: 1; }
|
|
@@ -2626,7 +2626,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2626
2626
|
.membership-checkbox input { margin: 0; accent-color: var(--pi-accent); }
|
|
2627
2627
|
|
|
2628
2628
|
}
|
|
2629
|
-
`]}};w([y()],Y.prototype,`title`,void 0),w([y({attribute:!1})],Y.prototype,`options`,void 0),w([y({attribute:!1})],Y.prototype,`catalog`,void 0),w([y({attribute:!1})],Y.prototype,`selectedValue`,void 0),w([y({attribute:!1})],Y.prototype,`defaultValue`,void 0),w([y({type:Boolean})],Y.prototype,`defaultsLoading`,void 0),w([y({attribute:!1})],Y.prototype,`onPick`,void 0),w([y({attribute:!1})],Y.prototype,`onSetDefault`,void 0),w([y({attribute:!1})],Y.prototype,`onCancel`,void 0),w([y({attribute:!1})],Y.prototype,`onToggleEnabled`,void 0),w([y({attribute:!1})],Y.prototype,`onSetScope`,void 0),w([C()],Y.prototype,`mode`,void 0),w([C()],Y.prototype,`defaultPending`,void 0),w([C()],Y.prototype,`selectedIndex`,void 0),w([C()],Y.prototype,`query`,void 0),w([C()],Y.prototype,`pendingToggles`,void 0),w([C()],Y.prototype,`toggleAllPending`,void 0),Y=w([b(`model-picker`)],Y);var
|
|
2629
|
+
`]}};w([y()],Y.prototype,`title`,void 0),w([y({attribute:!1})],Y.prototype,`options`,void 0),w([y({attribute:!1})],Y.prototype,`catalog`,void 0),w([y({attribute:!1})],Y.prototype,`selectedValue`,void 0),w([y({attribute:!1})],Y.prototype,`defaultValue`,void 0),w([y({type:Boolean})],Y.prototype,`defaultsLoading`,void 0),w([y({attribute:!1})],Y.prototype,`onPick`,void 0),w([y({attribute:!1})],Y.prototype,`onSetDefault`,void 0),w([y({attribute:!1})],Y.prototype,`onCancel`,void 0),w([y({attribute:!1})],Y.prototype,`onToggleEnabled`,void 0),w([y({attribute:!1})],Y.prototype,`onSetScope`,void 0),w([C()],Y.prototype,`mode`,void 0),w([C()],Y.prototype,`defaultPending`,void 0),w([C()],Y.prototype,`selectedIndex`,void 0),w([C()],Y.prototype,`query`,void 0),w([C()],Y.prototype,`pendingToggles`,void 0),w([C()],Y.prototype,`toggleAllPending`,void 0),Y=w([b(`model-picker`)],Y);var qS=class extends O{constructor(){super(),this.actions=[],this.queryText=``,this.selectedIndex=0,v.createController(this)}render(){let e=this.filteredActions();return E`
|
|
2630
2630
|
<modal-surface
|
|
2631
2631
|
.onClose=${()=>this.onCancel?.()}
|
|
2632
2632
|
.initialFocus=${`input`}
|
|
@@ -2663,14 +2663,14 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2663
2663
|
`})}
|
|
2664
2664
|
</div>
|
|
2665
2665
|
</modal-surface>
|
|
2666
|
-
`}updated(e){if(!e.has(`actions`)&&!e.has(`queryText`))return;let t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){return
|
|
2666
|
+
`}updated(e){if(!e.has(`actions`)&&!e.has(`queryText`))return;let t=Math.max(0,this.filteredActions().length-1);this.selectedIndex>t&&(this.selectedIndex=t)}filteredActions(){return JS(this.actions,this.queryText)}handleKeyDown(e){if(ut(e))return;let t=this.filteredActions();if(e.key===`ArrowDown`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key===`ArrowUp`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key===`Enter`){e.preventDefault();let n=t[this.selectedIndex];n!==void 0&&this.run(n)}}run(e){e.enabled!==!1&&this.onRun?.(e)}static{this.styles=[bt,st,T`
|
|
2667
2667
|
.heading, .details { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 12px; min-width: 0; }
|
|
2668
2668
|
strong { flex: 1 1 12ch; min-width: 0; }
|
|
2669
2669
|
.description { flex: 1 1 24ch; min-width: 0; font: inherit; }
|
|
2670
2670
|
.disabled-reason { color: var(--pi-warning); }
|
|
2671
2671
|
.group { flex: 0 1 auto; min-width: 0; max-width: 100%; margin-inline-start: auto; text-align: end; font-size: 12px; }
|
|
2672
2672
|
kbd { flex: 0 1 auto; max-width: 100%; margin-inline-start: auto; 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 var(--pi-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); white-space: normal; }
|
|
2673
|
-
`]}};w([y({attribute:!1})],
|
|
2673
|
+
`]}};w([y({attribute:!1})],qS.prototype,`actions`,void 0),w([y({attribute:!1})],qS.prototype,`onRun`,void 0),w([y({attribute:!1})],qS.prototype,`onCancel`,void 0),w([C()],qS.prototype,`queryText`,void 0),w([C()],qS.prototype,`selectedIndex`,void 0),qS=w([b(`action-palette`)],qS);function JS(e,t){let n=t.trim().toLowerCase();return e.filter(e=>e.enabled!==!1||e.disabledReason!==void 0).filter(e=>n===``||[e.title,e.description??``,e.disabledReason??``,e.group??``,e.shortcut??``].join(` `).toLowerCase().includes(n))}var YS=class extends O{constructor(){super(),this.selectedIndex=0,this.query=``,v.createController(this)}render(){let e=this.state;if(e===void 0)return null;let t=e.step===`apiKey`?e.saving===!0:e.step===`oauth`&&e.responding===!0;return E`
|
|
2674
2674
|
<modal-surface .onClose=${()=>{this.cancel()}} .onBusyEscape=${e.step===`oauth`?()=>this.onOAuthCancel?.():void 0} .busy=${t} .initialFocus=${this.initialFocus(e)} .label=${this.dialogTitle(e)} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
2675
2675
|
<header class="ui-dialog-header">
|
|
2676
2676
|
<strong class="ui-dialog-title">${this.dialogTitle(e)}</strong>
|
|
@@ -2678,7 +2678,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2678
2678
|
</header>
|
|
2679
2679
|
${this.renderBody(e)}
|
|
2680
2680
|
</modal-surface>
|
|
2681
|
-
`}willUpdate(e){if(!e.has(`state`))return;if(
|
|
2681
|
+
`}willUpdate(e){if(!e.has(`state`))return;if(rC(e.get(`state`))!==this.state?.step){this.selectedIndex=0,this.query=``;return}let t=this.state===void 0?void 0:this.visibleOptions(this.state);t!==void 0&&(this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,t.length-1)))}updated(e){if(!e.has(`state`))return;let t=rC(e.get(`state`));if(t===void 0)return;let n=this.state?.step,r=t!==n,i=t===`oauth`&&n===`oauth`&&tC(e.get(`state`))!==tC(this.state);(r||i)&&this.modalSurface?.focusDialog()}dialogTitle(e){let t=e.target.projectName===void 0?``:` · ${e.target.projectName}`;switch(e.step){case`method`:return D(`ui.authDialog.configureProviderAuthentication`,`Configure provider authentication{scope}`,{scope:t});case`starting`:return e.title;case`providers`:return`${e.authType===void 0?D(`ui.authDialog.selectProviderAuthentication`,`Select provider authentication`):e.authType===`oauth`?D(`ui.authDialog.selectSubscriptionProvider`,`Select subscription provider`):D(`ui.authDialog.selectApiKeyProvider`,`Select API key provider`)}${t}`;case`apiKey`:return D(`ui.authDialog.apiKeyFor`,`API key for {name}{scope}`,{name:e.provider.name,scope:t});case`oauth`:return e.flow.target===`mcp`?e.flow.mcpMode===void 0?D(`ui.mcp.authentication`,`MCP authentication`):D(`ui.mcp.authenticationTitle`,`MCP {mode}{server}`,{mode:e.flow.mcpMode===`login`?D(`ui.mcp.login`,`Login`):D(`ui.mcp.logout`,`Logout`),server:e.flow.select===void 0?`: ${e.flow.providerName}`:``}):D(`ui.authDialog.logInTo`,`Log in to {providerName}{scope}`,{providerName:e.flow.providerName,scope:t});case`logout`:return D(`ui.authDialog.removeSavedProviderAuthentication`,`Remove saved provider authentication{scope}`,{scope:t})}}renderBody(e){let t=e.target.projectName===void 0?D(`ui.authDialog.currentMode`,`current mode`):D(`ui.authDialog.currentProject`,`current project`);switch(e.step){case`starting`:return E`<div class="form ui-dialog-body ui-form-body">
|
|
2682
2682
|
${e.error===void 0?E`<p role="status">${D(`ui.mcp.starting`,`Starting MCP authentication…`)}</p>`:E`<p class="ui-form-error" role="alert">${e.error}</p>`}
|
|
2683
2683
|
<div class="ui-form-actions"><button class="ui-button" @click=${()=>{this.onCancel?.()}}>${e.error===void 0?D(`ui.sessionCleanupDialog.cancel`,`Cancel`):D(`ui.common.close`,`Close`)}</button></div>
|
|
2684
2684
|
</div>`;case`method`:case`providers`:case`logout`:return this.renderOptionList(e,t);case`apiKey`:return E`
|
|
@@ -2702,7 +2702,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2702
2702
|
</button>
|
|
2703
2703
|
`)}
|
|
2704
2704
|
</div>
|
|
2705
|
-
`}optionsFor(e,t=e.target.projectName===void 0?D(`ui.authDialog.currentMode`,`current mode`):D(`ui.authDialog.currentProject`,`current project`)){switch(e.step){case`method`:return[{key:`oauth`,title:D(`ui.authDialog.useSubscription`,`Use subscription`),detail:D(`ui.authDialog.chatgptPlusProClaudeProMaxOrGithub`,`ChatGPT Plus/Pro, Claude Pro/Max, or GitHub Copilot`),searchText:D(`ui.authDialog.useSubscription`,`Use subscription`),run:()=>{this.onChooseMethod?.(`oauth`)}},{key:`api_key`,title:D(`ui.authDialog.useApiKey`,`Use API key`),detail:D(`ui.authDialog.credentialDestination`,`Save the API key in auth.json for the {scope}`,{scope:t}),searchText:D(`ui.authDialog.useApiKey`,`Use API key`),run:()=>{this.onChooseMethod?.(`api_key`)}}];case`providers`:return e.providers.map(e=>({key:`${e.id}:${e.authType}`,title:E`${e.name}${e.status.source===void 0?null:E` <em>${
|
|
2705
|
+
`}optionsFor(e,t=e.target.projectName===void 0?D(`ui.authDialog.currentMode`,`current mode`):D(`ui.authDialog.currentProject`,`current project`)){switch(e.step){case`method`:return[{key:`oauth`,title:D(`ui.authDialog.useSubscription`,`Use subscription`),detail:D(`ui.authDialog.chatgptPlusProClaudeProMaxOrGithub`,`ChatGPT Plus/Pro, Claude Pro/Max, or GitHub Copilot`),searchText:D(`ui.authDialog.useSubscription`,`Use subscription`),run:()=>{this.onChooseMethod?.(`oauth`)}},{key:`api_key`,title:D(`ui.authDialog.useApiKey`,`Use API key`),detail:D(`ui.authDialog.credentialDestination`,`Save the API key in auth.json for the {scope}`,{scope:t}),searchText:D(`ui.authDialog.useApiKey`,`Use API key`),run:()=>{this.onChooseMethod?.(`api_key`)}}];case`providers`:return e.providers.map(e=>({key:`${e.id}:${e.authType}`,title:E`${e.name}${e.status.source===void 0?null:E` <em>${iC(e)}</em>`}`,detail:`${e.id} · ${eC(e.authType)}`,searchText:e.name,run:()=>{this.onSelectProvider?.(e.id,e.authType)}}));case`logout`:return e.providers.map(e=>({key:`${e.id}:${e.authType}`,title:e.name,detail:`${e.id} · ${eC(e.authType)}`,searchText:e.name,run:()=>{this.onLogoutProvider?.(e.id)}}));case`apiKey`:case`starting`:case`oauth`:return}}stepHasSearch(e){return e.step===`providers`||e.step===`logout`}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(e){let t=this.query.trim().toLowerCase();return t===``?e:e.filter(e=>`${e.searchText} ${e.detail}`.toLowerCase().includes(t))}visibleOptions(e){return this.filteredOptions(this.optionsFor(e)??[])}renderOAuth(e){let t=e.flow,n=t.target===`mcp`,r=t.status===`running`,i=r&&t.cancelRequested!==!0?t.prompt:void 0,a=r&&t.cancelRequested!==!0?t.select:void 0,o=t.auth!==void 0&&(!n||r&&t.cancelRequested!==!0),s=XS(i?.promptType),c=(n||$S(e.target.machineId,window.location.hostname))&&t.status===`running`&&(n?i!==void 0&&t.auth!==void 0:i?.promptType===`manual_code`);return E`
|
|
2706
2706
|
<div class="form ui-dialog-body ui-form-body">
|
|
2707
2707
|
${o&&t.auth!==void 0?E`
|
|
2708
2708
|
<p>${n?D(`ui.mcp.approveBrowser`,`Approve access in your browser, then return here.`):D(`ui.authDialog.openThisAuthorizationLink`,`Open this authorization link:`)}</p>
|
|
@@ -2738,7 +2738,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2738
2738
|
`)}</div>
|
|
2739
2739
|
`}
|
|
2740
2740
|
${e.error!==void 0&&e.error!==``?E`<div class="error-text ui-form-error">${e.error}</div>`:null}
|
|
2741
|
-
${t.status===`error`||t.status===`cancelled`?E`<div class="error-text ui-form-error" role="alert">${t.error??
|
|
2741
|
+
${t.status===`error`||t.status===`cancelled`?E`<div class="error-text ui-form-error" role="alert">${t.error??aC(t.status)}</div>`:null}
|
|
2742
2742
|
${r?null:E`<div class="actions ui-form-actions"><button class="ui-button" @click=${()=>{this.cancel()}}>${D(`ui.common.close`,`Close`)}</button></div>`}
|
|
2743
2743
|
${i===void 0&&(a===void 0||n)&&r?E`<div class="actions ui-form-actions"><button class="ui-button" @click=${()=>{t.cancelRequested===!0?this.onCancel?.():this.onOAuthCancel?.()}}>${t.cancelRequested===!0?D(`ui.common.close`,`Close`):D(`ui.sessionCleanupDialog.cancel`,`Cancel`)}</button></div>`:null}
|
|
2744
2744
|
</div>
|
|
@@ -2753,12 +2753,12 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2753
2753
|
em { color: var(--pi-success); font-style: normal; font-size: 12px; }
|
|
2754
2754
|
|
|
2755
2755
|
}
|
|
2756
|
-
`]}};w([y({attribute:!1})],
|
|
2757
|
-
<modal-surface .onClose=${this.mode===`change`?()=>this.onCancel?.():void 0} .busy=${this.loading} .initialFocus=${`input`} .label=${
|
|
2756
|
+
`]}};w([y({attribute:!1})],YS.prototype,`state`,void 0),w([y({attribute:!1})],YS.prototype,`onChooseMethod`,void 0),w([y({attribute:!1})],YS.prototype,`onSelectProvider`,void 0),w([y({attribute:!1})],YS.prototype,`onApiKeyInput`,void 0),w([y({attribute:!1})],YS.prototype,`onSaveApiKey`,void 0),w([y({attribute:!1})],YS.prototype,`onLogoutProvider`,void 0),w([y({attribute:!1})],YS.prototype,`onOAuthInput`,void 0),w([y({attribute:!1})],YS.prototype,`onOAuthRespond`,void 0),w([y({attribute:!1})],YS.prototype,`onOAuthCancel`,void 0),w([y({attribute:!1})],YS.prototype,`onCancel`,void 0),w([S(`modal-surface`)],YS.prototype,`modalSurface`,void 0),w([C()],YS.prototype,`selectedIndex`,void 0),w([C()],YS.prototype,`query`,void 0),YS=w([b(`auth-dialog`)],YS);function XS(e){return e===`secret`?`password`:`text`}var ZS=new Set([`localhost`,`127.0.0.1`,`::1`]);function QS(e){return ZS.has(e.trim().replace(/^\[|\]$/gu,``).toLowerCase())}function $S(e,t){return e!==`local`||!QS(t)}function eC(e){return e===`oauth`?D(`ui.authDialog.subscription`,`Subscription`):`API key`}function tC(e){if(rC(e)!==`oauth`||typeof e!=`object`||!e||!(`flow`in e))return;let t=e.flow;if(typeof t!=`object`||!t)return;let n=`flowId`in t&&typeof t.flowId==`string`?t.flowId:``,r=`prompt`in t?nC(t.prompt):void 0;if(r!==void 0)return`${n}:prompt:${r}:${`responding`in e&&e.responding===!0?`responding`:`ready`}`;let i=`select`in t?nC(t.select):void 0;return i===void 0?`${n}:waiting:${`status`in t&&typeof t.status==`string`?t.status:`unknown`}`:`${n}:select:${i}`}function nC(e){if(typeof e==`object`&&e&&`requestId`in e)return typeof e.requestId==`string`?e.requestId:void 0}function rC(e){if(typeof e==`object`&&e&&`step`in e)switch(e.step){case`method`:case`starting`:case`providers`:case`apiKey`:case`oauth`:case`logout`:return e.step;default:return}}function iC(e){if(e.status.source===void 0)return``;switch(e.status.source){case`stored`:return D(`ui.authDialog.configured`,`✓ Configured`);case`environment`:return D(`ui.authDialog.environment`,`✓ Environment{label}`,{label:e.status.label===void 0?``:`: ${e.status.label}`});case`runtime`:return D(`ui.authDialog.runtime`,`✓ Runtime`);case`fallback`:return D(`ui.authDialog.customKey`,`✓ Custom key`);case`models_json_key`:return`✓ models.json key`;case`models_json_command`:return`✓ models.json command`;default:return``}}function aC(e){return e===`cancelled`?D(`client.shellMessages.cancelled.a37778`,`Cancelled`):e===`error`?D(`client.sessionNotifications.error.0bc1fb`,`Error`):e}var oC=class extends O{constructor(...e){super(...e),this.mode=`login`,this.loading=!1,this.error=``,this.currentPassword=``,this.password=``,this.confirmPassword=``,this.localError=``}render(){return E`
|
|
2757
|
+
<modal-surface .onClose=${this.mode===`change`?()=>this.onCancel?.():void 0} .busy=${this.loading} .initialFocus=${`input`} .label=${sC(this.mode)}>
|
|
2758
2758
|
<header>
|
|
2759
2759
|
<div>
|
|
2760
2760
|
<span class="eyebrow">${D(`ui.normalAuthDialog.normalMode`,`Normal mode`)}</span>
|
|
2761
|
-
<h1>${
|
|
2761
|
+
<h1>${sC(this.mode)}</h1>
|
|
2762
2762
|
</div>
|
|
2763
2763
|
${this.mode===`change`?E`<button class="close-button" title=${D(`ui.normalAuthDialog.close`,`Close`)} aria-label=${D(`ui.normalAuthDialog.close`,`Close`)} @click=${()=>this.onCancel?.()}>×</button>`:null}
|
|
2764
2764
|
</header>
|
|
@@ -2766,17 +2766,17 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2766
2766
|
${this.mode===`change`?E`
|
|
2767
2767
|
<label>
|
|
2768
2768
|
<span>${D(`ui.normalAuthDialog.currentPassword`,`Current password`)}</span>
|
|
2769
|
-
<input type="password" .value=${this.currentPassword} autocomplete="current-password" @input=${e=>{this.currentPassword=
|
|
2769
|
+
<input type="password" .value=${this.currentPassword} autocomplete="current-password" @input=${e=>{this.currentPassword=lC(e),this.localError=``}}>
|
|
2770
2770
|
</label>
|
|
2771
2771
|
`:null}
|
|
2772
2772
|
<label>
|
|
2773
2773
|
<span>${this.mode===`login`?D(`ui.normalAuthDialog.password`,`Password`):D(`ui.normalAuthDialog.newPassword`,`New password`)}</span>
|
|
2774
|
-
<input type="password" .value=${this.password} autocomplete=${this.mode===`login`?`current-password`:`new-password`} @input=${e=>{this.password=
|
|
2774
|
+
<input type="password" .value=${this.password} autocomplete=${this.mode===`login`?`current-password`:`new-password`} @input=${e=>{this.password=lC(e),this.localError=``}}>
|
|
2775
2775
|
</label>
|
|
2776
2776
|
${this.mode===`login`?null:E`
|
|
2777
2777
|
<label>
|
|
2778
2778
|
<span>${D(`ui.normalAuthDialog.confirmPassword`,`Confirm password`)}</span>
|
|
2779
|
-
<input type="password" .value=${this.confirmPassword} autocomplete="new-password" @input=${e=>{this.confirmPassword=
|
|
2779
|
+
<input type="password" .value=${this.confirmPassword} autocomplete="new-password" @input=${e=>{this.confirmPassword=lC(e),this.localError=``}}>
|
|
2780
2780
|
</label>
|
|
2781
2781
|
`}
|
|
2782
2782
|
${this.message()===``?null:E`<p class="message">${this.message()}</p>`}
|
|
@@ -2786,7 +2786,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2786
2786
|
</footer>
|
|
2787
2787
|
</form>
|
|
2788
2788
|
</modal-surface>
|
|
2789
|
-
`}submitLabel(){return this.mode===`setup`?D(`ui.normalAuthDialog.setPasswordAndEnter`,`Set password and enter`):this.mode===`change`?D(`ui.normalAuthDialog.savePassword`,`Save password`):D(`ui.normalAuthDialog.enter`,`Enter`)}message(){return this.localError||this.error}async submit(e){e.preventDefault();let t={currentPassword:this.currentPassword,password:this.password,confirmPassword:this.confirmPassword},n=
|
|
2789
|
+
`}submitLabel(){return this.mode===`setup`?D(`ui.normalAuthDialog.setPasswordAndEnter`,`Set password and enter`):this.mode===`change`?D(`ui.normalAuthDialog.savePassword`,`Save password`):D(`ui.normalAuthDialog.enter`,`Enter`)}message(){return this.localError||this.error}async submit(e){e.preventDefault();let t={currentPassword:this.currentPassword,password:this.password,confirmPassword:this.confirmPassword},n=cC(this.mode,t);n===void 0?(this.localError=``,await this.onSubmit?.(t)):this.localError=n}static{this.styles=T`
|
|
2790
2790
|
:host { position: fixed; inset: 0; z-index: 40; color: var(--pi-text); font: 14px system-ui, sans-serif; }
|
|
2791
2791
|
modal-surface { --modal-surface-backdrop-padding: max(20px, env(safe-area-inset-top)) max(20px, env(safe-area-inset-right)) max(20px, env(safe-area-inset-bottom)) max(20px, env(safe-area-inset-left)); --modal-surface-backdrop-background: var(--pi-bg); --modal-surface-width: min(420px, 100%); }
|
|
2792
2792
|
header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 16px; border-bottom: 1px solid var(--pi-border); }
|
|
@@ -2803,7 +2803,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2803
2803
|
.close-button { width: 34px; height: 34px; display: grid; place-items: center; border: 0; background: transparent; color: var(--pi-muted); padding: 0; font-size: 24px; }
|
|
2804
2804
|
.message { margin: 0; border: 1px solid var(--pi-danger-border); border-radius: 8px; background: var(--pi-danger-surface); color: var(--pi-danger); padding: 10px; }
|
|
2805
2805
|
footer { display: flex; justify-content: flex-end; gap: 8px; }
|
|
2806
|
-
`}};w([y()],
|
|
2806
|
+
`}};w([y()],oC.prototype,`mode`,void 0),w([y({type:Boolean})],oC.prototype,`loading`,void 0),w([y()],oC.prototype,`error`,void 0),w([y({attribute:!1})],oC.prototype,`onSubmit`,void 0),w([y({attribute:!1})],oC.prototype,`onCancel`,void 0),w([C()],oC.prototype,`currentPassword`,void 0),w([C()],oC.prototype,`password`,void 0),w([C()],oC.prototype,`confirmPassword`,void 0),w([C()],oC.prototype,`localError`,void 0),oC=w([b(`normal-auth-dialog`)],oC);function sC(e){return e===`setup`?D(`ui.normalAuthDialog.setAccessPassword`,`Set access password`):e===`change`?D(`ui.normalAuthDialog.changeAccessPassword`,`Change access password`):D(`ui.normalAuthDialog.enterPassword`,`Enter password`)}function cC(e,t){if(e===`change`&&(t.currentPassword??``)===``)return D(`ui.normalAuthDialog.enterYourCurrentPassword`,`Enter your current password.`);if(t.password===``)return D(`ui.normalAuthDialog.enterAPassword`,`Enter a password.`);if(e!==`login`&&t.password!==(t.confirmPassword??``))return D(`ui.normalAuthDialog.passwordsDoNotMatch`,`Passwords do not match.`)}function lC(e){return e.target instanceof HTMLInputElement?e.target.value:``}var uC=class extends O{constructor(){super(),this.machineId=`local`,this.managementMode=!1,this.path=``,this.createMissing=!0,this.suggestions=[],this.selected=0,this.loading=!1,this.suggestionError=!1,this.trustTouched=!1,this.requestId=0,this.trustRequestId=0,v.createController(this)}connectedCallback(){super.connectedCallback(),this.loadSuggestions()}disconnectedCallback(){this.requestId++,this.trustRequestId++,super.disconnectedCallback()}updated(e){(e.has(`machineId`)||e.has(`managementMode`))&&(this.trustTouched=!1,this.loadSuggestions(),this.loadTrust())}async loadSuggestions(){let e=++this.requestId;this.loading=!0,this.suggestionError=!1,this.suggestions=[];try{let t=await x.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.suggestionError=!0)}finally{e===this.requestId&&(this.loading=!1)}}setPath(e){this.path=e,this.selected=0,this.trustTouched=!1,this.loadSuggestions(),this.loadTrust()}pick(e){this.setPath(e.path)}submit(){this.path.trim()!==``&&this.onSubmit?.(this.path,this.createMissing,this.trust===void 0?void 0:{trusted:this.trust.trusted,changed:this.trustTouched})}onPathInput(e){e.target instanceof HTMLInputElement&&this.setPath(e.target.value)}onCreateMissingChange(e){e.target instanceof HTMLInputElement&&(this.createMissing=e.target.checked)}async loadTrust(){let e=++this.trustRequestId,t=this.path.trim();if(t===``||this.managementMode)e===this.trustRequestId&&(this.trust=void 0);else{this.trust={path:t,decision:this.trust?.decision??null,trusted:this.trust?.trusted??!1,loading:!0};try{let n=await ye.projectTrust(t,this.machineId);if(e!==this.trustRequestId||this.trustTouched)return;this.trust={path:n.path,decision:n.decision,trusted:n.trusted,loading:!1}}catch(n){if(e!==this.trustRequestId||this.trustTouched)return;this.trust={path:t,decision:null,trusted:!1,loading:!1,error:n instanceof Error?n.message:String(n)}}}}onTrustChange(e){this.trustTouched=!0,this.trust!==void 0&&(this.trust={...this.trust,trusted:e,loading:!1})}renderTrustChoice(){if(this.managementMode)return null;let e=this.trust===void 0||this.trust.loading||this.trust.error!==void 0;return E`
|
|
2807
2807
|
<label class="check ui-checkbox-field">
|
|
2808
2808
|
<input class="ui-input" type="checkbox" aria-describedby=${this.trust?.error===void 0?`project-trust-help`:`project-trust-help project-trust-error`} .checked=${this.trust?.trusted??!1} ?disabled=${e} @change=${e=>{e.target instanceof HTMLInputElement&&this.onTrustChange(e.target.checked)}} />
|
|
2809
2809
|
<span>${D(`ui.main.bb60ec05a965`,`Trust this project`)}</span>
|
|
@@ -2864,7 +2864,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2864
2864
|
.trust-hint a { color: var(--pi-accent); }
|
|
2865
2865
|
|
|
2866
2866
|
}
|
|
2867
|
-
`]}};w([y({attribute:!1})],
|
|
2867
|
+
`]}};w([y({attribute:!1})],uC.prototype,`onSubmit`,void 0),w([y({attribute:!1})],uC.prototype,`onCancel`,void 0),w([y()],uC.prototype,`machineId`,void 0),w([y({type:Boolean})],uC.prototype,`managementMode`,void 0),w([C()],uC.prototype,`path`,void 0),w([C()],uC.prototype,`createMissing`,void 0),w([C()],uC.prototype,`suggestions`,void 0),w([C()],uC.prototype,`selected`,void 0),w([C()],uC.prototype,`loading`,void 0),w([C()],uC.prototype,`suggestionError`,void 0),w([C()],uC.prototype,`trust`,void 0),w([C()],uC.prototype,`trustTouched`,void 0),w([S(`input`)],uC.prototype,`pathInput`,void 0),uC=w([b(`project-dialog`)],uC);var dC=class extends O{constructor(){super(),this.error=``,this.url=``,this.name=``,this.token=``,this.submitting=!1,this.nameEdited=!1,this.previousSuggestedName=``,v.createController(this)}handleUrlInput(e){if(!(e.target instanceof HTMLInputElement))return;let t=e.target.value,n=fC(t);this.nameEdited&&this.name.trim()!==``&&this.name!==this.previousSuggestedName||(this.name=n),this.previousSuggestedName=n,this.url=t}handleNameInput(e){e.target instanceof HTMLInputElement&&(this.nameEdited=!0,this.name=e.target.value)}handleTokenInput(e){e.target instanceof HTMLInputElement&&(this.token=e.target.value)}handleKeyDown(e){e.key===`Enter`&&e.target instanceof HTMLInputElement&&e.target.name===`baseUrl`&&pC(this.url)===void 0&&(e.preventDefault(),this.updateComplete.then(()=>{this.nameInput?.focus(),this.nameInput?.select()}))}handleSubmit(e){e.preventDefault(),this.submit()}async submit(){let e=this.validInput();if(!(e===void 0||this.submitting)){this.submitting=!0;try{await this.onSubmit?.(e)}finally{this.isConnected&&(this.submitting=!1)}}}validInput(){let e=this.url.trim(),t=this.name.trim();if(e===``||t===``||pC(e)!==void 0)return;let n=this.token.trim();return{name:t,baseUrl:e,...n===``?{}:{token:n}}}render(){let e=this.url.trim()!==``,t=e?pC(this.url):void 0,n=this.validInput()!==void 0&&!this.submitting;return E`
|
|
2868
2868
|
<modal-surface .onClose=${()=>this.onCancel?.()} .busy=${this.submitting} .initialFocus=${`input[name='baseUrl']`} .label=${D(`client.actions.add.machine.e4ad1b`,`Add machine`)} @keydown=${e=>{this.handleKeyDown(e)}}>
|
|
2869
2869
|
<form aria-describedby=${this.error===``?``:`machine-error`} @submit=${e=>{this.handleSubmit(e)}}>
|
|
2870
2870
|
<header class="ui-dialog-header">
|
|
@@ -2906,7 +2906,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2906
2906
|
.field-error { color: var(--pi-danger); }
|
|
2907
2907
|
|
|
2908
2908
|
}
|
|
2909
|
-
`]}};w([y({attribute:!1})],
|
|
2909
|
+
`]}};w([y({attribute:!1})],dC.prototype,`onSubmit`,void 0),w([y({attribute:!1})],dC.prototype,`onCancel`,void 0),w([y()],dC.prototype,`error`,void 0),w([C()],dC.prototype,`url`,void 0),w([C()],dC.prototype,`name`,void 0),w([C()],dC.prototype,`token`,void 0),w([C()],dC.prototype,`submitting`,void 0),w([S(`input[name='name']`)],dC.prototype,`nameInput`,void 0),dC=w([b(`machine-dialog`)],dC);function fC(e){let t=e.trim();if(t===``)return``;let n=mC(t)??mC(`http://${t.replace(/^\/+/u,``)}`);return n!==void 0&&n.hostname!==``?n.hostname.replace(/^\[(.*)\]$/u,`$1`):hC(t)}function pC(e){let t=e.trim();if(t===``)return D(`ui.machineDialog.remotePiWebUrlIsRequired`,`Remote PI WEB URL is required.`);let n;try{n=new URL(t)}catch{return D(`ui.machineDialog.enterAValidUrlIncludingHttpOrHttps`,`Enter a valid URL including http:// or https://.`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)return D(`ui.machineDialog.useAnHttpOrHttpsUrl`,`Use an http:// or https:// URL.`);if(n.username!==``||n.password!==``)return D(`ui.machineDialog.doNotIncludeCredentialsInTheMachineUrl`,`Do not include credentials in the machine URL.`);if(n.search!==``||n.hash!==``)return D(`ui.machineDialog.doNotIncludeAQueryStringOrFragment`,`Do not include a query string or fragment.`)}function mC(e){try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`?t:void 0}catch{return}}function hC(e){let t=e.replace(/^[a-z][a-z\d+.-]*:\/\//iu,``),n=t.slice(t.lastIndexOf(`@`)+1).split(/[/?#]/u)[0]??``;return n.startsWith(`[`)&&n.includes(`]`)?n.slice(1,n.indexOf(`]`)):n.replace(/:\d+$/u,``)}var gC=class{constructor(e,t,n,r){this.host=e,this.requested=t,this.load=n,this.reportError=r,this.loading=!1,this.loaded=!1,this.failed=!1,e.addController(this)}hostUpdated(){this.requested()?this.loaded||this.loading||this.failed||(this.loading=!0,this.load().then(()=>{this.loaded=!0}).catch(e=>{this.failed=!0,this.host.isConnected&&this.reportError(e)}).finally(()=>{this.loading=!1})):this.failed=!1}};function _C(){return Bt`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" focusable="false"><path d="M4 6h16M4 12h16M4 18h16"></path></svg>`}function vC(e){return typeof e==`string`?yC(e):E`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`}function yC(e){switch(e){case`navigation`:return Bt`
|
|
2910
2910
|
<svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
|
2911
2911
|
<circle cx="6" cy="7" r="1.5"></circle>
|
|
2912
2912
|
<path d="M10 7h8"></path>
|
|
@@ -2921,7 +2921,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2921
2921
|
<path d="M8 9h8"></path>
|
|
2922
2922
|
<path d="M8 13h5"></path>
|
|
2923
2923
|
</svg>
|
|
2924
|
-
`}}var
|
|
2924
|
+
`}}var bC=class extends O{constructor(){super(),this.error=``,this.panels=[],this.hideToolTabs=!1,this.pinnedIds=[],this.hiddenActiveDestination=!1,this.onSelectTool=()=>void 0,this.workspaceHeaderCanScrollLeft=!1,this.workspaceHeaderCanScrollRight=!1,this.onWorkspaceHeaderScroll=()=>{this.updateWorkspaceHeaderScrollState()},v.createController(this)}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&&this.panels.length===0)return this.renderEmptyState(this.error===``?this.emptyState??{title:D(`ui.workspacePanel.selectWorkspace`,`Select workspace`),body:D(`ui.main.272d152c38f6`,`Choose a workspace to use its tools.`)}:{title:D(`ui.main.110fc6609529`,`Navigation destination unavailable`),body:this.error},!0);let e=this.panels,t=this.error===``?this.tool===void 0?e[0]:e.find(e=>e.id===this.tool):void 0,n=s_(e,this.pinnedIds);return E`
|
|
2925
2925
|
${this.hideToolTabs?null:E`
|
|
2926
2926
|
<header>
|
|
2927
2927
|
<div class=${this.workspaceHeaderFrameClass()}>
|
|
@@ -2947,54 +2947,54 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
2947
2947
|
${e.icon===void 0?null:E`<span class="tab-custom-icon" aria-hidden="true">${e.icon}</span>`}
|
|
2948
2948
|
<span class="tab-label">${e.title}</span>
|
|
2949
2949
|
${this.isEmptyBadge(t)?null:E`<span class="tab-badge">${t}</span>`}
|
|
2950
|
-
`}isEmptyBadge(e){return e===void 0||e===``}renderNavigationButton(e=!1){return this.onShowNavigation===void 0?null:E`<button type="button" class=${`ui-button ui-button--icon navigation-menu-button${e?` selected`:``}`} title="${D(`ui.main.99aaea15ca9e`,`Open Navigation`)}" aria-label="${D(`ui.main.99aaea15ca9e`,`Open Navigation`)}" aria-haspopup="dialog" @click=${this.onShowNavigation}>${
|
|
2950
|
+
`}isEmptyBadge(e){return e===void 0||e===``}renderNavigationButton(e=!1){return this.onShowNavigation===void 0?null:E`<button type="button" class=${`ui-button ui-button--icon navigation-menu-button${e?` selected`:``}`} title="${D(`ui.main.99aaea15ca9e`,`Open Navigation`)}" aria-label="${D(`ui.main.99aaea15ca9e`,`Open Navigation`)}" aria-haspopup="dialog" @click=${this.onShowNavigation}>${_C()}</button>`}renderEmptyState(e,t=!1){return E`
|
|
2951
2951
|
${t&&!this.hideToolTabs?E`<header>${this.renderNavigationButton()}</header>`:null}
|
|
2952
2952
|
<section class="empty-state" role=${this.error===``?`status`:`alert`}>
|
|
2953
2953
|
<h2>${e.title}</h2>
|
|
2954
2954
|
${e.body===void 0?null:E`<p>${e.body}</p>`}
|
|
2955
2955
|
</section>
|
|
2956
|
-
`}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?` can-scroll-left`:``}${this.workspaceHeaderCanScrollRight?` can-scroll-right`:``}`}observeWorkspaceHeaderStrip(){let e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,e!==void 0&&typeof ResizeObserver<`u`&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){let e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=e!==void 0&&e.scrollLeft>1,r=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==n&&(this.workspaceHeaderCanScrollLeft=n),this.workspaceHeaderCanScrollRight!==r&&(this.workspaceHeaderCanScrollRight=r)}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=
|
|
2956
|
+
`}workspaceHeaderFrameClass(){return`workspace-header-scroll-frame${this.workspaceHeaderCanScrollLeft?` can-scroll-left`:``}${this.workspaceHeaderCanScrollRight?` can-scroll-right`:``}`}observeWorkspaceHeaderStrip(){let e=this.workspaceHeaderStripElement();this.observedWorkspaceHeaderStrip!==e&&(this.workspaceHeaderResizeObserver?.disconnect(),this.observedWorkspaceHeaderStrip=e,this.workspaceHeaderResizeObserver=void 0,e!==void 0&&typeof ResizeObserver<`u`&&(this.workspaceHeaderResizeObserver=new ResizeObserver(()=>{this.updateWorkspaceHeaderScrollState()}),this.workspaceHeaderResizeObserver.observe(e)))}updateWorkspaceHeaderScrollState(){let e=this.workspaceHeaderStripElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=e!==void 0&&e.scrollLeft>1,r=e!==void 0&&t-e.scrollLeft>1;this.workspaceHeaderCanScrollLeft!==n&&(this.workspaceHeaderCanScrollLeft=n),this.workspaceHeaderCanScrollRight!==r&&(this.workspaceHeaderCanScrollRight=r)}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=Bh}};w([y({attribute:!1})],bC.prototype,`workspace`,void 0),w([y({attribute:!1})],bC.prototype,`emptyState`,void 0),w([y()],bC.prototype,`error`,void 0),w([y()],bC.prototype,`tool`,void 0),w([y({attribute:!1})],bC.prototype,`panels`,void 0),w([y({type:Boolean})],bC.prototype,`hideToolTabs`,void 0),w([y({attribute:!1})],bC.prototype,`pinnedIds`,void 0),w([y({attribute:!1})],bC.prototype,`onShowNavigation`,void 0),w([y({type:Boolean})],bC.prototype,`hiddenActiveDestination`,void 0),w([y({attribute:!1})],bC.prototype,`onSelectTool`,void 0),w([S(`.workspace-header-strip`)],bC.prototype,`workspaceHeaderStrip`,void 0),w([C()],bC.prototype,`workspaceHeaderCanScrollLeft`,void 0),w([C()],bC.prototype,`workspaceHeaderCanScrollRight`,void 0),bC=w([b(`workspace-panel`)],bC);function xC(e){return e.kind===`local`||e.baseUrl===void 0?zt(`favicon.svg`):new URL(`favicon.svg`,e.baseUrl.endsWith(`/`)?e.baseUrl:`${e.baseUrl}/`).toString()}function SC(e){let t=new URL(e);return`${t.host}${t.pathname.replace(/\/+$/,``)}`}function CC(){return SC(zt(``))}var X=class extends O{constructor(){super(),this.machines=[],this.presentationContext={mode:`normal`},this.locationIndicator=!1,this.workspaceSelectionVisible=!0,this.hiddenActiveDestination=!1,this.canScrollLeft=!1,this.canScrollRight=!1,this.hideBrokenIcon=e=>{e.currentTarget instanceof HTMLImageElement&&(e.currentTarget.style.display=`none`)},this.onContextScroll=()=>{this.updateScrollState()},v.createController(this)}disconnectedCallback(){this.contextItemsResizeObserver?.disconnect(),this.contextItemsResizeObserver=void 0,this.observedContextItems=void 0,super.disconnectedCallback()}firstUpdated(){this.observeContextItems(),this.updateScrollState()}updated(){this.observeContextItems(),this.updateScrollState()}render(){let e=wC(this.machine,this.machines),t=this.machines.length>1,n=e===void 0?`context-chip machine-chip empty`:`context-chip machine-chip`,r=kC(this.project),i=jC(this.workspace),a=NC(this.session);return E`
|
|
2957
2957
|
<pi-web-ui-presentation region="context-bar" .runtime=${this.presentationRuntime} .context=${this.presentationContext}>
|
|
2958
2958
|
<nav slot="content" class=${this.contextBarClass()} aria-label="${D(`ui.appContextBar.currentLocation`,`Current location`)}">
|
|
2959
2959
|
<span class="context-bar-label">${D(`ui.appContextBar.location`,`Location`)}</span>
|
|
2960
2960
|
<ol class="context-items" @scroll=${this.onContextScroll}>
|
|
2961
2961
|
<li class="context-item">
|
|
2962
2962
|
${t?E`
|
|
2963
|
-
<button type="button" class=${n} title=${
|
|
2963
|
+
<button type="button" class=${n} title=${OC(e)} aria-label=${D(`ui.appContextBar.machineOpenMachineSelection`,`Machine: {machineLabel}. Open machine selection.`,{machineLabel:TC(e)})} @click=${()=>{this.onOpenSection?.(`machines`)}}>
|
|
2964
2964
|
${this.renderMachineChipContent(e,this.locationIndicator)}
|
|
2965
2965
|
</button>
|
|
2966
2966
|
`:E`
|
|
2967
2967
|
<!-- No machine choice: the chip is the instance identity, not a control. -->
|
|
2968
|
-
<span class="${n} static" title=${
|
|
2968
|
+
<span class="${n} static" title=${OC(e)}>
|
|
2969
2969
|
${this.renderMachineChipContent(e,this.locationIndicator)}
|
|
2970
2970
|
</span>
|
|
2971
2971
|
`}
|
|
2972
2972
|
</li>
|
|
2973
2973
|
<li class="context-item">
|
|
2974
|
-
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${
|
|
2974
|
+
<button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${AC(this.project)} aria-label=${D(`ui.appContextBar.projectOpenProjectSelection`,`Project: {projectLabel}. Open project selection.`,{projectLabel:r})} @click=${()=>{this.onOpenSection?.(`projects`)}}>
|
|
2975
2975
|
<span class="context-kind">${D(`client.actions.project.79f326`,`Project`)}</span>
|
|
2976
2976
|
<span class="context-value">${r}</span>
|
|
2977
2977
|
</button>
|
|
2978
2978
|
</li>
|
|
2979
2979
|
${this.workspaceSelectionVisible?E`<li class="context-item">
|
|
2980
|
-
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${
|
|
2980
|
+
<button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${MC(this.workspace)} aria-label=${D(`ui.appContextBar.workspaceOpenWorkspaceSelection`,`Workspace: {workspaceLabel}. Open workspace selection.`,{workspaceLabel:i})} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
|
|
2981
2981
|
<span class="context-kind">${D(`bundled.workspace-tasks.workspace.379798`,`Workspace`)}</span>
|
|
2982
2982
|
<span class="context-value">${i}</span>
|
|
2983
2983
|
</button>
|
|
2984
2984
|
</li>`:null}
|
|
2985
2985
|
<li class="context-item">
|
|
2986
|
-
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${
|
|
2986
|
+
<button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${PC(this.session)} aria-label=${D(`ui.appContextBar.sessionOpenSessionSelection`,`Session: {sessionLabel}. Open session selection.`,{sessionLabel:a})} @click=${()=>{this.onOpenSection?.(`sessions`)}}>
|
|
2987
2987
|
<span class="context-kind">${D(`ui.sessionSearchDialog.sessions`,`Sessions`)}</span>
|
|
2988
2988
|
<span class="context-value">${a}</span>
|
|
2989
2989
|
</button>
|
|
2990
2990
|
</li>
|
|
2991
2991
|
</ol>
|
|
2992
|
-
${this.hasContextActions()?E`<div class="context-actions">${this.onShowNavigation===void 0?null:E`<button type="button" class=${`context-action-button${this.hiddenActiveDestination?` selected`:``}`} title="${D(`ui.main.99aaea15ca9e`,`Open Navigation`)}" aria-label="${D(`ui.main.99aaea15ca9e`,`Open Navigation`)}" aria-haspopup="dialog" aria-pressed=${String(this.hiddenActiveDestination)} @click=${this.onShowNavigation}>${
|
|
2992
|
+
${this.hasContextActions()?E`<div class="context-actions">${this.onShowNavigation===void 0?null:E`<button type="button" class=${`context-action-button${this.hiddenActiveDestination?` selected`:``}`} title="${D(`ui.main.99aaea15ca9e`,`Open Navigation`)}" aria-label="${D(`ui.main.99aaea15ca9e`,`Open Navigation`)}" aria-haspopup="dialog" aria-pressed=${String(this.hiddenActiveDestination)} @click=${this.onShowNavigation}>${_C()}</button>`}${this.renderActionsButton()}${this.refreshControl}</div>`:null}
|
|
2993
2993
|
</nav>
|
|
2994
2994
|
</pi-web-ui-presentation>
|
|
2995
|
-
`}renderMachineChipContent(e,t){if(e===void 0)return E`<span class="context-value">${D(`ui.machineList.noMachineSelected`,`No machine selected`)}</span>`;if(!t)return E`<span class="context-value">${
|
|
2996
|
-
<img class="context-chip-icon" src=${
|
|
2997
|
-
${this.machines.length>1?E`<span class="context-value">${
|
|
2995
|
+
`}renderMachineChipContent(e,t){if(e===void 0)return E`<span class="context-value">${D(`ui.machineList.noMachineSelected`,`No machine selected`)}</span>`;if(!t)return E`<span class="context-value">${EC(e)}</span>`;let n=DC(e,CC());return E`
|
|
2996
|
+
<img class="context-chip-icon" src=${xC(e)} alt="" @error=${this.hideBrokenIcon} />
|
|
2997
|
+
${this.machines.length>1?E`<span class="context-value">${TC(e)}</span>`:null}
|
|
2998
2998
|
${n===void 0?null:E`<span class=${this.machines.length>1?`context-detail`:`context-value`}>${n}</span>`}
|
|
2999
2999
|
`}renderActionsButton(){return this.onShowActions===void 0?null:E`
|
|
3000
3000
|
<button type="button" class="context-action-button" title="${D(`client.actions.show.actions.a514ad`,`Show actions`)}" aria-label="${D(`client.actions.show.actions.a514ad`,`Show actions`)}" @click=${e=>{e.stopPropagation(),this.onShowActions?.()}}>
|
|
@@ -3032,7 +3032,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3032
3032
|
button { cursor: pointer; }
|
|
3033
3033
|
|
|
3034
3034
|
}
|
|
3035
|
-
`}};w([y({attribute:!1})],X.prototype,`machines`,void 0),w([y({attribute:!1})],X.prototype,`presentationRuntime`,void 0),w([y({attribute:!1})],X.prototype,`presentationContext`,void 0),w([y({attribute:!1})],X.prototype,`machine`,void 0),w([y({type:Boolean})],X.prototype,`locationIndicator`,void 0),w([y({attribute:!1})],X.prototype,`project`,void 0),w([y({type:Boolean})],X.prototype,`workspaceSelectionVisible`,void 0),w([y({attribute:!1})],X.prototype,`workspace`,void 0),w([y({attribute:!1})],X.prototype,`session`,void 0),w([y({attribute:!1})],X.prototype,`refreshControl`,void 0),w([y({attribute:!1})],X.prototype,`onOpenSection`,void 0),w([y({attribute:!1})],X.prototype,`onShowActions`,void 0),w([y({attribute:!1})],X.prototype,`onShowNavigation`,void 0),w([y({type:Boolean})],X.prototype,`hiddenActiveDestination`,void 0),w([S(`.context-items`)],X.prototype,`contextItems`,void 0),w([C()],X.prototype,`canScrollLeft`,void 0),w([C()],X.prototype,`canScrollRight`,void 0),X=w([b(`app-context-bar`)],X);function
|
|
3035
|
+
`}};w([y({attribute:!1})],X.prototype,`machines`,void 0),w([y({attribute:!1})],X.prototype,`presentationRuntime`,void 0),w([y({attribute:!1})],X.prototype,`presentationContext`,void 0),w([y({attribute:!1})],X.prototype,`machine`,void 0),w([y({type:Boolean})],X.prototype,`locationIndicator`,void 0),w([y({attribute:!1})],X.prototype,`project`,void 0),w([y({type:Boolean})],X.prototype,`workspaceSelectionVisible`,void 0),w([y({attribute:!1})],X.prototype,`workspace`,void 0),w([y({attribute:!1})],X.prototype,`session`,void 0),w([y({attribute:!1})],X.prototype,`refreshControl`,void 0),w([y({attribute:!1})],X.prototype,`onOpenSection`,void 0),w([y({attribute:!1})],X.prototype,`onShowActions`,void 0),w([y({attribute:!1})],X.prototype,`onShowNavigation`,void 0),w([y({type:Boolean})],X.prototype,`hiddenActiveDestination`,void 0),w([S(`.context-items`)],X.prototype,`contextItems`,void 0),w([C()],X.prototype,`canScrollLeft`,void 0),w([C()],X.prototype,`canScrollRight`,void 0),X=w([b(`app-context-bar`)],X);function wC(e,t){return e??t.find(e=>e.id===`local`)??t[0]}function TC(e){return e?.name??D(`ui.machineList.noMachineSelected`,`No machine selected`)}function EC(e){return`${e.name}${e.kind===`remote`?D(`ui.appContextBar.remote`,` · Remote`):``}`}function DC(e,t){if(e.kind===`local`||e.baseUrl===void 0)return t;try{return new URL(e.baseUrl).host}catch{return}}function OC(e){return e===void 0?D(`ui.machineList.noMachineSelected`,`No machine selected`):e.baseUrl??e.name}function kC(e){return e?.name??D(`ui.projectList.noProjectSelected`,`No project selected`)}function AC(e){return e===void 0?D(`ui.projectList.noProjectSelected`,`No project selected`):`${e.name} — ${e.path}`}function jC(e){return e===void 0?D(`ui.workspaceList.noWorkspaceSelected`,`No workspace selected`):`${e.label}${e.isMain?D(`ui.appContextBar.mainWorkspace`,` · Main workspace`):``} · ${e.path}`}function MC(e){return e===void 0?D(`ui.workspaceList.noWorkspaceSelected`,`No workspace selected`):`${e.label}${e.isMain?D(`ui.appContextBar.mainWorkspace`,` · Main workspace`):``} — ${e.path}`}function NC(e){let t=e?.name?.trim(),n=e?.firstMessage.trim();return t!==void 0&&t!==``?t:n!==void 0&&n!==``?n:e===void 0?D(`ui.sessionList.noSessionSelected`,`No session selected`):$_(e.id)}function PC(e){return e===void 0?D(`ui.sessionList.noSessionSelected`,`No session selected`):e.path}var FC=class extends O{constructor(){super(),this.tabs=[],this.hiddenActiveDestination=!1,this.selectedTab=`chat`,this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()},v.createController(this)}disconnectedCallback(){this.mobileTabsResizeObserver?.disconnect(),this.mobileTabsResizeObserver=void 0,this.observedMobileTabs=void 0,super.disconnectedCallback()}firstUpdated(){this.observeMobileTabs(),this.updateScrollState()}updated(){this.observeMobileTabs(),this.updateScrollState()}render(){let e=this.fallbackLabels();return E`
|
|
3036
3036
|
<div class=${this.frameClass()}>
|
|
3037
3037
|
<div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
|
|
3038
3038
|
${this.tabs.map(t=>{let n=this.selectedTab===t.id;return E`
|
|
@@ -3042,10 +3042,10 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3042
3042
|
${this.renderBadge(t.badge,t.badgeTone)}
|
|
3043
3043
|
</button>
|
|
3044
3044
|
`})}
|
|
3045
|
-
${this.onShowNavigation===void 0?null:E`<button type="button" class=${`navigation-menu-button${this.hiddenActiveDestination?` selected`:``}`} title="${D(`ui.main.99aaea15ca9e`,`Open Navigation`)}" aria-label="${D(`ui.main.99aaea15ca9e`,`Open Navigation`)}" aria-haspopup="dialog" aria-pressed=${String(this.hiddenActiveDestination)} @click=${this.onShowNavigation}>${
|
|
3045
|
+
${this.onShowNavigation===void 0?null:E`<button type="button" class=${`navigation-menu-button${this.hiddenActiveDestination?` selected`:``}`} title="${D(`ui.main.99aaea15ca9e`,`Open Navigation`)}" aria-label="${D(`ui.main.99aaea15ca9e`,`Open Navigation`)}" aria-haspopup="dialog" aria-pressed=${String(this.hiddenActiveDestination)} @click=${this.onShowNavigation}>${_C()}</button>`}
|
|
3046
3046
|
</div>
|
|
3047
3047
|
</div>
|
|
3048
|
-
`}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.selectedTab===e.id?[`selected`]:[]].join(` `)}tabAriaLabel(e){let t=e.badgeLabel??(typeof e.badge==`string`||typeof e.badge==`number`?String(e.badge).trim():``);return t===``?e.label:`${e.label}, ${t}`}renderBadge(e,t){return e===void 0||e===``?null:E`<span class=${`tab-badge${t===void 0?``:` ${t}`}`}>${e}</span>`}renderTabMark(e,t){return e.icon===void 0?E`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:
|
|
3048
|
+
`}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.selectedTab===e.id?[`selected`]:[]].join(` `)}tabAriaLabel(e){let t=e.badgeLabel??(typeof e.badge==`string`||typeof e.badge==`number`?String(e.badge).trim():``);return t===``?e.label:`${e.label}, ${t}`}renderBadge(e,t){return e===void 0||e===``?null:E`<span class=${`tab-badge${t===void 0?``:` ${t}`}`}>${e}</span>`}renderTabMark(e,t){return e.icon===void 0?E`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:vC(e.icon)}fallbackLabels(){let e=this.tabs.filter(e=>e.icon===void 0),t=new Map;for(let n of e){let e=this.initialsLabel(n.label);t.set(e,(t.get(e)??0)+1)}let n=new Map;for(let r of e){let e=this.initialsLabel(r.label);n.set(r.id,(t.get(e)??0)>1?this.fullFallbackLabel(r.label):e)}return n}initialsLabel(e){let t=(e.match(/[\p{L}\p{N}]+/gu)??[]).map(e=>Array.from(e)[0]??``).join(``).toLocaleUpperCase();return t===``?`?`:t}fullFallbackLabel(e){let t=e.trim();return t===``?`?`:t}observeMobileTabs(){let e=this.mobileTabsElement();this.observedMobileTabs!==e&&(this.mobileTabsResizeObserver?.disconnect(),this.observedMobileTabs=e,this.mobileTabsResizeObserver=void 0,e!==void 0&&typeof ResizeObserver<`u`&&(this.mobileTabsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.mobileTabsResizeObserver.observe(e)))}updateScrollState(){let e=this.mobileTabsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=e!==void 0&&e.scrollLeft>1,r=e!==void 0&&t-e.scrollLeft>1;this.canScrollLeft!==n&&(this.canScrollLeft=n),this.canScrollRight!==r&&(this.canScrollRight=r)}mobileTabsElement(){let e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}static{this.styles=T`
|
|
3049
3049
|
@layer pi-web-base {
|
|
3050
3050
|
:host { flex: 0 0 auto; min-width: 0; }
|
|
3051
3051
|
.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); }
|
|
@@ -3077,7 +3077,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3077
3077
|
}
|
|
3078
3078
|
|
|
3079
3079
|
}
|
|
3080
|
-
`}};w([y({attribute:!1})],
|
|
3080
|
+
`}};w([y({attribute:!1})],FC.prototype,`tabs`,void 0),w([y({attribute:!1})],FC.prototype,`onShowNavigation`,void 0),w([y({type:Boolean})],FC.prototype,`hiddenActiveDestination`,void 0),w([y({attribute:!1})],FC.prototype,`selectedTab`,void 0),w([y({attribute:!1})],FC.prototype,`onSelect`,void 0),w([S(`.mobile-tabs`)],FC.prototype,`mobileTabs`,void 0),w([C()],FC.prototype,`canScrollLeft`,void 0),w([C()],FC.prototype,`canScrollRight`,void 0),FC=w([b(`app-mobile-main-tabs`)],FC);var IC=class extends O{constructor(){super(),this.tabs=[],this.preferences={pinnedIds:[],mobileCollapsed:!1},this.query=``,this.selectedIndex=0,this.navigateDestinations=e=>{if(e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let t=e.target;if(t instanceof HTMLInputElement){let t=this.filteredTabs();switch(e.key){case`ArrowDown`:this.selectedIndex=t.length>0?(this.selectedIndex+1)%t.length:0;break;case`ArrowUp`:this.selectedIndex=t.length>0?(this.selectedIndex+t.length-1)%t.length:0;break;case`Home`:this.selectedIndex=0;break;case`End`:this.selectedIndex=Math.max(0,t.length-1);break;case`Enter`:{let e=t[this.selectedIndex];e!==void 0&&this.select(e);break}default:return}e.preventDefault(),e.stopPropagation();return}if(!(t instanceof HTMLButtonElement))return;let n=t.classList.contains(`pin-button`)?`.pin-button`:`.destination-button`,r=[...this.renderRoot.querySelectorAll(n)],i=r.indexOf(t);if(i<0)return;let a;switch(e.key){case`ArrowDown`:a=(i+1)%r.length;break;case`ArrowUp`:a=(i+r.length-1)%r.length;break;case`Home`:a=0;break;case`End`:a=r.length-1;break;default:return}e.preventDefault(),e.stopPropagation(),r[a]?.focus(),r[a]?.scrollIntoView({block:`nearest`})},v.createController(this)}filteredTabs(){let e=this.query.trim().toLowerCase();return this.tabs.filter(t=>t.label.toLowerCase().includes(e))}willUpdate(e){e.has(`selectedTab`)&&(this.selectedIndex=Math.max(0,this.filteredTabs().findIndex(e=>e.id===this.selectedTab))),this.selectedIndex=Math.min(this.selectedIndex,Math.max(0,this.filteredTabs().length-1))}select(e){this.onSelect?.(e.id),this.onClose?.()}render(){let e=this.filteredTabs();return E`
|
|
3081
3081
|
<modal-surface .label=${D(`client.actions.navigation.e72622`,`Navigation`)} .initialFocus=${`input`} .onClose=${this.onClose} @keydown=${this.navigateDestinations}>
|
|
3082
3082
|
<header class="ui-dialog-header">
|
|
3083
3083
|
<input class="ui-dialog-search" aria-label="${D(`ui.main.cf6ca6ffaff0`,`Search navigation`)}" aria-describedby="navigation-selection" placeholder="${D(`ui.main.5bb0ee874a51`,`Search navigation...`)}" .value=${this.query} @input=${e=>{e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}}>
|
|
@@ -3090,8 +3090,8 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3090
3090
|
${e.map((e,t)=>E`
|
|
3091
3091
|
<div class="destination ui-selection-row">
|
|
3092
3092
|
<button class=${`destination-button ui-button ui-selection-option ${t===this.selectedIndex?`selected`:``}`} aria-current=${e.id===this.selectedTab?`page`:k} aria-pressed=${String(e.id===this.selectedTab)} ${yt(t===this.selectedIndex,e.id)} @focus=${()=>{this.selectedIndex=t}} @click=${()=>{this.select(e)}}>${e.label}</button>
|
|
3093
|
-
<button type="button" class="pin-button ui-button ui-button--icon" aria-label=${
|
|
3094
|
-
<svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill=${
|
|
3093
|
+
<button type="button" class="pin-button ui-button ui-button--icon" aria-label=${o_(e.id,this.preferences.pinnedIds)?D(`ui.main.d6686d214b38`,`Unpin: {arg0}`,{arg0:e.label}):D(`ui.main.4fe1972f5fb0`,`Pin: {arg0}`,{arg0:e.label})} title=${o_(e.id,this.preferences.pinnedIds)?D(`ui.main.09250f2cdb60`,`Unpin`):D(`ui.main.63d21f5557f8`,`Pin to tab bar`)} aria-pressed=${String(o_(e.id,this.preferences.pinnedIds))} @click=${()=>{this.onPreferencesChange?.({...this.preferences,pinnedIds:l_(e.id,this.preferences.pinnedIds,this.pinUniverse??this.tabs.map(e=>e.id))})}}>
|
|
3094
|
+
<svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill=${o_(e.id,this.preferences.pinnedIds)?`currentColor`:`none`} stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
|
3095
3095
|
<path d="M8 3h8l-1 7 4 4v2H5v-2l4-4-1-7Z"></path><path d="M12 16v6"></path>
|
|
3096
3096
|
</svg>
|
|
3097
3097
|
</button>
|
|
@@ -3121,7 +3121,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3121
3121
|
.mobile-navigation { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; font-size: 12px; }
|
|
3122
3122
|
|
|
3123
3123
|
}
|
|
3124
|
-
`]}};w([y({attribute:!1})],
|
|
3124
|
+
`]}};w([y({attribute:!1})],IC.prototype,`tabs`,void 0),w([y({attribute:!1})],IC.prototype,`pinUniverse`,void 0),w([y({attribute:!1})],IC.prototype,`preferences`,void 0),w([y({attribute:!1})],IC.prototype,`selectedTab`,void 0),w([y({attribute:!1})],IC.prototype,`onSelect`,void 0),w([y({attribute:!1})],IC.prototype,`onPreferencesChange`,void 0),w([y({attribute:!1})],IC.prototype,`onClose`,void 0),w([C()],IC.prototype,`query`,void 0),w([C()],IC.prototype,`selectedIndex`,void 0),IC=w([b(`navigation-dialog`)],IC);var LC=`pi-web:navigation-section-sizes:v1`,RC=class{constructor(e,t={}){this.host=e,this.storage=t.storage??WC(),this.heights=HC(this.storage),e.addController(this)}hostConnected(){}height(e){return this.heights[e]}resize(e,t){if(!Number.isFinite(t))return;let n=VC(t);this.heights[e]!==n&&(this.heights[e]=n,this.persist(),this.host.requestUpdate())}reset(e){this.heights[e]!==void 0&&(e===`projects`?delete this.heights.projects:delete this.heights.workspaces,this.persist(),this.host.requestUpdate())}persist(){try{this.heights.projects===void 0&&this.heights.workspaces===void 0?this.storage?.removeItem(LC):this.storage?.setItem(LC,JSON.stringify({version:1,...this.heights}))}catch{}}};function zC(e,t,n){return VC(e+n-t)}function BC(e,t,n={}){if(t===`Home`)return 44;let r=n.largeStep===!0?72:24;if(t===`ArrowUp`)return VC(e-r);if(t===`ArrowDown`)return VC(e+r)}function VC(e){return Number.isFinite(e)?Math.max(44,Math.round(e)):44}function HC(e){try{let t=e?.getItem(LC);if(t==null||t===``)return{};let n=JSON.parse(t);if(!UC(n)||n.version!==1)return{};let r={};for(let e of[`projects`,`workspaces`]){let t=n[e];typeof t==`number`&&Number.isFinite(t)&&(r[e]=VC(t))}return r}catch{return{}}}function UC(e){return typeof e==`object`&&!!e}function WC(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}var GC=class extends O{constructor(){super(),this.sectionLabel=``,this.controls=``,this.measurement={height:44,maxHeight:44},this.lastTapAt=0,v.createController(this)}disconnectedCallback(){this.finishResize(),super.disconnectedCallback()}commit(e){let{maxHeight:t}=this.measurement,n=Math.round(Math.max(44,Math.min(e,t)));return this.onResize?.(n),n}pointerDown(e){if(e.button!==0||!(e.currentTarget instanceof HTMLElement))return;e.preventDefault(),e.stopPropagation();let t=e.currentTarget;t.setPointerCapture(e.pointerId),this.active={pointerId:e.pointerId,startY:e.clientY,startHeight:this.measurement.height,handle:t,moved:!1},this.toggleAttribute(`resizing`,!0)}pointerMove(e){if(this.active?.pointerId!==e.pointerId)return;e.preventDefault();let t=e.clientY-this.active.startY;if(Math.abs(t)<=4&&!this.active.moved)return;this.active.moved=!0;let n=this.active.startHeight+t,r=this.commit(zC(this.active.startHeight,this.active.startY,e.clientY));(n<44||n>this.measurement.maxHeight)&&(this.active.startY=e.clientY,this.active.startHeight=r)}pointerUp(e){let t=this.active;if(t?.pointerId===e.pointerId){if(this.finishResize(),t.moved)this.lastTapAt=0;else{let e=Date.now();e-this.lastTapAt<=420?(this.lastTapAt=0,this.onReset?.()):this.lastTapAt=e}}}finishResize(){let e=this.active;e!==void 0&&(this.active=void 0,e.handle.hasPointerCapture(e.pointerId)&&e.handle.releasePointerCapture(e.pointerId),this.toggleAttribute(`resizing`,!1))}keyDown(e){let{height:t,maxHeight:n}=this.measurement,r=e.key===`End`?n:BC(t,e.key,{largeStep:e.shiftKey});r!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commit(r))}render(){return E`<div
|
|
3125
3125
|
role="separator" tabindex="0" aria-orientation="horizontal"
|
|
3126
3126
|
aria-label=${D(`ui.navigation.resizeSection`,`Resize {section}`,{section:this.sectionLabel})}
|
|
3127
3127
|
title=${D(`ui.navigation.resizeSectionReset`,`Resize {section}. Double-click or double-tap to reset.`,{section:this.sectionLabel})}
|
|
@@ -3142,18 +3142,18 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3142
3142
|
[role="separator"]::after { content: ""; position: absolute; top: 50%; inset-inline: 0; height: 1px; transform: translateY(-50%); background: transparent; transition: height .12s ease, background .12s ease, opacity .12s ease; }
|
|
3143
3143
|
[role="separator"]:hover::after, [role="separator"]:focus-visible::after,
|
|
3144
3144
|
:host([resizing]) [role="separator"]::after { height: 3px; background: var(--pi-accent); opacity: .72; }
|
|
3145
|
-
`}};w([y()],
|
|
3145
|
+
`}};w([y()],GC.prototype,`sectionLabel`,void 0),w([y()],GC.prototype,`controls`,void 0),w([y({attribute:!1})],GC.prototype,`measurement`,void 0),w([y({attribute:!1})],GC.prototype,`onResize`,void 0),w([y({attribute:!1})],GC.prototype,`onReset`,void 0),GC=w([b(`navigation-section-resize-handle`)],GC);function KC(e,t,n){if(n===void 0)return null;let r=e===`navigation`?t?D(`ui.navigation.expandPanel`,`Expand navigation panel`):D(`ui.navigation.collapsePanel`,`Collapse navigation panel`):t?D(`ui.workspacePanel.expandPanel`,`Expand workspace panel`):D(`ui.workspacePanel.collapsePanel`,`Collapse workspace panel`),i=e===`navigation`?!t:t,a=typeof document<`u`&&document.documentElement.dir===`rtl`?!i:i;return E`
|
|
3146
3146
|
<button type="button" class="panel-toggle ui-button ui-button--icon"
|
|
3147
3147
|
data-panel-toggle=${e} title=${r} aria-label=${r}
|
|
3148
3148
|
aria-controls=${`${e}-panel`} aria-expanded=${String(!t)} @click=${n}>
|
|
3149
3149
|
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d=${a?`M15 18l-6-6 6-6`:`M9 18l6-6-6-6`}/></svg>
|
|
3150
3150
|
</button>
|
|
3151
|
-
`}var
|
|
3151
|
+
`}var qC=class extends O{constructor(){super(),this.actionsPopup=new D_(this,()=>{let e=this.shadowRoot?.querySelector(`.machine-option-actions-panel`);return e&&this.actionMenuAnchor?{anchor:this.actionMenuAnchor,panel:e,onClose:()=>{this.openActionsMachineId=void 0},options:{minWidth:120}}:void 0}),this.popup=new D_(this,()=>{let e=this.shadowRoot?.querySelector(`.machine-switcher-menu`);return e&&this.menuAnchor?{anchor:this.menuAnchor,panel:e,onClose:()=>{this.open=!1,this.openActionsMachineId=void 0},options:{minWidth:120}}:void 0}),this.machines=[],this.locationIndicator=!1,this.statuses={},this.activities={},this.unreadMachineIds=new Set,this.statusSnapshots={},this.open=!1,this.hideBrokenIcon=e=>{e.currentTarget instanceof HTMLImageElement&&(e.currentTarget.style.display=`none`)},v.createController(this)}connectedCallback(){super.connectedCallback()}disconnectedCallback(){super.disconnectedCallback()}updated(e){e.has(`machines`)&&this.open&&this.selectedMachine()===void 0&&(this.open=!1),e.has(`machines`)&&this.open&&this.machines.length<=1&&(this.open=!1),e.has(`machines`)&&this.openActionsMachineId!==void 0&&!this.machines.some(e=>e.id===this.openActionsMachineId)&&(this.openActionsMachineId=void 0)}async focusSelectedOrFirst(){let e=this.switcherButton();return e!==null&&await this.openMenuAndFocusOption(e)}render(){let e=this.selectedMachine();if(this.machines.length<=1)return this.renderMachineInfo(e??{id:`local`,name:`PI-WEB`,kind:`local`,createdAt:``,updatedAt:``});if(e===void 0)return null;let t=JC(e,this.statuses),n=e.name;return E`
|
|
3152
3152
|
<div class="machine-switcher">
|
|
3153
3153
|
<button
|
|
3154
3154
|
type="button"
|
|
3155
3155
|
class=${`machine-switcher-button ${t===`offline`||t===`error`?`disconnected`:``}`}
|
|
3156
|
-
title=${`${e.name} · ${
|
|
3156
|
+
title=${`${e.name} · ${ZC(e)} · ${YC(t)}`}
|
|
3157
3157
|
aria-label=${this.machineSwitcherAriaLabel(e)}
|
|
3158
3158
|
aria-expanded=${String(this.open)}
|
|
3159
3159
|
@click=${e=>{this.toggleMenu(e.currentTarget)}}
|
|
@@ -3174,18 +3174,18 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3174
3174
|
</div>
|
|
3175
3175
|
`:null}
|
|
3176
3176
|
</div>
|
|
3177
|
-
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=
|
|
3177
|
+
`}renderMachineOption(e){let t=this.selected?.id===e.id,n=JC(e,this.statuses),r=G_(e)&&this.onRemove!==void 0,i=this.openActionsMachineId===e.id;return E`
|
|
3178
3178
|
<div class=${`machine-option ${t?`selected`:``} ${r?``:`no-actions`}`}>
|
|
3179
3179
|
<button
|
|
3180
3180
|
type="button"
|
|
3181
3181
|
class="ui-button ui-menu-item machine-option-main"
|
|
3182
|
-
title=${
|
|
3182
|
+
title=${XC(e)}
|
|
3183
3183
|
data-machine-id=${e.id}
|
|
3184
3184
|
@click=${()=>{this.select(e)}}
|
|
3185
3185
|
@keydown=${e=>{this.handleMachineOptionKeydown(e)}}
|
|
3186
3186
|
>
|
|
3187
3187
|
<span class="machine-option-name">${this.renderMachineIcon(e)}${this.renderActivity(e)}<span>${e.name}</span></span>
|
|
3188
|
-
<small>${
|
|
3188
|
+
<small>${ZC(e)} · ${YC(n)}</small>
|
|
3189
3189
|
</button>
|
|
3190
3190
|
${r?E`
|
|
3191
3191
|
<div class="machine-option-actions">
|
|
@@ -3205,16 +3205,16 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3205
3205
|
</div>
|
|
3206
3206
|
`:null}
|
|
3207
3207
|
</div>
|
|
3208
|
-
`}renderMachineInfo(e){let t=
|
|
3209
|
-
<div class=${`machine-info ${t===`offline`||t===`error`?`disconnected`:``}`} title=${`${e.name} · ${
|
|
3208
|
+
`}renderMachineInfo(e){let t=JC(e,this.statuses);return E`
|
|
3209
|
+
<div class=${`machine-info ${t===`offline`||t===`error`?`disconnected`:``}`} title=${`${e.name} · ${ZC(e)} · ${YC(t)}`}>
|
|
3210
3210
|
${this.renderMachineIcon(e)}
|
|
3211
3211
|
${this.renderActivity(e)}
|
|
3212
3212
|
<span class="machine-switcher-text">
|
|
3213
3213
|
<span class="machine-switcher-label"><bdi>${e.name}</bdi></span>
|
|
3214
|
-
${this.locationIndicator?E`<span class="machine-info-url"><bdi dir="ltr">${
|
|
3214
|
+
${this.locationIndicator?E`<span class="machine-info-url"><bdi dir="ltr">${ZC(e)}</bdi></span>`:null}
|
|
3215
3215
|
</span>
|
|
3216
3216
|
</div>
|
|
3217
|
-
`}renderMachineIcon(e){let t=
|
|
3217
|
+
`}renderMachineIcon(e){let t=JC(e,this.statuses);return E`<img class=${t===`offline`||t===`error`?`machine-icon dimmed`:`machine-icon`} src=${xC(e)} alt="" @error=${this.hideBrokenIcon} />`}renderActivity(e){let t=JC(e,this.statuses),n=this.statusSnapshots[e.id],r=n?.machine,i=t===`offline`||t===`error`?void 0:n===void 0?fr(this.activities[e.id]):w_(r),a=n===void 0?this.unreadMachineIds.has(e.id)?D(`ui.machineSwitcher.unreadSessionsOnThisMachine`,`Unread sessions on this machine`):void 0:T_(r)?D(`ui.machineSwitcher.unreadSessionsOnThisMachine`,`Unread sessions on this machine`):void 0;return S_(i,i===`terminal`?D(`ui.machineSwitcher.machineTerminalActive`,`Machine terminal active`):D(`ui.machineSwitcher.machineActive`,`Machine active`),a)}renderOtherMachinesActivity(e){let t=this.machines.filter(t=>t.id!==e.id),n=t.filter(e=>![`offline`,`error`].includes(JC(e,this.statuses))).map(e=>this.statusSnapshots[e.id]===void 0?fr(this.activities[e.id]):w_(this.statusSnapshots[e.id]?.machine)),r=n.includes(`session`)?`session`:n.includes(`terminal`)?`terminal`:void 0,i=t.some(e=>this.statusSnapshots[e.id]===void 0?this.unreadMachineIds.has(e.id):T_(this.statusSnapshots[e.id]?.machine)),a=S_(r,r===`terminal`?D(`ui.navigation.otherMachinesTerminalActive`,`Terminal active on other machines`):D(`ui.navigation.otherMachinesActive`,`Other machines active`),i?D(`ui.navigation.otherMachinesUnread`,`Unread sessions on other machines`):void 0);return a===void 0?void 0:E`<span class="other-machines-activity">${a}</span>`}selectedMachine(){return this.selected??this.machines.find(e=>e.id===`local`)??this.machines[0]}machineSwitcherAriaLabel(e){return D(`ui.navigation.machineSwitchStatus`,`Machine: {name}. {status}. Switch machine.`,{name:e.name,status:YC(JC(e,this.statuses))})}switcherButton(){return this.renderRoot.querySelector(`.machine-switcher-button`)}handleSwitcherButtonKeydown(e){e.key===`ArrowDown`||e.key===`ArrowUp`?(e.preventDefault(),e.stopPropagation(),this.openMenuAndFocusOption(e.currentTarget)):e.key===`ArrowRight`&&this.onFocusNextSection!==void 0?(e.preventDefault(),e.stopPropagation(),this.onFocusNextSection()):e.key===`Escape`&&this.onCancelKeyboardNavigation!==void 0&&(e.preventDefault(),e.stopPropagation(),this.onCancelKeyboardNavigation())}handleMachineOptionKeydown(e){e.key===`ArrowUp`?this.focusRelativeMachineOption(e.currentTarget,-1,e):e.key===`ArrowDown`?this.focusRelativeMachineOption(e.currentTarget,1,e):e.key===`Home`?this.focusIndexedMachineOption(0,e):e.key===`End`?this.focusIndexedMachineOption(-1,e):e.key===`ArrowRight`&&this.onFocusNextSection!==void 0?(e.preventDefault(),e.stopPropagation(),this.open=!1,this.onFocusNextSection()):(e.key===`ArrowLeft`||e.key===`Escape`)&&(e.preventDefault(),e.stopPropagation(),this.open=!1,this.updateComplete.then(()=>{this.focusSwitcherButton()}))}toggleMenu(e){this.menuAnchor=e instanceof HTMLElement?e:void 0,this.open=!this.open,this.openActionsMachineId=void 0}focusSwitcherButton(){let e=this.switcherButton();return e!==null&&(e.focus(),!0)}async openMenuAndFocusOption(e){return this.menuAnchor=e instanceof HTMLElement?e:void 0,this.open=!0,this.openActionsMachineId=void 0,await this.updateComplete,this.focusSelectedMachineOption()}focusSelectedMachineOption(){let e=this.renderRoot.querySelector(`.machine-option.selected .machine-option-main`),t=this.machineOptionButtons()[0],n=e??t;return n!==void 0&&(n.focus(),n.scrollIntoView({block:`nearest`}),!0)}focusRelativeMachineOption(e,t,n){n.preventDefault(),n.stopPropagation();let r=this.machineOptionButtons();if(r.length===0||!(e instanceof HTMLElement))return;let i=r.indexOf(e);i<0||this.focusMachineOptionAt(i+t)}focusIndexedMachineOption(e,t){t.preventDefault(),t.stopPropagation(),this.focusMachineOptionAt(e<0?this.machineOptionButtons().length-1:e)}focusMachineOptionAt(e){let t=this.machineOptionButtons(),n=t[Math.min(Math.max(e,0),t.length-1)];n?.focus(),n?.scrollIntoView({block:`nearest`})}machineOptionButtons(){return Array.from(this.renderRoot.querySelectorAll(`.machine-option-main`))}toggleActionsMenu(e,t){this.openActionsMachineId===e?this.openActionsMachineId=void 0:(this.actionMenuAnchor=t instanceof HTMLElement?t:void 0,this.openActionsMachineId=e)}select(e){this.open=!1,this.openActionsMachineId=void 0,this.onSelect?.(e)}removeMachine(e){this.open=!1,this.openActionsMachineId=void 0,this.onRemove?.(e)}static{this.styles=[de,f,T`
|
|
3218
3218
|
@layer pi-web-base {
|
|
3219
3219
|
:host { min-width: 0; display: flex; container: machine-selector / inline-size; }
|
|
3220
3220
|
.machine-switcher { flex: 1 1 auto; min-width: 0; display: flex; }
|
|
@@ -3255,17 +3255,17 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3255
3255
|
@keyframes pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
|
|
3256
3256
|
|
|
3257
3257
|
}
|
|
3258
|
-
`]}};w([y({attribute:!1})],
|
|
3258
|
+
`]}};w([y({attribute:!1})],qC.prototype,`machines`,void 0),w([y({attribute:!1})],qC.prototype,`selected`,void 0),w([y({type:Boolean})],qC.prototype,`locationIndicator`,void 0),w([y({attribute:!1})],qC.prototype,`statuses`,void 0),w([y({attribute:!1})],qC.prototype,`activities`,void 0),w([y({attribute:!1})],qC.prototype,`unreadMachineIds`,void 0),w([y({attribute:!1})],qC.prototype,`statusSnapshots`,void 0),w([y({attribute:!1})],qC.prototype,`onSelect`,void 0),w([y({attribute:!1})],qC.prototype,`onRemove`,void 0),w([y({attribute:!1})],qC.prototype,`onFocusNextSection`,void 0),w([y({attribute:!1})],qC.prototype,`onCancelKeyboardNavigation`,void 0),w([C()],qC.prototype,`open`,void 0),w([C()],qC.prototype,`openActionsMachineId`,void 0),qC=w([b(`machine-switcher`)],qC);function JC(e,t){return t[e.id]?.status??e.status??`unknown`}function YC(e){return e===`online`?D(`ui.machineSwitcher.online`,`Online`):e===`offline`?D(`ui.machineSwitcher.offline`,`Offline`):e===`error`?D(`client.sessionNotifications.error.0bc1fb`,`Error`):D(`bundled.updates.unknown.4d8c1c`,`Unknown`)}function XC(e){return e.baseUrl??e.name}function ZC(e){return e.kind===`local`?CC():e.baseUrl??D(`ui.machineSwitcher.remotePiWeb`,`Remote PI WEB`)}var Z=class extends O{constructor(){super(),this.machines=[],this.presentationContext={mode:`normal`},this.locationIndicator=!1,this.machineStatuses={},this.machineActivities={},this.machineStatusSnapshots={},this.projects=[],this.workspaces=[],this.sessions=[],this.pinnedSessionIds=[],this.pinnedRootIds=[],this.workspaceSelectionVisible=!0,this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.unreadSessionIds=new Set,this.unreadPresence=uu,this.workspacesByProjectId={},this.deletingWorkspaceIds=[],this.workspaceLabelItems=()=>[],this.sessionLabelItems=()=>[],this.collapsible=!1,this.compact=!1,this.showBrand=!0,this.managementMode=!1,this.machinesCollapsed=!1,this.projectsCollapsed=!1,this.workspacesCollapsed=!1,this.sessionsCollapsed=!1,this.startingSessionCount=0,this.canStartSession=!1,this.canDeleteArchivedSessions=!1,this.canReloadSessions=!1,this.canCleanupSessions=!1,this.authoritativeSessionPersistence=!1,this.archivedDeleteUnavailableMessage=D(`ui.appNavigationPanel.updateAndRestartPiWebOnThisMachine2`,`Update and restart Pi-Web on this machine before deleting archived sessions.`),this.cleanupUnavailableMessage=D(`ui.appNavigationPanel.updateAndRestartPiWebOnThisMachine`,`Update and restart Pi-Web on this machine before cleaning up sessions.`),this.sectionSizes=new RC(this),this.sectionMeasurements={projects:{height:44,maxHeight:44},workspaces:{height:44,maxHeight:44}},this.observedLayoutElements=[],this.presentationActionKey=``,this.presentationActionContext={mode:`normal`},this.childCallbacks={moveProject:(e,t)=>this.onMoveProject?.(e,t),moveWorkspace:(e,t)=>this.onMoveWorkspace?.(e,t),moveSessionPin:(e,t)=>this.onMoveSessionPin?.(e,t),toggleProjects:()=>{this.onToggleProjects?.()},selectProject:e=>this.onSelectProject?.(e),closeProject:e=>this.onCloseProject?.(e),toggleWorkspaces:()=>{this.onToggleWorkspaces?.()},selectWorkspace:e=>this.onSelectWorkspace?.(e),deleteWorkspace:e=>this.onDeleteWorkspace?.(e),toggleSessions:()=>{this.onToggleSessions?.()},archivedCollapsed:()=>this.onArchivedCollapsed?.(),startSession:()=>this.onStartSession?.(),selectSession:e=>this.onSelectSession?.(e),searchSessions:()=>this.onSearchSessions?.(),toggleSessionPin:e=>this.onToggleSessionPin?.(e),renameSession:(e,t)=>this.onRenameSession?.(e,t),archiveSession:e=>this.onArchiveSession?.(e),archiveSessionWithDescendants:e=>this.onArchiveSessionWithDescendants?.(e),archiveSessions:e=>this.onArchiveSessions?.(e),restoreSession:e=>this.onRestoreSession?.(e),deleteCachedNewSession:e=>this.onDeleteCachedNewSession?.(e),deleteArchivedSession:e=>this.onDeleteArchivedSession?.(e),deleteArchivedSessions:e=>this.onDeleteArchivedSessions?.(e),detachParentSession:e=>this.onDetachParentSession?.(e),markSessionRead:e=>this.onMarkSessionRead?.(e),markSessionsRead:e=>this.onMarkSessionsRead?.(e),reloadSession:e=>this.onReloadSession?.(e),cleanupSessions:()=>this.onCleanupSessions?.(),previousFromProjects:()=>{this.focusPreviousFrom(`projects`)},nextFromProjects:()=>{this.focusNextFrom(`projects`)},previousFromWorkspaces:()=>{this.focusPreviousFrom(`workspaces`)},nextFromWorkspaces:()=>{this.focusNextFrom(`workspaces`)},previousFromSessions:()=>{this.focusPreviousFrom(`sessions`)},nextFromSessions:()=>{this.focusNextFrom(`sessions`)},cancelKeyboardNavigation:()=>{this.cancelKeyboardNavigation()}},this.treeChildInputs=[],this.filteredWorkspaces=[],this.filteredSessions=[],v.createController(this)}connectedCallback(){super.connectedCallback(),this.subscribePresentation(),typeof ResizeObserver<`u`&&(this.layoutObserver=new ResizeObserver(()=>{this.refreshSectionMeasurements()}),this.requestUpdate())}disconnectedCallback(){this.unsubscribePresentation?.(),this.unsubscribePresentation=void 0,this.layoutObserver?.disconnect(),this.layoutObserver=void 0,this.observedLayoutElements=[],this.clearTreeCache(),super.disconnectedCallback()}willUpdate(e){e.has(`presentationRuntime`)&&this.subscribePresentation();let t=this.presentationRuntime?.navigationLayout();t===void 0?(this.removeAttribute(`data-navigation-layout`),this.clearTreeCache()):this.setAttribute(`data-navigation-layout`,t)}subscribePresentation(){this.unsubscribePresentation?.(),this.unsubscribePresentation=this.isConnected?this.presentationRuntime?.subscribe(()=>{this.requestUpdate()}):void 0}navigationPresentationContext(){let e=JSON.stringify([this.canStartSession,this.onStartSession!==void 0,this.onSearchSessions!==void 0,this.managementMode,this.onAddProject!==void 0,this.onShowSettings!==void 0]);if(e===this.presentationActionKey&&this.presentationActionSource===this.presentationContext)return this.presentationActionContext;let t=[];return this.onStartSession!==void 0&&t.push({id:`new-task`,label:D(`client.sessionController.new.session.c57c30`,`New session`),disabled:!this.canStartSession,run:()=>this.onStartSession?.()}),this.onSearchSessions!==void 0&&t.push({id:`search`,label:D(`ui.sessionSearchDialog.searchSessions`,`Search sessions`),run:()=>{this.onSearchSessions?.()}}),!this.managementMode&&this.onAddProject!==void 0&&t.push({id:`add-project`,label:D(`client.actions.add.project.8964f5`,`Add project`),run:()=>{this.onAddProject?.()}}),this.onShowSettings!==void 0&&t.push({id:`settings`,label:D(`ui.settingsDialog.settings`,`Settings`),run:()=>{this.onShowSettings?.()}}),this.presentationActionKey=e,this.presentationActionSource=this.presentationContext,this.presentationActionContext=Object.freeze({...this.presentationContext,actions:Object.freeze(t)}),this.presentationActionContext}updated(){if(this.layoutObserver===void 0)return;let e=[this,...this.renderRoot.querySelectorAll(`header, machine-list, project-list, workspace-list, session-list`)];if(!(e.length===this.observedLayoutElements.length&&e.every((e,t)=>e===this.observedLayoutElements[t]))){this.layoutObserver.disconnect();for(let t of e)this.layoutObserver.observe(t);this.observedLayoutElements=e}}refreshSectionMeasurements(){let e=this.measureSection(`projects`),t=this.measureSection(`workspaces`);(e.height!==this.sectionMeasurements.projects.height||e.maxHeight!==this.sectionMeasurements.projects.maxHeight||t.height!==this.sectionMeasurements.workspaces.height||t.maxHeight!==this.sectionMeasurements.workspaces.maxHeight)&&(this.sectionMeasurements={projects:e,workspaces:t})}sectionSizeStyle(e){let t=this.sectionSizes.height(e);return this.compact||t===void 0?{}:{"--navigation-section-height":`${String(t)}px`}}renderSectionResizeHandle(e){return this.compact?null:E`<navigation-section-resize-handle
|
|
3259
3259
|
slot=${e===`projects`?`project-resize`:`workspace-resize`}
|
|
3260
3260
|
.sectionLabel=${e===`projects`?D(`ui.projectList.projects`,`Projects`):D(`ui.workspaceList.workspaces`,`Workspaces`)}
|
|
3261
3261
|
.controls=${`navigation-${e}`}
|
|
3262
3262
|
.measurement=${this.sectionMeasurements[e]}
|
|
3263
3263
|
.onResize=${t=>{this.sectionSizes.resize(e,t)}}
|
|
3264
3264
|
.onReset=${()=>{this.sectionSizes.reset(e)}}
|
|
3265
|
-
></navigation-section-resize-handle>`}measureSection(e){let t=this.renderRoot.querySelector(`#navigation-${e}`)?.getBoundingClientRect().height??44,n=this.sessionList?.getBoundingClientRect().height??44;return{height:t,maxHeight:Math.max(44,t+n-44)}}get workspaceList(){return this.renderRoot.querySelector(`workspace-list`)??this.renderRoot.querySelector(`project-list`)?.shadowRoot?.querySelector(`workspace-list`)??void 0}get sessionList(){return this.renderRoot.querySelector(`session-list`)??this.workspaceList?.shadowRoot?.querySelector(`session-list`)??this.renderRoot.querySelector(`project-list`)?.shadowRoot?.querySelector(`session-list`)??void 0}automaticSessionCandidates(e){return this.presentationRuntime?.navigationLayout()!==`tree`&&this.sessionsCollapsed?[]:this.sessionList?.automaticSessionCandidates(e)??[]}async focusSection(e){switch(await this.updateComplete,await this.projectList?.updateComplete,this.presentationRuntime?.navigationLayout()===`tree`&&(e===`workspaces`||e===`sessions`)&&(await this.projectList?.revealSelectedBranch(),e===`sessions`&&await this.workspaceList?.revealSelectedBranch()),e===`sessions`&&await this.workspaceList?.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 this.workspaceSelectionVisible&&await this.focusNavigableSection(this.workspaceList);case`sessions`:return await this.focusNavigableSection(this.sessionList)}}render(){let e=this.presentationRuntime?.navigationLayout()===`tree`,t
|
|
3265
|
+
></navigation-section-resize-handle>`}measureSection(e){let t=this.renderRoot.querySelector(`#navigation-${e}`)?.getBoundingClientRect().height??44,n=this.sessionList?.getBoundingClientRect().height??44;return{height:t,maxHeight:Math.max(44,t+n-44)}}get workspaceList(){return this.renderRoot.querySelector(`workspace-list`)??this.renderRoot.querySelector(`project-list`)?.shadowRoot?.querySelector(`workspace-list`)??void 0}get sessionList(){return this.renderRoot.querySelector(`session-list`)??this.workspaceList?.shadowRoot?.querySelector(`session-list`)??this.renderRoot.querySelector(`project-list`)?.shadowRoot?.querySelector(`session-list`)??void 0}automaticSessionCandidates(e){return this.presentationRuntime?.navigationLayout()!==`tree`&&this.sessionsCollapsed?[]:this.sessionList?.automaticSessionCandidates(e)??[]}async focusSection(e){switch(await this.updateComplete,await this.projectList?.updateComplete,this.presentationRuntime?.navigationLayout()===`tree`&&(e===`workspaces`||e===`sessions`)&&(await this.projectList?.revealSelectedBranch(),e===`sessions`&&await this.workspaceList?.revealSelectedBranch()),e===`sessions`&&await this.workspaceList?.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 this.workspaceSelectionVisible&&await this.focusNavigableSection(this.workspaceList);case`sessions`:return await this.focusNavigableSection(this.sessionList)}}render(){let e=this.presentationRuntime?.navigationLayout()===`tree`,t=$C(this.machines),n=!this.managementMode||t||this.locationIndicator,r=this.refreshControl!==void 0||this.onShowActions!==void 0,i=this.showBrand||n||r||this.onTogglePanel!==void 0;return E`
|
|
3266
3266
|
<pi-web-ui-presentation region="navigation" .runtime=${this.presentationRuntime} .context=${this.navigationPresentationContext()}>
|
|
3267
3267
|
${i?E`<header slot="header">
|
|
3268
|
-
${
|
|
3268
|
+
${KC(`navigation`,!1,this.onTogglePanel)}
|
|
3269
3269
|
${n?E`
|
|
3270
3270
|
<machine-switcher
|
|
3271
3271
|
.machines=${this.machines}
|
|
@@ -3320,7 +3320,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3320
3320
|
slot="projects"
|
|
3321
3321
|
.machineId=${this.selectedMachine?.id??`local`}
|
|
3322
3322
|
id="navigation-projects"
|
|
3323
|
-
style=${
|
|
3323
|
+
style=${Jb(this.sectionSizeStyle(`projects`))}
|
|
3324
3324
|
?data-manual-size=${!this.compact&&this.sectionSizes.height(`projects`)!==void 0}
|
|
3325
3325
|
.projects=${this.projects}
|
|
3326
3326
|
.selected=${this.selectedProject}
|
|
@@ -3343,7 +3343,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3343
3343
|
></project-list>`}clearTreeCache(){this.treeChildContent!==void 0&&(this.treeChildInputs=[],this.treeChildContent=void 0,this.filteredWorkspaceSource=void 0,this.filteredWorkspaces=[],this.filteredSessionSource=void 0,this.filteredSessions=[])}treeChildren(){let e=[this.selectedMachine?.id,this.selectedProject?.id,this.selectedWorkspace,this.workspaceSelectionVisible,this.workspaces,this.workspaceActivities,this.deletingWorkspaceIds,this.unreadPresence.workspaces,this.selectedMachineStatusSnapshot(),this.collapsible,this.workspacesCollapsed,this.workspaceLabelItems,this.managementMode,this.onMoveWorkspace===void 0,this.sessions,this.pinnedSessionIds,this.pinnedRootIds,this.onMoveSessionPin===void 0,this.sessionStatuses,this.sessionActivities,this.sendingPrompts,this.unreadSessionIds,this.selectedSession,this.sessionLabelItems,this.startingSessionCount,this.canStartSession,this.canDeleteArchivedSessions,this.canReloadSessions,this.canCleanupSessions,this.authoritativeSessionPersistence,this.archivedDeleteUnavailableMessage,this.cleanupUnavailableMessage,this.sessionsCollapsed];return this.treeChildContent!==void 0&&e.every((e,t)=>e===this.treeChildInputs[t])||(this.treeChildInputs=e,this.treeChildContent=this.selectedProject===void 0?E``:this.workspaceSelectionVisible?this.renderWorkspaceList(!0):this.selectedWorkspace?.projectId===this.selectedProject.id?this.renderSessionList(!0):E``),this.treeChildContent}treeWorkspaces(){return(this.filteredWorkspaceSource!==this.workspaces||this.filteredWorkspaceProject!==this.selectedProject?.id)&&(this.filteredWorkspaceSource=this.workspaces,this.filteredWorkspaceProject=this.selectedProject?.id,this.filteredWorkspaces=this.workspaces.filter(e=>e.projectId===this.selectedProject?.id)),this.filteredWorkspaces}treeSessions(){let e=this.selectedWorkspace?.projectId===this.selectedProject?.id?this.selectedWorkspace?.path:void 0;return(this.filteredSessionSource!==this.sessions||this.filteredSessionWorkspace!==e)&&(this.filteredSessionSource=this.sessions,this.filteredSessionWorkspace=e,this.filteredSessions=e===void 0?[]:this.sessions.filter(t=>t.cwd===e)),this.filteredSessions}renderWorkspaceList(e){return E`<workspace-list
|
|
3344
3344
|
slot="workspaces"
|
|
3345
3345
|
id="navigation-workspaces"
|
|
3346
|
-
style=${
|
|
3346
|
+
style=${Jb(this.sectionSizeStyle(`workspaces`))}
|
|
3347
3347
|
?data-manual-size=${!this.compact&&this.sectionSizes.height(`workspaces`)!==void 0}
|
|
3348
3348
|
.machineId=${this.selectedMachine?.id??`local`}
|
|
3349
3349
|
.managementMode=${this.managementMode}
|
|
@@ -3368,7 +3368,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3368
3368
|
></workspace-list>`}renderSessionList(e){return E`<session-list
|
|
3369
3369
|
slot="sessions"
|
|
3370
3370
|
.externalScroll=${e}
|
|
3371
|
-
.scopeKey=${
|
|
3371
|
+
.scopeKey=${QC(this.selectedMachine?.id,this.selectedWorkspace?.id)}
|
|
3372
3372
|
.sessions=${e?this.treeSessions():this.sessions}
|
|
3373
3373
|
.pinnedSessionIds=${this.pinnedSessionIds}
|
|
3374
3374
|
.pinnedRootIds=${this.pinnedRootIds}
|
|
@@ -3412,7 +3412,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3412
3412
|
.onFocusPreviousSection=${this.childCallbacks.previousFromSessions}
|
|
3413
3413
|
.onFocusNextSection=${this.childCallbacks.nextFromSessions}
|
|
3414
3414
|
.onCancelKeyboardNavigation=${this.childCallbacks.cancelKeyboardNavigation}
|
|
3415
|
-
></session-list>`}selectedMachineStatusSnapshot(){return this.machineStatusSnapshots[M({selectedMachine:this.selectedMachine})]}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=
|
|
3415
|
+
></session-list>`}selectedMachineStatusSnapshot(){return this.machineStatusSnapshots[M({selectedMachine:this.selectedMachine})]}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=ew(e,this.machines,this.workspaceSelectionVisible);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(tw(e,this.machines,this.workspaceSelectionVisible))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=[de,T`
|
|
3416
3416
|
:host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; container: navigation-panel / inline-size; }
|
|
3417
3417
|
:host([compact]) { flex: 1 1 auto; }
|
|
3418
3418
|
header { flex: 0 0 auto; display: flex; align-items: stretch; min-height: 44px; gap: 0; padding: 0; border-bottom: 1px solid var(--pi-border); }
|
|
@@ -3441,7 +3441,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3441
3441
|
project-list[collapsed],
|
|
3442
3442
|
workspace-list[collapsed],
|
|
3443
3443
|
session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; border-bottom: 0; }
|
|
3444
|
-
`]}};w([y({attribute:!1})],Z.prototype,`machines`,void 0),w([y({attribute:!1})],Z.prototype,`presentationRuntime`,void 0),w([y({attribute:!1})],Z.prototype,`presentationContext`,void 0),w([y({attribute:!1})],Z.prototype,`selectedMachine`,void 0),w([y({type:Boolean})],Z.prototype,`locationIndicator`,void 0),w([y({attribute:!1})],Z.prototype,`machineStatuses`,void 0),w([y({attribute:!1})],Z.prototype,`machineActivities`,void 0),w([y({attribute:!1})],Z.prototype,`machineStatusSnapshots`,void 0),w([y({attribute:!1})],Z.prototype,`projects`,void 0),w([y({attribute:!1})],Z.prototype,`selectedProject`,void 0),w([y({attribute:!1})],Z.prototype,`workspaces`,void 0),w([y({attribute:!1})],Z.prototype,`selectedWorkspace`,void 0),w([y({attribute:!1})],Z.prototype,`sessions`,void 0),w([y({attribute:!1})],Z.prototype,`pinnedSessionIds`,void 0),w([y({attribute:!1})],Z.prototype,`pinnedRootIds`,void 0),w([y({type:Boolean})],Z.prototype,`workspaceSelectionVisible`,void 0),w([y({attribute:!1})],Z.prototype,`onMoveProject`,void 0),w([y({attribute:!1})],Z.prototype,`onMoveWorkspace`,void 0),w([y({attribute:!1})],Z.prototype,`onMoveSessionPin`,void 0),w([y({attribute:!1})],Z.prototype,`onTogglePanel`,void 0),w([y({attribute:!1})],Z.prototype,`selectedSession`,void 0),w([y({attribute:!1})],Z.prototype,`workspaceActivities`,void 0),w([y({attribute:!1})],Z.prototype,`sessionActivities`,void 0),w([y({attribute:!1})],Z.prototype,`sessionStatuses`,void 0),w([y({attribute:!1})],Z.prototype,`sendingPrompts`,void 0),w([y({attribute:!1})],Z.prototype,`unreadSessionIds`,void 0),w([y({attribute:!1})],Z.prototype,`unreadPresence`,void 0),w([y({attribute:!1})],Z.prototype,`workspacesByProjectId`,void 0),w([y({attribute:!1})],Z.prototype,`deletingWorkspaceIds`,void 0),w([y({attribute:!1})],Z.prototype,`workspaceLabelItems`,void 0),w([y({attribute:!1})],Z.prototype,`sessionLabelItems`,void 0),w([y({attribute:!1})],Z.prototype,`refreshControl`,void 0),w([y({type:Boolean,reflect:!0})],Z.prototype,`collapsible`,void 0),w([y({type:Boolean,reflect:!0})],Z.prototype,`compact`,void 0),w([y({type:Boolean})],Z.prototype,`showBrand`,void 0),w([y({type:Boolean})],Z.prototype,`managementMode`,void 0),w([y({type:Boolean})],Z.prototype,`machinesCollapsed`,void 0),w([y({type:Boolean})],Z.prototype,`projectsCollapsed`,void 0),w([y({type:Boolean})],Z.prototype,`workspacesCollapsed`,void 0),w([y({type:Boolean})],Z.prototype,`sessionsCollapsed`,void 0),w([y({type:Number})],Z.prototype,`startingSessionCount`,void 0),w([y({type:Boolean})],Z.prototype,`canStartSession`,void 0),w([y({type:Boolean})],Z.prototype,`canDeleteArchivedSessions`,void 0),w([y({type:Boolean})],Z.prototype,`canReloadSessions`,void 0),w([y({type:Boolean})],Z.prototype,`canCleanupSessions`,void 0),w([y({type:Boolean})],Z.prototype,`authoritativeSessionPersistence`,void 0),w([y({type:String})],Z.prototype,`archivedDeleteUnavailableMessage`,void 0),w([y({type:String})],Z.prototype,`cleanupUnavailableMessage`,void 0),w([y({attribute:!1})],Z.prototype,`onShowActions`,void 0),w([y({attribute:!1})],Z.prototype,`onAddProject`,void 0),w([y({attribute:!1})],Z.prototype,`onShowSettings`,void 0),w([y({attribute:!1})],Z.prototype,`onToggleMachines`,void 0),w([y({attribute:!1})],Z.prototype,`onToggleProjects`,void 0),w([y({attribute:!1})],Z.prototype,`onToggleWorkspaces`,void 0),w([y({attribute:!1})],Z.prototype,`onToggleSessions`,void 0),w([y({attribute:!1})],Z.prototype,`onSelectProject`,void 0),w([y({attribute:!1})],Z.prototype,`onCloseProject`,void 0),w([y({attribute:!1})],Z.prototype,`onSelectWorkspace`,void 0),w([y({attribute:!1})],Z.prototype,`onDeleteWorkspace`,void 0),w([y({attribute:!1})],Z.prototype,`onStartSession`,void 0),w([y({attribute:!1})],Z.prototype,`onSelectSession`,void 0),w([y({attribute:!1})],Z.prototype,`onSearchSessions`,void 0),w([y({attribute:!1})],Z.prototype,`onToggleSessionPin`,void 0),w([y({attribute:!1})],Z.prototype,`onArchiveSession`,void 0),w([y({attribute:!1})],Z.prototype,`onArchiveSessionWithDescendants`,void 0),w([y({attribute:!1})],Z.prototype,`onArchiveSessions`,void 0),w([y({attribute:!1})],Z.prototype,`onRestoreSession`,void 0),w([y({attribute:!1})],Z.prototype,`onDeleteCachedNewSession`,void 0),w([y({attribute:!1})],Z.prototype,`onDeleteArchivedSession`,void 0),w([y({attribute:!1})],Z.prototype,`onDeleteArchivedSessions`,void 0),w([y({attribute:!1})],Z.prototype,`onRenameSession`,void 0),w([y({attribute:!1})],Z.prototype,`onDetachParentSession`,void 0),w([y({attribute:!1})],Z.prototype,`onMarkSessionRead`,void 0),w([y({attribute:!1})],Z.prototype,`onMarkSessionsRead`,void 0),w([y({attribute:!1})],Z.prototype,`onReloadSession`,void 0),w([y({attribute:!1})],Z.prototype,`onCleanupSessions`,void 0),w([y({attribute:!1})],Z.prototype,`onArchivedCollapsed`,void 0),w([y({attribute:!1})],Z.prototype,`onSelectMachine`,void 0),w([y({attribute:!1})],Z.prototype,`onRemoveMachine`,void 0),w([y({attribute:!1})],Z.prototype,`onFocusNavigationTarget`,void 0),w([y({attribute:!1})],Z.prototype,`onCancelKeyboardNavigation`,void 0),w([C()],Z.prototype,`sectionMeasurements`,void 0),w([S(`machine-list`)],Z.prototype,`machineList`,void 0),w([S(`machine-switcher`)],Z.prototype,`machineSwitcher`,void 0),w([S(`project-list`)],Z.prototype,`projectList`,void 0),Z=w([b(`app-navigation-panel`)],Z);function
|
|
3444
|
+
`]}};w([y({attribute:!1})],Z.prototype,`machines`,void 0),w([y({attribute:!1})],Z.prototype,`presentationRuntime`,void 0),w([y({attribute:!1})],Z.prototype,`presentationContext`,void 0),w([y({attribute:!1})],Z.prototype,`selectedMachine`,void 0),w([y({type:Boolean})],Z.prototype,`locationIndicator`,void 0),w([y({attribute:!1})],Z.prototype,`machineStatuses`,void 0),w([y({attribute:!1})],Z.prototype,`machineActivities`,void 0),w([y({attribute:!1})],Z.prototype,`machineStatusSnapshots`,void 0),w([y({attribute:!1})],Z.prototype,`projects`,void 0),w([y({attribute:!1})],Z.prototype,`selectedProject`,void 0),w([y({attribute:!1})],Z.prototype,`workspaces`,void 0),w([y({attribute:!1})],Z.prototype,`selectedWorkspace`,void 0),w([y({attribute:!1})],Z.prototype,`sessions`,void 0),w([y({attribute:!1})],Z.prototype,`pinnedSessionIds`,void 0),w([y({attribute:!1})],Z.prototype,`pinnedRootIds`,void 0),w([y({type:Boolean})],Z.prototype,`workspaceSelectionVisible`,void 0),w([y({attribute:!1})],Z.prototype,`onMoveProject`,void 0),w([y({attribute:!1})],Z.prototype,`onMoveWorkspace`,void 0),w([y({attribute:!1})],Z.prototype,`onMoveSessionPin`,void 0),w([y({attribute:!1})],Z.prototype,`onTogglePanel`,void 0),w([y({attribute:!1})],Z.prototype,`selectedSession`,void 0),w([y({attribute:!1})],Z.prototype,`workspaceActivities`,void 0),w([y({attribute:!1})],Z.prototype,`sessionActivities`,void 0),w([y({attribute:!1})],Z.prototype,`sessionStatuses`,void 0),w([y({attribute:!1})],Z.prototype,`sendingPrompts`,void 0),w([y({attribute:!1})],Z.prototype,`unreadSessionIds`,void 0),w([y({attribute:!1})],Z.prototype,`unreadPresence`,void 0),w([y({attribute:!1})],Z.prototype,`workspacesByProjectId`,void 0),w([y({attribute:!1})],Z.prototype,`deletingWorkspaceIds`,void 0),w([y({attribute:!1})],Z.prototype,`workspaceLabelItems`,void 0),w([y({attribute:!1})],Z.prototype,`sessionLabelItems`,void 0),w([y({attribute:!1})],Z.prototype,`refreshControl`,void 0),w([y({type:Boolean,reflect:!0})],Z.prototype,`collapsible`,void 0),w([y({type:Boolean,reflect:!0})],Z.prototype,`compact`,void 0),w([y({type:Boolean})],Z.prototype,`showBrand`,void 0),w([y({type:Boolean})],Z.prototype,`managementMode`,void 0),w([y({type:Boolean})],Z.prototype,`machinesCollapsed`,void 0),w([y({type:Boolean})],Z.prototype,`projectsCollapsed`,void 0),w([y({type:Boolean})],Z.prototype,`workspacesCollapsed`,void 0),w([y({type:Boolean})],Z.prototype,`sessionsCollapsed`,void 0),w([y({type:Number})],Z.prototype,`startingSessionCount`,void 0),w([y({type:Boolean})],Z.prototype,`canStartSession`,void 0),w([y({type:Boolean})],Z.prototype,`canDeleteArchivedSessions`,void 0),w([y({type:Boolean})],Z.prototype,`canReloadSessions`,void 0),w([y({type:Boolean})],Z.prototype,`canCleanupSessions`,void 0),w([y({type:Boolean})],Z.prototype,`authoritativeSessionPersistence`,void 0),w([y({type:String})],Z.prototype,`archivedDeleteUnavailableMessage`,void 0),w([y({type:String})],Z.prototype,`cleanupUnavailableMessage`,void 0),w([y({attribute:!1})],Z.prototype,`onShowActions`,void 0),w([y({attribute:!1})],Z.prototype,`onAddProject`,void 0),w([y({attribute:!1})],Z.prototype,`onShowSettings`,void 0),w([y({attribute:!1})],Z.prototype,`onToggleMachines`,void 0),w([y({attribute:!1})],Z.prototype,`onToggleProjects`,void 0),w([y({attribute:!1})],Z.prototype,`onToggleWorkspaces`,void 0),w([y({attribute:!1})],Z.prototype,`onToggleSessions`,void 0),w([y({attribute:!1})],Z.prototype,`onSelectProject`,void 0),w([y({attribute:!1})],Z.prototype,`onCloseProject`,void 0),w([y({attribute:!1})],Z.prototype,`onSelectWorkspace`,void 0),w([y({attribute:!1})],Z.prototype,`onDeleteWorkspace`,void 0),w([y({attribute:!1})],Z.prototype,`onStartSession`,void 0),w([y({attribute:!1})],Z.prototype,`onSelectSession`,void 0),w([y({attribute:!1})],Z.prototype,`onSearchSessions`,void 0),w([y({attribute:!1})],Z.prototype,`onToggleSessionPin`,void 0),w([y({attribute:!1})],Z.prototype,`onArchiveSession`,void 0),w([y({attribute:!1})],Z.prototype,`onArchiveSessionWithDescendants`,void 0),w([y({attribute:!1})],Z.prototype,`onArchiveSessions`,void 0),w([y({attribute:!1})],Z.prototype,`onRestoreSession`,void 0),w([y({attribute:!1})],Z.prototype,`onDeleteCachedNewSession`,void 0),w([y({attribute:!1})],Z.prototype,`onDeleteArchivedSession`,void 0),w([y({attribute:!1})],Z.prototype,`onDeleteArchivedSessions`,void 0),w([y({attribute:!1})],Z.prototype,`onRenameSession`,void 0),w([y({attribute:!1})],Z.prototype,`onDetachParentSession`,void 0),w([y({attribute:!1})],Z.prototype,`onMarkSessionRead`,void 0),w([y({attribute:!1})],Z.prototype,`onMarkSessionsRead`,void 0),w([y({attribute:!1})],Z.prototype,`onReloadSession`,void 0),w([y({attribute:!1})],Z.prototype,`onCleanupSessions`,void 0),w([y({attribute:!1})],Z.prototype,`onArchivedCollapsed`,void 0),w([y({attribute:!1})],Z.prototype,`onSelectMachine`,void 0),w([y({attribute:!1})],Z.prototype,`onRemoveMachine`,void 0),w([y({attribute:!1})],Z.prototype,`onFocusNavigationTarget`,void 0),w([y({attribute:!1})],Z.prototype,`onCancelKeyboardNavigation`,void 0),w([C()],Z.prototype,`sectionMeasurements`,void 0),w([S(`machine-list`)],Z.prototype,`machineList`,void 0),w([S(`machine-switcher`)],Z.prototype,`machineSwitcher`,void 0),w([S(`project-list`)],Z.prototype,`projectList`,void 0),Z=w([b(`app-navigation-panel`)],Z);function QC(e,t){return JSON.stringify([e??``,t??``])}function $C(e){return e.length>1}function ew(e,t,n=!0){let r=nw(t,n);return r[r.indexOf(e)-1]}function tw(e,t,n=!0){let r=nw(t,n);return r[r.indexOf(e)+1]??`chat`}function nw(e,t=!0){return Cg.filter(n=>(n!==`machines`||$C(e))&&(n!==`workspaces`||t))}var rw=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),iw=420,aw=4,Q=class extends O{constructor(){super(),this.side=`navigation`,this.collapsed=!1,this.resizable=!1,this.controls=``,this.resizeLabel=D(`ui.appPanelEdgeControl.resizePanel`,`Resize panel`),this.expandLabel=D(`ui.appPanelEdgeControl.expandPanel`,`Expand panel`),this.collapseLabel=D(`ui.appPanelEdgeControl.collapsePanel`,`Collapse panel`),this.lastTapAt=0,v.createController(this)}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){let e=this.collapsed?this.expandLabel:this.collapseLabel;return E`
|
|
3445
3445
|
${this.renderResizeHandle()}
|
|
3446
3446
|
<button
|
|
3447
3447
|
type="button"
|
|
@@ -3471,7 +3471,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3471
3471
|
@dblclick=${e=>{this.onResizeDoubleClick(e)}}
|
|
3472
3472
|
@keydown=${e=>{this.onResizeKeyDown(e)}}
|
|
3473
3473
|
></div>
|
|
3474
|
-
`}resizeAriaValueNow(){return this.panelWidth===void 0?k:String(Math.round(this.panelWidth))}renderIcon(){let e=this.iconDirection()===`left`?`M15 18l-6-6 6-6`:`M9 18l6-6-6-6`;return E`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${e}/></svg>`}iconDirection(){return this.side===`navigation`?this.collapsed?`right`:`left`:this.collapsed?`left`:`right`}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;let t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=this.resizeStartWidth();n!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:n,handle:t,moved:!1},this.toggleAttribute(`resizing`,!0))}onResizePointerMove(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=
|
|
3474
|
+
`}resizeAriaValueNow(){return this.panelWidth===void 0?k:String(Math.round(this.panelWidth))}renderIcon(){let e=this.iconDirection()===`left`?`M15 18l-6-6 6-6`:`M9 18l6-6-6-6`;return E`<svg class="edge-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d=${e}/></svg>`}iconDirection(){return this.side===`navigation`?this.collapsed?`right`:`left`:this.collapsed?`left`:`right`}onResizePointerDown(e){if(!this.resizable||e.button!==0)return;let t=e.currentTarget;if(!(t instanceof HTMLElement))return;let n=this.resizeStartWidth();n!==void 0&&(e.preventDefault(),e.stopPropagation(),t.setPointerCapture(e.pointerId),this.activeResize={pointerId:e.pointerId,startClientX:e.clientX,startWidth:n,handle:t,moved:!1},this.toggleAttribute(`resizing`,!0))}onResizePointerMove(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),!(Math.abs(e.clientX-t.startClientX)<=aw)&&(t.moved=!0,this.commitPanelWidth(Ug(this.side,t.startWidth,t.startClientX,e.clientX,this.resizeConstraints()))))}onResizePointerUp(e){let t=this.activeResize;t?.pointerId===e.pointerId&&(e.preventDefault(),this.finishActiveResize(),t.moved||this.registerTapForReset())}onResizePointerCancel(e){this.activeResize?.pointerId===e.pointerId&&this.finishActiveResize()}onResizeDoubleClick(e){e.preventDefault(),e.stopPropagation(),this.resetPanelSize()}onResizeKeyDown(e){if(!this.resizable||!rw.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=Wg(this.side,t,e.key,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});n!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(n),this.onResizeEnd?.())}registerTapForReset(){let e=Date.now();e-this.lastTapAt<=iw?(this.lastTapAt=0,this.resetPanelSize()):this.lastTapAt=e}resetPanelSize(){this.finishActiveResize(),this.onReset?.()}resizeStartWidth(){let e=this.onResizeStart?.()??this.panelWidth;if(e!==void 0)return Gg(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(Gg(this.side,e,this.resizeConstraints()))}finishActiveResize(){let e=this.activeResize;if(e!==void 0){try{e.handle.releasePointerCapture(e.pointerId)}catch{}this.activeResize=void 0,this.toggleAttribute(`resizing`,!1),this.onResizeEnd?.()}}resizeConstraints(){let e=Vg(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=T`
|
|
3475
3475
|
@layer pi-web-base {
|
|
3476
3476
|
: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; }
|
|
3477
3477
|
:host([side="navigation"]) { grid-column: 2; }
|
|
@@ -3493,7 +3493,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3493
3493
|
}
|
|
3494
3494
|
|
|
3495
3495
|
}
|
|
3496
|
-
`}};w([y({reflect:!0})],Q.prototype,`side`,void 0),w([y({type:Boolean,reflect:!0})],Q.prototype,`collapsed`,void 0),w([y({type:Boolean})],Q.prototype,`resizable`,void 0),w([y({type:Number})],Q.prototype,`panelWidth`,void 0),w([y({type:Number})],Q.prototype,`minWidth`,void 0),w([y({type:Number})],Q.prototype,`maxWidth`,void 0),w([y()],Q.prototype,`controls`,void 0),w([y()],Q.prototype,`resizeLabel`,void 0),w([y()],Q.prototype,`expandLabel`,void 0),w([y()],Q.prototype,`collapseLabel`,void 0),w([y({attribute:!1})],Q.prototype,`onToggle`,void 0),w([y({attribute:!1})],Q.prototype,`onResizeStart`,void 0),w([y({attribute:!1})],Q.prototype,`onResize`,void 0),w([y({attribute:!1})],Q.prototype,`onResizeEnd`,void 0),w([y({attribute:!1})],Q.prototype,`onReset`,void 0),Q=w([b(`app-panel-edge-control`)],Q);var
|
|
3496
|
+
`}};w([y({reflect:!0})],Q.prototype,`side`,void 0),w([y({type:Boolean,reflect:!0})],Q.prototype,`collapsed`,void 0),w([y({type:Boolean})],Q.prototype,`resizable`,void 0),w([y({type:Number})],Q.prototype,`panelWidth`,void 0),w([y({type:Number})],Q.prototype,`minWidth`,void 0),w([y({type:Number})],Q.prototype,`maxWidth`,void 0),w([y()],Q.prototype,`controls`,void 0),w([y()],Q.prototype,`resizeLabel`,void 0),w([y()],Q.prototype,`expandLabel`,void 0),w([y()],Q.prototype,`collapseLabel`,void 0),w([y({attribute:!1})],Q.prototype,`onToggle`,void 0),w([y({attribute:!1})],Q.prototype,`onResizeStart`,void 0),w([y({attribute:!1})],Q.prototype,`onResize`,void 0),w([y({attribute:!1})],Q.prototype,`onResizeEnd`,void 0),w([y({attribute:!1})],Q.prototype,`onReset`,void 0),Q=w([b(`app-panel-edge-control`)],Q);var ow=class extends O{constructor(){super(),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()},v.createController(this)}render(){let e=D(`ui.appRefreshControl.reloadEntirePage`,`Reload entire page`);return E`
|
|
3497
3497
|
<button
|
|
3498
3498
|
class="app-refresh-button"
|
|
3499
3499
|
title=${e}
|
|
@@ -3517,18 +3517,18 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3517
3517
|
.app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
|
|
3518
3518
|
|
|
3519
3519
|
}
|
|
3520
|
-
`}};w([y({attribute:!1})],
|
|
3520
|
+
`}};w([y({attribute:!1})],ow.prototype,`onReload`,void 0),ow=w([b(`app-refresh-control`)],ow);function sw(e,t,n=`error`,r){if(e===``)return null;let i=D(`ui.main.dcf2e3223649`,`Dismiss {arg0}`,{arg0:cw(n)});return E`<div class=${`error ${n}`} role="alert">
|
|
3521
3521
|
<span class="error-text">${e}</span>
|
|
3522
3522
|
${r===void 0?null:E`<button type="button" class="error-retry ui-button ui-button--compact" @click=${()=>{r()}}>${D(`ui.errorBanner.retry`,`Retry`)}</button>`}
|
|
3523
3523
|
<button type="button" class="error-dismiss" aria-label=${i} title=${i} @click=${()=>{t()}}>✕</button>
|
|
3524
|
-
</div>`}function aw(e){return e===`error`?D(`client.sessionNotifications.error.0bc1fb`,`Error`):e===`warning`?D(`client.sessionNotifications.warning.a8b7a4`,`Warning`):D(`bundled.info.info.e70286`,`Info`)}var ow=9e5,sw=5e3,cw=750,lw=[1e3,3e3,8e3,15e3,3e4],uw=[`machine`,`project`,`workspace`,`session`,`tool`,`view`],dw=[`machine`,`project`,`workspace`,`session`],fw=[`tool`,`view`],pw=[1e3,2e3,5e3,1e4],mw={capture:!0},hw=320,gw=2,_w=`workspace.terminal`,vw=uw;function yw(e){let t=F();return{machineId:M(e),projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id,...t.tool===void 0?{}:{tool:t.tool},...t.view===void 0?{}:{view:t.view}}}function bw(e){return{url:xw(),...e===void 0?{}:{navigation:e}}}function xw(){return window.location.href}function Sw(e,t){let n=e.selectedSession,r=t.sessionId;return{machineId:t.machineId??`local`,...t.projectId===void 0?{}:{projectId:t.projectId},...t.workspaceId===void 0?{}:{workspaceId:t.workspaceId},...r===void 0?{}:{sessionId:r},...n===void 0||n.id!==r?{}:{cwd:n.cwd}}}function Cw(e,t){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&ww(e[n],t[n]))}function ww(e,t){return Array.isArray(e)||Array.isArray(t)?Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>e===t[n]):e===t}function Tw(e){if(e.projectId!==void 0&&e.projectId!==``&&e.workspaceId!==void 0&&e.workspaceId!==``)return{machineId:e.machineId??`local`,projectId:e.projectId,workspaceId:e.workspaceId}}function Ew(e,t){return e.machineId===t.machineId&&e.projectId===t.projectId&&e.workspaceId===t.workspaceId}var $=class extends O{constructor(){super(),this.chatBehaviors=Nn,this.state=Un(),this.browserErrors=new $n(()=>this.state,e=>{this.setState(e)}),this.handleChatNavigationChange=e=>{this.chatNavigation=e},this.apiScope=Ow(),this.sessionUnread=new nu({onChange:e=>{this.syncUnreadPresence(),M(this.state)===e&&(this.syncUnreadSessionIds(),this.refreshSelectedUnreadHistory(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(M(this.state),this.state.sessions),this.unreadPresence=uu,this.unreadConnected=!1,this.handleTranscriptRendered=e=>{this.renderedTranscript=e,this.syncSelectedSessionReadState()},this.modelDialogInstanceId=0,this.modelDialogMutationInFlight=0,this.modelDialogRefreshPending=!1,this.modelDialogScopeInvalidation=0,this.notifications=new al(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessionWorkTransitions=new Pc,this.sessions=new mc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Ys,{socket:new Ds(this.apiScope),canMutateQueueMessage:(e,t)=>this.canMutateQueueMessage(e,t),notifications:this.notifications,isChatVisible:()=>this.isChatVisible(),automaticSessionCandidates:e=>this.navigationPanel?.automaticSessionCandidates(e)??Mv(e,{collapsed:this.navigationSections.isCollapsed(`sessions`)}),observeSessionSnapshot:(e,t)=>{let n=this.sessionWorkTransitions.snapshotObserver(e,t);return r=>{if(r.sessionId!==t)return;let i=n(r);(rr(r)||i!==void 0)&&this.invalidateFilesForSessionActivity(e,t)}},captureNavigation:()=>this.captureNavigation(),beginNavigationOperation:e=>this.beginNavigationOperation(e),navigateToSession:(e,t)=>this.navigateToSessionFromController(e,t),onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},isPendingSessionStartRouteCurrent:e=>this.isPendingSessionStartRouteCurrent(e),onPendingSessionStartCommitted:(e,t)=>{this.commitPendingSessionStartNavigation(e,t)},onModelScopeChanged:()=>{this.modelDialogScopeInvalidation+=1,this.refreshOpenModelDialog()},replacePromptEditorText:async({machineId:e,sessionId:t,text:n,isCurrent:r})=>{await this.updateComplete,r?.()!==!1&&M(this.state)===e&&this.state.selectedSession?.id===t&&this.promptEditor?.replaceText(n)}}),this.projectActivityOwnership=new Vr(()=>this.state,e=>{this.setState(e)},{api:d,onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new _r(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.machineStatus=new kr(()=>this.state,e=>{this.setState(e)}),this.auth=new br(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)},{scope:this.apiScope}),this.workspaces=new gl(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new fl,{captureNavigation:()=>this.captureNavigation(),beginNavigationOperation:e=>this.beginNavigationOperation(e),navigateToWorkspace:(e,t)=>this.navigateToWorkspaceFromController(e,t)}),this.projects=new zr(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)},captureNavigation:()=>this.captureNavigation(),navigateToProject:(e,t)=>this.navigateToProjectFromController(e,t)}),this.machines=new Tr(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects,{captureNavigation:()=>this.captureNavigation(),navigateToMachine:(e,t)=>this.selectMachineWithMemory(e,t)}),this.piWebStatusController=new Ur(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}),this.navigationOrderVersion=0,this.navigationOrder=new Mr(Ir,{onChange:()=>{this.navigationOrderVersion+=1},onError:(e,t)=>{this.browserErrors.report(A(e.machineId),D(`ui.navigationOrder.failure`,`Failed to load or save navigation order: {error}`,{error:Jw(t)}))}}),this.keyboard=new De,this.realtime=new Os(this.apiScope),this.serverNotices=new ku({onChange:e=>{M(this.state)===e&&this.requestUpdate()},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} server notices for ${t}`,n)}}),this.machineRealtimeSockets=new Map,this.machineNavigation=new El,this.appShell=new pg(this),this.browserResume=new hg({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new Mg(this),this.panelResize=new Lg(this),this.navigationSections=new Og(this,()=>({...this.state,workspaceSelectionVisible:ll(this.state.workspaceResolution)}),()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.workspaceDeletionRefreshQueued=!1,this.workspaceDeletionRefreshGeneration=0,this.workspaceDeletionReconcileRetries=new Map,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.workspaceNavigationGeneration=0,this.routeSelectionRestoreSeq=0,this.navigationGeneration=0,this.navigationFieldGenerations={machine:0,project:0,workspace:0,session:0,tool:0,view:0},this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.stylesheetRuntime=new n(et,e=>{this.plugins.failUiPresentationStylesheetError(e),console.error(`Failed to apply plugin stylesheets`,e)}),this.pluginLoadErrors=new Map,this.requiredTerminalByMachine=new Map,this.knownRequiredTerminalByMachine=new Map,this.verifiedPluginModeByMachine=new Map,this.requiredPluginFailureByMachine=new Map,this.dismissedRequiredPluginFailureByMachine=new Map,this.plugins=new Am({onPromptChipsChanged:()=>{this.requestUpdate()},isContributionEnabled:(e,t)=>this.pluginContributionAvailable(e,t),getSelection:()=>Qt(this.state),onUiPresentationError:(e,t)=>{let n=`${e}: ${Jw(t)}`;this.pluginLoadErrors.set(`local`,n),this.browserErrors.report(A(M(this.state)),n),this.applyPreferredTheme(!1),this.requestUpdate()}}),this.resetKeyboardSequence=()=>{this.keyboard.reset()},this.builtInPluginsReady=this.plugins.registerBatch([{id:`core`,plugin:fd},{id:`themes`,plugin:pd}]).then(({failures:e})=>{if(e.length>0)throw e[0]?.error;this.isConnected&&this.applyPreferredTheme(!1),this.invalidateWorkspaceSurface()}),this.pluginLoads=new ig((e,t,n)=>this.registerExternalPlugins(e,t,n),(e,t)=>this.plugins.shouldLoadRemotePlugin(e,t)&&(this.apiScope!==`management`||e!==`pi-web.terminal`),e=>!this.plugins.hasPlugin(e)||e===`pi-web.terminal`&&!this.terminalAvailableForMachine(`local`)),this.localThemePreference=ne(),this.activeThemeId=i,this.navigationPreferences=t_(),this.navigationDialogOpen=!1,this.isRefreshingApp=!1,this.sessionSearchDialogOpen=!1,this.settingsSection=s_(),this.normalAuthLoading=!0,this.normalAuthError=``,this.shortcutConfig={},this.defaultStreamingBehavior=`steer`,this.workspaceUploadDefaultFolder=it(void 0),this.workspaceAttachmentsDefaultFolder=Pe(void 0),this.sessionWarningVisibility=bu(),this.authenticatedAppRunning=!1,this.normalAuthInitSeq=0,this.dismissedActivityNotices=new Set,this.onPopState=()=>{this.invalidateNavigationSelection(),this.workspaceNavigationGeneration+=1,this.syncNavigationFreshness(),this.routeRestoreSeq+=1,this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.isRenderedModalOpen()||e.key===`Escape`&&Be(this.ownerDocument)||this.promptEditor?.ownsKeyboardEvent(e)===!0?this.keyboard.reset():this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleDismissActivityNotice=async()=>{let e=this.unacknowledgedActivitySessionKey();if(e===void 0)return;this.dismissedActivityNotices.add(e),this.requestUpdate(),await this.updateComplete,await this.promptEditor?.updateComplete;let t=this.state.selectedSession;t!==void 0&&j(M(this.state),t.id)===e&&this.unacknowledgedActivitySessionKey()===void 0&&this.effectiveMainView()===`chat`&&this.promptEditor?.disabled===!1&&!this.isRenderedModalOpen()&&this.promptEditor.focusInput()},this.handleWorkspaceFileOpen=e=>{let t=this.state.selectedWorkspace,n=e.detail;if(e.defaultPrevented||t===void 0||n.machineId!==M(this.state)||n.projectId!==t.projectId||n.workspaceId!==t.id||n.root!==t.path)return;let r=this.plugins.resolveWorkspaceFileOpen(this.createWorkspacePanelContext(t),n.path);if(r===void 0)return;let i=ia(this.currentContributionQueryForState(),r.contributionId,r.navigationAliases??[],r.query);e.preventDefault(),this.publishWorkspaceTool(r.contributionId,i)},this.workspaceSurfaceRevision=0,this.navigationActions={toggleMachines:()=>{this.navigationSections.toggle(`machines`)},selectMachine:e=>this.selectNavigationItem(`machines`,`projects`,()=>this.selectMachineWithMemory(e)),removeMachine:e=>{this.removeMachine(e)},showActions:()=>{this.setState({actionPaletteOpen:!0})},toggleProjects:()=>{this.navigationSections.toggle(`projects`)},toggleWorkspaces:()=>{this.navigationSections.toggle(`workspaces`)},toggleSessions:()=>{this.navigationSections.toggle(`sessions`)},selectProject:e=>this.selectNavigationItem(`projects`,`workspaces`,()=>this.selectProjectFromNavigation(e)),closeProject:e=>this.projects.closeProject(e.id),selectWorkspace:e=>this.selectNavigationItem(`workspaces`,`sessions`,()=>this.selectWorkspaceFromNavigation(e)),deleteWorkspace:e=>{this.deleteWorkspace(e)},archivedCollapsed:()=>{this.sessions.clearSelectionAfterArchivedCollapse()},startSession:()=>this.startSessionFromNavigation(),selectSession:e=>this.selectNavigationItem(`sessions`,`chat`,()=>this.selectSessionFromNavigation(e)),markSessionRead:e=>{this.markSessionsRead([e])},markSessionsRead:e=>{this.markSessionsRead(e)},searchSessions:()=>{this.openSessionSearchDialog()},toggleSessionPin:e=>{this.sessions.togglePinned(e)},archiveSession:e=>this.sessions.archiveSession(e),archiveSessionWithDescendants:e=>this.sessions.archiveSessionWithDescendants(e),archiveSessions:e=>this.sessions.archiveSessions(e),restoreSession:e=>this.selectNavigationItem(`sessions`,`chat`,()=>this.sessions.restoreSession(e)),deleteCachedNewSession:e=>this.sessions.deleteCachedNewSession(e),deleteArchivedSession:e=>this.sessions.deleteArchivedSessions([e]),deleteArchivedSessions:e=>this.sessions.deleteArchivedSessions(e),renameSession:(e,t)=>this.sessions.renameSession(e,t),detachParentSession:e=>this.sessions.detachParent(e),reloadSession:e=>this.sessions.reloadSession(e),cleanupSessions:()=>{this.openSessionCleanupDialog()},focusNavigationTarget:e=>{this.focusNavigationTarget(e)},cancelKeyboardNavigation:()=>{this.openChatAndFocusComposer()},moveProject:(e,t)=>{this.moveNavigationItem({kind:`projects`,machineId:M(this.state)},e.id,t)},moveWorkspace:(e,t)=>{this.moveNavigationItem({kind:`workspaces`,machineId:M(this.state),projectId:e.projectId},e.id,t)},moveSessionPin:(e,t)=>{this.moveSessionPin(e,t)}},this.presentationContextKey=``,this.presentationContextCache={mode:`normal`},this.handleSendPrompt=(e,t,n,r,i,a)=>this.sendPrompt(e,t,n,r,i,a),this.visiblePromptChips=[],this.handleRemovePromptChip=e=>{this.plugins.promptChips.removeByUser(e)},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleQueuedMessageAction=async e=>{let t=this.state.selectedSession;if(t===void 0||this.queuedMessageActionTarget!==void 0||this.messageRevertTarget!==void 0||this.isReplacingPrompt(this.state)||M(this.state)!==e.machineId||t.id!==e.sessionId||t.cwd!==e.cwd||!this.canMutateQueueMessage(t,e.machineId))return;let n=this.promptEditor??void 0;if(e.action===`edit`){let t=An(e.expectedQueue,e.index);if(t!==void 0&&!window.confirm(t)||(n?.view?.state.doc.toString()??``)!==``&&!window.confirm(D(`ui.piWebApp.confirmRecallDraft`,`Recalling will replace your unsent draft. Continue?`)))return}let r=this.navigationSelectionSeq;this.queuedMessageActionTarget=e;try{e.action===`edit`&&n!==void 0&&(n.disabled=!0,await n.updateComplete);let i=this.state.selectedSession;if(r!==this.navigationSelectionSeq||M(this.state)!==e.machineId||i?.id!==t.id||i.cwd!==t.cwd||i.path!==t.path)return;await this.sessions.mutateQueuedMessage(e.action,e.index,e.expectedQueue)}finally{this.queuedMessageActionTarget===e&&(this.queuedMessageActionTarget=void 0),this.requestUpdate()}},this.handleMessageAction=async(e,t)=>{let n=this.state,r=this.messageActionContext(n);if(r?.machine.id!==e.machine.id||r.session.id!==e.session.id||r.session.cwd!==e.session.cwd)return;let i=n.messages.find(t=>t.entryId===e.message.entryId),a=i===void 0?void 0:wn(i,e.message.role);if(a===void 0)return;let o={...r,message:a};return this.plugins.runMessageAction(t,o,e=>{let t=()=>M(this.state)===o.machine.id&&this.state.selectedSession?.id===o.session.id&&this.state.selectedSession.cwd===o.session.cwd,n=async n=>{if(!t()||!this.plugins.promptChipOwnerAvailable(e.registrationPluginId,o.machine.id))throw Error(`This message's conversation is no longer available.`);if(n===`fork`)return this.sessions.actOnMessage(o.message.entryId,n);if(this.messageRevertTarget!==void 0||this.queuedMessageActionTarget!==void 0||this.isReplacingPrompt(this.state))throw Error(D(`ui.piWebApp.draftActionInProgress`,`Another draft-replacing action is already in progress.`));let r=this.promptEditor??void 0,i=r?.view?.state.doc.toString()??``;if(o.message.role===`user`&&i!==``&&!window.confirm(D(`ui.piWebApp.confirmGoBackDraft`,`Going back will replace your unsent draft. Continue?`)))return;let a=this.state.selectedSession;if(a===void 0)return;let s={machineId:o.machine.id,sessionId:a.id,cwd:a.cwd,path:a.path},c=this.navigationSelectionSeq;this.messageRevertTarget=s;try{if(r!==void 0&&(r.disabled=!0,await r.updateComplete),!t()||c!==this.navigationSelectionSeq||this.state.selectedSession?.path!==s.path)return;await this.sessions.actOnMessage(o.message.entryId,n)}finally{this.messageRevertTarget===s&&(this.messageRevertTarget=void 0),this.requestUpdate()}};return{...o,...this.messageActionHelpers(e,o),history:{fork:()=>n(`fork`),goBack:()=>n(`back`)}}})},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleSubmitAsk=(e,t)=>this.sessions.submitAsk(e,t),this.handleAnswerDialog=(e,t)=>this.sessions.answerDialog(e,t),this.handleCancelDialog=e=>this.sessions.cancelDialog(e),this.handleDismissClosedDialog=e=>{this.sessions.dismissClosedDialog(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=Tu(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleToggleModelEnabled=async(e,t,n)=>{if(this.apiScope!==`normal`)return;let r=this.currentModelDialog();if(r!==void 0){this.modelDialogMutationInFlight+=1;try{this.applyModelDialogCatalog(r,await this.sessions.setModelEnabled(e,t,n))}finally{this.finishModelDialogMutation()}}},this.handleSetModelScope=async e=>{if(this.apiScope!==`normal`)return;let t=this.currentModelDialog();if(t!==void 0){this.modelDialogMutationInFlight+=1;try{this.applyModelDialogCatalog(t,await this.sessions.setModelScope(e))}finally{this.finishModelDialogMutation()}}},this.handleSetDefaultModel=e=>this.pinSessionDefault(`model`,e),this.handleSetDefaultThinking=e=>this.pinSessionDefault(`thinking`,e),this.handleSelectThinking=()=>{this.openThinkingDialog()},this.showNavigation=()=>{let e=ft(this.ownerDocument);this.navigationOpener=e instanceof HTMLElement?e:void 0,this.navigationDialogOpen=!0},this.closeNavigation=()=>{this.navigationDialogOpen=!1;let e=this.navigationOpener;this.navigationOpener=void 0,this.updateComplete.then(()=>{if(this.navigationDialogOpen||Ye(this.ownerDocument)||e!==void 0&&ot(e))return;let t=ft(this.ownerDocument);if(!(t instanceof HTMLElement&&t!==this&&t!==this.ownerDocument.body&&t!==this.ownerDocument.documentElement&&ot(t)))for(let e of this.renderRoot.querySelectorAll(`app-context-bar, app-mobile-main-tabs, workspace-panel`)){let t=e.shadowRoot?.querySelector(`button[aria-haspopup="dialog"][aria-pressed]`);if(t!=null&&ot(t))return}})},this.changeNavigationPreferences=e=>{let t=this.navigationPreferences.pinnedIds,n=this.resolvedNavigationPreferences().pinnedIds,r=new Set(e.pinnedIds),i=t.length===0||r.size===0?e.pinnedIds:[...t.filter(e=>r.has(this.resolveNavigationPinnedId(e))),...e.pinnedIds.filter(e=>!n.includes(e))];this.navigationPreferences={...e,pinnedIds:[...new Set(i)]},n_(this.navigationPreferences)},this.navigationPanelActions=this.createPanelActions(`navigation`),this.workspacePanelActions=this.createPanelActions(`workspace`),this.deletingWorkspaceIds=[],this.handleUseSuggestedInput=(e,t)=>{this.sessions.useSuggestedInput(e,t)},this.emptyClientQueue=[],this.handleLoadEarlierMessages=()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages()),this.handleOpenNavigationSection=e=>{this.openNavigationSection(e)},this.handleReloadApp=()=>{this.hardReloadApp()},this.selectNavigationTab=e=>{e===`navigation`||e===`chat`?this.selectMainView(e):this.openWorkspaceTool(e)},this.messageActionInputs=``,this.handleDisplayedMessageAction=async(e,t)=>{let n=this.messageActionContext(this.state);if(n?.machine.id!==e.machine.id||n.session.id!==e.session.id||n.session.cwd!==e.session.cwd)return;let r={...n,message:e.message};return this.plugins.runDisplayedMessageAction(t,r,e=>({...r,...this.messageActionHelpers(e,r)}))},v.createController(this),new pC(this,()=>this.settingsSection!==void 0,()=>$t(()=>import(`./SettingsDialog-vGDo1-BJ.js`),__vite__mapDeps([0,1,2]),import.meta.url),e=>{this.closeSettings(),this.setState({error:Jw(e)})})}get themePreference(){return Ce(this.localThemePreference,this.configuredThemePreference,this.plugins.getThemes())}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility(),this.syncSessionActivityAcknowledgement()}updated(){this.sessions.isChatLoadDeferred&&(this.readyChatIdentity=void 0),this.committedChatIdentity=Mw(this.state),this.syncSelectedSessionReadState(),this.plugins.notifySelectionChanged(),this.syncPluginStylesheets(),this.isChatVisible()?this.sessions.isChatLoadDeferred?this.scheduleSelectedChatLoad():this.displayedChatIdentity=Mw(this.state):this.cancelSelectedChatLoad()}scheduleSelectedChatLoad(){this.selectedChatLoadFrame===void 0&&(this.selectedChatLoadFrame=requestAnimationFrame(()=>{this.selectedChatLoadFrame=requestAnimationFrame(()=>{this.selectedChatLoadFrame=void 0,this.isConnected&&this.isChatVisible()&&this.sessions.loadSelectedSession()})}))}cancelSelectedChatLoad(){this.selectedChatLoadFrame!==void 0&&(cancelAnimationFrame(this.selectedChatLoadFrame),this.selectedChatLoadFrame=void 0)}isChatVisible(){let e=this.effectiveMainView();return e===`chat`||e===`navigation`&&!this.appShell.isMobileNavigationLayout||this.isDesktopSideBySideLayout()}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=Su(this.sessionWarningVisibility,e===void 0?void 0:j(M(this.state),e.id),this.state.status?.sessionId===e?.id?this.state.status?.warnings??[]:void 0)}syncSessionActivityAcknowledgement(){if(this.dismissedActivityNotices.size===0)return;let e=this.state.selectedSession,t=this.state.status,n=M(this.state);for(let t of Object.values(this.state.sessionStatuses))t.sessionId!==e?.id&&t.recentlyActiveElsewhere===!1&&this.dismissedActivityNotices.delete(j(n,t.sessionId));e!==void 0&&t?.sessionId===e.id&&t.recentlyActiveElsewhere===!1&&this.dismissedActivityNotices.delete(j(n,e.id))}unacknowledgedActivitySessionKey(e=this.state){let t=e.selectedSession;if(t===void 0||e.status?.sessionId!==t.id||e.status.recentlyActiveElsewhere!==!0)return;let n=j(M(e),t.id);return this.dismissedActivityNotices.has(n)?void 0:n}renderSessionActivityNotice(){return this.unacknowledgedActivitySessionKey()===void 0?null:E`
|
|
3524
|
+
</div>`}function cw(e){return e===`error`?D(`client.sessionNotifications.error.0bc1fb`,`Error`):e===`warning`?D(`client.sessionNotifications.warning.a8b7a4`,`Warning`):D(`bundled.info.info.e70286`,`Info`)}var lw=9e5,uw=5e3,dw=750,fw=[1e3,3e3,8e3,15e3,3e4],pw=[`machine`,`project`,`workspace`,`session`,`tool`,`view`],mw=[`machine`,`project`,`workspace`,`session`],hw=[`tool`,`view`],gw=[1e3,2e3,5e3,1e4],_w={capture:!0},vw=320,yw=2,bw=`workspace.terminal`,xw=pw;function Sw(e){let t=F();return{machineId:M(e),projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id,...t.tool===void 0?{}:{tool:t.tool},...t.view===void 0?{}:{view:t.view}}}function Cw(e){return{url:ww(),...e===void 0?{}:{navigation:e}}}function ww(){return window.location.href}function Tw(e,t){let n=e.selectedSession,r=t.sessionId;return{machineId:t.machineId??`local`,...t.projectId===void 0?{}:{projectId:t.projectId},...t.workspaceId===void 0?{}:{workspaceId:t.workspaceId},...r===void 0?{}:{sessionId:r},...n===void 0||n.id!==r?{}:{cwd:n.cwd}}}function Ew(e,t){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&Dw(e[n],t[n]))}function Dw(e,t){return Array.isArray(e)||Array.isArray(t)?Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>e===t[n]):e===t}function Ow(e){if(e.projectId!==void 0&&e.projectId!==``&&e.workspaceId!==void 0&&e.workspaceId!==``)return{machineId:e.machineId??`local`,projectId:e.projectId,workspaceId:e.workspaceId}}function kw(e,t){return e.machineId===t.machineId&&e.projectId===t.projectId&&e.workspaceId===t.workspaceId}var $=class extends O{constructor(){super(),this.chatBehaviors=Nn,this.state=Un(),this.browserErrors=new $n(()=>this.state,e=>{this.setState(e)}),this.handleChatNavigationChange=e=>{this.chatNavigation=e},this.apiScope=jw(),this.sessionUnread=new nu({onChange:e=>{this.syncUnreadPresence(),M(this.state)===e&&(this.syncUnreadSessionIds(),this.refreshSelectedUnreadHistory(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(M(this.state),this.state.sessions),this.unreadPresence=uu,this.unreadConnected=!1,this.handleTranscriptRendered=e=>{this.renderedTranscript=e,this.syncSelectedSessionReadState()},this.modelDialogInstanceId=0,this.modelDialogMutationInFlight=0,this.modelDialogRefreshPending=!1,this.modelDialogScopeInvalidation=0,this.notifications=new al(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessionWorkTransitions=new Pc,this.sessions=new mc(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Ys,{socket:new Ds(this.apiScope),canMutateQueueMessage:(e,t)=>this.canMutateQueueMessage(e,t),notifications:this.notifications,isChatVisible:()=>this.isChatVisible(),automaticSessionCandidates:e=>this.navigationPanel?.automaticSessionCandidates(e)??Fv(e,{collapsed:this.navigationSections.isCollapsed(`sessions`)}),observeSessionSnapshot:(e,t)=>{let n=this.sessionWorkTransitions.snapshotObserver(e,t);return r=>{if(r.sessionId!==t)return;let i=n(r);(rr(r)||i!==void 0)&&this.invalidateFilesForSessionActivity(e,t)}},captureNavigation:()=>this.captureNavigation(),beginNavigationOperation:e=>this.beginNavigationOperation(e),navigateToSession:(e,t)=>this.navigateToSessionFromController(e,t),onSelectedSessionReady:({machineId:e,session:t})=>{this.commitReadyChatAfterRender(e,t)},isPendingSessionStartRouteCurrent:e=>this.isPendingSessionStartRouteCurrent(e),onPendingSessionStartCommitted:(e,t)=>{this.commitPendingSessionStartNavigation(e,t)},onModelScopeChanged:()=>{this.modelDialogScopeInvalidation+=1,this.refreshOpenModelDialog()},replacePromptEditorText:async({machineId:e,sessionId:t,text:n,isCurrent:r})=>{await this.updateComplete,r?.()!==!1&&M(this.state)===e&&this.state.selectedSession?.id===t&&this.promptEditor?.replaceText(n)}}),this.projectActivityOwnership=new Vr(()=>this.state,e=>{this.setState(e)},{api:d,onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new _r(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.machineStatus=new kr(()=>this.state,e=>{this.setState(e)}),this.auth=new br(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)},{scope:this.apiScope}),this.workspaces=new gl(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new fl,{captureNavigation:()=>this.captureNavigation(),beginNavigationOperation:e=>this.beginNavigationOperation(e),navigateToWorkspace:(e,t)=>this.navigateToWorkspaceFromController(e,t)}),this.projects=new zr(()=>this.state,e=>{this.setState(e)},this.workspaces,{onProjectsApplied:e=>{this.projectActivityOwnership.handleProjectsApplied(e)},captureNavigation:()=>this.captureNavigation(),navigateToProject:(e,t)=>this.navigateToProjectFromController(e,t)}),this.machines=new Tr(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects,{captureNavigation:()=>this.captureNavigation(),navigateToMachine:(e,t)=>this.selectMachineWithMemory(e,t)}),this.piWebStatusController=new Ur(()=>this.state,e=>{this.setState(e)},{onRefreshError:(e,t)=>{console.warn(`Failed to refresh PI WEB status for ${e}`,t)}}),this.navigationOrderVersion=0,this.navigationOrder=new Mr(Ir,{onChange:()=>{this.navigationOrderVersion+=1},onError:(e,t)=>{this.browserErrors.report(A(e.machineId),D(`ui.navigationOrder.failure`,`Failed to load or save navigation order: {error}`,{error:Zw(t)}))}}),this.keyboard=new De,this.realtime=new Os(this.apiScope),this.serverNotices=new ku({onChange:e=>{M(this.state)===e&&this.requestUpdate()},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} server notices for ${t}`,n)}}),this.machineRealtimeSockets=new Map,this.machineNavigation=new El,this.appShell=new gg(this),this.browserResume=new vg({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:()=>this.refreshAfterBrowserResume(),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new Fg(this),this.panelResize=new Bg(this),this.navigationSections=new jg(this,()=>({...this.state,workspaceSelectionVisible:ll(this.state.workspaceResolution)}),()=>this.appShell.isMobileNavigationLayout),this.systemLightThemeMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(`(prefers-color-scheme: light)`):void 0,this.workspaceDeletionRefreshQueued=!1,this.workspaceDeletionRefreshGeneration=0,this.workspaceDeletionReconcileRetries=new Map,this.handledWorkspaceDeletionRunIds=new Set,this.terminalCommandRunRuntimes=new Map,this.machineNavigationRestoreSeq=0,this.navigationSelectionSeq=0,this.routeRestoreSeq=0,this.workspaceNavigationGeneration=0,this.routeSelectionRestoreSeq=0,this.navigationGeneration=0,this.navigationFieldGenerations={machine:0,project:0,workspace:0,session:0,tool:0,view:0},this.routeRestoreDepth=0,this.remoteRouteRestoreAttempt=0,this.remoteRouteRestoreInProgress=!1,this.stylesheetRuntime=new n(et,e=>{this.plugins.failUiPresentationStylesheetError(e),console.error(`Failed to apply plugin stylesheets`,e)}),this.pluginLoadErrors=new Map,this.requiredTerminalByMachine=new Map,this.knownRequiredTerminalByMachine=new Map,this.verifiedPluginModeByMachine=new Map,this.requiredPluginFailureByMachine=new Map,this.dismissedRequiredPluginFailureByMachine=new Map,this.plugins=new Am({onPromptChipsChanged:()=>{this.requestUpdate()},isContributionEnabled:(e,t)=>this.pluginContributionAvailable(e,t),getSelection:()=>Qt(this.state),onUiPresentationError:(e,t)=>{let n=`${e}: ${Zw(t)}`;this.pluginLoadErrors.set(`local`,n),this.browserErrors.report(A(M(this.state)),n),this.applyPreferredTheme(!1),this.requestUpdate()}}),this.resetKeyboardSequence=()=>{this.keyboard.reset()},this.builtInPluginsReady=this.plugins.registerBatch([{id:`core`,plugin:fd},{id:`themes`,plugin:pd}]).then(({failures:e})=>{if(e.length>0)throw e[0]?.error;this.isConnected&&this.applyPreferredTheme(!1),this.invalidateWorkspaceSurface()}),this.pluginLoads=new sg((e,t,n)=>this.registerExternalPlugins(e,t,n),(e,t)=>this.plugins.shouldLoadRemotePlugin(e,t)&&(this.apiScope!==`management`||e!==`pi-web.terminal`),e=>!this.plugins.hasPlugin(e)||e===`pi-web.terminal`&&!this.terminalAvailableForMachine(`local`)),this.localThemePreference=ne(),this.activeThemeId=i,this.navigationPreferences=i_(),this.navigationDialogOpen=!1,this.isRefreshingApp=!1,this.sessionSearchDialogOpen=!1,this.settingsSection=u_(),this.normalAuthLoading=!0,this.normalAuthError=``,this.shortcutConfig={},this.defaultStreamingBehavior=`steer`,this.workspaceUploadDefaultFolder=it(void 0),this.workspaceAttachmentsDefaultFolder=Pe(void 0),this.sessionWarningVisibility=bu(),this.authenticatedAppRunning=!1,this.normalAuthInitSeq=0,this.dismissedActivityNotices=new Set,this.onPopState=()=>{this.invalidateNavigationSelection(),this.workspaceNavigationGeneration+=1,this.syncNavigationFreshness(),this.routeRestoreSeq+=1,this.withChatScrollTransition(async()=>{this.restoreSettingsRoute(),await this.restoreRoute(!1)})},this.onSystemLightThemeChange=()=>{this.themePreference.auto&&this.applyPreferredTheme(!1)},this.onKeyDown=e=>{this.isRenderedModalOpen()||e.key===`Escape`&&Be(this.ownerDocument)||this.promptEditor?.ownsKeyboardEvent(e)===!0?this.keyboard.reset():this.keyboard.handle(e,this.getDefaultActions(),{shortcuts:this.shortcutConfig})&&(e.preventDefault(),e.stopPropagation())},this.handleDismissActivityNotice=async()=>{let e=this.unacknowledgedActivitySessionKey();if(e===void 0)return;this.dismissedActivityNotices.add(e),this.requestUpdate(),await this.updateComplete,await this.promptEditor?.updateComplete;let t=this.state.selectedSession;t!==void 0&&j(M(this.state),t.id)===e&&this.unacknowledgedActivitySessionKey()===void 0&&this.effectiveMainView()===`chat`&&this.promptEditor?.disabled===!1&&!this.isRenderedModalOpen()&&this.promptEditor.focusInput()},this.handleWorkspaceFileOpen=e=>{let t=this.state.selectedWorkspace,n=e.detail;if(e.defaultPrevented||t===void 0||n.machineId!==M(this.state)||n.projectId!==t.projectId||n.workspaceId!==t.id||n.root!==t.path)return;let r=this.plugins.resolveWorkspaceFileOpen(this.createWorkspacePanelContext(t),n.path);if(r===void 0)return;let i=ia(this.currentContributionQueryForState(),r.contributionId,r.navigationAliases??[],r.query);e.preventDefault(),this.publishWorkspaceTool(r.contributionId,i)},this.workspaceSurfaceRevision=0,this.navigationActions={toggleMachines:()=>{this.navigationSections.toggle(`machines`)},selectMachine:e=>this.selectNavigationItem(`machines`,`projects`,()=>this.selectMachineWithMemory(e)),removeMachine:e=>{this.removeMachine(e)},showActions:()=>{this.setState({actionPaletteOpen:!0})},toggleProjects:()=>{this.navigationSections.toggle(`projects`)},toggleWorkspaces:()=>{this.navigationSections.toggle(`workspaces`)},toggleSessions:()=>{this.navigationSections.toggle(`sessions`)},selectProject:e=>this.selectNavigationItem(`projects`,`workspaces`,()=>this.selectProjectFromNavigation(e)),closeProject:e=>this.projects.closeProject(e.id),selectWorkspace:e=>this.selectNavigationItem(`workspaces`,`sessions`,()=>this.selectWorkspaceFromNavigation(e)),deleteWorkspace:e=>{this.deleteWorkspace(e)},archivedCollapsed:()=>{this.sessions.clearSelectionAfterArchivedCollapse()},startSession:()=>this.startSessionFromNavigation(),selectSession:e=>this.selectNavigationItem(`sessions`,`chat`,()=>this.selectSessionFromNavigation(e)),markSessionRead:e=>{this.markSessionsRead([e])},markSessionsRead:e=>{this.markSessionsRead(e)},searchSessions:()=>{this.openSessionSearchDialog()},toggleSessionPin:e=>{this.sessions.togglePinned(e)},archiveSession:e=>this.sessions.archiveSession(e),archiveSessionWithDescendants:e=>this.sessions.archiveSessionWithDescendants(e),archiveSessions:e=>this.sessions.archiveSessions(e),restoreSession:e=>this.selectNavigationItem(`sessions`,`chat`,()=>this.sessions.restoreSession(e)),deleteCachedNewSession:e=>this.sessions.deleteCachedNewSession(e),deleteArchivedSession:e=>this.sessions.deleteArchivedSessions([e]),deleteArchivedSessions:e=>this.sessions.deleteArchivedSessions(e),renameSession:(e,t)=>this.sessions.renameSession(e,t),detachParentSession:e=>this.sessions.detachParent(e),reloadSession:e=>this.sessions.reloadSession(e),cleanupSessions:()=>{this.openSessionCleanupDialog()},focusNavigationTarget:e=>{this.focusNavigationTarget(e)},cancelKeyboardNavigation:()=>{this.openChatAndFocusComposer()},moveProject:(e,t)=>{this.moveNavigationItem({kind:`projects`,machineId:M(this.state)},e.id,t)},moveWorkspace:(e,t)=>{this.moveNavigationItem({kind:`workspaces`,machineId:M(this.state),projectId:e.projectId},e.id,t)},moveSessionPin:(e,t)=>{this.moveSessionPin(e,t)}},this.presentationContextKey=``,this.presentationContextCache={mode:`normal`},this.handleSendPrompt=(e,t,n,r,i,a)=>this.sendPrompt(e,t,n,r,i,a),this.visiblePromptChips=[],this.handleRemovePromptChip=e=>{this.plugins.promptChips.removeByUser(e)},this.handleStopActiveWork=()=>{this.sessions.stopActiveWork()},this.handleClearServerQueue=()=>{this.sessions.clearServerQueue()},this.handleQueuedMessageAction=async e=>{let t=this.state.selectedSession;if(t===void 0||this.queuedMessageActionTarget!==void 0||this.messageRevertTarget!==void 0||this.isReplacingPrompt(this.state)||M(this.state)!==e.machineId||t.id!==e.sessionId||t.cwd!==e.cwd||!this.canMutateQueueMessage(t,e.machineId))return;let n=this.promptEditor??void 0;if(e.action===`edit`){let t=An(e.expectedQueue,e.index);if(t!==void 0&&!window.confirm(t)||(n?.view?.state.doc.toString()??``)!==``&&!window.confirm(D(`ui.piWebApp.confirmRecallDraft`,`Recalling will replace your unsent draft. Continue?`)))return}let r=this.navigationSelectionSeq;this.queuedMessageActionTarget=e;try{e.action===`edit`&&n!==void 0&&(n.disabled=!0,await n.updateComplete);let i=this.state.selectedSession;if(r!==this.navigationSelectionSeq||M(this.state)!==e.machineId||i?.id!==t.id||i.cwd!==t.cwd||i.path!==t.path)return;await this.sessions.mutateQueuedMessage(e.action,e.index,e.expectedQueue)}finally{this.queuedMessageActionTarget===e&&(this.queuedMessageActionTarget=void 0),this.requestUpdate()}},this.handleMessageAction=async(e,t)=>{let n=this.state,r=this.messageActionContext(n);if(r?.machine.id!==e.machine.id||r.session.id!==e.session.id||r.session.cwd!==e.session.cwd)return;let i=n.messages.find(t=>t.entryId===e.message.entryId),a=i===void 0?void 0:wn(i,e.message.role);if(a===void 0)return;let o={...r,message:a};return this.plugins.runMessageAction(t,o,e=>{let t=()=>M(this.state)===o.machine.id&&this.state.selectedSession?.id===o.session.id&&this.state.selectedSession.cwd===o.session.cwd,n=async n=>{if(!t()||!this.plugins.promptChipOwnerAvailable(e.registrationPluginId,o.machine.id))throw Error(`This message's conversation is no longer available.`);if(n===`fork`)return this.sessions.actOnMessage(o.message.entryId,n);if(this.messageRevertTarget!==void 0||this.queuedMessageActionTarget!==void 0||this.isReplacingPrompt(this.state))throw Error(D(`ui.piWebApp.draftActionInProgress`,`Another draft-replacing action is already in progress.`));let r=this.promptEditor??void 0,i=r?.view?.state.doc.toString()??``;if(o.message.role===`user`&&i!==``&&!window.confirm(D(`ui.piWebApp.confirmGoBackDraft`,`Going back will replace your unsent draft. Continue?`)))return;let a=this.state.selectedSession;if(a===void 0)return;let s={machineId:o.machine.id,sessionId:a.id,cwd:a.cwd,path:a.path},c=this.navigationSelectionSeq;this.messageRevertTarget=s;try{if(r!==void 0&&(r.disabled=!0,await r.updateComplete),!t()||c!==this.navigationSelectionSeq||this.state.selectedSession?.path!==s.path)return;await this.sessions.actOnMessage(o.message.entryId,n)}finally{this.messageRevertTarget===s&&(this.messageRevertTarget=void 0),this.requestUpdate()}};return{...o,...this.messageActionHelpers(e,o),history:{fork:()=>n(`fork`),goBack:()=>n(`back`)}}})},this.handleDismissWarning=e=>{this.sessions.dismissWarning(e)},this.handleSubmitAsk=(e,t)=>this.sessions.submitAsk(e,t),this.handleAnswerDialog=(e,t)=>this.sessions.answerDialog(e,t),this.handleCancelDialog=e=>this.sessions.cancelDialog(e),this.handleDismissClosedDialog=e=>{this.sessions.dismissClosedDialog(e)},this.handleDismissNotification=e=>{this.notifications.dismissNotification(e)},this.handleDismissAllNotifications=()=>{this.notifications.dismissAll()},this.handleToggleWarnings=()=>{let e=Tu(this.sessionWarningVisibility);e!==this.sessionWarningVisibility&&(this.sessionWarningVisibility=e,this.requestUpdate())},this.handleSelectModel=()=>{this.openModelDialog()},this.handleToggleModelEnabled=async(e,t,n)=>{if(this.apiScope!==`normal`)return;let r=this.currentModelDialog();if(r!==void 0){this.modelDialogMutationInFlight+=1;try{this.applyModelDialogCatalog(r,await this.sessions.setModelEnabled(e,t,n))}finally{this.finishModelDialogMutation()}}},this.handleSetModelScope=async e=>{if(this.apiScope!==`normal`)return;let t=this.currentModelDialog();if(t!==void 0){this.modelDialogMutationInFlight+=1;try{this.applyModelDialogCatalog(t,await this.sessions.setModelScope(e))}finally{this.finishModelDialogMutation()}}},this.handleSetDefaultModel=e=>this.pinSessionDefault(`model`,e),this.handleSetDefaultThinking=e=>this.pinSessionDefault(`thinking`,e),this.handleSelectThinking=()=>{this.openThinkingDialog()},this.showNavigation=()=>{let e=ft(this.ownerDocument);this.navigationOpener=e instanceof HTMLElement?e:void 0,this.navigationDialogOpen=!0},this.closeNavigation=()=>{this.navigationDialogOpen=!1;let e=this.navigationOpener;this.navigationOpener=void 0,this.updateComplete.then(()=>{if(this.navigationDialogOpen||Ye(this.ownerDocument)||e!==void 0&&ot(e))return;let t=ft(this.ownerDocument);if(!(t instanceof HTMLElement&&t!==this&&t!==this.ownerDocument.body&&t!==this.ownerDocument.documentElement&&ot(t)))for(let e of this.renderRoot.querySelectorAll(`app-context-bar, app-mobile-main-tabs, workspace-panel`)){let t=e.shadowRoot?.querySelector(`button[aria-haspopup="dialog"][aria-pressed]`);if(t!=null&&ot(t))return}})},this.changeNavigationPreferences=e=>{let t=this.navigationPreferences.pinnedIds,n=this.resolvedNavigationPreferences().pinnedIds,r=new Set(e.pinnedIds),i=t.length===0||r.size===0?e.pinnedIds:[...t.filter(e=>r.has(this.resolveNavigationPinnedId(e))),...e.pinnedIds.filter(e=>!n.includes(e))];this.navigationPreferences={...e,pinnedIds:[...new Set(i)]},a_(this.navigationPreferences)},this.navigationPanelActions=this.createPanelActions(`navigation`),this.workspacePanelActions=this.createPanelActions(`workspace`),this.deletingWorkspaceIds=[],this.handleUseSuggestedInput=(e,t)=>{this.sessions.useSuggestedInput(e,t)},this.emptyClientQueue=[],this.handleLoadEarlierMessages=()=>this.withChatPrependTransition(()=>this.sessions.loadEarlierMessages()),this.handleOpenNavigationSection=e=>{this.openNavigationSection(e)},this.handleReloadApp=()=>{this.hardReloadApp()},this.selectNavigationTab=e=>{e===`navigation`||e===`chat`?this.selectMainView(e):this.openWorkspaceTool(e)},this.messageActionInputs=``,this.handleDisplayedMessageAction=async(e,t)=>{let n=this.messageActionContext(this.state);if(n?.machine.id!==e.machine.id||n.session.id!==e.session.id||n.session.cwd!==e.session.cwd)return;let r={...n,message:e.message};return this.plugins.runDisplayedMessageAction(t,r,e=>({...r,...this.messageActionHelpers(e,r)}))},v.createController(this),new gC(this,()=>this.settingsSection!==void 0,()=>$t(()=>import(`./SettingsDialog-DFUpwUyp.js`),__vite__mapDeps([0,1,2]),import.meta.url),e=>{this.closeSettings(),this.setState({error:Zw(e)})})}get themePreference(){return Ce(this.localThemePreference,this.configuredThemePreference,this.plugins.getThemes())}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionWarningVisibility(),this.syncSessionActivityAcknowledgement()}updated(){this.sessions.isChatLoadDeferred&&(this.readyChatIdentity=void 0),this.committedChatIdentity=Fw(this.state),this.syncSelectedSessionReadState(),this.plugins.notifySelectionChanged(),this.syncPluginStylesheets(),this.isChatVisible()?this.sessions.isChatLoadDeferred?this.scheduleSelectedChatLoad():this.displayedChatIdentity=Fw(this.state):this.cancelSelectedChatLoad()}scheduleSelectedChatLoad(){this.selectedChatLoadFrame===void 0&&(this.selectedChatLoadFrame=requestAnimationFrame(()=>{this.selectedChatLoadFrame=requestAnimationFrame(()=>{this.selectedChatLoadFrame=void 0,this.isConnected&&this.isChatVisible()&&this.sessions.loadSelectedSession()})}))}cancelSelectedChatLoad(){this.selectedChatLoadFrame!==void 0&&(cancelAnimationFrame(this.selectedChatLoadFrame),this.selectedChatLoadFrame=void 0)}isChatVisible(){let e=this.effectiveMainView();return e===`chat`||e===`navigation`&&!this.appShell.isMobileNavigationLayout||this.isDesktopSideBySideLayout()}syncSessionWarningVisibility(){let e=this.state.selectedSession;this.sessionWarningVisibility=Su(this.sessionWarningVisibility,e===void 0?void 0:j(M(this.state),e.id),this.state.status?.sessionId===e?.id?this.state.status?.warnings??[]:void 0)}syncSessionActivityAcknowledgement(){if(this.dismissedActivityNotices.size===0)return;let e=this.state.selectedSession,t=this.state.status,n=M(this.state);for(let t of Object.values(this.state.sessionStatuses))t.sessionId!==e?.id&&t.recentlyActiveElsewhere===!1&&this.dismissedActivityNotices.delete(j(n,t.sessionId));e!==void 0&&t?.sessionId===e.id&&t.recentlyActiveElsewhere===!1&&this.dismissedActivityNotices.delete(j(n,e.id))}unacknowledgedActivitySessionKey(e=this.state){let t=e.selectedSession;if(t===void 0||e.status?.sessionId!==t.id||e.status.recentlyActiveElsewhere!==!0)return;let n=j(M(e),t.id);return this.dismissedActivityNotices.has(n)?void 0:n}renderSessionActivityNotice(){return this.unacknowledgedActivitySessionKey()===void 0?null:E`
|
|
3525
3525
|
<section class="composer-activity-notice" role="alert" aria-label=${D(`ui.sessionActivity.title`,`Recent activity in another instance`)}>
|
|
3526
3526
|
<div class="composer-activity-notice-text">
|
|
3527
3527
|
<p>${D(`ui.sessionActivity.message`,`Recently active in another PI-WEB instance. Avoid working on this session in both instances at once.`)}</p>
|
|
3528
3528
|
</div>
|
|
3529
3529
|
<button type="button" class="ui-button ui-button--action" @click=${this.handleDismissActivityNotice}>${D(`ui.sessionActivity.dismiss`,`Dismiss and continue`)}</button>
|
|
3530
3530
|
</section>
|
|
3531
|
-
`}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=M(this.state);if(!this.isSessionSeen(t,e))return;let n=this.renderedTranscript;n?.sessionId===e.id&&n.messages===this.state.messages&&n.start===this.state.messagePageStart&&n.end===this.state.messagePageEnd&&this.sessionUnread.acknowledgeLoaded(t,e,{start:n.start,end:n.end,total:this.state.messagePageTotal,leafId:this.state.messagePageLeafId})}markSessionsRead(e){let t=M(this.state);for(let n of e)this.sessionUnread.acknowledge(t,n)}async commitReadyChatAfterRender(e,t){let n=jw(e,t);await this.updateComplete,this.unreadConnected&&Mw(this.state)===n&&(this.readyChatIdentity=n,this.refreshSelectedUnreadHistory(),this.syncSelectedSessionReadState())}refreshSelectedUnreadHistory(){let e=this.state.selectedSession,t=M(this.state);e!==void 0&&this.readyChatIdentity===jw(t,e)&&this.sessionUnread.needsHistoryRefresh(t,e,this.state.messagePageEnd,this.state.messagePageLeafId)&&this.sessions.refreshSelectedSession(e.id)}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(M(this.state),this.state.sessions);Rw(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncUnreadPresence(){let e=du({machineIds:this.state.machines.map(e=>e.id),projectionFor:e=>this.sessionUnread.projection(e),selectedMachineId:M(this.state),projects:this.state.projects,workspaces:this.state.workspaces,workspacesByProjectId:this.state.workspacesByProjectId});_u(e,this.unreadPresence)||(this.unreadPresence=e)}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=jw(e,t);if(Mw(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isRenderedModalOpen())return!1;let r=this.effectiveMainView();return r===`chat`?!0:r===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isRenderedModalOpen(){return Ye(this.ownerDocument)}connectedCallback(){super.connectedCallback(),this.normalAuthInitSeq+=1,this.stylesheetRuntime.connect(this.ownerDocument),window.addEventListener(`popstate`,this.onPopState),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,mw),window.addEventListener(`focusin`,this.resetKeyboardSequence),window.addEventListener(`blur`,this.resetKeyboardSequence),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.initializeNormalAuth(this.normalAuthInitSeq)}startAuthenticatedApp(){this.isConnected&&!this.authenticatedAppRunning&&(this.authenticatedAppRunning=!0,this.syncNavigationOrder(),this.unreadConnected=!0,this.connectRealtime(),this.renegotiateUnreadMachines(),this.apiScope===`normal`&&(this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},ow)),this.scheduleSelectedSessionRefresh(),this.refreshWorkspaceActivity(),this.refreshMachineStatusSnapshots(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()}))}async initializeNormalAuth(e){if(this.apiScope===`management`){if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthStatus={configured:!0,authenticated:!0},this.normalAuthLoading=!1,this.startAuthenticatedApp()}else{this.normalAuthLoading=!0,this.normalAuthError=``;try{let t=await je.status();if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthStatus=t,t.authenticated&&this.startAuthenticatedApp()}catch(t){if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthError=D(`ui.piWebApp.failedToCheckNormalModePassword`,`Failed to check normal-mode password: {errorMessageerror}`,{errorMessageerror:Jw(t)})}finally{this.isConnected&&e===this.normalAuthInitSeq&&(this.normalAuthLoading=!1)}}}disconnectedCallback(){this.workspaceNavigationGeneration+=1,this.normalAuthInitSeq+=1,this.authenticatedAppRunning=!1,this.stylesheetRuntime.disconnect(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,mw),window.removeEventListener(`focusin`,this.resetKeyboardSequence),window.removeEventListener(`blur`,this.resetKeyboardSequence),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.builtInPluginsReady.catch(()=>void 0),this.plugins.beginShutdown(),this.plugins.dispose(),this.auth.dispose(),this.sessions.dispose(),this.sessionWorkTransitions.clear(),this.cancelSelectedChatLoad(),this.notifications.dispose(),this.serverNotices.retainMachines(new Set),this.realtime.close(),this.closeMachineActivitySockets(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.selectedSessionRefreshTimer!==void 0&&window.clearTimeout(this.selectedSessionRefreshTimer),this.selectedSessionRefreshTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.cancelWorkspaceDeletionRefresh(),this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!Lw(this.state,e))return;let t=this.state;this.state={...this.state,...e},Uw(t)!==Uw(this.state)&&(this.cancelWorkspaceDeletionRefresh(),this.state={...this.state,workspaceDeletionRuns:{}}),(M(t)!==M(this.state)||t.selectedProject?.id!==this.state.selectedProject?.id||t.selectedWorkspace?.id!==this.state.selectedWorkspace?.id||t.workspaceTool!==this.state.workspaceTool||t.mainView!==this.state.mainView)&&(this.workspaceNavigationGeneration+=1);let n=Dw(t.status)!==Dw(this.state.status);this.state.modelDialog!==void 0&&(n||!this.modelDialogOriginIsCurrent(this.state.modelDialog.origin))&&(this.state={...this.state,modelDialog:void 0}),this.state.thinkingDialog!==void 0&&(n||!this.modelDialogOriginIsCurrent(this.state.thinkingDialog.origin))&&(this.state={...this.state,thinkingDialog:void 0}),Mw(t)!==Mw(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.displayedChatIdentity=void 0),Nw(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.syncUnreadPresence(),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),Pw(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),(M(t)!==M(this.state)||t.selectedProject?.id!==this.state.selectedProject?.id||t.selectedWorkspace?.id!==this.state.selectedWorkspace?.id)&&this.syncNavigationOrder()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=F();if(!await this.machines.loadMachines(e.machineId)){this.setContentError(e,this.state.error);return}if(!this.routeLocationMatchesUrl(e)){await this.projects.loadProjects(),await this.withChatScrollTransition(async()=>{await this.restoreRoute(!1)}),await this.refreshWorkspaceDeletionRuns();return}let t=this.state.machineStatuses[e.machineId??`local`];if(M(this.state)===(e.machineId??`local`)&&await this.projects.loadProjects(),!this.routeLocationMatchesUrl(e)){await this.withChatScrollTransition(async()=>{await this.restoreRoute(!1)}),await this.refreshWorkspaceDeletionRuns();return}let n=this.apiScope===`management`?this.projects.managementEntryProject({...e,machineId:e.machineId??`local`}):void 0;n===void 0?await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)):await this.navigateToProjectFromController(n,{expected:{...e,machineId:e.machineId??`local`}}),this.shouldDeferRemoteRouteRestore(e,t)?this.deferRemoteRouteRestore(e):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){await Fc([this.renegotiateUnreadMachines(),this.sessions.refreshSelectedSession(void 0,{recoverNetwork:!0}),this.sessions.refreshCurrentWorkspaceSessions(M(this.state),{recoverNetwork:!0}),this.refreshMachineActivities(),this.refreshMachineStatusSnapshots(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology(),...this.navigationOrderScopes().map(e=>this.navigationOrder.load(e))])}schedulePiWebStatusRefresh(e=cw){this.apiScope!==`management`&&(this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.piWebStatusController.refresh()},e))}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshWorkspaceActivity(e=M(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){let e=this.state.machines.length===0?[M(this.state)]:this.state.machines.filter(e=>Iw(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}scheduleSelectedSessionRefresh(e=this.normalAuthInitSeq){this.isConnected&&this.authenticatedAppRunning&&e===this.normalAuthInitSeq&&(this.selectedSessionRefreshTimer!==void 0&&window.clearTimeout(this.selectedSessionRefreshTimer),this.selectedSessionRefreshTimer=window.setTimeout(()=>{this.selectedSessionRefreshTimer=void 0,this.refreshSelectedTranscript().finally(()=>{this.scheduleSelectedSessionRefresh(e)})},sw))}async refreshSelectedTranscript(){let e=this.state.selectedSession,t=this.state.status;e!==void 0&&e.archived!==!0&&this.isChatVisible()&&document.visibilityState===`visible`&&(t?.isStreaming===!0||t?.isCompacting===!0||t?.isBashRunning===!0||(t?.pendingMessageCount??0)>0||await this.sessions.refreshSelectedSession(e.id,{silent:!0}))}async refreshMachineStatusSnapshots(){let e=this.state.machines.length===0?[M(this.state)]:this.state.machines.filter(e=>Iw(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(async e=>{try{await this.machineStatus.refresh(e)}catch(t){console.warn(`Failed to refresh machine status for ${e}`,t)}}))}async loadClientConfig(){if(this.apiScope!==`management`)try{this.applyClientConfig((await Xe.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEB config`,e)}}applyClientConfig(e){this.configuredThemePreference=e.defaultTheme,this.applyPreferredTheme(!1),this.shortcutConfig=e.shortcuts??{},this.defaultStreamingBehavior=e.defaultStreamingBehavior??`steer`,this.workspaceUploadDefaultFolder=it(e),this.workspaceAttachmentsDefaultFolder=Pe(e)}async submitNormalAuth(e){let t=this.normalAuthDialogMode??this.normalAuthGateMode();if(!(t===void 0||this.normalAuthLoading)){this.normalAuthLoading=!0,this.normalAuthError=``;try{t===`setup`?await je.setup(e.password):t===`change`?await je.changePassword(e.currentPassword??``,e.password):await je.login(e.password);let n=await je.status();this.normalAuthStatus=n,this.normalAuthDialogMode=void 0,n.authenticated&&this.startAuthenticatedApp()}catch(e){this.normalAuthError=Jw(e)}finally{this.normalAuthLoading=!1}}}normalAuthGateMode(){if(this.apiScope!==`management`&&this.normalAuthStatus?.authenticated!==!0)return this.normalAuthStatus?.configured===!0?`login`:`setup`}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Fc([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology(),...this.navigationOrderScopes().map(e=>this.navigationOrder.load(e))]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let e=this.state.selectedWorkspace,t=this.effectiveWorkspaceTool();e!==void 0&&t!==void 0&&await this.invalidateWorkspacePanels(t)}hardReloadApp(){window.location.reload()}async restoreRoute(e,t,n=`current-url`){let r=this.restoreRouteFor(F(),e,void 0,t,n),i=this.routeRestoreSeq;return await r,i===this.routeRestoreSeq&&(this.rememberCurrentMachineNavigation(),!0)}async navigate(e,t,n){let{route:r,contributionQuery:i}=Nu(e,t,F(),na(),M(this.state),(e,t)=>{let n=this.plugins.resolveWorkspacePanelRouteId(e,t);if(n!==void 0)return{contributionId:n,sourceContributionId:this.plugins.getWorkspacePanels().find(e=>e.id===n)?.sourceContributionId}},n);await this.commitAndRestoreNavigation({...r,machineId:r.machineId??`local`,tool:r.tool,view:r.view,surface:{contributionQuery:i}},{replace:t?.history===`replace`})}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r,i=`current-url`){this.setContentError(e,``);let a=M(this.state),o=e.projectId===void 0||e.projectId===``?Bw():n,s=this.beginNavigationOperation(vw),c=this.beginNavigationOperation(dw);this.routeMatchesCurrentSelection(e)||(this.routeSelectionRestoreSeq+=1);let l=this.routeSelectionRestoreSeq,u={...c,isCurrent:()=>l===this.routeSelectionRestoreSeq&&c.isCurrent()},d=++this.routeRestoreSeq;this.routeRestoreDepth+=1;try{if(!await this.restoreRouteMachine(e,!1)){if(!u.isCurrent())return;let t=this.state.error;this.workspaces.clearSelection({updateUrl:!1}),t!==``&&this.setState({error:t});let n=e.machineId??`local`;this.setContentError(e,D(`ui.main.9c637b97e1a5`,`Machine not found: {arg0}`,{arg0:n}));let r=A(n);this.state.browserErrors[qn(r)]===void 0&&this.browserErrors.report(r,t||D(`ui.main.9c637b97e1a5`,`Machine not found: {arg0}`,{arg0:n}));return}if(!u.isCurrent())return;let n=this.loadPluginsForSelectedMachine();n.catch(()=>void 0);let a=Ta({...e,tool:void 0},()=>void 0),c=e.view!==void 0&&a.view===void 0,l=Tw(a),f={updateUrl:t,urlPublication:i,unavailableToolRoute:!1,unavailablePanelViewRoute:c,requestedTool:void 0,requestedRoute:e,restoreSeq:d,navigation:s,...l===void 0?{}:{restoredWorkspaceIdentity:l}},p=e.tool!==void 0||c,m=async()=>{if(!p)return f;if(await n,!this.isCurrentRouteRestore(d,s)||M(this.state)!==(e.machineId??`local`))return;let t=this.resolveBrowserAppRoute(e);return this.setState({workspaceTool:t.tool,...r===void 0&&t.view!==void 0?{mainView:t.view}:{}}),{...f,unavailableToolRoute:e.tool!==void 0&&t.tool===void 0,unavailablePanelViewRoute:e.view!==void 0&&t.view===void 0,requestedTool:t.tool}};if(this.isCurrentRouteRestore(d,s)&&this.setState({...p?{}:{workspaceTool:void 0},mainView:r??a.view??this.defaultRouteView()}),a.projectId===void 0||a.projectId===``){let e=this.state.error;this.workspaces.clearSelection({updateUrl:!1}),e!==``&&this.setState({error:e});let t=await m();t!==void 0&&await this.finishWorkspaceRouteRestore(o,t);return}if(this.routeMatchesCurrentSelection(a)){let e=await m();e!==void 0&&await this.finishWorkspaceRouteRestore(o,e);return}let h=this.state.projects.find(e=>e.id===a.projectId);if(!h){let t=this.state.error;this.workspaces.clearSelection({updateUrl:!1}),t!==``&&this.setState({error:t}),this.setContentError(e,this.projects.loadErrors.get(M(this.state))??D(`ui.main.bd4a8479284a`,`Project not found: {arg0}`,{arg0:a.projectId}));let n=A(M(this.state));this.state.browserErrors[qn(n)]===void 0&&this.browserErrors.report(n,D(`ui.main.bd4a8479284a`,`Project not found: {arg0}`,{arg0:a.projectId})),await m();return}let g=i===`deferred`&&this.state.selectedProject?.id===h.id&&a.workspaceId!==void 0?this.state.workspaces.find(e=>e.projectId===h.id&&e.id===a.workspaceId):void 0,ee=g!==void 0&&this.state.selectedWorkspace?.projectId===g.projectId&&this.state.selectedWorkspace.id===g.id?this.sessions.preferredSession(g.path,this.state.sessions,a.sessionId):void 0,_;if(ee===void 0?_=g===void 0?await this.workspaces.selectProject(h,{workspaceId:a.workspaceId,sessionId:a.sessionId,updateUrl:!1,navigation:u}):await this.workspaces.selectWorkspace(g,{sessionId:a.sessionId,updateUrl:!1,navigation:u}):await this.sessions.selectSession(ee,{deferChatLoading:a.sessionId===void 0,updateUrl:!1,navigation:u}),u.isCurrent()&&this.setContentError(e,_??``),!this.isCurrentRouteRestore(d,s))return;let te=await m();te!==void 0&&await this.finishWorkspaceRouteRestore(o,te)}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),M(this.state)!==a&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e,t){return e===this.routeRestoreSeq&&(t===void 0||t.isCurrent())}beginNavigationOperation(e){this.syncNavigationFreshness();let t={generation:this.navigationGeneration,scope:Object.freeze([...e]),isCurrent:()=>this.isNavigationFresh(t)};return t}isNavigationFresh(e){return this.syncNavigationFreshness(),e.scope.every(t=>this.navigationFieldGenerations[t]<=e.generation)}syncNavigationFreshness(){let e=F(),t=this.observedNavigationRoute;if(t!==void 0){let n=uw.filter(n=>Vw(t,n)!==Vw(e,n));if(n.length>0){let e=++this.navigationGeneration;for(let t of n)this.navigationFieldGenerations[t]=e}}this.observedNavigationRoute=e}retireNavigationScope(e){if(this.workspaceNavigationGeneration+=1,this.syncNavigationFreshness(),e.length===0)return;let t=++this.navigationGeneration;for(let n of e)this.navigationFieldGenerations[n]=t;this.sessions.retireReadRecoveries(e),this.invalidateWorkspaceSurface()}retireRouteRestoreForSynchronousNavigation(){this.retireNavigationScope(fw),this.routeRestoreSeq+=1}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?Bw():{contributionQuery:na()}}isPendingSessionStartRouteCurrent(e){return wa(F(),e)}commitPendingSessionStartNavigation(e,t){this.isPendingSessionStartRouteCurrent(e)&&(this.syncNavigationFreshness(),Oa({...F(),sessionId:t.id},{replace:!0}),this.syncNavigationFreshness(),this.rememberCurrentMachineNavigation())}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??`local`]){let n=e.machineId??`local`,r=this.state.selectedMachine;return n===`local`||r?.id!==n||r.kind!==`remote`||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===``?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=Ww(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;let e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e))this.clearPendingRemoteRouteRestore();else{this.remoteRouteRestoreInProgress=!0;try{let t=e.machineId??`local`,n=A(t),r=this.state.browserErrors[qn(n)],i=()=>this.state.browserErrors[qn(n)]!==r,a=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(a?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i()){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i()){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.contentError()===``&&this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}}scheduleNextRemoteRouteRestoreAttempt(e){this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=lw.length?(this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore()):(this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore())}setRemoteRouteRestoreMessage(e,t={}){let n=e.machineId??`local`,r=this.state.machines.find(e=>e.id===n)?.name??this.state.selectedMachine?.name??D(`bundled.info.remote.machine.674281`,`Remote machine`),i=this.state.machineStatuses[n],a=A(n),o=this.state.browserErrors[qn(a)]?.message,s=i?.error??(o!==void 0&&!o.startsWith(D(`ui.main.8829a2aadeba`,`{arg0} is unavailable`,{arg0:r}))&&!o.startsWith(D(`ui.main.ae729e314f15`,`{arg0} is still unavailable`,{arg0:r}))?o:void 0),c=t.exhausted===!0?D(`ui.piWebApp.isStillUnavailable`,`{machineName} is still unavailable.`,{machineName:r}):D(`ui.piWebApp.isUnavailableReconnecting`,`{machineName} is unavailable. Reconnecting…`,{machineName:r});this.browserErrors.report(a,`${c}${s===void 0?``:` ${s}`}`)}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.routeLocationMatchesUrl(e)&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){let n=e.machineId??`local`;if(M(this.state)===n)return!0;let r=this.state.machines.find(e=>e.id===n);return r!==void 0&&(await this.machines.selectMachine(r,{updateUrl:t}),this.state.selectedMachine?.id===n)}routeMatchesCurrentSelection(e){let t=this.state.selectedWorkspace;return(e.machineId??`local`)!==M(this.state)||e.workspaceId===void 0||e.workspaceId===``||this.state.selectedProject?.id!==e.projectId||t?.id!==e.workspaceId||!this.sessions.canReuseSelectedSession()?!1:e.sessionId===void 0?this.state.selectedSession?.id===this.sessions.preferredSession(t.path,this.state.sessions,void 0)?.id:this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e!==void 0&&await this.invalidateWorkspacePanels(e,t)}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await Xw(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return!this.isRenderedModalOpen()&&this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e,t=this.currentContributionQueryForState()){this.commitMachineNavigationSnapshot(Ol(this.state,t),e)}rememberCurrentMachineNavigation(){this.machineNavigation.remember(Ol(this.state,this.currentContributionQueryForState()))}writeWorkspaceRouteSurfaceToUrl(e){aa(e.contributionQuery??{},{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return!0;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();let n=++this.machineNavigationRestoreSeq,r=this.machineNavigation.latest(e.id)??Dl(e.id);return!await this.commitAndRestoreNavigation(r,t)||n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id?!1:this.shouldPreserveUnrestoredMachineNavigation(r)?(this.replaceMachineNavigationSnapshot(r),!0):(this.replaceNavigationUrl(this.currentContributionQueryForState()),!0)}captureNavigation(){let e=F();return{...e,machineId:e.machineId??`local`}}navigationSelectionMatchesUrl(e,t=!1){let n=F();return(n.machineId??`local`)===e.machineId&&n.projectId===e.projectId&&n.workspaceId===e.workspaceId&&n.sessionId===e.sessionId&&(t||n.tool===e.tool&&n.view===e.view)}routeLocationMatchesUrl(e){let t=F();return this.routeSelectionMatchesUrl(e)&&t.tool===e.tool&&t.view===e.view}async commitAndRestoreNavigation(e,t={}){return t.expected!==void 0&&!this.navigationSelectionMatchesUrl(t.expected,t.creationHandoff===!0)?!1:t.creationHandoff===!0?Ca(t.expected?.sessionId)?(Oa({...F(),sessionId:e.sessionId},{replace:!0}),this.restoreRoute(!1,void 0,`deferred`)):!1:(this.commitMachineNavigationSnapshot(e,{replace:t.replace}),this.restoreCommittedNavigation(e))}async navigateToProjectFromController(e,t={}){let n=Ol(this.state,this.currentContributionQueryForState()),r=e===void 0?{...n,projectId:void 0,workspaceId:void 0,sessionId:void 0,surface:{}}:{...n,projectId:e.id,workspaceId:void 0,sessionId:void 0,surface:{}};return await this.commitAndRestoreNavigation(r,t)?(this.replaceNavigationUrl(),!0):!1}async navigateToWorkspaceFromController(e,t={}){let n=Ol(this.state,this.currentContributionQueryForState()),r=e===void 0?{...n,projectId:void 0,workspaceId:void 0,sessionId:void 0,surface:{}}:{...n,projectId:e.projectId,workspaceId:e.id,sessionId:void 0,surface:{}};return await this.commitAndRestoreNavigation(r,t)?(this.replaceNavigationUrl(),!0):!1}async navigateToSessionFromController(e,t={}){let n=Ol(this.state,this.currentContributionQueryForState()),r=this.state.selectedWorkspace,i={...n,...e!==void 0&&r!==void 0?{projectId:r.projectId,workspaceId:r.id}:{},sessionId:e?.id};return await this.commitAndRestoreNavigation(i,t)?(this.replaceNavigationUrl(),!0):!1}shouldPreserveUnrestoredMachineNavigation(e){let t=this.state.browserErrors[qn(A(M(this.state)))];return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&(this.state.error!==``||t!==void 0)}openWorkspaceTool(e,t={}){let n=M(this.state),r=this.state.selectedWorkspace;r!==void 0&&this.terminalAvailableForMachine(n)&&e===this.requiredTerminalPanelId(n)?this.workspaceTerminal(`core`,r,n).open():this.publishWorkspaceTool(e,this.currentContributionQueryForState(),t)}publishWorkspaceTool(e,t=this.currentContributionQueryForState(),n={}){let r=this.availableWorkspacePanelId(e);if(r===void 0)return;let i=this.state.workspaceTool!==r||this.state.mainView!==`workspace`;i&&n.invalidateNavigationSelection!==!1&&this.invalidateNavigationSelection();let a=Ol(this.state,t);this.commitMachineNavigationSnapshot({...a,tool:r,view:`workspace`,surface:{contributionQuery:t}}),i?this.retireRouteRestoreForSynchronousNavigation():this.routeRestoreSeq+=1,i?this.setState({workspaceTool:r,mainView:`workspace`}):this.requestUpdate(),this.refreshSelectedWorkspaceTool(r)}openTerminal(e){let t=M(this.state),n=this.state.selectedWorkspace;n!==void 0&&this.workspaceTerminal(`core`,n,t).open(e)}workspaceTerminal(e,t,n,r){if(this.apiScope===`management`)return Object.freeze({open:()=>void 0,runCommand:r=>this.terminalCommandRunsForOrigin(e,n).runCommand({...r,workspace:t})});let i=this.requiredTerminalByMachine.get(n),a=i===void 0?void 0:Ad(i.binding,t,n);if(i===void 0||a===void 0){let e=$h(n);return Object.freeze({open:()=>{r?.isCurrent()!==!1&&this.setState({error:e.message})},runCommand:()=>Promise.reject(e)})}let o=e=>M(this.state)===n&&(r===void 0||this.state.selectedProject?.id===t.projectId&&this.state.selectedWorkspace?.id===t.id&&Da(F(),{machineId:n,projectId:t.projectId,workspaceId:t.id})&&(!e||r.isCurrent())),s=r=>i.facade.createWorkspaceTerminal({origin:e,registrationPluginId:i.binding.registrationPluginId,workspace:t,peer:a,host:{navigateWorkspaceContribution:(e,t)=>this.navigateRuntimeWorkspaceContribution(n,e,t,r)}});return Object.freeze({open:e=>{o(!0)&&s({...bw(r),generation:this.workspaceNavigationGeneration}).open(e)},runCommand:e=>{if(!o(e.open===!0))return Promise.reject(Error(D(`ui.main.4971c700c4fd`,`Workspace panel context is no longer current`)));let t={...bw(e.open===!0?r:void 0),generation:this.workspaceNavigationGeneration};return s(t).runCommand(e)}})}async navigateRuntimeWorkspaceContribution(e,t,n,r){if(!this.navigationUrlContextMatchesUrl(r))return;let i=n.navigationAliases??[],a=this.selectedWorkspaceRouteIdentity(),o={machineId:e,projectId:t.projectId,workspaceId:t.id},s=ia(a!==void 0&&Ew(a,o)?this.currentContributionQueryForState():{},n.contributionId,i,n.query),c={machineId:e,projectId:t.projectId,workspaceId:t.id,sessionId:void 0,tool:n.contributionId,view:`workspace`,surface:{contributionQuery:s}};if(M(this.state)!==e||this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId){if(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),!await this.commitAndRestoreNavigation(c))return;this.replaceNavigationUrl()}else this.publishWorkspaceTool(n.contributionId,s)}terminalCommandRunsForOrigin(e,t=M(this.state)){let n=Hw(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;if(this.apiScope===`normal`){let r={runCommand:({workspace:n,...r})=>this.workspaceTerminal(e,n,t).runCommand(r),listCommandRuns:e=>this.listTerminalCommandRuns(t,e),getCommandRun:async e=>(await this.listTerminalCommandRuns(t)).find(t=>t.id===e),open:e=>{M(this.state)===t&&this.openTerminal(e)}};return this.terminalCommandRunRuntimes.set(n,r),r}let i=m_(e,{api:{runTerminalCommand:(e,n)=>Dt.runTerminalCommand(e,n,t),listCommandRuns:e=>Dt.listCommandRuns(e,t),getCommandRun:e=>Dt.getCommandRun(e,t)},openTerminal:()=>void 0});return this.terminalCommandRunRuntimes.set(n,i),i}async listTerminalCommandRuns(e,t){let n=this.requiredTerminalByMachine.get(e);if(n===void 0)throw $h(e);if(M(this.state)!==e)return[];let r=t?.projectId??this.state.selectedProject?.id,i=((r===this.state.selectedProject?.id?this.state.workspaces:this.state.workspacesByProjectId[r??``])??[]).filter(e=>t?.workspaceId===void 0||e.id===t.workspaceId);return(await Promise.all(i.map(r=>{let i=Ad(n.binding,r,e);if(i===void 0)throw $h(e);return n.facade.listCommandRuns({peer:i,filter:{...t?.terminalId===void 0?{}:{terminalId:t.terminalId},...t?.statuses===void 0?{}:{statuses:t.statuses},...t?.metadata===void 0?{}:{metadata:t.metadata}}})}))).flat()}selectMainView(e,t={}){t.invalidateNavigationSelection!==!1&&this.invalidateNavigationSelection();let n=Ol(this.state,this.currentContributionQueryForState());this.commitMachineNavigationSnapshot({...n,view:e}),this.retireRouteRestoreForSynchronousNavigation(),this.setState({mainView:e})}openSettings(e=`general`){c_(e),this.settingsSection=e}closeSettings(){this.settingsSection=void 0,c_(void 0)}navigateSettings(e){this.settingsSection=e,c_(e)}restoreSettingsRoute(){this.settingsSection=s_()}handleWorkspaceChange(e,t){(M(e)!==M(t)||e.selectedProject?.id!==t.selectedProject?.id||e.selectedWorkspace?.id!==t.selectedWorkspace?.id)&&(this.routeRestoreInProgress||(this.reconcileWorkspacePanelSelection(),this.rememberCurrentMachineNavigation()),this.sessions.updatePolling(),t.selectedWorkspace!==void 0&&(this.sessions.refreshPinnedSessions(t.selectedWorkspace.path,M(this.state)),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(this.state.workspaceTool)))}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));e.add(M(this.state)),this.sessionUnread.retainMachines(e);for(let t of e)this.sessionUnread.projection(t)===void 0&&this.sessionUnread.refresh(t)}async renegotiateUnreadMachines(){if(!this.unreadConnected)return;let e=new Set(this.state.machines.map(e=>e.id));e.add(M(this.state)),await Promise.all([...e].map(async e=>{await this.renegotiateUnreadMachine(e)}))}renegotiateUnreadMachine(e){return this.unreadConnected?this.sessionUnread.refresh(e):Promise.resolve()}connectRealtime(){let e=M(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.sessions.refreshCurrentWorkspaceSessions(e,{recoverNetwork:!0}),M(this.state)===e&&this.workspaces.refreshSelectedProjectTopology(),this.renegotiateUnreadMachine(e),this.apiScope===`normal`&&this.serverNotices.refresh(e),this.refreshWorkspaceActivity(e),this.machineStatus.refresh(e).catch(t=>{console.warn(`Failed to refresh machine status for ${e}`,t)})},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new Os(this.apiScope);e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t),this.machineStatus.refresh(t).catch(e=>{console.warn(`Failed to refresh machine status for ${t}`,e)})},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=M(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>Fw(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity,e):t.type===`machine.status`&&this.machineStatus.apply(e,t.status)}handleRealtimeEvent(e,t){if(t.type===`sessions.unread`)this.sessionUnread.applyEvent(e,t);else if(t.type===`notices.updated`)this.serverNotices.applyEvent(e,t);else if(t.type===`workspace.activity`)this.activity.applyWorkspaceActivity(t.activity);else if(t.type===`machine.status`)this.machineStatus.apply(e,t.status);else if(t.type===`workspaces.changed`)M(this.state)===e&&this.state.selectedProject?.id===t.projectId&&this.workspaces.refreshSelectedProjectTopology();else if(zw(t))t.type===`terminal.exited`&&this.refreshWorkspaceDeletionRuns();else{if(t.type===`status.update`||t.type===`activity.update`){let n=this.sessionWorkTransitions.observe(e,t);n!==void 0&&this.invalidateFilesForSessionActivity(e,n)}this.sessions.applyGlobalEvent(t)}}invalidateFilesForSessionActivity(e,t){let n=this.state,r=n.selectedWorkspace;if(e!==M(n)||r===void 0||!n.sessions.some(e=>e.id===t&&e.cwd===r.path))return;let i=()=>{console.warn(`Workspace file refresh after session activity failed`)};try{this.invalidateWorkspaceResources(r,kw(n),{reason:`agent-activity`,resources:[`workspace.files`]}).catch(i)}catch{i()}}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&(this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.sessionCleanupDialog=void 0,this.setState({piWebStatus:void 0}),this.sessions.updatePolling(),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e!==void 0&&this.invalidateWorkspacePanels(e)}invalidateWorkspaceSurface(){this.workspaceSurfaceRevision+=1}workspaceSurfaceInputs(){let e=this.state;return[e.selectedMachine,e.selectedWorkspace,e.selectedSession,e.workspaceTool,e.mainView,e.piWebStatus,this.appShell.isMobileNavigationLayout,e.selectedProject,e.projects,e.workspaces,e.isLoadingProjects,e.isLoadingWorkspaces,this.workspaceContentError(),this.workspaceUploadDefaultFolder,this.workspaceSurfaceRevision,this.navigationPreferences,this.isDesktopSideBySideLayout(),xw()]}renderWorkspacePanel(){let e=this.state.selectedWorkspace,t=e===void 0?this.workspacePanelEmptyState():void 0,n=this.visibleWorkspacePanels();return E`
|
|
3531
|
+
`}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=M(this.state);if(!this.isSessionSeen(t,e))return;let n=this.renderedTranscript;n?.sessionId===e.id&&n.messages===this.state.messages&&n.start===this.state.messagePageStart&&n.end===this.state.messagePageEnd&&this.sessionUnread.acknowledgeLoaded(t,e,{start:n.start,end:n.end,total:this.state.messagePageTotal,leafId:this.state.messagePageLeafId})}markSessionsRead(e){let t=M(this.state);for(let n of e)this.sessionUnread.acknowledge(t,n)}async commitReadyChatAfterRender(e,t){let n=Pw(e,t);await this.updateComplete,this.unreadConnected&&Fw(this.state)===n&&(this.readyChatIdentity=n,this.refreshSelectedUnreadHistory(),this.syncSelectedSessionReadState())}refreshSelectedUnreadHistory(){let e=this.state.selectedSession,t=M(this.state);e!==void 0&&this.readyChatIdentity===Pw(t,e)&&this.sessionUnread.needsHistoryRefresh(t,e,this.state.messagePageEnd,this.state.messagePageLeafId)&&this.sessions.refreshSelectedSession(e.id)}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(M(this.state),this.state.sessions);Vw(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncUnreadPresence(){let e=du({machineIds:this.state.machines.map(e=>e.id),projectionFor:e=>this.sessionUnread.projection(e),selectedMachineId:M(this.state),projects:this.state.projects,workspaces:this.state.workspaces,workspacesByProjectId:this.state.workspacesByProjectId});_u(e,this.unreadPresence)||(this.unreadPresence=e)}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=Pw(e,t);if(Fw(this.state)!==n||this.committedChatIdentity!==n||this.readyChatIdentity!==n||typeof document<`u`&&(document.visibilityState!==`visible`||typeof document.hasFocus==`function`&&!document.hasFocus())||this.isRenderedModalOpen())return!1;let r=this.effectiveMainView();return r===`chat`?!0:r===`navigation`?!this.appShell.isMobileNavigationLayout:this.isDesktopSideBySideLayout()}isRenderedModalOpen(){return Ye(this.ownerDocument)}connectedCallback(){super.connectedCallback(),this.normalAuthInitSeq+=1,this.stylesheetRuntime.connect(this.ownerDocument),window.addEventListener(`popstate`,this.onPopState),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,_w),window.addEventListener(`focusin`,this.resetKeyboardSequence),window.addEventListener(`blur`,this.resetKeyboardSequence),this.systemLightThemeMedia?.addEventListener(`change`,this.onSystemLightThemeChange),this.applyPreferredTheme(!1),this.initializeNormalAuth(this.normalAuthInitSeq)}startAuthenticatedApp(){this.isConnected&&!this.authenticatedAppRunning&&(this.authenticatedAppRunning=!0,this.syncNavigationOrder(),this.unreadConnected=!0,this.connectRealtime(),this.renegotiateUnreadMachines(),this.apiScope===`normal`&&(this.piWebStatusTimer=window.setInterval(()=>{this.schedulePiWebStatusRefresh()},lw)),this.scheduleSelectedSessionRefresh(),this.refreshWorkspaceActivity(),this.refreshMachineStatusSnapshots(),this.loadClientConfig(),this.ensureGatewayPluginsLoaded(),this.loadProjectsAndRestoreRoute().finally(()=>{this.schedulePiWebStatusRefresh()}))}async initializeNormalAuth(e){if(this.apiScope===`management`){if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthStatus={configured:!0,authenticated:!0},this.normalAuthLoading=!1,this.startAuthenticatedApp()}else{this.normalAuthLoading=!0,this.normalAuthError=``;try{let t=await je.status();if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthStatus=t,t.authenticated&&this.startAuthenticatedApp()}catch(t){if(!this.isConnected||e!==this.normalAuthInitSeq)return;this.normalAuthError=D(`ui.piWebApp.failedToCheckNormalModePassword`,`Failed to check normal-mode password: {errorMessageerror}`,{errorMessageerror:Zw(t)})}finally{this.isConnected&&e===this.normalAuthInitSeq&&(this.normalAuthLoading=!1)}}}disconnectedCallback(){this.workspaceNavigationGeneration+=1,this.normalAuthInitSeq+=1,this.authenticatedAppRunning=!1,this.stylesheetRuntime.disconnect(),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,_w),window.removeEventListener(`focusin`,this.resetKeyboardSequence),window.removeEventListener(`blur`,this.resetKeyboardSequence),this.systemLightThemeMedia?.removeEventListener(`change`,this.onSystemLightThemeChange),this.keyboard.reset(),this.builtInPluginsReady.catch(()=>void 0),this.plugins.beginShutdown(),this.plugins.dispose(),this.auth.dispose(),this.sessions.dispose(),this.sessionWorkTransitions.clear(),this.cancelSelectedChatLoad(),this.notifications.dispose(),this.serverNotices.retainMachines(new Set),this.realtime.close(),this.closeMachineActivitySockets(),this.piWebStatusTimer!==void 0&&window.clearInterval(this.piWebStatusTimer),this.piWebStatusTimer=void 0,this.selectedSessionRefreshTimer!==void 0&&window.clearTimeout(this.selectedSessionRefreshTimer),this.selectedSessionRefreshTimer=void 0,this.clearScheduledPiWebStatusRefresh(),this.cancelWorkspaceDeletionRefresh(),this.clearPendingRemoteRouteRestore(),super.disconnectedCallback()}setState(e){if(!Bw(this.state,e))return;let t=this.state;this.state={...this.state,...e},Kw(t)!==Kw(this.state)&&(this.cancelWorkspaceDeletionRefresh(),this.state={...this.state,workspaceDeletionRuns:{}}),(M(t)!==M(this.state)||t.selectedProject?.id!==this.state.selectedProject?.id||t.selectedWorkspace?.id!==this.state.selectedWorkspace?.id||t.workspaceTool!==this.state.workspaceTool||t.mainView!==this.state.mainView)&&(this.workspaceNavigationGeneration+=1);let n=Aw(t.status)!==Aw(this.state.status);this.state.modelDialog!==void 0&&(n||!this.modelDialogOriginIsCurrent(this.state.modelDialog.origin))&&(this.state={...this.state,modelDialog:void 0}),this.state.thinkingDialog!==void 0&&(n||!this.modelDialogOriginIsCurrent(this.state.thinkingDialog.origin))&&(this.state={...this.state,thinkingDialog:void 0}),Fw(t)!==Fw(this.state)&&(this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.displayedChatIdentity=void 0),Iw(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.syncUnreadPresence(),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),Lw(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),(M(t)!==M(this.state)||t.selectedProject?.id!==this.state.selectedProject?.id||t.selectedWorkspace?.id!==this.state.selectedWorkspace?.id)&&this.syncNavigationOrder()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=F();if(!await this.machines.loadMachines(e.machineId)){this.setContentError(e,this.state.error);return}if(!this.routeLocationMatchesUrl(e)){await this.projects.loadProjects(),await this.withChatScrollTransition(async()=>{await this.restoreRoute(!1)}),await this.refreshWorkspaceDeletionRuns();return}let t=this.state.machineStatuses[e.machineId??`local`];if(M(this.state)===(e.machineId??`local`)&&await this.projects.loadProjects(),!this.routeLocationMatchesUrl(e)){await this.withChatScrollTransition(async()=>{await this.restoreRoute(!1)}),await this.refreshWorkspaceDeletionRuns();return}let n=this.apiScope===`management`?this.projects.managementEntryProject({...e,machineId:e.machineId??`local`}):void 0;n===void 0?await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)):await this.navigateToProjectFromController(n,{expected:{...e,machineId:e.machineId??`local`}}),this.shouldDeferRemoteRouteRestore(e,t)?this.deferRemoteRouteRestore(e):(this.clearPendingRemoteRouteRestore(),this.rememberCurrentMachineNavigation()),await this.refreshWorkspaceDeletionRuns()}handleBrowserResumeSignal(){this.appShell.repairViewportPosition(),this.schedulePiWebStatusRefresh(),this.retryPendingRemoteRouteRestoreSoon()}async refreshAfterBrowserResume(){await Fc([this.renegotiateUnreadMachines(),this.sessions.refreshSelectedSession(void 0,{recoverNetwork:!0}),this.sessions.refreshCurrentWorkspaceSessions(M(this.state),{recoverNetwork:!0}),this.refreshMachineActivities(),this.refreshMachineStatusSnapshots(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology(),...this.navigationOrderScopes().map(e=>this.navigationOrder.load(e))])}schedulePiWebStatusRefresh(e=dw){this.apiScope!==`management`&&(this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.piWebStatusController.refresh()},e))}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshWorkspaceActivity(e=M(this.state)){try{await this.activity.refresh(e)}catch(t){console.warn(`Failed to refresh workspace activity for ${e}`,t)}}async refreshMachineActivities(){let e=this.state.machines.length===0?[M(this.state)]:this.state.machines.filter(e=>zw(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(e=>this.refreshWorkspaceActivity(e)))}scheduleSelectedSessionRefresh(e=this.normalAuthInitSeq){this.isConnected&&this.authenticatedAppRunning&&e===this.normalAuthInitSeq&&(this.selectedSessionRefreshTimer!==void 0&&window.clearTimeout(this.selectedSessionRefreshTimer),this.selectedSessionRefreshTimer=window.setTimeout(()=>{this.selectedSessionRefreshTimer=void 0,this.refreshSelectedTranscript().finally(()=>{this.scheduleSelectedSessionRefresh(e)})},uw))}async refreshSelectedTranscript(){let e=this.state.selectedSession,t=this.state.status;e!==void 0&&e.archived!==!0&&this.isChatVisible()&&document.visibilityState===`visible`&&(t?.isStreaming===!0||t?.isCompacting===!0||t?.isBashRunning===!0||(t?.pendingMessageCount??0)>0||await this.sessions.refreshSelectedSession(e.id,{silent:!0}))}async refreshMachineStatusSnapshots(){let e=this.state.machines.length===0?[M(this.state)]:this.state.machines.filter(e=>zw(e,this.state.machineStatuses[e.id])).map(e=>e.id);await Promise.all(e.map(async e=>{try{await this.machineStatus.refresh(e)}catch(t){console.warn(`Failed to refresh machine status for ${e}`,t)}}))}async loadClientConfig(){if(this.apiScope!==`management`)try{this.applyClientConfig((await Xe.config()).effectiveConfig)}catch(e){console.warn(`Failed to load PI WEB config`,e)}}applyClientConfig(e){this.configuredThemePreference=e.defaultTheme,this.applyPreferredTheme(!1),this.shortcutConfig=e.shortcuts??{},this.defaultStreamingBehavior=e.defaultStreamingBehavior??`steer`,this.workspaceUploadDefaultFolder=it(e),this.workspaceAttachmentsDefaultFolder=Pe(e)}async submitNormalAuth(e){let t=this.normalAuthDialogMode??this.normalAuthGateMode();if(!(t===void 0||this.normalAuthLoading)){this.normalAuthLoading=!0,this.normalAuthError=``;try{t===`setup`?await je.setup(e.password):t===`change`?await je.changePassword(e.currentPassword??``,e.password):await je.login(e.password);let n=await je.status();this.normalAuthStatus=n,this.normalAuthDialogMode=void 0,n.authenticated&&this.startAuthenticatedApp()}catch(e){this.normalAuthError=Zw(e)}finally{this.normalAuthLoading=!1}}}normalAuthGateMode(){if(this.apiScope!==`management`&&this.normalAuthStatus?.authenticated!==!0)return this.normalAuthStatus?.configured===!0?`login`:`setup`}async refreshAppData(){if(!this.isRefreshingApp){this.isRefreshingApp=!0;try{await Fc([this.sessions.refreshSelectedSession(),this.refreshMachineActivities(),this.loadClientConfig(),this.refreshWorkspaceDeletionRuns(),this.refreshCurrentWorkspaceSurface(),this.workspaces.refreshSelectedProjectTopology(),...this.navigationOrderScopes().map(e=>this.navigationOrder.load(e))]),this.schedulePiWebStatusRefresh()}finally{this.isRefreshingApp=!1}}}async refreshCurrentWorkspaceSurface(){let e=this.state.selectedWorkspace,t=this.effectiveWorkspaceTool();e!==void 0&&t!==void 0&&await this.invalidateWorkspacePanels(t)}hardReloadApp(){window.location.reload()}async restoreRoute(e,t,n=`current-url`){let r=this.restoreRouteFor(F(),e,void 0,t,n),i=this.routeRestoreSeq;return await r,i===this.routeRestoreSeq&&(this.rememberCurrentMachineNavigation(),!0)}async navigate(e,t,n){let{route:r,contributionQuery:i}=Nu(e,t,F(),na(),M(this.state),(e,t)=>{let n=this.plugins.resolveWorkspacePanelRouteId(e,t);if(n!==void 0)return{contributionId:n,sourceContributionId:this.plugins.getWorkspacePanels().find(e=>e.id===n)?.sourceContributionId}},n);await this.commitAndRestoreNavigation({...r,machineId:r.machineId??`local`,tool:r.tool,view:r.view,surface:{contributionQuery:i}},{replace:t?.history===`replace`})}async restoreRouteFor(e,t,n=this.readWorkspaceRouteSurface(e),r,i=`current-url`){this.setContentError(e,``);let a=M(this.state),o=e.projectId===void 0||e.projectId===``?Uw():n,s=this.beginNavigationOperation(xw),c=this.beginNavigationOperation(mw);this.routeMatchesCurrentSelection(e)||(this.routeSelectionRestoreSeq+=1);let l=this.routeSelectionRestoreSeq,u={...c,isCurrent:()=>l===this.routeSelectionRestoreSeq&&c.isCurrent()},d=++this.routeRestoreSeq;this.routeRestoreDepth+=1;try{if(!await this.restoreRouteMachine(e,!1)){if(!u.isCurrent())return;let t=this.state.error;this.workspaces.clearSelection({updateUrl:!1}),t!==``&&this.setState({error:t});let n=e.machineId??`local`;this.setContentError(e,D(`ui.main.9c637b97e1a5`,`Machine not found: {arg0}`,{arg0:n}));let r=A(n);this.state.browserErrors[qn(r)]===void 0&&this.browserErrors.report(r,t||D(`ui.main.9c637b97e1a5`,`Machine not found: {arg0}`,{arg0:n}));return}if(!u.isCurrent())return;let n=this.loadPluginsForSelectedMachine();n.catch(()=>void 0);let a=Ta({...e,tool:void 0},()=>void 0),c=e.view!==void 0&&a.view===void 0,l=Ow(a),f={updateUrl:t,urlPublication:i,unavailableToolRoute:!1,unavailablePanelViewRoute:c,requestedTool:void 0,requestedRoute:e,restoreSeq:d,navigation:s,...l===void 0?{}:{restoredWorkspaceIdentity:l}},p=e.tool!==void 0||c,m=async()=>{if(!p)return f;if(await n,!this.isCurrentRouteRestore(d,s)||M(this.state)!==(e.machineId??`local`))return;let t=this.resolveBrowserAppRoute(e);return this.setState({workspaceTool:t.tool,...r===void 0&&t.view!==void 0?{mainView:t.view}:{}}),{...f,unavailableToolRoute:e.tool!==void 0&&t.tool===void 0,unavailablePanelViewRoute:e.view!==void 0&&t.view===void 0,requestedTool:t.tool}};if(this.isCurrentRouteRestore(d,s)&&this.setState({...p?{}:{workspaceTool:void 0},mainView:r??a.view??this.defaultRouteView()}),a.projectId===void 0||a.projectId===``){let e=this.state.error;this.workspaces.clearSelection({updateUrl:!1}),e!==``&&this.setState({error:e});let t=await m();t!==void 0&&await this.finishWorkspaceRouteRestore(o,t);return}if(this.routeMatchesCurrentSelection(a)){let e=await m();e!==void 0&&await this.finishWorkspaceRouteRestore(o,e);return}let h=this.state.projects.find(e=>e.id===a.projectId);if(!h){let t=this.state.error;this.workspaces.clearSelection({updateUrl:!1}),t!==``&&this.setState({error:t}),this.setContentError(e,this.projects.loadErrors.get(M(this.state))??D(`ui.main.bd4a8479284a`,`Project not found: {arg0}`,{arg0:a.projectId}));let n=A(M(this.state));this.state.browserErrors[qn(n)]===void 0&&this.browserErrors.report(n,D(`ui.main.bd4a8479284a`,`Project not found: {arg0}`,{arg0:a.projectId})),await m();return}let g=i===`deferred`&&this.state.selectedProject?.id===h.id&&a.workspaceId!==void 0?this.state.workspaces.find(e=>e.projectId===h.id&&e.id===a.workspaceId):void 0,ee=g!==void 0&&this.state.selectedWorkspace?.projectId===g.projectId&&this.state.selectedWorkspace.id===g.id?this.sessions.preferredSession(g.path,this.state.sessions,a.sessionId):void 0,_;if(ee===void 0?_=g===void 0?await this.workspaces.selectProject(h,{workspaceId:a.workspaceId,sessionId:a.sessionId,updateUrl:!1,navigation:u}):await this.workspaces.selectWorkspace(g,{sessionId:a.sessionId,updateUrl:!1,navigation:u}):await this.sessions.selectSession(ee,{deferChatLoading:a.sessionId===void 0,updateUrl:!1,navigation:u}),u.isCurrent()&&this.setContentError(e,_??``),!this.isCurrentRouteRestore(d,s))return;let te=await m();te!==void 0&&await this.finishWorkspaceRouteRestore(o,te)}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),M(this.state)!==a&&this.schedulePiWebStatusRefresh()}}isCurrentRouteRestore(e,t){return e===this.routeRestoreSeq&&(t===void 0||t.isCurrent())}beginNavigationOperation(e){this.syncNavigationFreshness();let t={generation:this.navigationGeneration,scope:Object.freeze([...e]),isCurrent:()=>this.isNavigationFresh(t)};return t}isNavigationFresh(e){return this.syncNavigationFreshness(),e.scope.every(t=>this.navigationFieldGenerations[t]<=e.generation)}syncNavigationFreshness(){let e=F(),t=this.observedNavigationRoute;if(t!==void 0){let n=pw.filter(n=>Ww(t,n)!==Ww(e,n));if(n.length>0){let e=++this.navigationGeneration;for(let t of n)this.navigationFieldGenerations[t]=e}}this.observedNavigationRoute=e}retireNavigationScope(e){if(this.workspaceNavigationGeneration+=1,this.syncNavigationFreshness(),e.length===0)return;let t=++this.navigationGeneration;for(let n of e)this.navigationFieldGenerations[n]=t;this.sessions.retireReadRecoveries(e),this.invalidateWorkspaceSurface()}retireRouteRestoreForSynchronousNavigation(){this.retireNavigationScope(hw),this.routeRestoreSeq+=1}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?Uw():{contributionQuery:na()}}isPendingSessionStartRouteCurrent(e){return wa(F(),e)}commitPendingSessionStartNavigation(e,t){this.isPendingSessionStartRouteCurrent(e)&&(this.syncNavigationFreshness(),Oa({...F(),sessionId:t.id},{replace:!0}),this.syncNavigationFreshness(),this.rememberCurrentMachineNavigation())}shouldDeferRemoteRouteRestore(e,t=this.state.machineStatuses[e.machineId??`local`]){let n=e.machineId??`local`,r=this.state.selectedMachine;return n===`local`||r?.id!==n||r.kind!==`remote`||t?.ok!==!1?!1:e.projectId===void 0||e.projectId===``?this.state.projects.length===0:this.state.selectedProject?.id!==e.projectId}deferRemoteRouteRestore(e){this.pendingRemoteRouteRestore=e,this.remoteRouteRestoreAttempt=0,this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore()}retryPendingRemoteRouteRestoreSoon(){this.pendingRemoteRouteRestore!==void 0&&this.schedulePendingRemoteRouteRestore(0)}schedulePendingRemoteRouteRestore(e=qw(this.remoteRouteRestoreAttempt)){this.pendingRemoteRouteRestore!==void 0&&(this.clearPendingRemoteRouteRestoreTimer(),this.remoteRouteRestoreTimer=window.setTimeout(()=>{this.remoteRouteRestoreTimer=void 0,this.retryPendingRemoteRouteRestore()},e))}async retryPendingRemoteRouteRestore(){if(this.remoteRouteRestoreInProgress)return;let e=this.pendingRemoteRouteRestore;if(e!==void 0){if(!this.pendingRemoteRouteRestoreStillCurrent(e))this.clearPendingRemoteRouteRestore();else{this.remoteRouteRestoreInProgress=!0;try{let t=e.machineId??`local`,n=A(t),r=this.state.browserErrors[qn(n)],i=()=>this.state.browserErrors[qn(n)]!==r,a=await this.machines.refreshMachineHealth(t);if(!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(a?.ok!==!0){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.machines.refreshMachineRuntime(t),!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i()){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.projects.loadProjects(),!this.pendingRemoteRouteRestoreStillCurrent(e))return;if(i()){this.scheduleNextRemoteRouteRestoreAttempt(e);return}if(await this.withChatScrollTransition(()=>this.restoreRouteFor(e,!1)),!this.pendingRemoteRouteRestoreStillCurrent(e))return;this.clearPendingRemoteRouteRestore(),this.contentError()===``&&this.rememberCurrentMachineNavigation(),await this.refreshWorkspaceDeletionRuns()}finally{this.remoteRouteRestoreInProgress=!1}}}}scheduleNextRemoteRouteRestoreAttempt(e){this.remoteRouteRestoreAttempt+=1,this.remoteRouteRestoreAttempt>=fw.length?(this.setRemoteRouteRestoreMessage(e,{exhausted:!0}),this.clearPendingRemoteRouteRestore()):(this.setRemoteRouteRestoreMessage(e),this.schedulePendingRemoteRouteRestore())}setRemoteRouteRestoreMessage(e,t={}){let n=e.machineId??`local`,r=this.state.machines.find(e=>e.id===n)?.name??this.state.selectedMachine?.name??D(`bundled.info.remote.machine.674281`,`Remote machine`),i=this.state.machineStatuses[n],a=A(n),o=this.state.browserErrors[qn(a)]?.message,s=i?.error??(o!==void 0&&!o.startsWith(D(`ui.main.8829a2aadeba`,`{arg0} is unavailable`,{arg0:r}))&&!o.startsWith(D(`ui.main.ae729e314f15`,`{arg0} is still unavailable`,{arg0:r}))?o:void 0),c=t.exhausted===!0?D(`ui.piWebApp.isStillUnavailable`,`{machineName} is still unavailable.`,{machineName:r}):D(`ui.piWebApp.isUnavailableReconnecting`,`{machineName} is unavailable. Reconnecting…`,{machineName:r});this.browserErrors.report(a,`${c}${s===void 0?``:` ${s}`}`)}pendingRemoteRouteRestoreStillCurrent(e){let t=e.machineId??`local`;return t!==`local`&&this.pendingRemoteRouteRestore===e&&this.routeLocationMatchesUrl(e)&&this.state.selectedMachine?.id===t&&this.state.machines.some(e=>e.id===t)}clearPendingRemoteRouteRestore(){this.clearPendingRemoteRouteRestoreTimer(),this.pendingRemoteRouteRestore=void 0,this.remoteRouteRestoreAttempt=0}clearPendingRemoteRouteRestoreTimer(){this.remoteRouteRestoreTimer!==void 0&&(window.clearTimeout(this.remoteRouteRestoreTimer),this.remoteRouteRestoreTimer=void 0)}async restoreRouteMachine(e,t){let n=e.machineId??`local`;if(M(this.state)===n)return!0;let r=this.state.machines.find(e=>e.id===n);return r!==void 0&&(await this.machines.selectMachine(r,{updateUrl:t}),this.state.selectedMachine?.id===n)}routeMatchesCurrentSelection(e){let t=this.state.selectedWorkspace;return(e.machineId??`local`)!==M(this.state)||e.workspaceId===void 0||e.workspaceId===``||this.state.selectedProject?.id!==e.projectId||t?.id!==e.workspaceId||!this.sessions.canReuseSelectedSession()?!1:e.sessionId===void 0?this.state.selectedSession?.id===this.sessions.preferredSession(t.path,this.state.sessions,void 0)?.id:this.state.selectedSession?.id===e.sessionId}async refreshRestoredWorkspaceTool(e,t){e!==void 0&&await this.invalidateWorkspacePanels(e,t)}async withChatScrollTransition(e,t=()=>!0){this.chatView?.saveScrollPosition(),await e(),t()&&(await this.updateComplete,t()&&(await this.chatView?.updateComplete,t()&&(await $w(),t()&&(this.chatView?.restoreScrollPosition(),this.shouldAutoFocusPrompt()&&this.promptEditor?.focusInput()))))}shouldAutoFocusPrompt(){return!this.isRenderedModalOpen()&&this.appShell.shouldAutoFocusPrompt()}async withChatPrependTransition(e){await e(),await this.updateComplete,await this.chatView?.updateComplete}defaultRouteView(){return this.appShell.defaultRouteView()}updateUrl(e,t=this.currentContributionQueryForState()){this.commitMachineNavigationSnapshot(Ol(this.state,t),e)}rememberCurrentMachineNavigation(){this.machineNavigation.remember(Ol(this.state,this.currentContributionQueryForState()))}writeWorkspaceRouteSurfaceToUrl(e){aa(e.contributionQuery??{},{replace:!0})}async selectMachineWithMemory(e,t={}){if(this.state.selectedMachine?.id===e.id)return!0;t.rememberCurrent!==!1&&!this.routeRestoreInProgress&&this.rememberCurrentMachineNavigation();let n=++this.machineNavigationRestoreSeq,r=this.machineNavigation.latest(e.id)??Dl(e.id);return!await this.commitAndRestoreNavigation(r,t)||n!==this.machineNavigationRestoreSeq||this.state.selectedMachine?.id!==e.id?!1:this.shouldPreserveUnrestoredMachineNavigation(r)?(this.replaceMachineNavigationSnapshot(r),!0):(this.replaceNavigationUrl(this.currentContributionQueryForState()),!0)}captureNavigation(){let e=F();return{...e,machineId:e.machineId??`local`}}navigationSelectionMatchesUrl(e,t=!1){let n=F();return(n.machineId??`local`)===e.machineId&&n.projectId===e.projectId&&n.workspaceId===e.workspaceId&&n.sessionId===e.sessionId&&(t||n.tool===e.tool&&n.view===e.view)}routeLocationMatchesUrl(e){let t=F();return this.routeSelectionMatchesUrl(e)&&t.tool===e.tool&&t.view===e.view}async commitAndRestoreNavigation(e,t={}){return t.expected!==void 0&&!this.navigationSelectionMatchesUrl(t.expected,t.creationHandoff===!0)?!1:t.creationHandoff===!0?Ca(t.expected?.sessionId)?(Oa({...F(),sessionId:e.sessionId},{replace:!0}),this.restoreRoute(!1,void 0,`deferred`)):!1:(this.commitMachineNavigationSnapshot(e,{replace:t.replace}),this.restoreCommittedNavigation(e))}async navigateToProjectFromController(e,t={}){let n=Ol(this.state,this.currentContributionQueryForState()),r=e===void 0?{...n,projectId:void 0,workspaceId:void 0,sessionId:void 0,surface:{}}:{...n,projectId:e.id,workspaceId:void 0,sessionId:void 0,surface:{}};return await this.commitAndRestoreNavigation(r,t)?(this.replaceNavigationUrl(),!0):!1}async navigateToWorkspaceFromController(e,t={}){let n=Ol(this.state,this.currentContributionQueryForState()),r=e===void 0?{...n,projectId:void 0,workspaceId:void 0,sessionId:void 0,surface:{}}:{...n,projectId:e.projectId,workspaceId:e.id,sessionId:void 0,surface:{}};return await this.commitAndRestoreNavigation(r,t)?(this.replaceNavigationUrl(),!0):!1}async navigateToSessionFromController(e,t={}){let n=Ol(this.state,this.currentContributionQueryForState()),r=this.state.selectedWorkspace,i={...n,...e!==void 0&&r!==void 0?{projectId:r.projectId,workspaceId:r.id}:{},sessionId:e?.id};return await this.commitAndRestoreNavigation(i,t)?(this.replaceNavigationUrl(),!0):!1}shouldPreserveUnrestoredMachineNavigation(e){let t=this.state.browserErrors[qn(A(M(this.state)))];return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&(this.state.error!==``||t!==void 0)}openWorkspaceTool(e,t={}){let n=M(this.state),r=this.state.selectedWorkspace;r!==void 0&&this.terminalAvailableForMachine(n)&&e===this.requiredTerminalPanelId(n)?this.workspaceTerminal(`core`,r,n).open():this.publishWorkspaceTool(e,this.currentContributionQueryForState(),t)}publishWorkspaceTool(e,t=this.currentContributionQueryForState(),n={}){let r=this.availableWorkspacePanelId(e);if(r===void 0)return;let i=this.state.workspaceTool!==r||this.state.mainView!==`workspace`;i&&n.invalidateNavigationSelection!==!1&&this.invalidateNavigationSelection();let a=Ol(this.state,t);this.commitMachineNavigationSnapshot({...a,tool:r,view:`workspace`,surface:{contributionQuery:t}}),i?this.retireRouteRestoreForSynchronousNavigation():this.routeRestoreSeq+=1,i?this.setState({workspaceTool:r,mainView:`workspace`}):this.requestUpdate(),this.refreshSelectedWorkspaceTool(r)}openTerminal(e){let t=M(this.state),n=this.state.selectedWorkspace;n!==void 0&&this.workspaceTerminal(`core`,n,t).open(e)}workspaceTerminal(e,t,n,r){if(this.apiScope===`management`)return Object.freeze({open:()=>void 0,runCommand:r=>this.terminalCommandRunsForOrigin(e,n).runCommand({...r,workspace:t})});let i=this.requiredTerminalByMachine.get(n),a=i===void 0?void 0:Ad(i.binding,t,n);if(i===void 0||a===void 0){let e=ng(n);return Object.freeze({open:()=>{r?.isCurrent()!==!1&&this.setState({error:e.message})},runCommand:()=>Promise.reject(e)})}let o=e=>M(this.state)===n&&(r===void 0||this.state.selectedProject?.id===t.projectId&&this.state.selectedWorkspace?.id===t.id&&Da(F(),{machineId:n,projectId:t.projectId,workspaceId:t.id})&&(!e||r.isCurrent())),s=r=>i.facade.createWorkspaceTerminal({origin:e,registrationPluginId:i.binding.registrationPluginId,workspace:t,peer:a,host:{navigateWorkspaceContribution:(e,t)=>this.navigateRuntimeWorkspaceContribution(n,e,t,r)}});return Object.freeze({open:e=>{o(!0)&&s({...Cw(r),generation:this.workspaceNavigationGeneration}).open(e)},runCommand:e=>{if(!o(e.open===!0))return Promise.reject(Error(D(`ui.main.4971c700c4fd`,`Workspace panel context is no longer current`)));let t={...Cw(e.open===!0?r:void 0),generation:this.workspaceNavigationGeneration};return s(t).runCommand(e)}})}async navigateRuntimeWorkspaceContribution(e,t,n,r){if(!this.navigationUrlContextMatchesUrl(r))return;let i=n.navigationAliases??[],a=this.selectedWorkspaceRouteIdentity(),o={machineId:e,projectId:t.projectId,workspaceId:t.id},s=ia(a!==void 0&&kw(a,o)?this.currentContributionQueryForState():{},n.contributionId,i,n.query),c={machineId:e,projectId:t.projectId,workspaceId:t.id,sessionId:void 0,tool:n.contributionId,view:`workspace`,surface:{contributionQuery:s}};if(M(this.state)!==e||this.state.selectedWorkspace?.id!==t.id||this.state.selectedProject?.id!==t.projectId){if(this.routeRestoreInProgress||this.rememberCurrentMachineNavigation(),!await this.commitAndRestoreNavigation(c))return;this.replaceNavigationUrl()}else this.publishWorkspaceTool(n.contributionId,s)}terminalCommandRunsForOrigin(e,t=M(this.state)){let n=Gw(t,e),r=this.terminalCommandRunRuntimes.get(n);if(r!==void 0)return r;if(this.apiScope===`normal`){let r={runCommand:({workspace:n,...r})=>this.workspaceTerminal(e,n,t).runCommand(r),listCommandRuns:e=>this.listTerminalCommandRuns(t,e),getCommandRun:async e=>(await this.listTerminalCommandRuns(t)).find(t=>t.id===e),open:e=>{M(this.state)===t&&this.openTerminal(e)}};return this.terminalCommandRunRuntimes.set(n,r),r}let i=__(e,{api:{runTerminalCommand:(e,n)=>Dt.runTerminalCommand(e,n,t),listCommandRuns:e=>Dt.listCommandRuns(e,t),getCommandRun:e=>Dt.getCommandRun(e,t)},openTerminal:()=>void 0});return this.terminalCommandRunRuntimes.set(n,i),i}async listTerminalCommandRuns(e,t){let n=this.requiredTerminalByMachine.get(e);if(n===void 0)throw ng(e);if(M(this.state)!==e)return[];let r=t?.projectId??this.state.selectedProject?.id,i=((r===this.state.selectedProject?.id?this.state.workspaces:this.state.workspacesByProjectId[r??``])??[]).filter(e=>t?.workspaceId===void 0||e.id===t.workspaceId);return(await Promise.all(i.map(r=>{let i=Ad(n.binding,r,e);if(i===void 0)throw ng(e);return n.facade.listCommandRuns({peer:i,filter:{...t?.terminalId===void 0?{}:{terminalId:t.terminalId},...t?.statuses===void 0?{}:{statuses:t.statuses},...t?.metadata===void 0?{}:{metadata:t.metadata}}})}))).flat()}selectMainView(e,t={}){t.invalidateNavigationSelection!==!1&&this.invalidateNavigationSelection();let n=Ol(this.state,this.currentContributionQueryForState());this.commitMachineNavigationSnapshot({...n,view:e}),this.retireRouteRestoreForSynchronousNavigation(),this.setState({mainView:e})}openSettings(e=`general`){d_(e),this.settingsSection=e}closeSettings(){this.settingsSection=void 0,d_(void 0)}navigateSettings(e){this.settingsSection=e,d_(e)}restoreSettingsRoute(){this.settingsSection=u_()}handleWorkspaceChange(e,t){(M(e)!==M(t)||e.selectedProject?.id!==t.selectedProject?.id||e.selectedWorkspace?.id!==t.selectedWorkspace?.id)&&(this.routeRestoreInProgress||(this.reconcileWorkspacePanelSelection(),this.rememberCurrentMachineNavigation()),this.sessions.updatePolling(),t.selectedWorkspace!==void 0&&(this.sessions.refreshPinnedSessions(t.selectedWorkspace.path,M(this.state)),this.refreshWorkspaceDeletionRuns(),this.refreshSelectedWorkspaceTool(this.state.workspaceTool)))}syncSessionUnreadMachines(){if(!this.unreadConnected){this.sessionUnread.retainMachines(new Set);return}let e=new Set(this.state.machines.map(e=>e.id));e.add(M(this.state)),this.sessionUnread.retainMachines(e);for(let t of e)this.sessionUnread.projection(t)===void 0&&this.sessionUnread.refresh(t)}async renegotiateUnreadMachines(){if(!this.unreadConnected)return;let e=new Set(this.state.machines.map(e=>e.id));e.add(M(this.state)),await Promise.all([...e].map(async e=>{await this.renegotiateUnreadMachine(e)}))}renegotiateUnreadMachine(e){return this.unreadConnected?this.sessionUnread.refresh(e):Promise.resolve()}connectRealtime(){let e=M(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.sessions.refreshCurrentWorkspaceSessions(e,{recoverNetwork:!0}),M(this.state)===e&&this.workspaces.refreshSelectedProjectTopology(),this.renegotiateUnreadMachine(e),this.apiScope===`normal`&&this.serverNotices.refresh(e),this.refreshWorkspaceActivity(e),this.machineStatus.refresh(e).catch(t=>{console.warn(`Failed to refresh machine status for ${e}`,t)})},e)}syncMachineActivitySubscriptions(){let e=this.machineActivitySubscriptionIds();for(let[t,n]of this.machineRealtimeSockets.entries())e.has(t)||(n.close(),this.machineRealtimeSockets.delete(t));for(let t of e){if(this.machineRealtimeSockets.has(t))continue;let e=new Os(this.apiScope);e.connect(e=>{this.handleMachineActivityEvent(t,e)},()=>{this.renegotiateUnreadMachine(t),this.refreshWorkspaceActivity(t),this.machineStatus.refresh(t).catch(e=>{console.warn(`Failed to refresh machine status for ${t}`,e)})},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=M(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>Rw(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`sessions.unread`?this.sessionUnread.applyEvent(e,t):t.type===`workspace.activity`?this.activity.applyWorkspaceActivity(t.activity,e):t.type===`machine.status`&&this.machineStatus.apply(e,t.status)}handleRealtimeEvent(e,t){if(t.type===`sessions.unread`)this.sessionUnread.applyEvent(e,t);else if(t.type===`notices.updated`)this.serverNotices.applyEvent(e,t);else if(t.type===`workspace.activity`)this.activity.applyWorkspaceActivity(t.activity);else if(t.type===`machine.status`)this.machineStatus.apply(e,t.status);else if(t.type===`workspaces.changed`)M(this.state)===e&&this.state.selectedProject?.id===t.projectId&&this.workspaces.refreshSelectedProjectTopology();else if(Hw(t))t.type===`terminal.exited`&&this.refreshWorkspaceDeletionRuns();else{if(t.type===`status.update`||t.type===`activity.update`){let n=this.sessionWorkTransitions.observe(e,t);n!==void 0&&this.invalidateFilesForSessionActivity(e,n)}this.sessions.applyGlobalEvent(t)}}invalidateFilesForSessionActivity(e,t){let n=this.state,r=n.selectedWorkspace;if(e!==M(n)||r===void 0||!n.sessions.some(e=>e.id===t&&e.cwd===r.path))return;let i=()=>{console.warn(`Workspace file refresh after session activity failed`)};try{this.invalidateWorkspaceResources(r,Mw(n),{reason:`agent-activity`,resources:[`workspace.files`]}).catch(i)}catch{i()}}handleMachineChange(e,t){(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)&&(this.projectActivityOwnership.handleSelectedMachineChanged(),(this.pendingRemoteRouteRestore?.machineId??`local`)!==(t.selectedMachine?.id??`local`)&&this.clearPendingRemoteRouteRestore(),this.sessions.clearActiveSession(),this.realtime.close(),this.connectRealtime(),this.sessionCleanupDialog=void 0,this.setState({piWebStatus:void 0}),this.sessions.updatePolling(),this.loadPluginsForSelectedMachine())}refreshSelectedWorkspaceTool(e){e!==void 0&&this.invalidateWorkspacePanels(e)}invalidateWorkspaceSurface(){this.workspaceSurfaceRevision+=1}workspaceSurfaceInputs(){let e=this.state;return[e.selectedMachine,e.selectedWorkspace,e.selectedSession,e.workspaceTool,e.mainView,e.piWebStatus,this.appShell.isMobileNavigationLayout,e.selectedProject,e.projects,e.workspaces,e.isLoadingProjects,e.isLoadingWorkspaces,this.workspaceContentError(),this.workspaceUploadDefaultFolder,this.workspaceSurfaceRevision,this.navigationPreferences,this.isDesktopSideBySideLayout(),ww()]}renderWorkspacePanel(){let e=this.state.selectedWorkspace,t=e===void 0?this.workspacePanelEmptyState():void 0,n=this.visibleWorkspacePanels();return E`
|
|
3532
3532
|
<workspace-panel
|
|
3533
3533
|
id="workspace-panel"
|
|
3534
3534
|
.workspace=${e}
|
|
@@ -3576,7 +3576,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3576
3576
|
.onResizeEnd=${this.workspacePanelActions.resizeEnd}
|
|
3577
3577
|
.onReset=${this.workspacePanelActions.reset}
|
|
3578
3578
|
></app-panel-edge-control>
|
|
3579
|
-
`}startPanelResize(e){return e===`navigation`?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){let t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){let n=this.getBoundingClientRect().width||(typeof window>`u`?0:window.innerWidth);if(n<=0)return t.maxWidth;let r=this.oppositeResizablePanelWidth(e),i=Math.floor(n-r-
|
|
3579
|
+
`}startPanelResize(e){return e===`navigation`?this.panelCollapse.expandNavigationPanel():this.panelCollapse.expandWorkspacePanel(),this.measuredPanelWidth(e)??this.panelResize.panelWidth(e)}resizablePanelConstraints(e){let t=this.panelResize.constraints(e);return{...t,maxWidth:this.resizablePanelMaxWidth(e,t)}}resizablePanelMaxWidth(e,t){let n=this.getBoundingClientRect().width||(typeof window>`u`?0:window.innerWidth);if(n<=0)return t.maxWidth;let r=this.oppositeResizablePanelWidth(e),i=Math.floor(n-r-yw-vw);return Math.max(t.minWidth,Math.min(t.maxWidth,i))}oppositeResizablePanelWidth(e){let t=e===`navigation`?`workspace`:`navigation`;return this.isResizablePanelCollapsedOrStacked(t)?0:this.measuredPanelWidth(t)??this.panelResize.panelWidth(t)}isResizablePanelCollapsedOrStacked(e){return e===`navigation`?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed||!this.isDesktopSideBySideLayout()}isDesktopSideBySideLayout(){return this.appShell.isDesktopSideBySideLayout&&!this.panelCollapse.workspacePanelCollapsed}measuredPanelWidth(e){let t=(e===`navigation`?this.navigationPanelFrame:this.workspacePanelFrame)?.getBoundingClientRect().width;return t===void 0||t<=0?void 0:t}resetResizablePanel(e){this.panelResize.resetPanel(e)}resetResizablePanels(){this.panelResize.resetPanels()}canDeleteArchivedSessions(){return!0}canReloadSessions(){return this.selectedMachineRuntime()?.ok===!0}canClearServerQueue(){return this.selectedMachineRuntime()?.ok===!0}canMutateQueueMessage(e,t){let n=this.state.machineRuntimes[t];return e.archived!==!0&&n?.ok===!0&&ht(n,Ut.sessionsQueueMessageActions)}canCleanupSessions(){let e=this.selectedMachineRuntime();return this.apiScope===`management`&&this.state.selectedProject===void 0?!1:e?.ok===!0}hasAuthoritativeSessionPersistence(){return Is(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=M(this.state)){return e===`local`||this.state.machineRuntimes[e]?.ok===!0}archivedDeleteUnavailableMessage(){let e=this.state.selectedMachine?.name??D(`client.sessionCleanupUi.this.machine.74a83f`,`this machine`);return D(`ui.piWebApp.updateAndRestartPiWebOnBeforeDeleting`,`Update and restart Pi-Web on {machineName} before deleting archived sessions.`,{machineName:e})}sessionCleanupUnavailableMessage(){return Xl(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[M(this.state)]}openSessionCleanupDialog(){this.sessionCleanupDialog={error:``}}openSessionSearchDialog(){this.sessions.searchSessions(``),this.sessionSearchDialogOpen=!0}closeSessionSearchDialog(){this.sessionSearchDialogOpen=!1,this.sessions.searchSessions(``)}async selectSessionSearchMatch(e,t){let n=this.state.sessionSearchQuery.trim();this.sessionSearchDialogOpen=!1,await this.selectNavigationItem(`sessions`,`chat`,()=>this.sessions.selectSearchMatch(e,t,n))}closeSessionCleanupDialog(){this.sessionCleanupDialog=void 0}async previewSessionCleanup(e){let t=this.sessionCleanupRequestForCurrentProject(e);if(!this.canCleanupSessions()){this.sessionCleanupDialog={...this.sessionCleanupDialog??{},error:this.sessionCleanupUnavailableMessage(),preview:void 0,previewRequest:void 0,result:void 0,loading:!1};return}let n=M(this.state);this.sessionCleanupDialog={...this.sessionCleanupDialog??{},loading:!0,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let e=await s.cleanupPreview(t,n);if(M(this.state)!==n)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:e,previewRequest:t,result:void 0,loading:!1,error:``}}catch(e){M(this.state)===n&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:D(`ui.piWebApp.failedToPreviewCleanup`,`Failed to preview cleanup: {errorMessageerror}`,{errorMessageerror:Zw(e)})})}}async runSessionCleanup(e){let t=this.sessionCleanupRequestForCurrentProject(e),n=this.sessionCleanupDialog;if(n?.preview===void 0||Hl(n.previewRequest)!==Hl(t)){this.sessionCleanupDialog={...n??{},error:D(`ui.sessionCleanupDialog.previewBeforeRunningCleanup`,`Preview before running cleanup.`)};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...n,error:this.sessionCleanupUnavailableMessage(),running:!1};return}let r=M(this.state);this.sessionCleanupDialog={...n,running:!0,error:``};try{let e=await s.cleanup(t,r);if(M(this.state)!==r)return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:e,previewRequest:t,result:e,running:!1,error:``},await this.sessions.applySessionCleanupResult(e,r)}catch(e){M(this.state)===r&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:D(`ui.piWebApp.failedToRunCleanup`,`Failed to run cleanup: {errorMessageerror}`,{errorMessageerror:Zw(e)})})}}sessionCleanupRequestForCurrentProject(e){if(this.apiScope!==`management`)return e;let t=this.state.selectedProject,n=t===void 0?[]:this.state.workspaces.filter(e=>e.projectId===t.id).map(e=>e.path),r=e.projectCwds??n,i=new Set(n);return{...e,projectId:t?.id??``,projectCwds:r.filter(e=>i.has(e))}}navigationOrderScopes(){if(this.apiScope!==`normal`)return[];let e=M(this.state),t=[{kind:`projects`,machineId:e}],n=this.state.selectedProject,r=this.state.selectedWorkspace;return n!==void 0&&t.push({kind:`workspaces`,machineId:e,projectId:n.id}),r!==void 0&&t.push({kind:`sessionPins`,machineId:e,projectId:r.projectId,workspaceId:r.id}),t}syncNavigationOrder(){if(this.authenticatedAppRunning)for(let e of this.navigationOrderScopes())this.navigationOrder.ensure(e).catch(()=>void 0)}moveNavigationItem(e,t,n){if(this.apiScope!==`normal`)return;let r=(e.kind===`projects`?this.state.projects:this.state.workspaces).map(e=>e.id);this.navigationOrder.mutate(e,e=>{let i=Lr(r.map(e=>({id:e})),e).map(e=>e.id),a=i.indexOf(t),o=a<0?void 0:i[a+n];return o===void 0?e:Rr(e,i,t,o,n<0?`before`:`after`)}).catch(()=>void 0)}moveSessionPin(e,t){let n=this.state.selectedWorkspace;if(this.apiScope!==`normal`||e.cwd!==n?.path)return;let r={kind:`sessionPins`,machineId:M(this.state),projectId:n.projectId,workspaceId:n.id},i=kv(this.state.sessions,this.state.pinnedSessionIds);this.navigationOrder.mutate(r,n=>{let r=Lr(i.map(e=>({id:e})),n).map(e=>e.id),a=r.indexOf(e.id),o=a<0?void 0:r[a+t];return o===void 0?n:Rr(n,r,e.id,o,t<0?`before`:`after`)}).catch(()=>void 0)}uiPresentationContext(){let{selectedMachine:e,selectedProject:t,selectedWorkspace:n,selectedSession:r}=this.state,i=this.appShell.isMobileNavigationLayout,a=JSON.stringify([this.apiScope,i,e?.id,e?.name,t?.id,t?.name,n?.id,n?.label,r?.id,r?.name]);return a!==this.presentationContextKey&&(this.presentationContextKey=a,this.presentationContextCache=Object.freeze({mode:this.apiScope,compact:i,...e===void 0?{}:{machine:Object.freeze({id:e.id,name:e.name})},...t===void 0?{}:{project:Object.freeze({id:t.id,name:t.name})},...n===void 0?{}:{workspace:Object.freeze({id:n.id,label:n.label})},...r===void 0?{}:{session:Object.freeze({id:r.id,label:r.name??r.id})}})),this.presentationContextCache}renderNavigationPanel(){this.workspaceDeletionInput!==this.state.workspaceDeletionRuns&&(this.workspaceDeletionInput=this.state.workspaceDeletionRuns,this.deletingWorkspaceIds=Uu(this.state.workspaceDeletionRuns));let e=this.navigationOrderScopes(),t=e.find(e=>e.kind===`projects`),n=e.find(e=>e.kind===`workspaces`),r=e.find(e=>e.kind===`sessionPins`);return E`
|
|
3580
3580
|
<app-navigation-panel
|
|
3581
3581
|
.presentationRuntime=${this.plugins.uiPresentation}
|
|
3582
3582
|
.presentationContext=${this.uiPresentationContext()}
|
|
@@ -3660,7 +3660,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3660
3660
|
.onFocusNavigationTarget=${this.navigationActions.focusNavigationTarget}
|
|
3661
3661
|
.onCancelKeyboardNavigation=${this.navigationActions.cancelKeyboardNavigation}
|
|
3662
3662
|
></app-navigation-panel>
|
|
3663
|
-
`}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq,a;if(await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),a=await n()},i),!i()||a===!1)return;let o=this.appShell.isMobileNavigationLayout&&e===`projects`&&t===`workspaces`&&this.state.workspaces.length===1&&this.state.selectedWorkspace?.id===this.state.workspaces[0]?.id;await this.focusNavigationTarget(o?`sessions`:t,i)}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}async startSessionAndOpenChat(e=()=>!0){let t=this.navigationSelectionSeq,n=this.state.selectedWorkspace,r=M(this.state);if(n===void 0)return;let i=()=>t===this.navigationSelectionSeq&&e()&&M(this.state)===r&&this.state.selectedProject?.id===n.projectId&&this.state.selectedWorkspace?.id===n.id;if(!i()||(this.selectMainView(`chat`,{invalidateNavigationSelection:!1}),!i()))return;let a;this.sessions.startSession(async()=>i()?(a=this.openChatAndFocusComposer(i),await a,i()):!1).catch(e=>{i()&&this.browserErrors.report(Gn(r,n.projectId,n.id),String(e))}),a!==void 0&&await a.catch(()=>void 0)}async focusNavigationTarget(e,t=()=>!0){let n=this.navigationSelectionSeq,r=()=>n===this.navigationSelectionSeq&&t();r()&&(e===`chat`?await this.openChatAndFocusComposer(r):await this.focusNavigationSection(e,r))}async focusNavigationSection(e,t=()=>!0){let n=this.navigationSelectionSeq,r=()=>n===this.navigationSelectionSeq&&t();r()&&(e===`machines
|
|
3663
|
+
`}openNavigationSection(e){this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq,a;if(await this.withChatScrollTransition(async()=>{this.navigationSections.advanceAfterSelection(e),a=await n()},i),!i()||a===!1)return;let o=this.appShell.isMobileNavigationLayout&&e===`projects`&&t===`workspaces`&&this.state.workspaces.length===1&&this.state.selectedWorkspace?.id===this.state.workspaces[0]?.id;await this.focusNavigationTarget(o?`sessions`:t,i)}async startSessionFromNavigation(){let e=++this.navigationSelectionSeq;this.navigationSections.advanceAfterSelection(`sessions`),await this.startSessionAndOpenChat(()=>e===this.navigationSelectionSeq)}async startSessionAndOpenChat(e=()=>!0){let t=this.navigationSelectionSeq,n=this.state.selectedWorkspace,r=M(this.state);if(n===void 0)return;let i=()=>t===this.navigationSelectionSeq&&e()&&M(this.state)===r&&this.state.selectedProject?.id===n.projectId&&this.state.selectedWorkspace?.id===n.id;if(!i()||(this.selectMainView(`chat`,{invalidateNavigationSelection:!1}),!i()))return;let a;this.sessions.startSession(async()=>i()?(a=this.openChatAndFocusComposer(i),await a,i()):!1).catch(e=>{i()&&this.browserErrors.report(Gn(r,n.projectId,n.id),String(e))}),a!==void 0&&await a.catch(()=>void 0)}async focusNavigationTarget(e,t=()=>!0){let n=this.navigationSelectionSeq,r=()=>n===this.navigationSelectionSeq&&t();r()&&(e===`chat`?await this.openChatAndFocusComposer(r):await this.focusNavigationSection(e,r))}async focusNavigationSection(e,t=()=>!0){let n=this.navigationSelectionSeq,r=()=>n===this.navigationSelectionSeq&&t();r()&&(e===`machines`&&!$C(this.state.machines)?await this.focusNavigationSection(`projects`,r):(this.panelCollapse.expandNavigationPanel(),this.appShell.isMobileNavigationLayout&&this.selectMainView(`navigation`,{invalidateNavigationSelection:!1}),this.navigationSections.expand(e),await this.updateComplete,r()&&(await $w(),r()&&await this.navigationPanel?.focusSection(e))))}async openChatAndFocusComposer(e=()=>!0){e()&&(this.effectiveMainView()!==`chat`&&this.selectMainView(`chat`,{invalidateNavigationSelection:!1}),await this.focusChatComposer(e))}async focusChatComposer(e=()=>!0){let t=this.navigationSelectionSeq,n=()=>t===this.navigationSelectionSeq&&e();n()&&this.isChatVisible()&&(await this.updateComplete,n()&&(await $w(),n()&&(this.sessions.isChatLoadDeferred&&await $w(),await this.updateComplete,await this.promptEditor?.updateComplete,n()&&this.isChatVisible()&&!this.isRenderedModalOpen()&&(this.unacknowledgedActivitySessionKey()===void 0?this.promptEditor?.focusInput():this.renderRoot.querySelector(`.composer-activity-notice button`)?.focus()))))}async navigateSessionTree(e,t){let n=M(this.state),r=this.state.selectedSession?.id,i=this.navigationSelectionSeq,a=await this.sessions.navigateTree(e,t);return!a.cancelled&&this.navigationSelectionSeq===i&&r!==void 0&&M(this.state)===n&&this.state.selectedSession?.id===r&&await this.focusChatComposer(),a}forkSessionTree(e){return this.sessions.forkFromTree(e)}closeSessionTreeNavigator(){this.sessions.closeTreeDialog(),this.focusChatComposer()}renderSessionTreeNavigator(e){return e.treeDialog===void 0?null:E`
|
|
3664
3664
|
<session-tree-navigator
|
|
3665
3665
|
.tree=${e.treeDialog}
|
|
3666
3666
|
.onNavigate=${(e,t)=>this.navigateSessionTree(e,t)}
|
|
@@ -3668,13 +3668,13 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3668
3668
|
.onAbort=${()=>this.sessions.abortTreeNavigation()}
|
|
3669
3669
|
.onCancel=${()=>{this.closeSessionTreeNavigator()}}
|
|
3670
3670
|
></session-tree-navigator>
|
|
3671
|
-
`}visibleWorkspacePanels(){let e=this.createApplicationPanelContext(),t=this.plugins.getApplicationPanels().filter(t=>t.visible?.(e)??!0).map(t=>({...t,badge:()=>t.badge?.(e),render:()=>t.render(e)})),n=this.state.selectedWorkspace;if(n!==void 0){let e=this.createWorkspacePanelContext(n);t.push(...this.plugins.getWorkspacePanels().filter(t=>t.visible?.(e)??!0).map(t=>({...t,badge:()=>t.badge?.(e),render:()=>t.render(e)})))}return t.sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}workspacePanelEmptyState(){let e=this.state.selectedProject;return this.state.isLoadingProjects?{title:D(`ui.piWebApp.loadingProjects`,`Loading projects…`),body:D(`ui.piWebApp.findingProjectsYouAddedToPiWeb`,`Finding projects you added to PI WEB.`)}:e===void 0?this.state.projects.length===0?{title:D(`ui.piWebApp.noProjectsYet`,`No projects yet`),body:D(`ui.piWebApp.useActionsAddProjectToAddAFolder`,`Use Actions → Add project to add a folder. Workspace tools appear here after you select a workspace.`)}:{title:D(`ui.piWebApp.selectProject`,`Select project`),body:D(`ui.piWebApp.selectAProjectInTheSidebarThenA`,`Select a project in the sidebar, then a workspace to view files, Git, or terminals.`)}:this.state.isLoadingWorkspaces?{title:D(`ui.piWebApp.loadingWorkspaces`,`Loading workspaces…`),body:D(`ui.piWebApp.preparingWorkspaceToolsFor`,`Preparing workspace tools for {name}.`,{name:e.name})}:this.state.workspaces.length===0?{title:D(`ui.piWebApp.noWorkspacesFound`,`No workspaces found`),body:D(`ui.piWebApp.noWorkspacesAvailableForTrySelectingOrAdding`,`No workspaces available for {name}. Try selecting or adding the project again.`,{name:e.name})}:{title:D(`ui.workspacePanel.selectWorkspace`,`Select workspace`),body:D(`ui.piWebApp.selectAWorkspaceInToViewFilesGit`,`Select a workspace in {name} to view files, Git, or terminals.`,{name:e.name})}}sessionEmptyMessage(){return this.contentError()===``?this.state.isLoadingProjects?D(`ui.piWebApp.loadingProjects`,`Loading projects…`):this.state.selectedWorkspace===void 0?this.state.selectedProject===void 0?this.state.projects.length===0?D(`ui.piWebApp.addAProjectToStartASession`,`Add a project to start a session.`):D(`ui.piWebApp.selectAProjectAndWorkspaceToStartA`,`Select a project and workspace to start a session.`):D(`ui.piWebApp.selectAWorkspaceToStartASession`,`Select a workspace to start a session.`):D(`ui.piWebApp.selectOrStartASession`,`Select or start a session.`):this.contentError()}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){let t=kw(this.state),n=r=>{let i=Ad(r,e,t.id);return Lm({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t),projects:md(_e,t.id),...i===void 0?{}:{peer:i},host:this.createWorkspaceHost()},n)};return n(Aw())}sessionLabelItems(e){let t=this.state.selectedWorkspace;if(t===void 0)return[];let n=kw(this.state),r=i=>{let a=Ad(i,t,n.id);return Rm({machine:n,workspace:t,session:Xt(e),state:this.state,files:this.createWorkspaceFiles(t,n),projects:md(_e,n.id),...a===void 0?{}:{peer:a},navigate:(e,t)=>this.navigate(e,t,n.id),host:this.createWorkspaceHost()},r)};return this.plugins.getSessionLabelItems(r(Aw()))}createWorkspaceFiles(e,t){return Dh(d,e,t.id,{defaultUploadFolder:Ve(e.effectiveConfig,this.workspaceUploadDefaultFolder),onInvalidate:n=>{this.invalidateWorkspaceResources(e,t,n)}})}createWorkspaceHost(){return{requestRender:()=>{this.invalidateWorkspaceSurface()}}}createApplicationPanelContext(){let e=kw(this.state),t=this.state.selectedWorkspace,n=r=>{let i=this.beginNavigationOperation(fw);return Fm({machine:e,state:this.state,projects:md(_e,e.id),...t===void 0?{}:{workspace:t},...t===void 0||!this.terminalAvailableForMachine(e.id)?{}:{terminal:this.workspaceTerminal(r,t,e.id,i)},navigate:(e,t)=>this.navigate(e,t),prompt:this.createPromptEditor(r,e.id),host:this.createWorkspaceHost()},n)};return n(`core`)}createWorkspacePanelContext(e,t=kw(this.state),n){let r=t.id,i=(a,o,s=[])=>{let c=this.beginNavigationOperation(fw),l=this.workspaceNavigationGeneration,u={...c,isCurrent:()=>c.isCurrent()&&l===this.workspaceNavigationGeneration},d=Ad(a,e,r);return Im({navigate:(n,r)=>this.workspacePanelContextIsCurrent(e,t,u)?this.navigate(n,r,t.id):Promise.resolve(),machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t),projects:md(_e,r),...d===void 0?{}:{peer:d},prompt:this.createPromptEditor(a.registrationPluginId,r),terminal:this.workspaceTerminal(a.registrationPluginId,e,r,u),...o===void 0?{}:{navigation:this.createWorkspacePanelNavigation(e,t,o,s,n,u)},openTerminal:t=>{this.workspaceTerminal(a.registrationPluginId,e,r,u).open(t)},piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(a.registrationPluginId,r)},host:this.createWorkspaceHost()},i)};return i(Aw())}invalidateWorkspacePanels(e,t){let n=this.state.selectedWorkspace;return n===void 0?Promise.resolve():this.plugins.invalidateWorkspacePanels(this.createWorkspacePanelContext(n,kw(this.state),t),e)}invalidateWorkspaceResources(e,t,n){return this.plugins.invalidateWorkspaceResources(this.createWorkspacePanelContext(e,t),n)}getActions(){return d_(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.normalAuthActions(),...this.workspaceSurfaceActions(),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}normalAuthActions(){return this.apiScope===`management`?[]:[{id:`app.normal-auth.change-password`,title:D(`ui.piWebApp.changeNormalModePassword`,`Change normal-mode password`),description:D(`ui.piWebApp.changeTheLocalPasswordRequiredForNormalMode`,`Change the local password required for normal mode`),group:D(`client.actions.preferences.57907a`,`Preferences`),enabled:this.normalAuthStatus?.authenticated===!0,run:()=>{this.normalAuthDialogMode=`change`,this.normalAuthError=``}}]}sessionActions(){let e=this.canCleanupSessions();return[{id:`app.sessions.cleanup`,title:D(`ui.sessionCleanupDialog.cleanUpSessions`,`Clean up sessions`),description:D(`ui.piWebApp.previewAndManuallyCleanUpIdleOrArchived`,`Preview and manually clean up idle or archived sessions on the selected machine`),group:D(`ui.sessionSearchDialog.sessions`,`Sessions`),...e?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.reset-navigation-panel-size`,title:D(`ui.piWebApp.resetNavigationPanelWidth`,`Reset navigation panel width`),description:D(`ui.piWebApp.restoreTheDefaultNavigationPanelWidth`,`Restore the default navigation panel width`),group:D(`ui.piWebApp.view`,`View`),run:()=>{this.resetResizablePanel(`navigation`)}},{id:`app.layout.reset-workspace-panel-size`,title:D(`ui.piWebApp.resetWorkspacePanelWidth`,`Reset workspace panel width`),description:D(`ui.piWebApp.restoreTheDefaultWorkspacePanelWidth`,`Restore the default workspace panel width`),group:D(`ui.piWebApp.view`,`View`),run:()=>{this.resetResizablePanel(`workspace`)}},{id:`app.layout.reset-panel-sizes`,title:D(`ui.piWebApp.resetPanelWidths`,`Reset panel widths`),description:D(`ui.piWebApp.restoreDefaultWidthsForAllSidePanels`,`Restore default widths for all side panels`),group:D(`ui.piWebApp.view`,`View`),run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:`app.navigation.open`,title:D(`ui.main.99aaea15ca9e`,`Open Navigation`),description:D(`ui.main.bfb109bc500b`,`Find destinations and manage pinned tabs`),group:D(`client.actions.navigation.e72622`,`Navigation`),run:this.showNavigation},{id:`app.navigation.focus-machines`,title:D(`ui.piWebApp.focusMachines`,`Focus machines`),description:D(`ui.piWebApp.moveKeyboardFocusToTheMachineSelector`,`Move keyboard focus to the machine selector`),shortcut:`mod+g m`,group:D(`client.actions.navigation.e72622`,`Navigation`),run:()=>this.focusNavigationSection(`machines`)},{id:`app.navigation.focus-projects`,title:D(`ui.piWebApp.focusProjects`,`Focus projects`),description:D(`ui.piWebApp.moveKeyboardFocusToTheProjectList`,`Move keyboard focus to the project list`),shortcut:`mod+g p`,group:D(`client.actions.navigation.e72622`,`Navigation`),run:()=>this.focusNavigationSection(`projects`)},{id:`app.navigation.focus-workspaces`,title:D(`ui.piWebApp.focusWorkspaces`,`Focus workspaces`),description:D(`ui.piWebApp.moveKeyboardFocusToTheWorkspaceList`,`Move keyboard focus to the workspace list`),shortcut:`mod+g w`,group:D(`client.actions.navigation.e72622`,`Navigation`),run:()=>this.focusNavigationSection(`workspaces`)},{id:`app.navigation.focus-sessions`,title:D(`ui.piWebApp.focusSessions`,`Focus sessions`),description:D(`ui.piWebApp.moveKeyboardFocusToTheSessionList`,`Move keyboard focus to the session list`),shortcut:`mod+g s`,group:D(`client.actions.navigation.e72622`,`Navigation`),run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){return this.pluginLoads.ensureGatewayLoaded().then(()=>void 0)}async loadPluginsForSelectedMachine(){await this.ensureGatewayPluginsLoaded();let e=this.state.selectedMachine;e?.kind===`remote`&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){let t=window.location.href;await this.ensureGatewayPluginsLoaded();let n=this.state.machineRuntimes[e.id];if(e.kind===`remote`&&n?.ok===!0&&!ht(n,Ut.pluginLifecycle)){let n=D(`ui.main.d5354f9f3542`,`PI WEB plugins from {arg0} require a compatible plugin lifecycle capability; update and restart PI WEB on that machine`,{arg0:e.name});console.warn(n),this.verifiedPluginModeByMachine.delete(e.id),this.clearRequiredTerminal(e.id),this.reconcilePluginLoadSelection(t),this.setRequiredPluginFailure(e.id,n)}else await this.pluginLoads.loadForMachine(e)}async registerExternalPlugins(e,t,n=`local`){let r=window.location.href;try{await this.builtInPluginsReady;let e=await t();if(this.apiScope===`management`){let t=e=>(e.sourcePluginId??e.id)!==Kt,r=e.declarations.filter(t),i=await this.plugins.registerBatch(e.registrations.filter(t),{declarations:r,failures:Gw(e,r)});this.pluginLoadErrors.delete(n),i.failures.length>0&&this.pluginLoadErrors.set(n,i.failures.map(e=>Jw(e.error)).join(`
|
|
3672
|
-
`));for(let e of i.failures)console.warn(`Failed to register PI WEB plugin ${e.declaration.id} (${e.phase})`,e.error);return this.applyPreferredTheme(!1),this.invalidateWorkspaceSurface(),i.failures.length===0}e.terminalMode===`recovery-disabled`&&(this.clearRequiredTerminal(n),this.verifiedPluginModeByMachine.set(n,`recovery-disabled`),this.clearRequiredPluginFailure(n));let i=e.failures.map(e=>
|
|
3673
|
-
`));let a=e.failures.length===0;for(let t of e.failures)console.warn(`Failed to load PI WEB plugin ${t.entry.id} (${t.entry.module})`,t.error);let o=e.declarations,s=
|
|
3674
|
-
`)),console.warn(`Failed to register PI WEB plugin ${e.declaration.id} during ${e.phase}`,e.error))}return e.terminalMode===`required`&&(!this.plugins.hasPlugin(l)||!this.terminalAvailableForMachine(n))?(a=!1,this.verifiedPluginModeByMachine.delete(n),this.clearRequiredTerminal(n),this.requiredPluginFailureByMachine.has(n)||this.setRequiredPluginFailure(n,D(`ui.main.97f88bf8726e`,`Required Terminal plugin is unavailable after plugin activation. Open Settings for recovery guidance.`))):e.terminalMode===`required`&&(this.verifiedPluginModeByMachine.set(n,`required`),this.clearRequiredPluginFailure(n)),this.reconcilePluginLoadSelection(r),this.applyPreferredTheme(!1),this.invalidateWorkspaceSurface(),a}catch(t){return console.warn(`Failed to load ${e}`,t),this.pluginLoadErrors.set(n,Jw(t)),this.verifiedPluginModeByMachine.delete(n),this.clearRequiredTerminal(n),this.reconcilePluginLoadSelection(r),this.applyPreferredTheme(!1),this.setRequiredPluginFailure(n,D(`ui.main.d05cfde8b518`,`Failed to load {arg0}: {arg1}`,{arg0:e,arg1:Jw(t)})),this.invalidateWorkspaceSurface(),!1}}reconcilePluginLoadSelection(e){xw()===e&&this.reconcileWorkspacePanelSelection()}setRequiredPluginFailure(e,t){this.requiredPluginFailureByMachine.set(e,t),this.dismissedRequiredPluginFailureByMachine.delete(e),M(this.state)===e&&this.requestUpdate()}clearRequiredPluginFailure(e){this.requiredPluginFailureByMachine.delete(e)&&(this.dismissedRequiredPluginFailureByMachine.delete(e),M(this.state)===e&&this.requestUpdate())}displayedError(){if(this.state.error!==``)return this.state.error;let e=M(this.state),t=this.requiredPluginFailureByMachine.get(e);return t!==void 0&&this.dismissedRequiredPluginFailureByMachine.get(e)!==t?t:``}dismissDisplayedError(){if(this.state.error!==``){this.setState({error:``});return}let e=M(this.state),t=this.requiredPluginFailureByMachine.get(e);t!==void 0&&(this.dismissedRequiredPluginFailureByMachine.set(e,t),this.requestUpdate())}clearRequiredTerminal(e){this.requiredTerminalByMachine.delete(e),this.invalidateWorkspaceSurface(),this.pluginLoads.invalidateMachine(e),M(this.state)===e&&(this.cancelWorkspaceDeletionRefresh(),this.setState({workspaceDeletionRuns:{}}))}terminalAvailableForMachine(e){return this.requiredTerminalByMachine.has(e)}pluginContributionAvailable(e,t){if(e===`core`||e===`themes`||this.apiScope===`management`)return!0;if(t!==void 0&&t!==M(this.state))return!1;let n=t??`local`,r=this.verifiedPluginModeByMachine.get(n);return e===(n===`local`?`pi-web.terminal`:Yt(n,`pi-web.terminal`))?r===`required`&&this.terminalAvailableForMachine(n):r===`recovery-disabled`||r===`required`&&this.terminalAvailableForMachine(n)}createPromptEditor(e=`core`,t=M(this.state)){let n=this.state.selectedSession,r=n!==void 0&&n.archived!==!0&&!Ca(n.id)&&t===M(this.state)?{machineId:t,sessionId:n.id,cwd:n.cwd}:void 0;return{...this.plugins.promptChipMethods(e,r),insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){let e=t=>Pm({state:this.state,projects:md(_e,M(this.state)),prompt:this.createPromptEditor(t),piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:e=>{this.openSettings(e)},openMcpAuth:e=>this.auth.openMcpAuth(e)},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.openChatAndFocusComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},openModelPicker:()=>this.openModelDialog(),openThinkingLevelPicker:()=>this.openThinkingDialog(),selectMainView:e=>{this.selectMainView(e)},navigate:(e,t)=>this.navigate(e,t),selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.invalidateSelectedWorkspaceFiles(),refreshGit:()=>this.invalidateWorkspacePanels(),refreshWorkspacePanels:e=>this.invalidateWorkspacePanels(e),refreshAppData:()=>this.refreshAppData(),checkForPiWebUpdates:()=>this.piWebStatusController.checkForUpdates(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:e=>this.deleteWorkspace(e),startSession:()=>this.withChatScrollTransition(()=>this.startSessionAndOpenChat()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;let t=M(this.state),n=Gn(t,e.projectId,e.id);if(!zu(e)){this.browserErrors.report(n,D(`ui.main.669305830b1b`,`Workspace removal is not available`));return}if(Wu(this.state,e))return;let r=e.removal,i=Bu(e);if(r===void 0||i===void 0||!confirm(i))return;let a=this.beginNavigationOperation(uw);try{let n=await d.deleteWorkspace(e.projectId,e.id,r.precondition,t),i=this.apiScope===`management`?h(n):this.requiredTerminalComposition(t).facade.parseCommandRun(n);if(M(this.state)!==t||!this.recordWorkspaceDeletionRun(i,t))return;let o=await this.workspaceForCommandRun(i,t);if(M(this.state)!==t||!a.isCurrent())return;o!==void 0&&this.workspaceTerminal(`core`,o,t).open({terminalId:i.terminalId})}catch(r){await this.reportWorkspaceRemovalFailure(e,t,n,r)}}async reportWorkspaceRemovalFailure(e,t,n,r){let i=Jw(r);if(this.apiScope===`management`||!(r instanceof te)||i.startsWith(`Session daemon unavailable:`)){this.browserErrors.report(n,D(`ui.piWebApp.failedToStartWorkspaceDeletion`,`Failed to start workspace deletion: {errorMessageerror}`,{errorMessageerror:i}));return}let a=D(`ui.main.f658c452e075`,`Workspace removal failed: {arg0}`,{arg0:i}),o=()=>this.serverNotices.hasNotice(t,t=>{let n=t.context??{};return t.source===`workspace.delete`&&t.message===a&&t.scope?.projectId===e.projectId&&n.targetWorkspaceId===e.id});o()||await this.serverNotices.refresh(t),o()||this.browserErrors.report(n,D(`ui.piWebApp.failedToStartWorkspaceDeletion`,`Failed to start workspace deletion: {errorMessageerror}`,{errorMessageerror:i}))}async workspaceForCommandRun(e,t){let n=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];if((n===void 0||n.length===0)&&(n=await this.workspaces.refreshProjectWorkspaces(e.projectId,t)),M(this.state)===t&&this.state.selectedProject?.id===e.projectId)return n.find(t=>t.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(M(this.state)!==t||this.state.selectedProject?.id!==e.projectId)return!1;let n=Gu(e);return n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling(),!0)}async refreshWorkspaceDeletionRuns(){let e=M(this.state),t=this.state.selectedProject,n=Uw(this.state);if(t===void 0||n===void 0||this.apiScope===`normal`&&!this.terminalAvailableForMachine(e)){this.cancelWorkspaceDeletionRefresh(),this.setState({workspaceDeletionRuns:{}});return}if(this.workspaceDeletionRefreshAbort!==void 0){if(this.workspaceDeletionRefreshScope===n){this.workspaceDeletionRefreshQueued=!0;return}this.cancelWorkspaceDeletionRefresh()}let r=new AbortController,i=++this.workspaceDeletionRefreshGeneration;this.workspaceDeletionRefreshAbort=r,this.workspaceDeletionRefreshScope=n;try{let n=Object.values(this.state.workspaceDeletionRuns).filter(e=>e.projectId===t.id);for(let a of n)Ku(a)||await this.handleCompletedWorkspaceDeletionRun(a,e,t.id,i,r);if(!this.workspaceDeletionRefreshIsCurrent(e,t.id,i,r))return;let a=Object.values(this.state.workspaceDeletionRuns).filter(e=>e.projectId===t.id&&Ku(e));if(n.length>0&&a.length===0)return;let o=Vu(),s=a.length===0?this.state.workspaces.filter(e=>e.projectId===t.id):[...new Map(a.map(e=>[e.workspaceId,{id:e.workspaceId,projectId:e.projectId}])).values()],c=this.apiScope===`management`?void 0:this.requiredTerminalByMachine.get(e),l=this.state.workspaceDeletionRuns,u=await Promise.allSettled(s.map(async n=>{if(this.apiScope===`management`)return Dt.listCommandRuns({...o,projectId:t.id,workspaceId:n.id},e,{signal:r.signal});let i=c===void 0?void 0:Ad(c.binding,n,e);if(i===void 0||c===void 0)throw $h(e);return c.facade.listCommandRuns({peer:i,filter:{metadata:o.metadata},signal:r.signal})}));if(!this.workspaceDeletionRefreshIsCurrent(e,t.id,i,r))return;let d=u.filter(e=>e.status===`rejected`),f=u.filter(e=>e.status===`fulfilled`);if(f.length===0&&d.length>0)throw d[0]?.reason;for(let e of d)console.warn(`Failed to query workspace deletion runs for one workspace`,e.reason);let p=new Set(u.flatMap((e,t)=>{let n=e.status===`rejected`?s[t]:void 0;return n===void 0?[]:[n.id]})),m=Object.entries(this.state.workspaceDeletionRuns).filter(([e,n])=>n.projectId===t.id&&(n!==l[e]||Ku(n)&&p.has(n.workspaceId))).map(([,e])=>e),h=Hu([...f.flatMap(e=>e.value),...m].filter(t=>!this.handledWorkspaceDeletionRunIds.has(Hw(e,t.id))));this.setState({workspaceDeletionRuns:h});for(let n of Object.values(h))Ku(n)||await this.handleCompletedWorkspaceDeletionRun(n,e,t.id,i,r)}catch(n){!r.signal.aborted&&this.workspaceDeletionRefreshIsCurrent(e,t.id,i,r)&&console.warn(`Failed to refresh workspace deletion runs`,n)}finally{if(this.workspaceDeletionRefreshAbort===r){this.workspaceDeletionRefreshAbort=void 0,this.workspaceDeletionRefreshScope=void 0;let e=this.workspaceDeletionRefreshQueued;this.workspaceDeletionRefreshQueued=!1,e&&Uw(this.state)===n?(this.workspaceDeletionPollTimer!==void 0&&window.clearTimeout(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,queueMicrotask(()=>{i===this.workspaceDeletionRefreshGeneration&&Uw(this.state)===n&&this.refreshWorkspaceDeletionRuns()})):this.updateWorkspaceDeletionPolling()}}}workspaceDeletionRefreshIsCurrent(e,t,n,r){return this.workspaceDeletionRefreshAbort===r&&!r.signal.aborted&&n===this.workspaceDeletionRefreshGeneration&&M(this.state)===e&&this.state.selectedProject?.id===t}cancelWorkspaceDeletionRefresh(){this.workspaceDeletionRefreshGeneration+=1,this.workspaceDeletionRefreshAbort?.abort(new DOMException(`Workspace deletion scope changed`,`AbortError`)),this.workspaceDeletionRefreshAbort=void 0,this.workspaceDeletionRefreshScope=void 0,this.workspaceDeletionRefreshQueued=!1,this.workspaceDeletionReconcileRetries.clear(),this.workspaceDeletionPollTimer!==void 0&&window.clearTimeout(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0}updateWorkspaceDeletionPolling(){let e=M(this.state),t=Date.now(),n=1/0;for(let r of Object.values(this.state.workspaceDeletionRuns)){let i=Hw(e,r.id);if(this.handledWorkspaceDeletionRunIds.has(i))continue;if(Ku(r)){n=Math.min(n,1e3);continue}let a=this.workspaceDeletionReconcileRetries.get(i)?.retryAt??t;n=Math.min(n,Math.max(0,a-t))}Number.isFinite(n)&&this.workspaceDeletionPollTimer===void 0?this.workspaceDeletionPollTimer=window.setTimeout(()=>{this.workspaceDeletionPollTimer=void 0,this.refreshWorkspaceDeletionRuns()},n):!Number.isFinite(n)&&this.workspaceDeletionPollTimer!==void 0&&(window.clearTimeout(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t,n,r,i){if(!this.workspaceDeletionRefreshIsCurrent(t,n,r,i))return;let a=Hw(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(a))return;let o=Gu(e);if(o!==void 0){if(e.status===`succeeded`){let s=this.workspaceDeletionReconcileRetries.get(a);if(s!==void 0&&s.retryAt>Date.now())return;let c=Gn(t,e.projectId,o);try{await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,o,t,{signal:i.signal,isCurrent:()=>this.workspaceDeletionRefreshIsCurrent(t,n,r,i)})}catch(e){if(!this.workspaceDeletionRefreshIsCurrent(t,n,r,i))return;let o=(s?.attempt??0)+1,l=pw[Math.min(o-1,pw.length-1)]??1e4;this.workspaceDeletionReconcileRetries.set(a,{attempt:o,retryAt:Date.now()+l}),this.browserErrors.report(c,D(`ui.main.2a2bb7043324`,`Workspace removed, but refreshing the workspace list failed: {arg0}. Retrying...`,{arg0:Jw(e)}));return}if(!this.workspaceDeletionRefreshIsCurrent(t,n,r,i))return;this.workspaceDeletionReconcileRetries.delete(a),this.handledWorkspaceDeletionRunIds.add(a),this.browserErrors.discard(c),this.setState({workspaceDeletionRuns:Yw(this.state.workspaceDeletionRuns,o)})}else e.status===`failed`&&(this.workspaceDeletionReconcileRetries.delete(a),this.handledWorkspaceDeletionRunIds.add(a))}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(D(`ui.piWebApp.removeThisOnlyRemovesItFromTheCurrent`,`Remove {name}?
|
|
3671
|
+
`}visibleWorkspacePanels(){let e=this.createApplicationPanelContext(),t=this.plugins.getApplicationPanels().filter(t=>t.visible?.(e)??!0).map(t=>({...t,badge:()=>t.badge?.(e),render:()=>t.render(e)})),n=this.state.selectedWorkspace;if(n!==void 0){let e=this.createWorkspacePanelContext(n);t.push(...this.plugins.getWorkspacePanels().filter(t=>t.visible?.(e)??!0).map(t=>({...t,badge:()=>t.badge?.(e),render:()=>t.render(e)})))}return t.sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}workspacePanelEmptyState(){let e=this.state.selectedProject;return this.state.isLoadingProjects?{title:D(`ui.piWebApp.loadingProjects`,`Loading projects…`),body:D(`ui.piWebApp.findingProjectsYouAddedToPiWeb`,`Finding projects you added to PI WEB.`)}:e===void 0?this.state.projects.length===0?{title:D(`ui.piWebApp.noProjectsYet`,`No projects yet`),body:D(`ui.piWebApp.useActionsAddProjectToAddAFolder`,`Use Actions → Add project to add a folder. Workspace tools appear here after you select a workspace.`)}:{title:D(`ui.piWebApp.selectProject`,`Select project`),body:D(`ui.piWebApp.selectAProjectInTheSidebarThenA`,`Select a project in the sidebar, then a workspace to view files, Git, or terminals.`)}:this.state.isLoadingWorkspaces?{title:D(`ui.piWebApp.loadingWorkspaces`,`Loading workspaces…`),body:D(`ui.piWebApp.preparingWorkspaceToolsFor`,`Preparing workspace tools for {name}.`,{name:e.name})}:this.state.workspaces.length===0?{title:D(`ui.piWebApp.noWorkspacesFound`,`No workspaces found`),body:D(`ui.piWebApp.noWorkspacesAvailableForTrySelectingOrAdding`,`No workspaces available for {name}. Try selecting or adding the project again.`,{name:e.name})}:{title:D(`ui.workspacePanel.selectWorkspace`,`Select workspace`),body:D(`ui.piWebApp.selectAWorkspaceInToViewFilesGit`,`Select a workspace in {name} to view files, Git, or terminals.`,{name:e.name})}}sessionEmptyMessage(){return this.contentError()===``?this.state.isLoadingProjects?D(`ui.piWebApp.loadingProjects`,`Loading projects…`):this.state.selectedWorkspace===void 0?this.state.selectedProject===void 0?this.state.projects.length===0?D(`ui.piWebApp.addAProjectToStartASession`,`Add a project to start a session.`):D(`ui.piWebApp.selectAProjectAndWorkspaceToStartA`,`Select a project and workspace to start a session.`):D(`ui.piWebApp.selectAWorkspaceToStartASession`,`Select a workspace to start a session.`):D(`ui.piWebApp.selectOrStartASession`,`Select or start a session.`):this.contentError()}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){let t=Mw(this.state),n=r=>{let i=Ad(r,e,t.id);return Lm({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t),projects:md(_e,t.id),...i===void 0?{}:{peer:i},host:this.createWorkspaceHost()},n)};return n(Nw())}sessionLabelItems(e){let t=this.state.selectedWorkspace;if(t===void 0)return[];let n=Mw(this.state),r=i=>{let a=Ad(i,t,n.id);return Rm({machine:n,workspace:t,session:Xt(e),state:this.state,files:this.createWorkspaceFiles(t,n),projects:md(_e,n.id),...a===void 0?{}:{peer:a},navigate:(e,t)=>this.navigate(e,t,n.id),host:this.createWorkspaceHost()},r)};return this.plugins.getSessionLabelItems(r(Nw()))}createWorkspaceFiles(e,t){return Ah(d,e,t.id,{managementMode:this.apiScope===`management`,defaultUploadFolder:Ve(e.effectiveConfig,this.workspaceUploadDefaultFolder),onInvalidate:n=>{this.invalidateWorkspaceResources(e,t,n)}})}createWorkspaceHost(){return{requestRender:()=>{this.invalidateWorkspaceSurface()}}}createApplicationPanelContext(){let e=Mw(this.state),t=this.state.selectedWorkspace,n=r=>{let i=this.beginNavigationOperation(hw);return Fm({machine:e,state:this.state,projects:md(_e,e.id),...t===void 0?{}:{workspace:t},...t===void 0||!this.terminalAvailableForMachine(e.id)?{}:{terminal:this.workspaceTerminal(r,t,e.id,i)},navigate:(e,t)=>this.navigate(e,t),prompt:this.createPromptEditor(r,e.id),host:this.createWorkspaceHost()},n)};return n(`core`)}createWorkspacePanelContext(e,t=Mw(this.state),n){let r=t.id,i=(a,o,s=[])=>{let c=this.beginNavigationOperation(hw),l=this.workspaceNavigationGeneration,u={...c,isCurrent:()=>c.isCurrent()&&l===this.workspaceNavigationGeneration},d=Ad(a,e,r);return Im({navigate:(n,r)=>this.workspacePanelContextIsCurrent(e,t,u)?this.navigate(n,r,t.id):Promise.resolve(),machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t),projects:md(_e,r),...d===void 0?{}:{peer:d},prompt:this.createPromptEditor(a.registrationPluginId,r),terminal:this.workspaceTerminal(a.registrationPluginId,e,r,u),...o===void 0?{}:{navigation:this.createWorkspacePanelNavigation(e,t,o,s,n,u)},openTerminal:t=>{this.workspaceTerminal(a.registrationPluginId,e,r,u).open(t)},piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(a.registrationPluginId,r)},host:this.createWorkspaceHost()},i)};return i(Nw())}invalidateWorkspacePanels(e,t){let n=this.state.selectedWorkspace;return n===void 0?Promise.resolve():this.plugins.invalidateWorkspacePanels(this.createWorkspacePanelContext(n,Mw(this.state),t),e)}invalidateWorkspaceResources(e,t,n){return this.plugins.invalidateWorkspaceResources(this.createWorkspacePanelContext(e,t),n)}getActions(){return m_(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.normalAuthActions(),...this.workspaceSurfaceActions(),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}normalAuthActions(){return this.apiScope===`management`?[]:[{id:`app.normal-auth.change-password`,title:D(`ui.piWebApp.changeNormalModePassword`,`Change normal-mode password`),description:D(`ui.piWebApp.changeTheLocalPasswordRequiredForNormalMode`,`Change the local password required for normal mode`),group:D(`client.actions.preferences.57907a`,`Preferences`),enabled:this.normalAuthStatus?.authenticated===!0,run:()=>{this.normalAuthDialogMode=`change`,this.normalAuthError=``}}]}sessionActions(){let e=this.canCleanupSessions();return[{id:`app.sessions.cleanup`,title:D(`ui.sessionCleanupDialog.cleanUpSessions`,`Clean up sessions`),description:D(`ui.piWebApp.previewAndManuallyCleanUpIdleOrArchived`,`Preview and manually clean up idle or archived sessions on the selected machine`),group:D(`ui.sessionSearchDialog.sessions`,`Sessions`),...e?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.reset-navigation-panel-size`,title:D(`ui.piWebApp.resetNavigationPanelWidth`,`Reset navigation panel width`),description:D(`ui.piWebApp.restoreTheDefaultNavigationPanelWidth`,`Restore the default navigation panel width`),group:D(`ui.piWebApp.view`,`View`),run:()=>{this.resetResizablePanel(`navigation`)}},{id:`app.layout.reset-workspace-panel-size`,title:D(`ui.piWebApp.resetWorkspacePanelWidth`,`Reset workspace panel width`),description:D(`ui.piWebApp.restoreTheDefaultWorkspacePanelWidth`,`Restore the default workspace panel width`),group:D(`ui.piWebApp.view`,`View`),run:()=>{this.resetResizablePanel(`workspace`)}},{id:`app.layout.reset-panel-sizes`,title:D(`ui.piWebApp.resetPanelWidths`,`Reset panel widths`),description:D(`ui.piWebApp.restoreDefaultWidthsForAllSidePanels`,`Restore default widths for all side panels`),group:D(`ui.piWebApp.view`,`View`),run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:`app.navigation.open`,title:D(`ui.main.99aaea15ca9e`,`Open Navigation`),description:D(`ui.main.bfb109bc500b`,`Find destinations and manage pinned tabs`),group:D(`client.actions.navigation.e72622`,`Navigation`),run:this.showNavigation},{id:`app.navigation.focus-machines`,title:D(`ui.piWebApp.focusMachines`,`Focus machines`),description:D(`ui.piWebApp.moveKeyboardFocusToTheMachineSelector`,`Move keyboard focus to the machine selector`),shortcut:`mod+g m`,group:D(`client.actions.navigation.e72622`,`Navigation`),run:()=>this.focusNavigationSection(`machines`)},{id:`app.navigation.focus-projects`,title:D(`ui.piWebApp.focusProjects`,`Focus projects`),description:D(`ui.piWebApp.moveKeyboardFocusToTheProjectList`,`Move keyboard focus to the project list`),shortcut:`mod+g p`,group:D(`client.actions.navigation.e72622`,`Navigation`),run:()=>this.focusNavigationSection(`projects`)},{id:`app.navigation.focus-workspaces`,title:D(`ui.piWebApp.focusWorkspaces`,`Focus workspaces`),description:D(`ui.piWebApp.moveKeyboardFocusToTheWorkspaceList`,`Move keyboard focus to the workspace list`),shortcut:`mod+g w`,group:D(`client.actions.navigation.e72622`,`Navigation`),run:()=>this.focusNavigationSection(`workspaces`)},{id:`app.navigation.focus-sessions`,title:D(`ui.piWebApp.focusSessions`,`Focus sessions`),description:D(`ui.piWebApp.moveKeyboardFocusToTheSessionList`,`Move keyboard focus to the session list`),shortcut:`mod+g s`,group:D(`client.actions.navigation.e72622`,`Navigation`),run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){return this.pluginLoads.ensureGatewayLoaded().then(()=>void 0)}async loadPluginsForSelectedMachine(){await this.ensureGatewayPluginsLoaded();let e=this.state.selectedMachine;e?.kind===`remote`&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){let t=window.location.href;await this.ensureGatewayPluginsLoaded();let n=this.state.machineRuntimes[e.id];if(e.kind===`remote`&&n?.ok===!0&&!ht(n,Ut.pluginLifecycle)){let n=D(`ui.main.d5354f9f3542`,`PI WEB plugins from {arg0} require a compatible plugin lifecycle capability; update and restart PI WEB on that machine`,{arg0:e.name});console.warn(n),this.verifiedPluginModeByMachine.delete(e.id),this.clearRequiredTerminal(e.id),this.reconcilePluginLoadSelection(t),this.setRequiredPluginFailure(e.id,n)}else await this.pluginLoads.loadForMachine(e)}async registerExternalPlugins(e,t,n=`local`){let r=window.location.href;try{await this.builtInPluginsReady;let e=await t();if(this.apiScope===`management`){let t=e=>(e.sourcePluginId??e.id)!==Kt,r=e.declarations.filter(t),i=await this.plugins.registerBatch(e.registrations.filter(t),{declarations:r,failures:Jw(e,r)});this.pluginLoadErrors.delete(n),i.failures.length>0&&this.pluginLoadErrors.set(n,i.failures.map(e=>Zw(e.error)).join(`
|
|
3672
|
+
`));for(let e of i.failures)console.warn(`Failed to register PI WEB plugin ${e.declaration.id} (${e.phase})`,e.error);return this.applyPreferredTheme(!1),this.invalidateWorkspaceSurface(),i.failures.length===0}e.terminalMode===`recovery-disabled`&&(this.clearRequiredTerminal(n),this.verifiedPluginModeByMachine.set(n,`recovery-disabled`),this.clearRequiredPluginFailure(n));let i=e.failures.map(e=>Zw(e.error));this.pluginLoadErrors.delete(n),i.length>0&&this.pluginLoadErrors.set(n,i.join(`
|
|
3673
|
+
`));let a=e.failures.length===0;for(let t of e.failures)console.warn(`Failed to load PI WEB plugin ${t.entry.id} (${t.entry.module})`,t.error);let o=e.declarations,s=Jw(e,o),c=e.terminalMode===`required`?e.failures.find(({entry:e})=>e.id===Kt):void 0;if(c!==void 0)return this.verifiedPluginModeByMachine.delete(n),this.clearRequiredTerminal(n),this.reconcilePluginLoadSelection(r),this.applyPreferredTheme(!1),this.setRequiredPluginFailure(n,D(`ui.main.734a3e4d0393`,`The required terminal plugin failed to load: {arg0}. Open settings for recovery guidance.`,{arg0:Zw(c.error)})),this.requestUpdate(),!1;let l=n===`local`?Kt:Yt(n,Kt);if(e.terminalMode===`required`){let t=`validate`;try{let r=e.registrations.find(({id:e})=>e===l);if(this.plugins.hasPlugin(l)){let e=this.knownRequiredTerminalByMachine.get(n);if(e===void 0)throw Error(`Required Terminal browser capability was not retained after activation`);if(r!==void 0){let t=Xw(r,n);if(!Yw(e.binding,t))throw Error(`Required Terminal revision changed after browser activation; reload PI WEB to activate the new paired revision`)}this.requiredTerminalByMachine.set(n,e)}else{if(r===void 0)throw Error(`Required Terminal browser registration is unavailable`);let e=Xw(r,n),i=o.find(({id:e})=>e===l);if(i===void 0)throw Error(`Required Terminal browser declaration is unavailable`);let a=(await this.plugins.registerBatch([r],{declarations:[i],failures:s.filter(({declaration:e})=>e.id===l),requiredCapabilities:[{registrationPluginId:l,capability:$h}]})).failures.find(({declaration:e})=>e.id===l);if(a!==void 0)throw t=a.phase,a.error;let c=this.plugins.resolveCapability(l,$h),u=Object.freeze({binding:e,facade:c});this.knownRequiredTerminalByMachine.set(n,u),this.requiredTerminalByMachine.set(n,u)}}catch(e){a=!1,console.warn(`Failed to register PI WEB plugin ${l} during ${t}`,e),this.verifiedPluginModeByMachine.delete(n),this.clearRequiredTerminal(n),this.setRequiredPluginFailure(n,D(`ui.main.5abfc40d98a4`,`The required terminal plugin failed during browser {arg0}: {arg1}. Open settings for recovery guidance.`,{arg0:t,arg1:Zw(e)}))}}if(e.terminalMode!==`required`||this.terminalAvailableForMachine(n)){let t=e.registrations.filter(({id:e})=>e!==l),r=o.filter(({id:e})=>e!==l),c=await this.plugins.registerBatch(t,{declarations:r,failures:s.filter(({declaration:e})=>e.id!==l)});for(let e of c.failures)e.phase!==`import`&&(a=!1,i.push(Zw(e.error)),this.pluginLoadErrors.set(n,i.join(`
|
|
3674
|
+
`)),console.warn(`Failed to register PI WEB plugin ${e.declaration.id} during ${e.phase}`,e.error))}return e.terminalMode===`required`&&(!this.plugins.hasPlugin(l)||!this.terminalAvailableForMachine(n))?(a=!1,this.verifiedPluginModeByMachine.delete(n),this.clearRequiredTerminal(n),this.requiredPluginFailureByMachine.has(n)||this.setRequiredPluginFailure(n,D(`ui.main.97f88bf8726e`,`Required Terminal plugin is unavailable after plugin activation. Open Settings for recovery guidance.`))):e.terminalMode===`required`&&(this.verifiedPluginModeByMachine.set(n,`required`),this.clearRequiredPluginFailure(n)),this.reconcilePluginLoadSelection(r),this.applyPreferredTheme(!1),this.invalidateWorkspaceSurface(),a}catch(t){return console.warn(`Failed to load ${e}`,t),this.pluginLoadErrors.set(n,Zw(t)),this.verifiedPluginModeByMachine.delete(n),this.clearRequiredTerminal(n),this.reconcilePluginLoadSelection(r),this.applyPreferredTheme(!1),this.setRequiredPluginFailure(n,D(`ui.main.d05cfde8b518`,`Failed to load {arg0}: {arg1}`,{arg0:e,arg1:Zw(t)})),this.invalidateWorkspaceSurface(),!1}}reconcilePluginLoadSelection(e){ww()===e&&this.reconcileWorkspacePanelSelection()}setRequiredPluginFailure(e,t){this.requiredPluginFailureByMachine.set(e,t),this.dismissedRequiredPluginFailureByMachine.delete(e),M(this.state)===e&&this.requestUpdate()}clearRequiredPluginFailure(e){this.requiredPluginFailureByMachine.delete(e)&&(this.dismissedRequiredPluginFailureByMachine.delete(e),M(this.state)===e&&this.requestUpdate())}displayedError(){if(this.state.error!==``)return this.state.error;let e=M(this.state),t=this.requiredPluginFailureByMachine.get(e);return t!==void 0&&this.dismissedRequiredPluginFailureByMachine.get(e)!==t?t:``}dismissDisplayedError(){if(this.state.error!==``){this.setState({error:``});return}let e=M(this.state),t=this.requiredPluginFailureByMachine.get(e);t!==void 0&&(this.dismissedRequiredPluginFailureByMachine.set(e,t),this.requestUpdate())}clearRequiredTerminal(e){this.requiredTerminalByMachine.delete(e),this.invalidateWorkspaceSurface(),this.pluginLoads.invalidateMachine(e),M(this.state)===e&&(this.cancelWorkspaceDeletionRefresh(),this.setState({workspaceDeletionRuns:{}}))}terminalAvailableForMachine(e){return this.requiredTerminalByMachine.has(e)}pluginContributionAvailable(e,t){if(e===`core`||e===`themes`||this.apiScope===`management`)return!0;if(t!==void 0&&t!==M(this.state))return!1;let n=t??`local`,r=this.verifiedPluginModeByMachine.get(n);return e===(n===`local`?`pi-web.terminal`:Yt(n,`pi-web.terminal`))?r===`required`&&this.terminalAvailableForMachine(n):r===`recovery-disabled`||r===`required`&&this.terminalAvailableForMachine(n)}createPromptEditor(e=`core`,t=M(this.state)){let n=this.state.selectedSession,r=n!==void 0&&n.archived!==!0&&!Ca(n.id)&&t===M(this.state)?{machineId:t,sessionId:n.id,cwd:n.cwd}:void 0;return{...this.plugins.promptChipMethods(e,r),insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){let e=t=>Pm({state:this.state,projects:md(_e,M(this.state)),prompt:this.createPromptEditor(t),piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:e=>{this.openSettings(e)},openMcpAuth:e=>this.auth.openMcpAuth(e)},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.openChatAndFocusComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},openModelPicker:()=>this.openModelDialog(),openThinkingLevelPicker:()=>this.openThinkingDialog(),selectMainView:e=>{this.selectMainView(e)},navigate:(e,t)=>this.navigate(e,t),selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.invalidateSelectedWorkspaceFiles(),refreshGit:()=>this.invalidateWorkspacePanels(),refreshWorkspacePanels:e=>this.invalidateWorkspacePanels(e),refreshAppData:()=>this.refreshAppData(),checkForPiWebUpdates:()=>this.piWebStatusController.checkForUpdates(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:e=>this.deleteWorkspace(e),startSession:()=>this.withChatScrollTransition(()=>this.startSessionAndOpenChat()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;let t=M(this.state),n=Gn(t,e.projectId,e.id);if(!zu(e)){this.browserErrors.report(n,D(`ui.main.669305830b1b`,`Workspace removal is not available`));return}if(Wu(this.state,e))return;let r=e.removal,i=Bu(e);if(r===void 0||i===void 0||!confirm(i))return;let a=this.beginNavigationOperation(pw);try{let n=await d.deleteWorkspace(e.projectId,e.id,r.precondition,t),i=this.apiScope===`management`?h(n):this.requiredTerminalComposition(t).facade.parseCommandRun(n);if(M(this.state)!==t||!this.recordWorkspaceDeletionRun(i,t))return;let o=await this.workspaceForCommandRun(i,t);if(M(this.state)!==t||!a.isCurrent())return;o!==void 0&&this.workspaceTerminal(`core`,o,t).open({terminalId:i.terminalId})}catch(r){await this.reportWorkspaceRemovalFailure(e,t,n,r)}}async reportWorkspaceRemovalFailure(e,t,n,r){let i=Zw(r);if(this.apiScope===`management`||!(r instanceof te)||i.startsWith(`Session daemon unavailable:`)){this.browserErrors.report(n,D(`ui.piWebApp.failedToStartWorkspaceDeletion`,`Failed to start workspace deletion: {errorMessageerror}`,{errorMessageerror:i}));return}let a=D(`ui.main.f658c452e075`,`Workspace removal failed: {arg0}`,{arg0:i}),o=()=>this.serverNotices.hasNotice(t,t=>{let n=t.context??{};return t.source===`workspace.delete`&&t.message===a&&t.scope?.projectId===e.projectId&&n.targetWorkspaceId===e.id});o()||await this.serverNotices.refresh(t),o()||this.browserErrors.report(n,D(`ui.piWebApp.failedToStartWorkspaceDeletion`,`Failed to start workspace deletion: {errorMessageerror}`,{errorMessageerror:i}))}async workspaceForCommandRun(e,t){let n=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];if((n===void 0||n.length===0)&&(n=await this.workspaces.refreshProjectWorkspaces(e.projectId,t)),M(this.state)===t&&this.state.selectedProject?.id===e.projectId)return n.find(t=>t.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(M(this.state)!==t||this.state.selectedProject?.id!==e.projectId)return!1;let n=Gu(e);return n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling(),!0)}async refreshWorkspaceDeletionRuns(){let e=M(this.state),t=this.state.selectedProject,n=Kw(this.state);if(t===void 0||n===void 0||this.apiScope===`normal`&&!this.terminalAvailableForMachine(e)||this.apiScope===`management`&&!this.state.workspaces.some(e=>e.projectId===t.id&&zu(e))&&!Object.values(this.state.workspaceDeletionRuns).some(e=>e.projectId===t.id)){this.cancelWorkspaceDeletionRefresh(),this.setState({workspaceDeletionRuns:{}});return}if(this.workspaceDeletionRefreshAbort!==void 0){if(this.workspaceDeletionRefreshScope===n){this.workspaceDeletionRefreshQueued=!0;return}this.cancelWorkspaceDeletionRefresh()}let r=new AbortController,i=++this.workspaceDeletionRefreshGeneration;this.workspaceDeletionRefreshAbort=r,this.workspaceDeletionRefreshScope=n;try{let n=Object.values(this.state.workspaceDeletionRuns).filter(e=>e.projectId===t.id);for(let a of n)Ku(a)||await this.handleCompletedWorkspaceDeletionRun(a,e,t.id,i,r);if(!this.workspaceDeletionRefreshIsCurrent(e,t.id,i,r))return;let a=Object.values(this.state.workspaceDeletionRuns).filter(e=>e.projectId===t.id&&Ku(e));if(n.length>0&&a.length===0)return;let o=Vu(),s=a.length===0?this.state.workspaces.filter(e=>e.projectId===t.id):[...new Map(a.map(e=>[e.workspaceId,{id:e.workspaceId,projectId:e.projectId}])).values()],c=this.apiScope===`management`?void 0:this.requiredTerminalByMachine.get(e),l=this.state.workspaceDeletionRuns,u=await Promise.allSettled(s.map(async n=>{if(this.apiScope===`management`)return Dt.listCommandRuns({...o,projectId:t.id,workspaceId:n.id},e,{signal:r.signal});let i=c===void 0?void 0:Ad(c.binding,n,e);if(i===void 0||c===void 0)throw ng(e);return c.facade.listCommandRuns({peer:i,filter:{metadata:o.metadata},signal:r.signal})}));if(!this.workspaceDeletionRefreshIsCurrent(e,t.id,i,r))return;let d=u.filter(e=>e.status===`rejected`),f=u.filter(e=>e.status===`fulfilled`);if(f.length===0&&d.length>0)throw d[0]?.reason;for(let e of d)console.warn(`Failed to query workspace deletion runs for one workspace`,e.reason);let p=new Set(u.flatMap((e,t)=>{let n=e.status===`rejected`?s[t]:void 0;return n===void 0?[]:[n.id]})),m=Object.entries(this.state.workspaceDeletionRuns).filter(([e,n])=>n.projectId===t.id&&(n!==l[e]||Ku(n)&&p.has(n.workspaceId))).map(([,e])=>e),h=Hu([...f.flatMap(e=>e.value),...m].filter(t=>!this.handledWorkspaceDeletionRunIds.has(Gw(e,t.id))));this.setState({workspaceDeletionRuns:h});for(let n of Object.values(h))Ku(n)||await this.handleCompletedWorkspaceDeletionRun(n,e,t.id,i,r)}catch(n){!r.signal.aborted&&this.workspaceDeletionRefreshIsCurrent(e,t.id,i,r)&&console.warn(`Failed to refresh workspace deletion runs`,n)}finally{if(this.workspaceDeletionRefreshAbort===r){this.workspaceDeletionRefreshAbort=void 0,this.workspaceDeletionRefreshScope=void 0;let e=this.workspaceDeletionRefreshQueued;this.workspaceDeletionRefreshQueued=!1,e&&Kw(this.state)===n?(this.workspaceDeletionPollTimer!==void 0&&window.clearTimeout(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,queueMicrotask(()=>{i===this.workspaceDeletionRefreshGeneration&&Kw(this.state)===n&&this.refreshWorkspaceDeletionRuns()})):this.updateWorkspaceDeletionPolling()}}}workspaceDeletionRefreshIsCurrent(e,t,n,r){return this.workspaceDeletionRefreshAbort===r&&!r.signal.aborted&&n===this.workspaceDeletionRefreshGeneration&&M(this.state)===e&&this.state.selectedProject?.id===t}cancelWorkspaceDeletionRefresh(){this.workspaceDeletionRefreshGeneration+=1,this.workspaceDeletionRefreshAbort?.abort(new DOMException(`Workspace deletion scope changed`,`AbortError`)),this.workspaceDeletionRefreshAbort=void 0,this.workspaceDeletionRefreshScope=void 0,this.workspaceDeletionRefreshQueued=!1,this.workspaceDeletionReconcileRetries.clear(),this.workspaceDeletionPollTimer!==void 0&&window.clearTimeout(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0}updateWorkspaceDeletionPolling(){let e=M(this.state),t=Date.now(),n=1/0;for(let r of Object.values(this.state.workspaceDeletionRuns)){let i=Gw(e,r.id);if(this.handledWorkspaceDeletionRunIds.has(i))continue;if(Ku(r)){n=Math.min(n,1e3);continue}let a=this.workspaceDeletionReconcileRetries.get(i)?.retryAt??t;n=Math.min(n,Math.max(0,a-t))}Number.isFinite(n)&&this.workspaceDeletionPollTimer===void 0?this.workspaceDeletionPollTimer=window.setTimeout(()=>{this.workspaceDeletionPollTimer=void 0,this.refreshWorkspaceDeletionRuns()},n):!Number.isFinite(n)&&this.workspaceDeletionPollTimer!==void 0&&(window.clearTimeout(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t,n,r,i){if(!this.workspaceDeletionRefreshIsCurrent(t,n,r,i))return;let a=Gw(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(a))return;let o=Gu(e);if(o!==void 0){if(e.status===`succeeded`){let s=this.workspaceDeletionReconcileRetries.get(a);if(s!==void 0&&s.retryAt>Date.now())return;let c=Gn(t,e.projectId,o);try{await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,o,t,{signal:i.signal,isCurrent:()=>this.workspaceDeletionRefreshIsCurrent(t,n,r,i)})}catch(e){if(!this.workspaceDeletionRefreshIsCurrent(t,n,r,i))return;let o=(s?.attempt??0)+1,l=gw[Math.min(o-1,gw.length-1)]??1e4;this.workspaceDeletionReconcileRetries.set(a,{attempt:o,retryAt:Date.now()+l}),this.browserErrors.report(c,D(`ui.main.2a2bb7043324`,`Workspace removed, but refreshing the workspace list failed: {arg0}. Retrying...`,{arg0:Zw(e)}));return}if(!this.workspaceDeletionRefreshIsCurrent(t,n,r,i))return;this.workspaceDeletionReconcileRetries.delete(a),this.handledWorkspaceDeletionRunIds.add(a),this.browserErrors.discard(c),this.setState({workspaceDeletionRuns:Qw(this.state.workspaceDeletionRuns,o)})}else e.status===`failed`&&(this.workspaceDeletionReconcileRetries.delete(a),this.handledWorkspaceDeletionRunIds.add(a))}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(D(`ui.piWebApp.removeThisOnlyRemovesItFromTheCurrent`,`Remove {name}?
|
|
3675
3675
|
|
|
3676
|
-
This only removes it from the current PI WEB gateway.`,{name:e.name})))return;let t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();let n=await this.machines.deleteMachine(e,{selectFallback:!t});if(this.state.machines.some(t=>t.id===e.id)||this.machineNavigation.forget(e.id),this.state.selectedMachine?.id===e.id&&n!==void 0){let e=
|
|
3677
|
-
<chat-view .onNavigationChange=${this.handleChatNavigationChange} .behaviors=${this.chatBehaviors} .canMutateQueuedMessages=${this.canMutateQueueMessage(t,M(e))} .queuedMessageActionPending=${this.queuedMessageActionTarget!==void 0||this.messageRevertTarget!==void 0||this.isReplacingPrompt(e)} .onQueuedMessageAction=${t.archived===!0?void 0:this.handleQueuedMessageAction} .onUseSuggestedInput=${t.archived===!0?void 0:this.handleUseSuggestedInput} .sessionCwd=${t.cwd} .onTranscriptRendered=${this.handleTranscriptRendered} .contentRendering=${this.plugins.chatContentRendering} .contentRendererVersion=${this.plugins.contentRendererVersion} .machineId=${M(e)} @workspace-file-open=${this.handleWorkspaceFileOpen} .workspaceContext=${this.chatWorkspaceContext} .sessionId=${t.id} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .searchTarget=${e.sessionSearchTarget} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isSendingPrompt=${e.sendingPrompts[t.id]===!0} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .clientQueuedMessages=${e.clientQueuedSessionMessages[t.id]??this.emptyClientQueue} .status=${e.status} .activity=${e.activity} .historyReady=${this.readyChatIdentity===
|
|
3676
|
+
This only removes it from the current PI WEB gateway.`,{name:e.name})))return;let t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();let n=await this.machines.deleteMachine(e,{selectFallback:!t});if(this.state.machines.some(t=>t.id===e.id)||this.machineNavigation.forget(e.id),this.state.selectedMachine?.id===e.id&&n!==void 0){let e=Sw(this.state);await this.selectMachineWithMemory(n,{rememberCurrent:!1,expected:e})}}openSelectedMachine(){let e=this.state.selectedMachine;e?.kind===`remote`&&e.baseUrl!==void 0&&window.open(e.baseUrl,`_blank`,`noopener,noreferrer`)}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{let n=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.browserErrors.report({kind:`global`},D(`ui.piWebApp.operationFailed`,`Operation failed: {message}`,{message:n}))})}async openModelDialog(){let e=this.state.selectedSession;if(e===void 0)return;let t={machineId:M(this.state),sessionId:e.id,cwd:e.cwd},{models:n,catalog:r}=await this.loadModelDialogData();if(!this.modelDialogOriginIsCurrent(t))return;let i=this.currentModelValue();this.setState({modelDialog:{instanceId:++this.modelDialogInstanceId,origin:t,title:D(`client.actions.choose.model.1afed6`,`Choose model`),...i===void 0?{}:{selectedValue:i},options:this.modelDialogOptions(n),...r===void 0?{}:{catalog:r},defaultsLoading:!0}}),this.loadSessionDefaultPins(t,`model`)}async loadModelDialogData(){for(;;){let e=this.modelDialogScopeInvalidation,[t,n]=await Promise.all([this.sessions.listModels(),this.apiScope===`normal`?this.sessions.listModelCatalog():Promise.resolve(void 0)]);if(e===this.modelDialogScopeInvalidation)return{models:t,...n===void 0?{}:{catalog:n}}}}async refreshOpenModelDialog(){if(this.modelDialogMutationInFlight>0){this.modelDialogRefreshPending=!0;return}let e=this.currentModelDialog();if(e===void 0)return;let{origin:t,instanceId:n}=e,{models:r,catalog:i}=await this.loadModelDialogData();if(this.modelDialogMutationInFlight>0||this.state.modelDialog?.instanceId!==n||!this.modelDialogOriginIsCurrent(t))return;let a={...e,options:this.modelDialogOptions(r),...i===void 0?{}:{catalog:i}},o=this.currentModelValue();o===void 0?delete a.selectedValue:a.selectedValue=o,this.setState({modelDialog:a})}currentModelValue(){return Aw(this.state.status)}modelDialogOptions(e){let t=this.currentModelValue();return e.map(e=>{let n=e.provider??``,r=e.id??``,i=`${n}/${r}`;return{value:i,label:`${r}${i===t?D(`ui.piWebApp.current`,` ✓ Current`):``}`,description:n}})}async pickModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){this.navigateSettings(`general`)}pickTheme(e){this.plugins.getThemes().some(t=>t.id===e.themeId)&&(this.localThemePreference={...e},this.applyPreferredTheme(!0))}useDefaultTheme(){this.localThemePreference=void 0,be(),this.applyPreferredTheme(!1)}syncPluginStylesheets(){if(!this.isConnected)return;let e=this.resolveCurrentThemePreference().activeTheme;this.stylesheetRuntime.update([...this.plugins.getStylesheets(M(this.state)),...e?.stylesheets??[]])}applyPreferredTheme(e){this.syncPluginStylesheets();let t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,m(t),e&&_(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return mt({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}async openThinkingDialog(){let e=this.state.selectedSession===void 0?{machineId:M(this.state),sessionId:``,cwd:``}:{machineId:M(this.state),sessionId:this.state.selectedSession.id,cwd:this.state.selectedSession.cwd},t=await this.sessions.listThinkingLevels();if(!this.modelDialogOriginIsCurrent(e))return;let n=this.state.status?.thinkingLevel??`off`;this.setState({thinkingDialog:{instanceId:++this.modelDialogInstanceId,origin:e,title:D(`client.actions.choose.thinking.level.77e3b8`,`Choose thinking level`),selectedValue:n,defaultsLoading:!0,options:t.map(e=>{let t=xt(e,D);return{value:e,label:`${ct(e,D)}${e===n?D(`ui.piWebApp.current`,` ✓ Current`):``}`,...t===void 0?{}:{description:t}}})}}),this.loadSessionDefaultPins(e,`thinking`)}async loadSessionDefaultPins(e,t){let n=t===`model`?this.state.modelDialog?.instanceId:this.state.thinkingDialog?.instanceId,r=await this.sessions.getSessionDefaults();if(t===`model`){let t=this.state.modelDialog;if(t===void 0||t.instanceId!==n||!this.modelDialogOriginIsCurrent(e))return;let i=r?.defaultProvider!==void 0&&r.defaultModel!==void 0?`${r.defaultProvider}/${r.defaultModel}`:void 0;this.setState({modelDialog:{...t,defaultsLoading:!1,...i===void 0?{}:{defaultValue:i}}});return}let i=this.state.thinkingDialog;i!==void 0&&i.instanceId===n&&this.modelDialogOriginIsCurrent(e)&&this.setState({thinkingDialog:{...i,defaultsLoading:!1,...r?.defaultThinkingLevel===void 0?{}:{defaultValue:r.defaultThinkingLevel}}})}async pinSessionDefault(e,n){let r=e===`model`?this.state.modelDialog:this.state.thinkingDialog;if(r===void 0||!this.modelDialogOriginIsCurrent(r.origin))return;let{instanceId:i,origin:a}=r;if(e===`model`){let e=n.indexOf(`/`);if(e<=0)return;let t=await this.sessions.setSessionDefaults({provider:n.slice(0,e),modelId:n.slice(e+1)}),r=this.state.modelDialog;if(t?.defaultProvider===void 0||t.defaultModel===void 0||r?.instanceId!==i||!this.modelDialogOriginIsCurrent(a))return;this.setState({modelDialog:{...r,defaultValue:`${t.defaultProvider}/${t.defaultModel}`,defaultsLoading:!1}});return}if(!t(n))return;let o=await this.sessions.setSessionDefaults({thinkingLevel:n}),s=this.state.thinkingDialog;o?.defaultThinkingLevel!==void 0&&s?.instanceId===i&&this.modelDialogOriginIsCurrent(a)&&this.setState({thinkingDialog:{...s,defaultValue:o.defaultThinkingLevel,defaultsLoading:!1}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==``&&await this.sessions.setThinkingLevel(e)}async sendPrompt(e,t,n,r,i,a=[]){if(this.unacknowledgedActivitySessionKey()!==void 0)return!1;let o=n!==void 0&&n.length>0;if(a.length===0)return!o&&t===void 0&&this.auth.handleSlashCommand(e)?!1:!o&&t===void 0&&(e.trim()===`/model`||e.trim()===`/scoped-models`)?(this.openModelDialog(),!1):this.sessions.send(e,t,n,r,i);let s=a[0]?.target;if(s===void 0||a.some(e=>!Ma(e.target,s)||!this.plugins.promptChipOwnerAvailable(e.pluginId,s.machineId)))return!1;let c=await this.sessions.send(Na(e,a),t,n,r,i,s);return c&&this.plugins.promptChips.consume(a),c}selectedPromptChips(){let e=M(this.state),t=this.state.selectedSession,n=t===void 0?[]:this.plugins.promptChips.list({machineId:e,sessionId:t.id,cwd:t.cwd}).filter(t=>this.plugins.promptChipOwnerAvailable(t.pluginId,e));return(n.length!==this.visiblePromptChips.length||n.some((e,t)=>e!==this.visiblePromptChips[t]))&&(this.visiblePromptChips=n),this.visiblePromptChips}isReplacingPrompt(e){let t=e.selectedSession;if(t===void 0)return!1;let n=M(e),r=this.queuedMessageActionTarget,i=this.messageRevertTarget;return r?.action===`edit`&&r.machineId===n&&r.sessionId===t.id&&r.cwd===t.cwd||i?.machineId===n&&i.sessionId===t.id&&i.cwd===t.cwd&&i.path===t.path||e.pendingTreeActions.some(e=>e.machineId===n&&e.sessionId===t.id)}finishModelDialogMutation(){--this.modelDialogMutationInFlight,this.modelDialogMutationInFlight===0&&this.modelDialogRefreshPending&&(this.modelDialogRefreshPending=!1,this.refreshOpenModelDialog())}currentModelDialog(){let e=this.state.modelDialog;if(e!==void 0&&this.modelDialogOriginIsCurrent(e.origin))return e;e!==void 0&&this.setState({modelDialog:void 0})}modelDialogOriginIsCurrent(e){let t=this.state.selectedSession;return t!==void 0&&e.machineId===M(this.state)&&e.sessionId===t.id&&e.cwd===t.cwd}applyModelDialogCatalog(e,t){t!==void 0&&this.state.modelDialog?.instanceId===e.instanceId&&this.modelDialogOriginIsCurrent(e.origin)&&this.setState({modelDialog:{...e,catalog:t,options:this.modelDialogOptions(t.filter(e=>e.enabled))}})}renderChatView(e,t){let n=Ll(M(e),e.selectedWorkspace,t),r=JSON.stringify(n);return r!==this.chatWorkspaceContextKey&&(this.chatWorkspaceContextKey=r,this.chatWorkspaceContext=n),this.notificationViewInput!==e.selectedNotificationInbox&&(this.notificationViewInput=e.selectedNotificationInbox,this.notificationView=Bc(e.selectedNotificationInbox)),E`
|
|
3677
|
+
<chat-view .onNavigationChange=${this.handleChatNavigationChange} .behaviors=${this.chatBehaviors} .canMutateQueuedMessages=${this.canMutateQueueMessage(t,M(e))} .queuedMessageActionPending=${this.queuedMessageActionTarget!==void 0||this.messageRevertTarget!==void 0||this.isReplacingPrompt(e)} .onQueuedMessageAction=${t.archived===!0?void 0:this.handleQueuedMessageAction} .onUseSuggestedInput=${t.archived===!0?void 0:this.handleUseSuggestedInput} .sessionCwd=${t.cwd} .onTranscriptRendered=${this.handleTranscriptRendered} .contentRendering=${this.plugins.chatContentRendering} .contentRendererVersion=${this.plugins.contentRendererVersion} .machineId=${M(e)} @workspace-file-open=${this.handleWorkspaceFileOpen} .workspaceContext=${this.chatWorkspaceContext} .sessionId=${t.id} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .searchTarget=${e.sessionSearchTarget} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isSendingPrompt=${e.sendingPrompts[t.id]===!0} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .clientQueuedMessages=${e.clientQueuedSessionMessages[t.id]??this.emptyClientQueue} .status=${e.status} .activity=${e.activity} .historyReady=${this.readyChatIdentity===Fw(e)} .pendingDialogs=${e.pendingDialogs} .closedDialogs=${e.closedDialogs} .onAnswerDialog=${this.handleAnswerDialog} .onCancelDialog=${this.handleCancelDialog} .onDismissClosedDialog=${this.handleDismissClosedDialog} .askDraftSessionId=${j(M(e),t.id)} .onSubmitAsk=${t.archived===!0?void 0:this.handleSubmitAsk} .notificationInbox=${this.notificationView} .canClearServerQueue=${this.canClearServerQueue()} .onClearServerQueue=${this.handleClearServerQueue} .onMessageAction=${this.handleMessageAction} .onDisplayedMessageAction=${this.handleDisplayedMessageAction} .messageActions=${this.plugins.getMessageActions(M(e))} .messageActionContext=${this.messageActionContext(e)} .onDismissWarning=${this.handleDismissWarning} .onDismissNotification=${this.handleDismissNotification} .onDismissAllNotifications=${this.handleDismissAllNotifications} .warningsVisible=${!this.sessionWarningVisibility.collapsed} .onToggleWarnings=${this.handleToggleWarnings} .onLoadMore=${this.handleLoadEarlierMessages}></chat-view>
|
|
3678
3678
|
`}renderStatusBar(e){let t=this.sessionWarningVisibility.warningCount;return E`
|
|
3679
3679
|
<status-bar slot="status" .status=${e.status} .warningCount=${t} .warningsExpanded=${t>0&&!this.sessionWarningVisibility.collapsed} .onToggleWarnings=${this.handleToggleWarnings}></status-bar>
|
|
3680
3680
|
`}renderContextBar(){return this.appShell.isMobileNavigationLayout?E`
|
|
@@ -3691,10 +3691,10 @@ This only removes it from the current PI WEB gateway.`,{name:e.name})))return;le
|
|
|
3691
3691
|
.refreshControl=${this.appShell.shouldShowAppRefreshInContextBar()?this.renderAppRefresh():void 0}
|
|
3692
3692
|
.onOpenSection=${this.handleOpenNavigationSection}
|
|
3693
3693
|
.onShowNavigation=${this.navigationPreferences.mobileCollapsed?this.showNavigation:void 0}
|
|
3694
|
-
.hiddenActiveDestination=${this.hiddenActiveNavigationDestination(this.availableNavigationTabs(),this.navigationPreferences.mobileCollapsed?[]:
|
|
3694
|
+
.hiddenActiveDestination=${this.hiddenActiveNavigationDestination(this.availableNavigationTabs(),this.navigationPreferences.mobileCollapsed?[]:s_(this.availableNavigationTabs(),this.resolvedNavigationPreferences().pinnedIds))}
|
|
3695
3695
|
.onShowActions=${this.apiScope===`management`?void 0:()=>{this.setState({actionPaletteOpen:!0})}}
|
|
3696
3696
|
></app-context-bar>
|
|
3697
|
-
`:null}renderMobileMainTabs(){if(this.appShell.isMobileNavigationLayout&&this.navigationPreferences.mobileCollapsed)return null;let e=this.visibleWorkspacePanels(),t=this.availableNavigationTabs(e),n=
|
|
3697
|
+
`:null}renderMobileMainTabs(){if(this.appShell.isMobileNavigationLayout&&this.navigationPreferences.mobileCollapsed)return null;let e=this.visibleWorkspacePanels(),t=this.availableNavigationTabs(e),n=s_(t,this.resolvedNavigationPreferences().pinnedIds),r=this.selectedNavigationTab(e);return E`
|
|
3698
3698
|
<app-mobile-main-tabs
|
|
3699
3699
|
.tabs=${n}
|
|
3700
3700
|
.hiddenActiveDestination=${t.some(e=>e.id===r)&&!n.some(e=>e.id===r)}
|
|
@@ -3702,20 +3702,20 @@ This only removes it from the current PI WEB gateway.`,{name:e.name})))return;le
|
|
|
3702
3702
|
.selectedTab=${r}
|
|
3703
3703
|
.onSelect=${this.selectNavigationTab}
|
|
3704
3704
|
></app-mobile-main-tabs>
|
|
3705
|
-
`}availableNavigationTabs(e=this.visibleWorkspacePanels()){return this.mobileMainTabs(e).filter(e=>e.id===`navigation`?this.appShell.isMobileNavigationLayout:e.id!==`chat`||!this.isDesktopSideBySideLayout())}selectedNavigationTab(e=this.visibleWorkspacePanels()){let t=this.effectiveMainView();if(!this.isDesktopSideBySideLayout()&&t!==`workspace`)return t;if(this.workspaceContentError()===``)return this.effectiveWorkspaceTool(e)}hiddenActiveNavigationDestination(e=this.availableNavigationTabs(),t=
|
|
3705
|
+
`}availableNavigationTabs(e=this.visibleWorkspacePanels()){return this.mobileMainTabs(e).filter(e=>e.id===`navigation`?this.appShell.isMobileNavigationLayout:e.id!==`chat`||!this.isDesktopSideBySideLayout())}selectedNavigationTab(e=this.visibleWorkspacePanels()){let t=this.effectiveMainView();if(!this.isDesktopSideBySideLayout()&&t!==`workspace`)return t;if(this.workspaceContentError()===``)return this.effectiveWorkspaceTool(e)}hiddenActiveNavigationDestination(e=this.availableNavigationTabs(),t=s_(e,this.resolvedNavigationPreferences().pinnedIds),n=this.selectedNavigationTab()){return c_(e,t,n)}mobileMainTabs(e=this.visibleWorkspacePanels()){let t=sv(this.state.sessions,this.unreadSessionIds);return[{id:`navigation`,label:D(`ui.sessionSearchDialog.sessions`,`Sessions`),icon:`navigation`,className:`navigation-tab`,...t===0?{}:{badge:t,badgeLabel:D(`ui.main.e979b9d71656`,`{arg0} unread`,{arg0:String(t)}),badgeTone:`unread`}},{id:`chat`,label:D(`ui.piWebApp.chat`,`Chat`),icon:`chat`},...e.map(e=>{let t=e.icon;return{id:e.id,label:e.title,...t===void 0?{}:{icon:t},badge:e.badge?.()}})]}resolveNavigationPinnedId(e){if(e===`navigation`||e===`chat`)return e;let t=M(this.state),n=this.plugins.resolveWorkspacePanelRouteId(e,t);if(n!==void 0)return n;let r=this.plugins.getWorkspacePanels().filter(n=>this.plugins.resolveWorkspacePanelRouteId(n.id,t)===n.id&&n.navigationAliases?.some(t=>t===e)===!0);return r.length===1?r[0]?.id??e:e}resolvedNavigationPreferences(){let e=this.navigationPreferences.pinnedIds.map(e=>this.resolveNavigationPinnedId(e));return{...this.navigationPreferences,pinnedIds:[...new Set(e)]}}renderAppRefresh(){return E`<app-refresh-control .onReload=${this.handleReloadApp}></app-refresh-control>`}renderServerNoticeBanners(){let e=M(this.state),t=this.serverNotices.projection(e),n=t?.status===`fresh`?Du(t.notices,Zn(this.state)):[];return n.length===0?null:E`${n.map(t=>sw(t.message,()=>{this.serverNotices.dismiss(e,t.id)},t.severity))}`}renderBrowserErrorBanners(e){let t=this.visibleBrowserErrorsForCurrentRoute(e);return t.length===0?null:E`${t.map(e=>sw(e.message,()=>{this.dismissBrowserError(e)},`error`,e.recovery===void 0?void 0:()=>{this.retryBrowserError(e)}))}`}retryBrowserError(e){if(!this.visibleBrowserErrorsForCurrentRoute(this.state).includes(e))return;let t=e.scope;t.kind===`session`&&e.recovery===`session-refresh`&&t.machineId===M(this.state)?this.sessions.refreshSelectedSession(t.sessionId,{recoverNetwork:!0}):t.kind===`workspace`&&e.recovery===`workspace-sessions-refresh`&&t.machineId===M(this.state)&&t.workspaceId===this.state.selectedWorkspace?.id&&t.projectId===this.state.selectedWorkspace.projectId&&this.sessions.refreshCurrentWorkspaceSessions(t.machineId,{recoverNetwork:!0})}dismissBrowserError(e){let t=Yn(this.state.browserErrors,e.scope,e.message);t!==this.state.browserErrors&&this.setState({browserErrors:t})}render(){let e=this.state,t=this.effectiveMainView(),n=this.normalAuthGateMode();if(this.apiScope===`normal`&&(n!==void 0||this.normalAuthStatus===void 0))return this.renderNormalAuthDialog(n??`login`);let r=this.unacknowledgedActivitySessionKey(e)!==void 0;return E`
|
|
3706
3706
|
<div class=${`${this.panelCollapse.shellClass(t)}${this.isDesktopSideBySideLayout()?``:` two-column-layout`}`} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints(`navigation`),workspace:this.resizablePanelConstraints(`workspace`)})}>
|
|
3707
3707
|
<aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
|
|
3708
3708
|
${this.renderNavigationPanelEdgeControl()}
|
|
3709
|
-
<main class=${
|
|
3709
|
+
<main class=${Ig(t)}>
|
|
3710
3710
|
${this.renderContextBar()}
|
|
3711
3711
|
${Rn([...this.workspaceSurfaceInputs(),e.sessions,this.unreadSessionIds,this.unreadPresence],()=>this.renderMobileMainTabs())}
|
|
3712
3712
|
${this.unknownRouteView()===void 0?null:E`<div class="error warning" role="alert"><span class="error-text">${D(`ui.main.ca62cfd1e0fa`,`Unknown view:`)}${this.unknownRouteView()}</span></div>`}
|
|
3713
3713
|
${this.renderServerNoticeBanners()}
|
|
3714
3714
|
${this.apiScope===`management`?null:In(Pn(e.machines,e.machineRuntimes))}
|
|
3715
|
-
${
|
|
3715
|
+
${sw(this.displayedError(),()=>{this.dismissDisplayedError()})}
|
|
3716
3716
|
${this.renderBrowserErrorBanners(e)}
|
|
3717
3717
|
<div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
|
|
3718
|
-
${e.selectedSession&&this.contentError()===``&&!this.sessions.isChatLoadDeferred&&(this.isChatVisible()||this.displayedChatIdentity===
|
|
3718
|
+
${e.selectedSession&&this.contentError()===``&&!this.sessions.isChatLoadDeferred&&(this.isChatVisible()||this.displayedChatIdentity===Fw(e))?E`
|
|
3719
3719
|
<conversation-layout .presentationRuntime=${this.plugins.uiPresentation} .presentationContext=${this.uiPresentationContext()} .status=${e.status} .activity=${e.activity} .sending=${e.sendingPrompts[e.selectedSession.id]===!0} .visualEffects=${this.chatBehaviors.visualEffects}>
|
|
3720
3720
|
${this.renderChatView(e,e.selectedSession)}
|
|
3721
3721
|
<div class="composer-area" slot="composer">
|
|
@@ -3758,4 +3758,4 @@ This only removes it from the current PI WEB gateway.`,{name:e.name})))return;le
|
|
|
3758
3758
|
.onSubmit=${e=>{this.submitNormalAuth(e)}}
|
|
3759
3759
|
.onCancel=${()=>{this.normalAuthDialogMode=void 0,this.normalAuthError=``}}
|
|
3760
3760
|
></normal-auth-dialog>
|
|
3761
|
-
`}static{this.styles=Ih}invalidateNavigationSelection(){this.navigationSelectionSeq+=1}refreshableMachineIds(){return this.state.machines.length===0?[M(this.state)]:this.state.machines.filter(e=>Iw(e,this.state.machineStatuses[e.id])).map(e=>e.id)}async restoreCommittedNavigation(e){return this.restoreRoute(!1,e.view,`deferred`)}async finishWorkspaceRouteRestore(e,t){if(t.restoreSeq!==void 0&&!this.isCurrentRouteRestore(t.restoreSeq,t.navigation))return;let n=this.visibleWorkspacePanels(),r=t.requestedTool!==void 0&&this.availableWorkspacePanelId(t.requestedTool,n)===void 0,i=t.requestedRoute?.workspaceId!==void 0&&(this.state.selectedProject?.id!==t.requestedRoute.projectId||this.state.selectedWorkspace?.id!==t.requestedRoute.workspaceId),a=t.requestedRoute?.sessionId!==void 0&&this.state.selectedSession?.id!==t.requestedRoute.sessionId,o=t.unavailableToolRoute||t.unavailablePanelViewRoute||r,s=this.pluginLoadErrors.get(M(this.state));if(o&&s!==void 0){let e=this.state.selectedWorkspace,t=e===void 0?A(M(this.state)):Gn(M(this.state),e.projectId,e.id);this.state.browserErrors[qn(t)]===void 0&&this.browserErrors.report(t,s)}this.reconcileWorkspacePanelSelection(),t.unavailablePanelViewRoute&&this.setState({mainView:this.effectiveMainView()});let c=t.restoredWorkspaceIdentity===void 0?void 0:{identity:t.restoredWorkspaceIdentity,query:e.contributionQuery??{}};if(await this.refreshRestoredWorkspaceTool(this.state.workspaceTool,c),(t.restoreSeq===void 0||this.isCurrentRouteRestore(t.restoreSeq,t.navigation))&&t.urlPublication===`current-url`&&t.updateUrl&&!o&&!i&&!a&&(t.requestedRoute===void 0||this.routeLocationMatchesUrl(t.requestedRoute)&&(t.requestedRoute.workspaceId===void 0||this.navigationSurfaceMatchesUrl(e)))){let n=this.restoredContributionQueryForSelectedWorkspace(e,t.restoredWorkspaceIdentity);this.updateUrl(void 0,n)}}restoredContributionQueryForSelectedWorkspace(e,t){let n=this.selectedWorkspaceRouteIdentity();return t!==void 0&&n!==void 0&&Ew(t,n)?e.contributionQuery??{}:{}}replaceNavigationUrl(e=this.currentContributionQueryForState()){this.replaceMachineNavigationSnapshot(Ol(this.state,e))}commitMachineNavigationSnapshot(e,t){this.syncNavigationFreshness(),this.machineNavigation.remember(e),Oa(kl(e),{...t,contributionQuery:e.surface.contributionQuery??{}}),this.syncNavigationFreshness()}currentContributionQueryForState(){let e=this.selectedWorkspaceRouteIdentity();return e===void 0||!Da(F(),e)?{}:na()}selectedWorkspaceRouteIdentity(e=this.state.selectedWorkspace,t=kw(this.state)){if(e!==void 0)return{machineId:t.id,projectId:e.projectId,workspaceId:e.id}}replaceMachineNavigationSnapshot(e){this.syncNavigationFreshness(),this.machineNavigation.remember(e);let t=kl(e),n=this.navigationRouteMatchesUrl(t);this.navigationSurfaceMatchesUrl(e.surface)||this.writeWorkspaceRouteSurfaceToUrl(e.surface),n||Oa(t,{replace:!0}),this.syncNavigationFreshness()}navigationRouteMatchesUrl(e){let t=F();return(t.machineId??`local`)===(e.machineId??`local`)&&t.projectId===e.projectId&&t.workspaceId===e.workspaceId&&t.sessionId===e.sessionId&&t.tool===e.tool&&t.view===e.view}routeSelectionMatchesUrl(e){let t=F();return(t.machineId??`local`)===(e.machineId??`local`)&&t.projectId===e.projectId&&t.workspaceId===e.workspaceId&&t.sessionId===e.sessionId}navigationUrlContextMatchesUrl(e){return(e.generation===void 0||e.generation===this.workspaceNavigationGeneration)&&(e.navigation===void 0||e.navigation.isCurrent())&&xw()===e.url}navigationSurfaceMatchesUrl(e){return Cw(na(),e.contributionQuery??{})}async navigateToMachineFromController(e,t={}){return this.selectMachineWithMemory(e,t)}selectProjectFromNavigation(e){return this.navigateToProjectFromController(e)}selectWorkspaceFromNavigation(e){return this.navigateToWorkspaceFromController(e)}selectSessionFromNavigation(e){return this.navigateToSessionFromController(e)}requiredTerminalComposition(e){let t=this.requiredTerminalByMachine.get(e);if(t===void 0)throw $h(e);return t}requiredTerminalPanelId(e){return`${this.requiredTerminalComposition(e).binding.registrationPluginId}:${_w}`}createPanelActions(e){return{toggle:()=>{e===`navigation`?this.panelCollapse.toggleNavigationPanel():this.panelCollapse.toggleWorkspacePanel()},resizeStart:()=>this.startPanelResize(e),resize:t=>{this.panelResize.resizePanel(e,t,{persist:!1})},resizeEnd:()=>{this.panelResize.persistPanelSizes()},reset:()=>{this.resetResizablePanel(e)}}}availableWorkspacePanelId(e,t=this.visibleWorkspacePanels()){return t.find(t=>t.id===e)?.id}unavailableRouteTool(e=this.visibleWorkspacePanels()){let t=F();if(t.tool===void 0)return;let n=this.resolveBrowserAppRoute(t).tool;return this.availableWorkspacePanelId(n,e)===void 0?t.tool:void 0}effectiveWorkspaceTool(e=this.visibleWorkspacePanels()){let t=F();return t.tool===void 0?(Sa(t.view)===void 0?this.resolveBrowserAppRoute(t).tool:void 0)??this.state.workspaceTool??e[0]?.id:this.resolveBrowserAppRoute(t).tool}unknownRouteView(){let e=F();return e.view!==void 0&&this.resolveBrowserAppRoute(e).view===void 0?e.view:void 0}effectiveMainView(){return this.unknownRouteView()===void 0?this.state.mainView:this.appShell.isMobileNavigationLayout?`navigation`:F().tool!==void 0&&this.unavailableRouteTool()===void 0?`workspace`:`chat`}reconcileWorkspacePanelSelection(){let e=this.visibleWorkspacePanels(),t=this.effectiveWorkspaceTool(e);return t!==this.state.workspaceTool&&(this.setState({workspaceTool:t}),!0)}contentDestination(e){return JSON.stringify([e.machineId??`local`,e.projectId,e.workspaceId,e.sessionId])}setContentError(e,t){this.contentLoadOutcome={destination:this.contentDestination(e),error:t},this.requestUpdate()}contentError(){return this.contentLoadOutcome?.destination===this.contentDestination(F())?this.contentLoadOutcome.error:``}workspaceContentError(){if(this.state.selectedWorkspace===void 0)return this.contentError();let e=F(),t=e.tool,n=t===void 0?this.effectiveWorkspaceTool():this.resolveBrowserAppRoute({...e,tool:t}).tool;return(t!==void 0||n!==void 0)&&this.availableWorkspacePanelId(n)===void 0?this.pluginLoadErrors.get(M(this.state))??this.requiredPluginFailureByMachine.get(M(this.state))??D(`ui.main.4d914bb120b8`,`Workspace panel unavailable: {arg0}`,{arg0:t??n??`unknown`}):``}workspacePanelContextIsCurrent(e,t,n){return M(this.state)===t.id&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.id&&Da(F(),{machineId:t.id,projectId:e.projectId,workspaceId:e.id})&&(n===void 0||n.isCurrent())}createWorkspacePanelNavigation(e,t,n,r,i,a){let o={machineId:t.id,projectId:e.projectId,workspaceId:e.id},s=i!==void 0&&Ew(o,i.identity)?ea(i.query,n,r):Da(F(),o)?$i(n,r):Object.freeze({}),c=s;return Object.freeze({version:1,contributionId:n,query:s,set:(e,t,i)=>{if(!ca(e))throw Error(D(`ui.main.2241ac67c24f`,`Invalid contribution navigation parameter: {arg0}`,{arg0:e}));if(!a.isCurrent())return!1;let s=this.selectedWorkspaceRouteIdentity();return s===void 0||!Ew(o,s)||!Da(F(),o)||!Cw($i(n,r),c)?!1:(oa(n,r,e,t,i)&&(c=$i(n,r),this.rememberCurrentMachineNavigation(),this.requestUpdate()),!0)}})}invalidateSelectedWorkspaceFiles(){let e=this.state.selectedWorkspace;return e===void 0?Promise.resolve():this.invalidateWorkspaceResources(e,kw(this.state),{reason:`manual`,resources:[`workspace.files`]})}workspaceSurfaceActions(){return[{id:`core:workspace.refresh-current`,title:D(`client.actions.refresh.current.panel.a33a0a`,`Refresh current panel`),shortcut:`mod+shift+r`,group:D(`bundled.workspace-tasks.workspace.379798`,`Workspace`),enabled:this.state.selectedWorkspace!==void 0,run:()=>this.refreshCurrentWorkspaceSurface()}]}visibleBrowserErrorsForCurrentRoute(e){return Qn(e.browserErrors,Sw(e,F()))}resolveBrowserAppRoute(e){let t=e=>this.plugins.resolveWorkspacePanelRouteId(e,M(this.state)),n=e.view!==void 0&&[`files`,`git`,`terminal`,`core:workspace.files`,`core:workspace.git`,`core:workspace.terminal`].includes(e.view)?t(e.view):void 0;return Ta(n===void 0?e:{...e,view:`workspace`,tool:e.tool??n},t)}messageActionContext(e){let t=Qt(e).selectedSession;if(t===void 0)return;let n={machine:Object.freeze(kw(e)),session:Object.freeze({...t,busy:e.sendingPrompts[t.id]===!0||rr(e.status,e.activity)})},r=JSON.stringify(n);return r!==this.messageActionInputs&&(this.messageActionInputs=r,this.messageActionSnapshot=n),this.messageActionSnapshot}messageActionHelpers(e,t){let n=this.state,r=t.machine.id,i=n.selectedWorkspace,a=Qt(n).selectedWorkspace,o=i===void 0?void 0:Ad(e,i,r),s=()=>M(this.state)===r&&this.state.selectedSession?.id===t.session.id&&this.state.selectedSession.cwd===t.session.cwd,c=this.createPromptEditor(e.registrationPluginId,r);return{prompt:{...c,insertText:e=>{s()&&c.insertText(e)},getText:()=>s()?c.getText():``,getSelection:()=>s()?c.getSelection():null},navigate:(e,t)=>this.navigate(e,t,r),projects:md(_e,r),...i===void 0||a===void 0?{}:{workspace:a,files:this.createWorkspaceFiles(i,t.machine),...this.terminalAvailableForMachine(r)?{terminal:this.workspaceTerminal(e.registrationPluginId,i,r)}:{}},...o===void 0?{}:{peer:o}}}};w([y({attribute:!1})],$.prototype,`chatBehaviors`,void 0),w([C()],$.prototype,`state`,void 0),w([S(`chat-view`)],$.prototype,`chatView`,void 0),w([C()],$.prototype,`chatNavigation`,void 0),w([C()],$.prototype,`queuedMessageActionTarget`,void 0),w([C()],$.prototype,`messageRevertTarget`,void 0),w([S(`prompt-editor`)],$.prototype,`promptEditor`,void 0),w([S(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),w([S(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),w([S(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),w([C()],$.prototype,`unreadSessionIds`,void 0),w([C()],$.prototype,`unreadPresence`,void 0),w([C()],$.prototype,`readyChatIdentity`,void 0),w([C()],$.prototype,`navigationOrderVersion`,void 0),w([C()],$.prototype,`localThemePreference`,void 0),w([C()],$.prototype,`configuredThemePreference`,void 0),w([C()],$.prototype,`activeThemeId`,void 0),w([C()],$.prototype,`navigationPreferences`,void 0),w([C()],$.prototype,`navigationDialogOpen`,void 0),w([C()],$.prototype,`isRefreshingApp`,void 0),w([C()],$.prototype,`sessionCleanupDialog`,void 0),w([C()],$.prototype,`sessionSearchDialogOpen`,void 0),w([C()],$.prototype,`settingsSection`,void 0),w([C()],$.prototype,`normalAuthStatus`,void 0),w([C()],$.prototype,`normalAuthLoading`,void 0),w([C()],$.prototype,`normalAuthError`,void 0),w([C()],$.prototype,`normalAuthDialogMode`,void 0),w([C()],$.prototype,`shortcutConfig`,void 0),w([C()],$.prototype,`defaultStreamingBehavior`,void 0),w([C()],$.prototype,`workspaceUploadDefaultFolder`,void 0),w([C()],$.prototype,`workspaceAttachmentsDefaultFolder`,void 0),w([C()],$.prototype,`workspaceSurfaceRevision`,void 0),$=w([b(`pi-web-app`)],$);function Dw(e){let t=e?.model?.provider,n=e?.model?.id;return t!==void 0&&n!==void 0?`${t}/${n}`:void 0}function Ow(){let e=Gt()?`management`:`normal`;return ke(e),e}function kw(e){let t=e.selectedMachine;return t===void 0?{id:`local`,name:D(`ui.piWebApp.local`,`Local`),kind:`local`}:{id:t.id,name:t.name,kind:t.kind}}function Aw(){return{registrationPluginId:`core`,sourcePluginId:`core`}}function jw(e,t){return JSON.stringify([e,t.id,t.cwd])}function Mw(e){let t=e.selectedSession;return t===void 0?void 0:jw(M(e),t)}function Nw(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function Pw(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function Fw(e,t){return Iw(e,t)}function Iw(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function Lw(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function Rw(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function zw(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function Bw(){return{}}function Vw(e,t){switch(t){case`machine`:return e.machineId??`local`;case`project`:return e.projectId;case`workspace`:return e.workspaceId;case`session`:return e.sessionId;case`tool`:return e.tool;case`view`:return e.view}}function Hw(e,t){return JSON.stringify([e,t])}function Uw(e){let t=e.selectedProject?.id;if(t!==void 0)return JSON.stringify([e.selectedMachine?.id??`local`,t])}function Ww(e){return lw[Math.min(e,lw.length-1)]??3e4}function Gw(e,t){return e.failures.flatMap(e=>{let n=t.find(t=>(t.sourcePluginId??t.id)===e.entry.id);return n===void 0?[]:[{declaration:n,phase:`import`,error:e.error}]})}function Kw(e,t){return e.registrationPluginId===t.registrationPluginId&&e.sourcePluginId===t.sourcePluginId&&e.backendRevision===t.backendRevision&&e.pairedRequestVersion===t.pairedRequestVersion&&e.pairedChannelVersion===t.pairedChannelVersion}function qw(e,t){let n=t===`local`?Kt:Yt(t,Kt),r=t===`local`?e.machineId===void 0&&e.sourcePluginId===void 0:e.machineId===t&&e.sourcePluginId===`pi-web.terminal`;if(e.id!==n||!r||e.machineSpecific!==!0||e.manifestSource!==void 0&&e.manifestSource!==`bundled`||e.manifestScope!==void 0&&e.manifestScope!==`bundled`||e.backendRevision===void 0||e.pairedRequestVersion!==1||e.pairedChannelVersion!==1)throw Error(`Required Terminal browser entry does not have bundled identity, machine scope, and matching peer request/channel capabilities`);return Object.freeze({registrationPluginId:e.id,sourcePluginId:Kt,backendRevision:e.backendRevision,pairedRequestVersion:1,pairedChannelVersion:1})}function Jw(e){return e instanceof Error?e.message:String(e)}function Yw(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function Xw(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}export{$ as PiWebApp};
|
|
3761
|
+
`}static{this.styles=zh}invalidateNavigationSelection(){this.navigationSelectionSeq+=1}refreshableMachineIds(){return this.state.machines.length===0?[M(this.state)]:this.state.machines.filter(e=>zw(e,this.state.machineStatuses[e.id])).map(e=>e.id)}async restoreCommittedNavigation(e){return this.restoreRoute(!1,e.view,`deferred`)}async finishWorkspaceRouteRestore(e,t){if(t.restoreSeq!==void 0&&!this.isCurrentRouteRestore(t.restoreSeq,t.navigation))return;let n=this.visibleWorkspacePanels(),r=t.requestedTool!==void 0&&this.availableWorkspacePanelId(t.requestedTool,n)===void 0,i=t.requestedRoute?.workspaceId!==void 0&&(this.state.selectedProject?.id!==t.requestedRoute.projectId||this.state.selectedWorkspace?.id!==t.requestedRoute.workspaceId),a=t.requestedRoute?.sessionId!==void 0&&this.state.selectedSession?.id!==t.requestedRoute.sessionId,o=t.unavailableToolRoute||t.unavailablePanelViewRoute||r,s=this.pluginLoadErrors.get(M(this.state));if(o&&s!==void 0){let e=this.state.selectedWorkspace,t=e===void 0?A(M(this.state)):Gn(M(this.state),e.projectId,e.id);this.state.browserErrors[qn(t)]===void 0&&this.browserErrors.report(t,s)}this.reconcileWorkspacePanelSelection(),t.unavailablePanelViewRoute&&this.setState({mainView:this.effectiveMainView()});let c=t.restoredWorkspaceIdentity===void 0?void 0:{identity:t.restoredWorkspaceIdentity,query:e.contributionQuery??{}};if(await this.refreshRestoredWorkspaceTool(this.state.workspaceTool,c),(t.restoreSeq===void 0||this.isCurrentRouteRestore(t.restoreSeq,t.navigation))&&t.urlPublication===`current-url`&&t.updateUrl&&!o&&!i&&!a&&(t.requestedRoute===void 0||this.routeLocationMatchesUrl(t.requestedRoute)&&(t.requestedRoute.workspaceId===void 0||this.navigationSurfaceMatchesUrl(e)))){let n=this.restoredContributionQueryForSelectedWorkspace(e,t.restoredWorkspaceIdentity);this.updateUrl(void 0,n)}}restoredContributionQueryForSelectedWorkspace(e,t){let n=this.selectedWorkspaceRouteIdentity();return t!==void 0&&n!==void 0&&kw(t,n)?e.contributionQuery??{}:{}}replaceNavigationUrl(e=this.currentContributionQueryForState()){this.replaceMachineNavigationSnapshot(Ol(this.state,e))}commitMachineNavigationSnapshot(e,t){this.syncNavigationFreshness(),this.machineNavigation.remember(e),Oa(kl(e),{...t,contributionQuery:e.surface.contributionQuery??{}}),this.syncNavigationFreshness()}currentContributionQueryForState(){let e=this.selectedWorkspaceRouteIdentity();return e===void 0||!Da(F(),e)?{}:na()}selectedWorkspaceRouteIdentity(e=this.state.selectedWorkspace,t=Mw(this.state)){if(e!==void 0)return{machineId:t.id,projectId:e.projectId,workspaceId:e.id}}replaceMachineNavigationSnapshot(e){this.syncNavigationFreshness(),this.machineNavigation.remember(e);let t=kl(e),n=this.navigationRouteMatchesUrl(t);this.navigationSurfaceMatchesUrl(e.surface)||this.writeWorkspaceRouteSurfaceToUrl(e.surface),n||Oa(t,{replace:!0}),this.syncNavigationFreshness()}navigationRouteMatchesUrl(e){let t=F();return(t.machineId??`local`)===(e.machineId??`local`)&&t.projectId===e.projectId&&t.workspaceId===e.workspaceId&&t.sessionId===e.sessionId&&t.tool===e.tool&&t.view===e.view}routeSelectionMatchesUrl(e){let t=F();return(t.machineId??`local`)===(e.machineId??`local`)&&t.projectId===e.projectId&&t.workspaceId===e.workspaceId&&t.sessionId===e.sessionId}navigationUrlContextMatchesUrl(e){return(e.generation===void 0||e.generation===this.workspaceNavigationGeneration)&&(e.navigation===void 0||e.navigation.isCurrent())&&ww()===e.url}navigationSurfaceMatchesUrl(e){return Ew(na(),e.contributionQuery??{})}async navigateToMachineFromController(e,t={}){return this.selectMachineWithMemory(e,t)}selectProjectFromNavigation(e){return this.navigateToProjectFromController(e)}selectWorkspaceFromNavigation(e){return this.navigateToWorkspaceFromController(e)}selectSessionFromNavigation(e){return this.navigateToSessionFromController(e)}requiredTerminalComposition(e){let t=this.requiredTerminalByMachine.get(e);if(t===void 0)throw ng(e);return t}requiredTerminalPanelId(e){return`${this.requiredTerminalComposition(e).binding.registrationPluginId}:${bw}`}createPanelActions(e){return{toggle:()=>{e===`navigation`?this.panelCollapse.toggleNavigationPanel():this.panelCollapse.toggleWorkspacePanel()},resizeStart:()=>this.startPanelResize(e),resize:t=>{this.panelResize.resizePanel(e,t,{persist:!1})},resizeEnd:()=>{this.panelResize.persistPanelSizes()},reset:()=>{this.resetResizablePanel(e)}}}availableWorkspacePanelId(e,t=this.visibleWorkspacePanels()){return t.find(t=>t.id===e)?.id}unavailableRouteTool(e=this.visibleWorkspacePanels()){let t=F();if(t.tool===void 0)return;let n=this.resolveBrowserAppRoute(t).tool;return this.availableWorkspacePanelId(n,e)===void 0?t.tool:void 0}effectiveWorkspaceTool(e=this.visibleWorkspacePanels()){let t=F();return t.tool===void 0?(Sa(t.view)===void 0?this.resolveBrowserAppRoute(t).tool:void 0)??this.state.workspaceTool??e[0]?.id:this.resolveBrowserAppRoute(t).tool}unknownRouteView(){let e=F();return e.view!==void 0&&this.resolveBrowserAppRoute(e).view===void 0?e.view:void 0}effectiveMainView(){return this.unknownRouteView()===void 0?this.state.mainView:this.appShell.isMobileNavigationLayout?`navigation`:F().tool!==void 0&&this.unavailableRouteTool()===void 0?`workspace`:`chat`}reconcileWorkspacePanelSelection(){let e=this.visibleWorkspacePanels(),t=this.effectiveWorkspaceTool(e);return t!==this.state.workspaceTool&&(this.setState({workspaceTool:t}),!0)}contentDestination(e){return JSON.stringify([e.machineId??`local`,e.projectId,e.workspaceId,e.sessionId])}setContentError(e,t){this.contentLoadOutcome={destination:this.contentDestination(e),error:t},this.requestUpdate()}contentError(){return this.contentLoadOutcome?.destination===this.contentDestination(F())?this.contentLoadOutcome.error:``}workspaceContentError(){if(this.state.selectedWorkspace===void 0)return this.contentError();let e=F(),t=e.tool,n=t===void 0?this.effectiveWorkspaceTool():this.resolveBrowserAppRoute({...e,tool:t}).tool;return(t!==void 0||n!==void 0)&&this.availableWorkspacePanelId(n)===void 0?this.pluginLoadErrors.get(M(this.state))??this.requiredPluginFailureByMachine.get(M(this.state))??D(`ui.main.4d914bb120b8`,`Workspace panel unavailable: {arg0}`,{arg0:t??n??`unknown`}):``}workspacePanelContextIsCurrent(e,t,n){return M(this.state)===t.id&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.id&&Da(F(),{machineId:t.id,projectId:e.projectId,workspaceId:e.id})&&(n===void 0||n.isCurrent())}createWorkspacePanelNavigation(e,t,n,r,i,a){let o={machineId:t.id,projectId:e.projectId,workspaceId:e.id},s=i!==void 0&&kw(o,i.identity)?ea(i.query,n,r):Da(F(),o)?$i(n,r):Object.freeze({}),c=s;return Object.freeze({version:1,contributionId:n,query:s,set:(e,t,i)=>{if(!ca(e))throw Error(D(`ui.main.2241ac67c24f`,`Invalid contribution navigation parameter: {arg0}`,{arg0:e}));if(!a.isCurrent())return!1;let s=this.selectedWorkspaceRouteIdentity();return s===void 0||!kw(o,s)||!Da(F(),o)||!Ew($i(n,r),c)?!1:(oa(n,r,e,t,i)&&(c=$i(n,r),this.rememberCurrentMachineNavigation(),this.requestUpdate()),!0)}})}invalidateSelectedWorkspaceFiles(){let e=this.state.selectedWorkspace;return e===void 0?Promise.resolve():this.invalidateWorkspaceResources(e,Mw(this.state),{reason:`manual`,resources:[`workspace.files`]})}workspaceSurfaceActions(){return[{id:`core:workspace.refresh-current`,title:D(`client.actions.refresh.current.panel.a33a0a`,`Refresh current panel`),shortcut:`mod+shift+r`,group:D(`bundled.workspace-tasks.workspace.379798`,`Workspace`),enabled:this.state.selectedWorkspace!==void 0,run:()=>this.refreshCurrentWorkspaceSurface()}]}visibleBrowserErrorsForCurrentRoute(e){return Qn(e.browserErrors,Tw(e,F()))}resolveBrowserAppRoute(e){let t=e=>this.plugins.resolveWorkspacePanelRouteId(e,M(this.state)),n=e.view!==void 0&&[`files`,`git`,`terminal`,`core:workspace.files`,`core:workspace.git`,`core:workspace.terminal`].includes(e.view)?t(e.view):void 0;return Ta(n===void 0?e:{...e,view:`workspace`,tool:e.tool??n},t)}messageActionContext(e){let t=Qt(e).selectedSession;if(t===void 0)return;let n={machine:Object.freeze(Mw(e)),session:Object.freeze({...t,busy:e.sendingPrompts[t.id]===!0||rr(e.status,e.activity)})},r=JSON.stringify(n);return r!==this.messageActionInputs&&(this.messageActionInputs=r,this.messageActionSnapshot=n),this.messageActionSnapshot}messageActionHelpers(e,t){let n=this.state,r=t.machine.id,i=n.selectedWorkspace,a=Qt(n).selectedWorkspace,o=i===void 0?void 0:Ad(e,i,r),s=()=>M(this.state)===r&&this.state.selectedSession?.id===t.session.id&&this.state.selectedSession.cwd===t.session.cwd,c=this.createPromptEditor(e.registrationPluginId,r);return{prompt:{...c,insertText:e=>{s()&&c.insertText(e)},getText:()=>s()?c.getText():``,getSelection:()=>s()?c.getSelection():null},navigate:(e,t)=>this.navigate(e,t,r),projects:md(_e,r),...i===void 0||a===void 0?{}:{workspace:a,files:this.createWorkspaceFiles(i,t.machine),...this.terminalAvailableForMachine(r)?{terminal:this.workspaceTerminal(e.registrationPluginId,i,r)}:{}},...o===void 0?{}:{peer:o}}}};w([y({attribute:!1})],$.prototype,`chatBehaviors`,void 0),w([C()],$.prototype,`state`,void 0),w([S(`chat-view`)],$.prototype,`chatView`,void 0),w([C()],$.prototype,`chatNavigation`,void 0),w([C()],$.prototype,`queuedMessageActionTarget`,void 0),w([C()],$.prototype,`messageRevertTarget`,void 0),w([S(`prompt-editor`)],$.prototype,`promptEditor`,void 0),w([S(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),w([S(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),w([S(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),w([C()],$.prototype,`unreadSessionIds`,void 0),w([C()],$.prototype,`unreadPresence`,void 0),w([C()],$.prototype,`readyChatIdentity`,void 0),w([C()],$.prototype,`navigationOrderVersion`,void 0),w([C()],$.prototype,`localThemePreference`,void 0),w([C()],$.prototype,`configuredThemePreference`,void 0),w([C()],$.prototype,`activeThemeId`,void 0),w([C()],$.prototype,`navigationPreferences`,void 0),w([C()],$.prototype,`navigationDialogOpen`,void 0),w([C()],$.prototype,`isRefreshingApp`,void 0),w([C()],$.prototype,`sessionCleanupDialog`,void 0),w([C()],$.prototype,`sessionSearchDialogOpen`,void 0),w([C()],$.prototype,`settingsSection`,void 0),w([C()],$.prototype,`normalAuthStatus`,void 0),w([C()],$.prototype,`normalAuthLoading`,void 0),w([C()],$.prototype,`normalAuthError`,void 0),w([C()],$.prototype,`normalAuthDialogMode`,void 0),w([C()],$.prototype,`shortcutConfig`,void 0),w([C()],$.prototype,`defaultStreamingBehavior`,void 0),w([C()],$.prototype,`workspaceUploadDefaultFolder`,void 0),w([C()],$.prototype,`workspaceAttachmentsDefaultFolder`,void 0),w([C()],$.prototype,`workspaceSurfaceRevision`,void 0),$=w([b(`pi-web-app`)],$);function Aw(e){let t=e?.model?.provider,n=e?.model?.id;return t!==void 0&&n!==void 0?`${t}/${n}`:void 0}function jw(){let e=Gt()?`management`:`normal`;return ke(e),e}function Mw(e){let t=e.selectedMachine;return t===void 0?{id:`local`,name:D(`ui.piWebApp.local`,`Local`),kind:`local`}:{id:t.id,name:t.name,kind:t.kind}}function Nw(){return{registrationPluginId:`core`,sourcePluginId:`core`}}function Pw(e,t){return JSON.stringify([e,t.id,t.cwd])}function Fw(e){let t=e.selectedSession;return t===void 0?void 0:Pw(M(e),t)}function Iw(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function Lw(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function Rw(e,t){return zw(e,t)}function zw(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function Bw(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function Vw(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function Hw(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function Uw(){return{}}function Ww(e,t){switch(t){case`machine`:return e.machineId??`local`;case`project`:return e.projectId;case`workspace`:return e.workspaceId;case`session`:return e.sessionId;case`tool`:return e.tool;case`view`:return e.view}}function Gw(e,t){return JSON.stringify([e,t])}function Kw(e){let t=e.selectedProject?.id;if(t!==void 0)return JSON.stringify([e.selectedMachine?.id??`local`,t])}function qw(e){return fw[Math.min(e,fw.length-1)]??3e4}function Jw(e,t){return e.failures.flatMap(e=>{let n=t.find(t=>(t.sourcePluginId??t.id)===e.entry.id);return n===void 0?[]:[{declaration:n,phase:`import`,error:e.error}]})}function Yw(e,t){return e.registrationPluginId===t.registrationPluginId&&e.sourcePluginId===t.sourcePluginId&&e.backendRevision===t.backendRevision&&e.pairedRequestVersion===t.pairedRequestVersion&&e.pairedChannelVersion===t.pairedChannelVersion}function Xw(e,t){let n=t===`local`?Kt:Yt(t,Kt),r=t===`local`?e.machineId===void 0&&e.sourcePluginId===void 0:e.machineId===t&&e.sourcePluginId===`pi-web.terminal`;if(e.id!==n||!r||e.machineSpecific!==!0||e.manifestSource!==void 0&&e.manifestSource!==`bundled`||e.manifestScope!==void 0&&e.manifestScope!==`bundled`||e.backendRevision===void 0||e.pairedRequestVersion!==1||e.pairedChannelVersion!==1)throw Error(`Required Terminal browser entry does not have bundled identity, machine scope, and matching peer request/channel capabilities`);return Object.freeze({registrationPluginId:e.id,sourcePluginId:Kt,backendRevision:e.backendRevision,pairedRequestVersion:1,pairedChannelVersion:1})}function Zw(e){return e instanceof Error?e.message:String(e)}function Qw(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function $w(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}export{$ as PiWebApp};
|