@chainingintention/pi-web-cn 2.202611.1 → 2.202611.3

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.
Files changed (38) hide show
  1. package/dist/client/assets/{PiWebApp-D9e-Nrxi.js → PiWebApp-Dur6Wi62.js} +245 -245
  2. package/dist/client/assets/{SettingsDialog-BvlvoXvD.js → SettingsDialog-SOljSiee.js} +1 -1
  3. package/dist/client/assets/{external-Bawe0tSn.js → external-DjGXa4ZP.js} +1 -1
  4. package/dist/client/assets/{index-0z4D-18M.js → index-CInvlJKI.js} +2 -2
  5. package/dist/client/assets/{main-DDgPZEYp.js → main-CWcn0Deu.js} +2 -2
  6. package/dist/client/assets/requiredTerminalPlugin-B-0wkiKe.js +3 -0
  7. package/dist/client/index.html +1 -1
  8. package/dist/pi-web-plugins/custom-ui-codex/fileIcons.js +30 -28
  9. package/dist/pi-web-plugins/custom-ui-codex/pi-web-plugin.js +3 -3
  10. package/dist/server/navigationPreferenceRoutes.js +50 -13
  11. package/dist/server/navigationPreferenceRoutes.js.map +1 -1
  12. package/dist/server/normalAuth.js +3 -0
  13. package/dist/server/normalAuth.js.map +1 -1
  14. package/dist/server/piWebPluginCatalog.js +13 -5
  15. package/dist/server/piWebPluginCatalog.js.map +1 -1
  16. package/dist/server/sessiond/sessionProxyRoutes.js +27 -7
  17. package/dist/server/sessiond/sessionProxyRoutes.js.map +1 -1
  18. package/dist/server/sessiond.js +3 -3
  19. package/dist/server/sessiond.js.map +1 -1
  20. package/dist/server/sessions/piSessionService.js +1 -26
  21. package/dist/server/sessions/piSessionService.js.map +1 -1
  22. package/dist/server/sessions/sessionRoutes.js +0 -27
  23. package/dist/server/sessions/sessionRoutes.js.map +1 -1
  24. package/dist/server/storage/navigationPreferenceStore.js +10 -4
  25. package/dist/server/storage/navigationPreferenceStore.js.map +1 -1
  26. package/dist/server/storage/sessionPinStore.js +10 -4
  27. package/dist/server/storage/sessionPinStore.js.map +1 -1
  28. package/dist/shared/apiTypes.js +1 -0
  29. package/dist/shared/apiTypes.js.map +1 -1
  30. package/dist/shared/capabilities.js +3 -0
  31. package/dist/shared/capabilities.js.map +1 -1
  32. package/dist/shared/federatedRoutes.js +0 -3
  33. package/dist/shared/federatedRoutes.js.map +1 -1
  34. package/docs/plugins.md +4 -4
  35. package/package.json +1 -1
  36. package/dist/client/assets/requiredTerminalPlugin-ZZOwUcbr.js +0 -3
  37. package/dist/server/sessions/sessionPinStore.js +0 -109
  38. package/dist/server/sessions/sessionPinStore.js.map +0 -1
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./SettingsDialog-BvlvoXvD.js","./styles-BwN5rgmt.js","./styleSources-CdF2T_pj.js","./lit-CJ6w1GHF.js","./themePreference-BBiJxLjs.js","./themeCatalog-B3yda95n.js","./composerShortcuts-BggqvE9J.js","./requiredTerminalPlugin-ZZOwUcbr.js"])))=>i.map(i=>d[i]);
2
- import{a as e,c as t,i as n,l as r,n as i,o as a,r as o,s,t as c,u as l}from"./styles-BwN5rgmt.js";import{_ as u,c as d,f,g as p,h as m,l as h,m as ee,p as te,s as ne,v as re}from"./themePreference-BBiJxLjs.js";import{a as ie,c as ae,d as oe,g as se,h as ce,l as le,m as ue,p as de,r as fe,s as pe,t as me,u as he}from"./themeCatalog-B3yda95n.js";import{t as ge}from"./styleSources-CdF2T_pj.js";import{t as _e}from"./preload-helper-CRzLMJPS.js";import{i as ve,n as ye,o as be,r as xe}from"./themeStartup-0b02tNrh.js";import{A as Se,B as Ce,D as g,E as we,G as _,H as Te,I as Ee,J as De,K as Oe,L as ke,M as Ae,N as je,O as Me,Q as Ne,R as Pe,S as Fe,T as Ie,U as v,V as Le,W as y,X as Re,Y as ze,Z as Be,_ as Ve,a as He,b as Ue,d as We,f as Ge,g as Ke,h as qe,i as Je,k as Ye,l as Xe,m as Ze,p as Qe,q as $e,s as et,t as tt,u as nt,v as rt,x as it,y as at,z as ot}from"./composerShortcuts-BggqvE9J.js";import{$ as st,A as ct,B as lt,C as ut,D as dt,E as ft,F as pt,G as mt,H as ht,I as gt,J as _t,K as b,L as vt,M as yt,N as bt,O as xt,P as St,Q as Ct,R as wt,S as Tt,T as Et,U as Dt,V as Ot,Y as kt,Z as At,_ as jt,a as Mt,b as Nt,bt as x,c as Pt,ct as Ft,d as It,et as Lt,f as Rt,g as zt,h as Bt,ht as Vt,i as Ht,j as Ut,k as Wt,l as Gt,lt as Kt,m as qt,mt as S,n as Jt,nt as Yt,p as Xt,pt as C,q as Zt,r as Qt,rt as $t,s as en,st as tn,t as nn,tt as rn,u as an,ut as on,vt as w,w as sn,x as cn,y as ln,z as un}from"./requiredTerminalPlugin-ZZOwUcbr.js";import{c as dn,d as T,i as fn,n as E,o as D,t as O}from"./lit-CJ6w1GHF.js";import{a as pn,i as mn,n as hn,o as gn,r as _n,t as vn}from"./external-Bawe0tSn.js";import{$ as yn,A as bn,J as xn,K as Sn,N as Cn,Q as wn,X as Tn,Y as En,Z as Dn,d as On,et as kn,f as An,k as jn,l as Mn,nt as Nn,p as Pn,q as Fn,rt as In,u as Ln,x as Rn}from"./vendor-editor-core-BfnHL1Dg.js";import{n as zn,r as Bn,t as Vn}from"./vendor-editor-languages-bNquDJP0.js";function Hn(e){return e.flatMap(e=>e.type===`customMessage`?e.parts:[e])}function Un(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:Gn(e.parts).join(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./SettingsDialog-SOljSiee.js","./styles-BwN5rgmt.js","./styleSources-CdF2T_pj.js","./lit-CJ6w1GHF.js","./themePreference-BBiJxLjs.js","./themeCatalog-B3yda95n.js","./composerShortcuts-BggqvE9J.js","./requiredTerminalPlugin-B-0wkiKe.js"])))=>i.map(i=>d[i]);
2
+ import{a as e,c as t,i as n,l as r,n as i,o as a,r as o,s,t as c,u as l}from"./styles-BwN5rgmt.js";import{_ as u,c as d,f,g as p,h as m,l as h,m as ee,p as te,s as ne,v as re}from"./themePreference-BBiJxLjs.js";import{a as ie,c as ae,d as oe,g as se,h as ce,l as le,m as ue,p as de,r as fe,s as pe,t as me,u as he}from"./themeCatalog-B3yda95n.js";import{t as ge}from"./styleSources-CdF2T_pj.js";import{t as _e}from"./preload-helper-CRzLMJPS.js";import{i as ve,n as ye,o as be,r as xe}from"./themeStartup-0b02tNrh.js";import{A as Se,B as Ce,D as g,E as we,G as _,H as Te,I as Ee,J as De,K as Oe,L as ke,M as Ae,N as je,O as Me,Q as Ne,R as Pe,S as Fe,T as Ie,U as v,V as Le,W as y,X as Re,Y as ze,Z as Be,_ as Ve,a as He,b as Ue,d as We,f as Ge,g as Ke,h as qe,i as Je,k as Ye,l as Xe,m as Ze,p as Qe,q as $e,s as et,t as tt,u as nt,v as rt,x as it,y as at,z as ot}from"./composerShortcuts-BggqvE9J.js";import{$ as st,A as ct,B as lt,C as ut,D as dt,E as ft,F as pt,G as mt,H as ht,I as gt,J as _t,K as b,L as vt,M as yt,N as bt,O as xt,P as St,Q as Ct,R as wt,S as Tt,T as Et,U as Dt,V as Ot,Y as kt,Z as At,_ as jt,a as Mt,b as Nt,bt as x,c as Pt,ct as Ft,d as It,et as Lt,f as Rt,g as zt,h as Bt,ht as Vt,i as Ht,j as Ut,k as Wt,l as Gt,lt as Kt,m as qt,mt as S,n as Jt,nt as Yt,p as Xt,pt as C,q as Zt,r as Qt,rt as $t,s as en,st as tn,t as nn,tt as rn,u as an,ut as on,vt as w,w as sn,x as cn,y as ln,z as un}from"./requiredTerminalPlugin-B-0wkiKe.js";import{c as dn,d as T,i as fn,n as E,o as D,t as O}from"./lit-CJ6w1GHF.js";import{a as pn,i as mn,n as hn,o as gn,r as _n,t as vn}from"./external-DjGXa4ZP.js";import{$ as yn,A as bn,J as xn,K as Sn,N as Cn,Q as wn,X as Tn,Y as En,Z as Dn,d as On,et as kn,f as An,k as jn,l as Mn,nt as Nn,p as Pn,q as Fn,rt as In,u as Ln,x as Rn}from"./vendor-editor-core-BfnHL1Dg.js";import{n as zn,r as Bn,t as Vn}from"./vendor-editor-languages-bNquDJP0.js";function Hn(e){return e.flatMap(e=>e.type===`customMessage`?e.parts:[e])}function Un(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:Gn(e.parts).join(`
3
3
 
4
4
  `)})}function Wn(e){return Object.freeze({...e.entryId===void 0?{}:{entryId:e.entryId},role:e.role,text:Gn(e.parts).map(e=>e.trim()).filter(Boolean).join(`
5
5
 
@@ -27,7 +27,7 @@ This will also remove {steers, number} later steers and # queued follow-ups.}}}}
27
27
  </button>
28
28
  `}var sr={actionPalette:x(`Action palette`,`Action chooser dialog accessible name`),searchActions:x(`Search actions`,`Action chooser search accessible name`),searchActionsPlaceholder:x(`Search actions...`,`Action chooser search placeholder`),noActions:x(`No actions found.`,`Empty filtered action list`),close:x(`Close`,`Dismiss the picker without choosing`),select:x(`Select`,`Fallback command chooser title; host-supplied titles are unchanged`),selectModel:x(`Select Model`,`Session model chooser title`),selectThinking:x(`Select Thinking Level`,`Session thinking level chooser title`),search:x(`Search`,`Command and model search placeholder`),searchOptions:x(`Search options`,`Command chooser search accessible name`),noOptions:x(`No matching options`,`Empty filtered command or model list`),defaultHelp:x(`New session default`,`Heading for pins that set the default for new sessions`),useDefault:x(`Use {label} as default for new sessions`,`Default pin action; label is an unchanged option/model name`),modelScope:x(`Model scope`,`Accessible name for model list mode controls`),enabled:x(`Enabled`,`Show only currently enabled models`),allModels:x(`All models`,`Show the complete model catalog`),projectOverride:x(`Project override`,`Workspace settings override model availability`),overrideNotice:x(`Showing models from this workspace’s <code>{path}</code>. Model availability selection is disabled.`,`Read-only workspace scope notice; code wraps the unchanged settings path`),searchModels:x(`Search models`,`Model chooser search accessible name`),catalogOrder:x(`All models in catalog order`,`Accessible name for complete model list`),enabledModels:x(`Enabled models`,`Accessible name for enabled model list`),selectAll:x(`Select all`,`Enable every model in the catalog`),deselectAll:x(`Deselect all`,`Keep only the current model enabled`),workspaceControl:x(`Workspace settings control model availability`,`Model scope cannot be edited here`),unavailableCurrent:x(`The current model is unavailable`,`Cannot reduce scope without identifying the current model`),updating:x(`Updating model availability`,`Live status during a model scope change`),controlledModel:x(`Model availability for {model} is controlled by workspace settings`,`Read-only model membership control accessible name`),protectedModel:x(`Current model {model} cannot be deselected`,`Current model membership control accessible name`),disableModel:x(`Disable {model}`,`Disable an unchanged provider/model identifier`),enableModel:x(`Enable {model}`,`Enable an unchanged provider/model identifier`),remainEnabled:x(`The current model must remain enabled`,`Current model checkbox tooltip`),currentModel:x(`{model} ✓ current`,`Current model or thinking-level row label; identifier stays unchanged`),reasoningOff:x(`No reasoning`,`Thinking level off description`),reasoningMinimal:x(`Very brief reasoning (~{tokens}k tokens)`,`Minimal thinking approximate token budget in thousands`),reasoningLow:x(`Light reasoning (~{tokens}k tokens)`,`Low thinking approximate token budget in thousands`),reasoningMedium:x(`Moderate reasoning (~{tokens}k tokens)`,`Medium thinking approximate token budget in thousands`),reasoningHigh:x(`Deep reasoning (~{tokens}k tokens)`,`High thinking approximate token budget in thousands`),reasoningXhigh:x(`Maximum reasoning (~{tokens}k tokens)`,`Extra-high thinking approximate token budget in thousands`)},A=w.registerMessages(`core.pickers`,sr),cr={configCompatibility:x(`config key {name} is deprecated with no replacement; remove it manually (local compatibility remains temporarily)`,`Deprecated legacy command config still honored by this fork; name remains unchanged`),environmentCompatibility:x(`environment variable {name} is deprecated with no replacement; remove it manually (local compatibility remains temporarily)`,`Deprecated legacy command environment variable still honored by this fork; name remains unchanged`),warning:x(`{machine}: {inputs}. Support for deprecated agent configuration inputs will be removed in a future release.`,`Non-dismissable machine configuration warning. machine is an unchanged machine name; inputs is a localized list of complete deprecation clauses.`),configReplacement:x(`config key {name} is deprecated; set {replacement} instead`,`Deprecated config key with replacement. Both identifiers must remain unchanged.`),environmentReplacement:x(`environment variable {name} is deprecated; set {replacement} instead`,`Deprecated environment variable with replacement. Both identifiers must remain unchanged.`),configIgnored:x(`config key {name} is deprecated and ignored; remove it, there is no replacement`,`Deprecated config key without replacement. name is an unchanged identifier.`),environmentIgnored:x(`environment variable {name} is deprecated and ignored; remove it, there is no replacement`,`Deprecated environment variable without replacement. name is an unchanged identifier.`)},lr=w.registerMessages(`core.deprecatedAgentInputs`,cr);function ur(e,t){let n=[];for(let r of e){let e=t[r.id]?.deprecatedAgentInputs;e!==void 0&&e.length!==0&&n.push({machineId:r.id,machineName:r.name,inputs:e})}return n}function dr(e){let t=w.list(e.inputs.map(fr),{type:`unit`});return lr.t(`warning`,{machine:e.machineName,inputs:t})}function fr(e){return e.replacement===void 0&&(e.source===`config`&&e.name===`agent.command`||e.source===`environment`&&e.name===`PI_WEB_AGENT_COMMAND`)?lr.t(e.source===`config`?`configCompatibility`:`environmentCompatibility`,{name:e.name}):e.replacement===void 0?lr.t(e.source===`config`?`configIgnored`:`environmentIgnored`,{name:e.name}):lr.t(e.source===`config`?`configReplacement`:`environmentReplacement`,{name:e.name,replacement:e.replacement})}function pr(e){return e.length===0?null:D`<div class="deprecation-notice" role="alert">
29
29
  ${e.map(e=>D`<p class="deprecation-notice-text">${dr(e)}</p>`)}
30
- </div>`}var mr={},hr=ot(class extends Ce{constructor(){super(...arguments),this.ot=mr}render(e,t){return t()}update(e,[t,n]){if(Array.isArray(t)){if(Array.isArray(this.ot)&&this.ot.length===t.length&&t.every((e,t)=>e===this.ot[t]))return fn}else if(this.ot===t)return fn;return this.ot=Array.isArray(t)?Array.from(t):t,this.render(t,n)}});function gr(e,t=`local`,n=m()){let r=typeof e==`string`?`${vr(t)}/sessions/${encodeURIComponent(e)}/events`:ft(e,t),i=re(r,void 0,n);return new WebSocket(ee(i))}function _r(e=`local`,t=m()){let n=re(`${vr(e)}/events`,void 0,t);return new WebSocket(ee(n))}function vr(e){return`api/machines/${encodeURIComponent(e)}`}function yr(){return{sessions:[],pinnedSessionIds:[],sessionSearchQuery:``,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``,sessionSearchTarget:void 0,clientQueuedSessionMessages:{},startingSessionCount:0,selectedNotificationInbox:void 0,treeDialog:void 0,error:``}}function br(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},machineStatusSnapshots:{},projects:[],workspaces:[],sessions:[],pinnedSessionIds:[],sessionSearchQuery:``,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``,sessionSearchTarget:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},selectedNotificationInbox:void 0,workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,pendingTreeActions:[],treeDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:void 0,mainView:`chat`,piWebStatus:void 0,browserErrors:{},error:``}}function j(e){return{kind:`machine`,machineId:e}}function xr(e,t){return{kind:`project`,machineId:e,projectId:t}}function Sr(e,t,n){return{kind:`workspace`,machineId:e,projectId:t,workspaceId:n}}function Cr(e,t,n={}){return{kind:`session`,machineId:e,sessionId:t,...n.cwd===void 0?{}:{cwd:n.cwd},...n.projectId===void 0?{}:{projectId:n.projectId},...n.workspaceId===void 0?{}:{workspaceId:n.workspaceId}}}function wr(e){switch(e.kind){case`global`:return`global`;case`machine`:return JSON.stringify([e.kind,e.machineId]);case`project`:return JSON.stringify([e.kind,e.machineId,e.projectId]);case`workspace`:return JSON.stringify([e.kind,e.machineId,e.projectId,e.workspaceId]);case`session`:return JSON.stringify([e.kind,e.machineId,e.sessionId,e.cwd,e.projectId,e.workspaceId])}}function Tr(e,t,n,r){return{...e,[wr(t)]:{scope:t,message:n,...r===void 0?{}:{recovery:r}}}}function Er(e,t,n){let r=wr(t),i=e[r];return i===void 0||n!==void 0&&i.message!==n?e:Object.fromEntries(Object.entries(e).filter(([e])=>e!==r))}function Dr(e,t){let n=Object.fromEntries(Object.entries(e).filter(([,e])=>!Nr(e.scope,t)));return Object.keys(n).length===Object.keys(e).length?e:n}function Or(e){let t=e.selectedSession;return{machineId:e.selectedMachine?.id??`local`,...e.selectedProject===void 0?{}:{projectId:e.selectedProject.id},...e.selectedWorkspace===void 0?{}:{workspaceId:e.selectedWorkspace.id},...t===void 0?{}:{sessionId:t.id,cwd:t.cwd}}}function kr(e,t){return Object.values(e).filter(e=>jr(e.scope,t)).sort((e,t)=>Mr(e.scope)-Mr(t.scope)||wr(e.scope).localeCompare(wr(t.scope)))}var Ar=class{constructor(e,t){this.getState=e,this.setState=t}report(e,t,n){this.setState({browserErrors:Tr(this.getState().browserErrors,e,t,n)})}reportLocalized(e,t,n){let r=t();this.setState({browserErrors:{...this.getState().browserErrors,[wr(e)]:{scope:e,message:r,displayMessage:t,...n===void 0?{}:{recovery:n}}}})}captureRecovery(e,t){let n=this.getState().browserErrors[wr(e)];return n?.recovery===t?n:void 0}clearRecovered(e){e?.recovery!==void 0&&this.getState().browserErrors[wr(e.scope)]===e&&this.clear(e.scope)}clear(e,t){let n=this.getState().browserErrors,r=Er(n,e,t);r!==n&&this.setState({browserErrors:r})}discard(e){let t=Dr(this.getState().browserErrors,e);t!==this.getState().browserErrors&&this.setState({browserErrors:t})}};function jr(e,t){return e.kind===`global`?!0:e.machineId===t.machineId?e.kind===`machine`?!0:e.kind===`project`?e.projectId===t.projectId:e.kind===`workspace`?e.projectId===t.projectId&&e.workspaceId===t.workspaceId:e.sessionId===t.sessionId&&(e.cwd===void 0||e.cwd===t.cwd)&&(e.projectId===void 0||e.projectId===t.projectId)&&(e.workspaceId===void 0||e.workspaceId===t.workspaceId):!1}function Mr(e){switch(e.kind){case`global`:return 0;case`machine`:return 1;case`project`:return 2;case`workspace`:return 3;case`session`:return 4}}function Nr(e,t){return t.kind===`global`?!0:e.kind===`global`||e.machineId!==t.machineId?!1:t.kind===`machine`?!0:t.kind===`project`?e.kind!==`machine`&&e.projectId===t.projectId:t.kind===`workspace`?e.kind===`workspace`?e.projectId===t.projectId&&e.workspaceId===t.workspaceId:e.kind===`session`&&e.projectId===t.projectId&&e.workspaceId===t.workspaceId:e.kind===`session`&&e.sessionId===t.sessionId&&(t.cwd===void 0||e.cwd===t.cwd)}function Pr(e,t){return t?.phase===`active`&&t.startup!==!0||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}var Fr=`workspace.delete`,Ir=`pi.operation`,Lr=`target.workspaceId`;function Rr(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}function zr(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function Br(e){return Vr(Object.values(e??{}))}function Vr(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function Hr(e,t){return`${e}:${t}`}function M(e,t){return`${e}:${t}`}function N(e){return e.selectedMachine?.id??`local`}var Ur=class{constructor(e=0){if(this.debounceMs=e,this.pendingByKey=new Map,!Number.isInteger(e)||e<0)throw Error(`debounceMs must be a non-negative integer`)}request(e,t){let n=this.pendingByKey.get(e);if(n!==void 0)return n.latestRefresh=t,n.phase===`running`?n.trailing=!0:this.rescheduleDebounce(n),n.promise;let r={promise:Promise.resolve(),latestRefresh:t,phase:`debouncing`,trailing:!1,debounceTimer:void 0,finishDebounce:void 0};return r.promise=Promise.resolve().then(async()=>{let t,n;do{r.trailing=!1,r.phase=`debouncing`,this.debounceMs>0&&await this.waitForDebounce(r),r.phase=`running`;let e=r.latestRefresh;n=!1;try{await e()}catch(e){t=e,n=!0}}while(this.hasTrailingRequest(r));if(this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e),n)throw t}).finally(()=>{this.cancelDebounce(r),this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e)}),this.pendingByKey.set(e,r),r.promise}hasTrailingRequest(e){return e.trailing}waitForDebounce(e){return new Promise(t=>{e.finishDebounce=t,this.rescheduleDebounce(e)})}rescheduleDebounce(e){e.finishDebounce!==void 0&&(e.debounceTimer!==void 0&&globalThis.clearTimeout(e.debounceTimer),e.debounceTimer=globalThis.setTimeout(()=>{let t=e.finishDebounce;e.debounceTimer=void 0,e.finishDebounce=void 0,e.phase=`running`,t?.()},this.debounceMs))}cancelDebounce(e){e.debounceTimer!==void 0&&globalThis.clearTimeout(e.debounceTimer),e.debounceTimer=void 0,e.finishDebounce=void 0}},Wr=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new Ur,this.api=n.api??Rt,this.onActivityApplied=n.onActivityApplied}refresh(e=N(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,Gr(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=N(this.getState())){let n=this.getState(),r=N(n)===t,i=Kr(n.machineActivities[t]??(r?n.workspaceActivities:{}),e);this.setState({machineActivities:{...n.machineActivities,[t]:i},...r?{workspaceActivities:i}:{}}),this.onActivityApplied?.(t)}applyMachineActivitySnapshot(e,t){let n=this.getState();this.setState({machineActivities:{...n.machineActivities,[e]:t},...N(n)===e?{workspaceActivities:t}:{}}),this.onActivityApplied?.(e)}};function Gr(e){let t={};for(let n of e.workspaces)Rr(n)&&(t[n.cwd]=n);return t}function Kr(e,t){let n={...e};return Rr(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}var qr={close:x(`Close`,`Dismiss the authentication dialog`),cancel:x(`Cancel`,`Cancel authentication or return from the starting step`),submit:x(`Submit`,`Submit the current provider prompt response`),methodTitle:x(`Configure provider authentication`,`Title of the provider authentication method chooser`),subscription:x(`Use a subscription`,`Authentication method using a provider subscription`),subscriptionDetail:x(`ChatGPT Plus/Pro, Claude Pro/Max, or GitHub Copilot`,`Examples of supported subscriptions; product names stay unchanged`),credentials:x(`Use provider credentials`,`Authentication method using an API key or other provider credentials`),credentialsDetail:x(`Configure an API key or provider-specific credentials in the active Pi-compatible profile's auth.json`,`Instructions for configuring provider credentials; auth.json is a literal filename`),selectProvider:x(`Select provider authentication`,`Provider chooser title when no authentication method was specified`),selectSubscription:x(`Select subscription provider`,`Provider chooser title for subscription authentication`),selectCredentials:x(`Select credential provider`,`Provider chooser title for credential authentication`),removeTitle:x(`Remove stored provider authentication`,`Stored-credential removal dialog title`),mcpAuthentication:x(`MCP authentication`,`MCP authentication dialog title before an operation is known`),mcpLogin:x(`MCP login`,`MCP sign-in chooser title`),mcpLogout:x(`MCP logout`,`MCP sign-out chooser title`),mcpLoginProvider:x(`MCP login: {provider}`,`Title when signing in to a named MCP server`),mcpLogoutProvider:x(`MCP logout: {provider}`,`Title when signing out of a named MCP server`),loginProvider:x(`Login to {provider}`,`Provider authentication dialog title`),startMcpLogin:x(`Sign in to an MCP server`,`Starting MCP sign-in dialog title`),startMcpLogout:x(`Sign out of an MCP server`,`Starting MCP sign-out dialog title`),startingMcp:x(`Starting MCP authentication…`,`Status while the host starts MCP authentication`),search:x(`Search providers`,`Accessible name and placeholder of provider search`),noCredentials:x(`No stored credentials. Environment variables and models.json settings are unchanged.`,`Empty stored-credential list; models.json is a literal filename`),noProviders:x(`No providers available.`,`Empty provider chooser`),noMatches:x(`No matching providers`,`Provider search has no matches`),approveBrowser:x(`Approve access in your browser, then return here.`,`MCP browser approval instructions`),authorizationLink:x(`Open this authorization link:`,`Instructions before a provider authorization URL`),authorizationPage:x(`Open authorization page`,`MCP browser authorization link label`),enterCode:x(`Enter code: <codeTag>{code}</codeTag>`,`Device authorization code instructions; codeTag tag wraps the unchanged code`),cancellationRequested:x(`Cancellation requested. Waiting for Pi to finish…`,`MCP cancellation may still be in progress`),finished:x(`Operation finished`,`MCP operation has ended, without claiming authentication succeeded`),waiting:x(`Waiting for Pi…`,`MCP authentication is awaiting the host`),startingLogin:x(`Starting login flow…`,`Provider authentication is starting`),logoutWarning:x(`Logout removes Pi’s saved credentials. It does not disable the server or revoke access at the provider. Other sessions using those credentials are also affected.`,`MCP logout consequences`),reusedCredentials:x(`No browser authorization was requested. Pi may have reused existing credentials; read its result below.`,`MCP completed without a browser authorization step`),cancelWarning:x(`Pi may already be completing authentication. Credentials may have been saved if approval happened before cancellation.`,`MCP cancellation race warning`),mcpPasteNote:x(`If the redirect page cannot load after approval, copy the full URL from your browser’s address bar and paste it below.`,`MCP manual redirect fallback instructions`),remotePasteNote:x(`After you approve, the redirect page will probably fail to load — that is expected. Copy the full URL from your browser's address bar and paste it below.`,`Remote provider manual redirect instructions`),messages:x(`Authentication messages`,`Accessible name for unchanged provider/host progress messages`),related:x(`Related information`,`Accessible name for provider-supplied links`),failed:x(`Authentication failed`,`Fallback status when a failed flow has no provider error`),cancelled:x(`Authentication cancelled`,`Fallback status when a cancelled flow has no provider error`),typeSubscription:x(`subscription`,`Authentication type in provider details`),typeCredentials:x(`credentials`,`Authentication type in provider details`),providerDetail:x(`{provider} · {type}`,`Provider identifier and localized authentication type; complete provider detail line`),configured:x(`✓ configured`,`Provider credential source badge: stored`),environment:x(`✓ env`,`Provider credential source badge: environment, without a variable label`),environmentLabel:x(`✓ env: {label}`,`Provider credential source badge with unchanged environment variable label`),runtime:x(`✓ runtime`,`Provider credential source badge: runtime`),customKey:x(`✓ custom key`,`Provider credential source badge: fallback key`),modelsKey:x(`✓ models.json key`,`Provider credential source badge: key in literal file models.json`),modelsCommand:x(`✓ models.json command`,`Provider credential source badge: command in literal file models.json`),selectSession:x(`Select a session to authenticate MCP servers.`,`Authentication cannot start without an active session`),noStoredProvider:x(`No stored credentials for {provider}`,`Requested provider has no stored credentials`),providerNotFound:x(`Auth provider not found: {provider}`,`Requested provider identifier was not found`)},P=w.registerMessages(`core.auth`,qr),Jr=class{constructor(e,t,n,r){this.getState=e,this.setState=t,this.applyStatus=n,this.oauthOperationGeneration=0,this.pollGeneration=0,this.api=r.api??Xt,this.pollIntervalMs=r.pollIntervalMs??1e3,this.scope=r.scope,this.browserErrors=new Ar(e,t)}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=Qr(e);return t!==void 0&&(t.command===`login`?this.openLogin(t.providerId):this.openLogout(t.providerId),!0)}async openLogin(e){this.advanceAuthOperation();let t=this.captureTarget();t!==void 0&&(e!==void 0&&e!==``?await this.openLoginProvider(e,t):this.setState({authDialog:{step:`method`,target:t}}))}async openMcpAuth(e,t,n){let r=this.getState(),i=n?.session??(r.selectedSession?.archived===!0?void 0:r.selectedSession),a=n?.machineId??N(r);if(i===void 0){this.browserErrors.reportLocalized(j(a),()=>P.t(`selectSession`));return}let o=this.advanceAuthOperation(),s={machineId:a},c={id:i.id,cwd:i.cwd};this.setState({authDialog:{step:`starting`,target:s,mcpSession:c,mode:e,title:e===`login`?C(`ui.mcp.signInTitle`,`Sign in to an MCP server`):C(`ui.mcp.signOutTitle`,`Sign out of an MCP server`)}}),await this.startFlow(()=>t===void 0?this.api.startMcpAuth(c,e,a):this.api.startMcpAuth(c,e,a,t),s,o,c)}async chooseLoginMethod(e){let t=this.getState().authDialog;if(t?.step!==`method`)return;let n=this.oauthOperationGeneration;try{let{providers:r}=await this.api.authProviders({mode:`login`,authType:e,...Xr(t.target)});if(n!==this.oauthOperationGeneration||this.getState().authDialog!==t)return;this.setState({authDialog:{step:`providers`,mode:`login`,authType:e,providers:r,target:t.target}})}catch(e){if(n!==this.oauthOperationGeneration||this.getState().authDialog!==t)return;this.browserErrors.report(j(t.target.machineId),String(e))}}async selectLoginProvider(e,t){let n=this.getState().authDialog;if(n?.step!==`providers`)return;let r=n.providers.find(n=>n.id===e&&(t===void 0||n.authType===t));r!==void 0&&(r.authType===`oauth`||r.loginFlow===`interactive`?await this.startOAuth(r,n.target):this.setState({authDialog:{step:`apiKey`,provider:r,value:``,target:n.target}}))}updateApiKey(e){let t=this.getState().authDialog;if(t?.step!==`apiKey`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,value:e}})}async saveApiKey(){let e=this.getState().authDialog;if(e?.step!==`apiKey`)return;let t=e.value.trim();if(t===``){this.setState({authDialog:{...e,error:C(`ui.shared.daf147632ea6`,`API key is required`)}});return}let n={...e};delete n.error,this.setState({authDialog:{...n,saving:!0}});let r=this.oauthOperationGeneration;try{let n=e.target;if(await this.api.saveApiKey(e.provider.id,t,n),r!==this.oauthOperationGeneration)return;this.closeDialog(),this.refreshStatus(n)}catch(t){if(r!==this.oauthOperationGeneration)return;this.setState({authDialog:{...e,saving:!1,error:String(t)}})}}async openLogout(e){let t=this.advanceAuthOperation(),n=this.captureTarget();if(n!==void 0)try{let{providers:r}=await this.api.authProviders({mode:`logout`,...Xr(n)});if(t!==this.oauthOperationGeneration)return;if(e!==void 0&&e!==``){let t=r.find(t=>t.id===e);t===void 0?this.browserErrors.reportLocalized(j(n.machineId),()=>P.t(`noStoredProvider`,{provider:e})):await this.logoutProviderForTarget(t.id,n);return}this.setState({authDialog:{step:`logout`,providers:r,target:n}})}catch(e){if(t!==this.oauthOperationGeneration)return;this.browserErrors.report(j(n.machineId),String(e))}}async logoutProvider(e){let t=this.getState().authDialog;t?.step===`logout`&&t.providers.find(t=>t.id===e)!==void 0&&await this.logoutProviderForTarget(e,t.target)}async logoutProviderForTarget(e,t){let n=this.advanceAuthOperation();try{if(await this.api.logoutProvider(e,t),n!==this.oauthOperationGeneration)return;this.closeDialog(),this.refreshStatus(t)}catch(e){if(n!==this.oauthOperationGeneration)return;this.browserErrors.report(j(t.machineId),String(e))}}updateOAuthInput(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,inputValue:e}})}async respondOAuth(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n=t.flow.prompt??t.flow.select;if(n===void 0)return;let r=this.oauthOperationGeneration,i=t.flow.flowId,a=n.requestId;if(this.inFlightResponse?.generation===r&&this.inFlightResponse.flowId===i&&this.inFlightResponse.requestId===a)return;let o={generation:r,flowId:i,requestId:a};this.inFlightResponse=o;let s=e??t.inputValue??``,c={...t};delete c.error,this.setState({authDialog:{...c,responding:!0}});try{let e=t.flow.target===`mcp`?await this.api.respondMcpAuthFlow(i,a,s,t.target.machineId):await this.api.respondOAuthFlow(i,a,s,t.target),n=this.currentOAuthDialog(r,i);if(e.flowId!==i||n===void 0||!Yr(n.target,t.target)||Zr(n.flow)!==a)return;this.updateOAuthFlow(e,t.target)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||Zr(t.flow)!==a)return;this.setState({authDialog:{...t,responding:!1,error:String(e)}})}finally{this.inFlightResponse===o&&(this.inFlightResponse=void 0)}}async cancelOAuth(){let e=this.getState().authDialog;if(e?.step!==`oauth`){this.closeDialog();return}let t=e.flow.flowId,n=e.target;if(e.flow.target===`mcp`){if(e.flow.status!==`running`){this.closeDialog();return}if(e.flow.cancelRequested===!0)return;let r=this.advanceAuthOperation();this.setState({authDialog:{...e,flow:{...e.flow,cancelRequested:!0}}});try{let e=await this.api.cancelMcpAuthFlow(t,n.machineId);this.currentOAuthDialog(r,t)!==void 0&&(this.updateOAuthFlow(e,n),e.status===`running`&&this.startPolling(t,n))}catch(e){let i=this.currentOAuthDialog(r,t);i!==void 0&&(this.setState({authDialog:{...i,flow:{...i.flow,cancelRequested:!1},error:String(e)}}),this.startPolling(t,n))}}else{this.closeDialog();try{await this.api.cancelOAuthFlow(t,n)}catch{}}}closeDialog(){this.advanceAuthOperation(),this.setState({authDialog:void 0})}async openLoginProvider(e,t){let n=this.oauthOperationGeneration;try{let{providers:r}=await this.api.authProviders({mode:`login`,...Xr(t)});if(n!==this.oauthOperationGeneration)return;let i=r.filter(t=>t.id===e);if(i.length===0){this.browserErrors.reportLocalized(j(t.machineId),()=>P.t(`providerNotFound`,{provider:e}));return}if(i.length>1){this.setState({authDialog:{step:`providers`,mode:`login`,providers:i,target:t}});return}let a=i[0];if(a===void 0)return;a.authType===`oauth`||a.loginFlow===`interactive`?await this.startOAuth(a,t):this.setState({authDialog:{step:`apiKey`,provider:a,value:``,target:t}})}catch(e){if(n!==this.oauthOperationGeneration)return;this.browserErrors.report(j(t.machineId),String(e))}}async startOAuth(e,t){let n=this.advanceAuthOperation();await this.startFlow(()=>e.authType===`oauth`?this.api.startOAuthLogin(e.id,t):this.api.startInteractiveApiKeyLogin(e.id,t),t,n)}async startFlow(e,t,n,r){if(n===this.oauthOperationGeneration)try{let i=await e();if(n!==this.oauthOperationGeneration){if(i.status===`running`)try{i.target===`mcp`?await this.api.cancelMcpAuthFlow(i.flowId,t.machineId):await this.api.cancelOAuthFlow(i.flowId,t)}catch{}return}this.updateOAuthFlow(i,t,r),i.status===`running`&&this.startPolling(i.flowId,t)}catch(e){if(n!==this.oauthOperationGeneration)return;let r=this.getState().authDialog;r?.step===`starting`?this.setState({authDialog:{...r,error:String(e)}}):this.browserErrors.report(j(t.machineId),String(e))}}updateOAuthFlow(e,t,n){let r=this.getState().authDialog;if(n??=e.target===`mcp`&&(r?.step===`oauth`||r?.step===`starting`)?r.mcpSession:void 0,e.status===`complete`&&e.target!==`mcp`){this.stopPolling(),this.closeDialog(),this.refreshStatus(t);return}e.status!==`running`&&(this.oauthOperationGeneration+=1,this.stopPolling(),e.target===`mcp`&&n!==void 0&&this.refreshMcpStatus(t.machineId,n));let i=r?.step===`oauth`&&r.flow.flowId===e.flowId?r.inputValue??``:``,a=r?.step===`oauth`?Zr(r.flow):void 0,o=Zr(e),s=a!==void 0&&a===o,c=s?i:``,l=s&&r?.step===`oauth`?r.responding===!0:!1;this.setState({authDialog:{step:`oauth`,flow:e,inputValue:c,responding:l,target:t,...n===void 0?{}:{mcpSession:n}}})}startPolling(e,t){this.stopPolling();let n=this.oauthOperationGeneration,r=this.pollGeneration;this.pollTimer=window.setInterval(()=>{this.poll(e,t,n,r)},this.pollIntervalMs)}stopPolling(){this.pollGeneration+=1,this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(e,t,n,r){if(r!==this.pollGeneration)return;let i=this.currentOAuthDialog(n,e);if(i===void 0||!Yr(i.target,t)){this.stopPolling();return}let a=Zr(i.flow);try{let o=i.flow.target===`mcp`?await this.api.mcpAuthFlow(e,i.target.machineId):await this.api.oauthFlow(e,i.target),s=this.currentOAuthDialog(n,e);if(o.flowId!==e||r!==this.pollGeneration||s===void 0||!Yr(s.target,t)||Zr(s.flow)!==a)return;this.updateOAuthFlow(o,i.target)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o===void 0||!Yr(o.target,t)||Zr(o.flow)!==a)return;this.stopPolling(),this.setState({authDialog:{...o,error:String(i)}})}}currentOAuthDialog(e,t){if(e!==this.oauthOperationGeneration)return;let n=this.getState().authDialog;return n?.step===`oauth`&&n.flow.flowId===t?n:void 0}advanceAuthOperation(){return this.oauthOperationGeneration+=1,this.stopPolling(),this.oauthOperationGeneration}async refreshStatus(e){let t=this.selectedSessionForMachine(e.machineId);if(t!==void 0&&this.targetStillSelected(e))try{let n=await this.api.status(t,e.machineId),r=this.selectedSessionForMachine(e.machineId);if(!this.targetStillSelected(e)||r?.id!==t.id||r.cwd!==t.cwd)return;this.applyStatus(n)}catch{}}async refreshMcpStatus(e,t){let n=()=>{let n=this.selectedSessionForMachine(e);return n?.id===t.id&&n.cwd===t.cwd};if(n())try{let r=await this.api.status(t,e);n()&&this.applyStatus(r)}catch{}}selectedSessionForMachine(e){let t=this.getState();if(N(t)!==e)return;let n=t.selectedSession;if(n!==void 0&&n.archived!==!0)return n}captureTarget(){let e=this.getState(),t=e.selectedMachine,n={machineId:N(e),...t?.kind===void 0?{}:{machineKind:t.kind}};if(this.scope===`management`)return n;let r=e.selectedProject;if(r===void 0)this.browserErrors.report(j(n.machineId),C(`client.authController.select.a.project.before.configuring.provider.authentication.a2a76e`,`Select a project before configuring provider authentication.`));else return{...n,projectId:r.id,projectName:r.name}}targetStillSelected(e){return N(this.getState())===e.machineId?e.projectId===void 0||this.getState().selectedProject?.id===e.projectId:!1}};function Yr(e,t){return e.machineId===t.machineId&&e.projectId===t.projectId}function Xr(e){return e.projectId===void 0?{machineId:e.machineId}:{machineId:e.machineId,projectId:e.projectId,...e.projectName===void 0?{}:{projectName:e.projectName}}}function Zr(e){return e.prompt?.requestId??e.select?.requestId}function Qr(e){let t=e.trim(),n=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(n===null)return;let r=n[1];if(r!==`login`&&r!==`logout`)return;let i=n[2];return i===void 0||i===``?{command:r}:{command:r,providerId:i}}var $r={editTitle:x(`Edit local display name`,`Machine name editing dialog title`),addTitle:x(`Add machine`,`Machine registration dialog title and action`),closeEdit:x(`Close edit local display name`,`Close editing dialog`),closeAdd:x(`Close add machine`,`Close registration dialog`),urlLabel:x(`Remote PI WEB URL`,`Machine address label`),urlHelp:x(`Enter the reachable base URL first, including http:// or https://.`,`Machine address guidance; protocols are literal`),nameLabel:x(`Local display name (optional)`,`Optional machine alias label`),nameHelp:x(`Only changes the name shown here. Leave blank to use the remote machine’s name.`,`Machine alias guidance`),tokenLabel:x(`Bearer token (optional)`,`Optional authentication token label`),tokenPlaceholder:x(`Leave blank if the remote machine does not require one`,`Token input placeholder`),tokenHelp:x(`If the remote machine requires a token, paste it without the “Bearer” prefix.`,`Token guidance; Bearer is a literal authentication scheme`),intro:x(`After you enter a URL, you can add an optional local display name and bearer token.`,`Machine registration first-step guidance`),cancel:x(`Cancel`,`Cancel machine dialog`),saving:x(`Saving…`,`Machine alias save in progress`),adding:x(`Adding…`,`Machine registration in progress`),save:x(`Save name`,`Save local machine alias`),urlRequired:x(`Remote PI WEB URL is required.`,`Missing machine address validation`),urlInvalid:x(`Enter a valid URL including http:// or https://.`,`Malformed machine address validation`),urlProtocol:x(`Use an http:// or https:// URL.`,`Unsupported machine address protocol validation`),urlCredentials:x(`Do not include credentials in the machine URL.`,`Credentials in machine address validation`),urlQuery:x(`Do not include a query string or fragment.`,`Machine address query or fragment validation`),online:x(`online`,`Machine connection status`),offline:x(`offline`,`Machine connection status`),error:x(`error`,`Machine connection status`),unknown:x(`unknown`,`Machine connection status`),local:x(`Local Pi Web`,`Local machine subtitle`),remote:x(`Remote Pi Web`,`Remote machine subtitle without an address`),unread:x(`Unread sessions on this machine`,`Machine activity accessible description`),terminal:x(`Machine terminal active`,`Machine activity accessible description`),active:x(`Machine active`,`Machine activity accessible description`),actions:x(`Machine actions`,`Machine actions tooltip`),edit:x(`Edit display name`,`Edit machine alias menu action`),remove:x(`Remove`,`Remove remote machine menu action`),machines:x(`Machines`,`Machine navigation heading`),machine:x(`Machine`,`Machine switcher kicker`),noSelection:x(`No machine selected`,`Machine navigation empty selection`),otherTerminal:x(`Terminal active on other machines`,`Other machines activity accessible description`),otherActive:x(`Other machines active`,`Other machines activity accessible description`),otherUnread:x(`Unread sessions on other machines`,`Other machines unread accessible description`),cannotRemove:x(`The local machine cannot be removed.`,`Attempt to delete the local machine`),actionsFor:x(`Actions for {name}`,`Machine-specific actions accessible label`),removeNamed:x(`Remove {name}`,`Machine-specific removal tooltip`),subtitle:x(`{location} · {status}`,`Machine address or localized fallback and translated connection status`),identity:x(`{name} · {location} · {status}`,`Machine switcher identity tooltip`),switch:x(`Machine: {name}. {status}. Switch machine.`,`Machine switcher accessible label`),reconnecting:x(`{name} is unavailable; reconnecting…`,`Selected remote machine connection notice`),refreshFailed:x(`Settings saved, but refreshing the machine name failed: {error}`,`Machine identity refresh failure; error is unchanged backend detail`)},F=w.registerMessages(`core.machines`,$r),ei=class{constructor(e,t,n,r,i={}){this.getState=e,this.setState=t,this.updateUrl=n,this.projects=r,this.runtimeRefreshSeqByMachine=new Map,this.identityRevisionByMachine=new Map,this.pendingIdentityEdits=new Set,this.navigateToMachine=i.navigateToMachine,this.captureNavigation=i.captureNavigation,this.browserErrors=new Ar(e,t)}async loadMachines(e){this.setState({error:``,isLoadingMachines:!0});try{let t=await Xt.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));for(let e of Object.values(this.getState().browserErrors))e.scope.kind!==`global`&&!r.has(e.scope.machineId)&&this.browserErrors.discard(j(e.scope.machineId));return this.setState({machines:t,selectedMachine:n,machineActivities:ri(this.getState().machineActivities,r),machineRuntimes:ri(this.getState().machineRuntimes,r),machineStatusSnapshots:ri(this.getState().machineStatusSnapshots,r)}),this.refreshMachineHealthFor(t),this.refreshMachineRuntimeFor(t),!0}catch(t){return this.setState({error:String(t)}),this.browserErrors.report(j(e??`local`),String(t)),!1}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(e,t={}){this.getState().selectedMachine?.id!==e.id&&(this.setState({selectedMachine:e,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,workspaceResolution:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},...yr()}),t.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(e.id),this.refreshMachineRuntime(e.id))}async addMachine(e){let t=ii(this.getState(),this.captureNavigation);this.setState({error:``});try{let n=await Xt.addMachine(e);return this.setState({machines:[...this.getState().machines.filter(e=>e.id!==n.id),n]}),this.navigateToMachine===void 0?await this.selectMachine(n):await this.navigateToMachine(n,{expected:t}),n}catch(e){this.setState({error:String(e)});return}}async refreshMachineIdentity(e){if(this.pendingIdentityEdits.has(e)||!this.getState().machines.some(t=>t.id===e))return;let t=this.invalidateMachineIdentity(e);try{let n=await Xt.machine(e);if(t!==this.identityRevisionByMachine.get(e))return;let r=this.getState(),i=r.machines.map(t=>t.id===e?ti(t,n):t);this.setState({machines:i,...r.selectedMachine===void 0?{}:{selectedMachine:i.find(e=>e.id===r.selectedMachine?.id)??r.selectedMachine}})}catch(n){if(t===this.identityRevisionByMachine.get(e)){let t=String(n);this.browserErrors.reportLocalized(j(e),()=>F.t(`refreshFailed`,{error:t}))}}}async updateMachine(e,t){let n=this.invalidateMachineIdentity(e);this.pendingIdentityEdits.add(e),this.setState({error:``});try{let r=await Xt.updateMachine(e,{name:t});if(n!==this.identityRevisionByMachine.get(e))return;let i=this.getState();if(!i.machines.some(t=>t.id===e))return;let a=i.machines.map(t=>t.id===e?ti(t,r):t);return this.setState({machines:a,...i.selectedMachine?.id===e?{selectedMachine:a.find(t=>t.id===e)}:{}}),r}catch(t){n===this.identityRevisionByMachine.get(e)&&this.setState({error:String(t)});return}finally{n===this.identityRevisionByMachine.get(e)&&(this.pendingIdentityEdits.delete(e),this.invalidateMachineIdentity(e))}}invalidateMachineIdentity(e){let t=(this.identityRevisionByMachine.get(e)??0)+1;return this.identityRevisionByMachine.set(e,t),t}async deleteMachine(e=this.getState().selectedMachine,t={}){if(e!==void 0){if(e.kind===`local`)this.browserErrors.reportLocalized(j(e.id),()=>F.t(`cannotRemove`));else try{await Xt.deleteMachine(e.id),this.invalidateMachineIdentity(e.id),this.pendingIdentityEdits.delete(e.id);let n=this.getState().machines.filter(t=>t.id!==e.id),r=n.find(e=>e.id===`local`)??n[0];if(this.browserErrors.discard(j(e.id)),this.setState({machines:n,machineStatuses:ni(this.getState().machineStatuses,e.id),machineRuntimes:ni(this.getState().machineRuntimes,e.id),machineActivities:ni(this.getState().machineActivities,e.id),machineStatusSnapshots:ni(this.getState().machineStatusSnapshots,e.id)}),this.getState().selectedMachine?.id===e.id&&r!==void 0){if(t.selectFallback===!1)return r;let e=ii(this.getState(),this.captureNavigation);return this.navigateToMachine===void 0?await this.selectMachine(r):await this.navigateToMachine(r,{expected:e}),r}return}catch(t){this.browserErrors.report(j(e.id),String(t));return}}}async refreshMachineHealth(e=this.getState().selectedMachine?.id??`local`){try{let t=await Xt.health(e);return this.setState({machineStatuses:{...this.getState().machineStatuses,[t.machineId]:t}}),t}catch(t){this.browserErrors.report(j(e),String(t));return}}async refreshMachineRuntime(e=this.getState().selectedMachine?.id??`local`){let t=(this.runtimeRefreshSeqByMachine.get(e)??0)+1;this.runtimeRefreshSeqByMachine.set(e,t);try{let n=await Xt.runtime(e,!0);return this.runtimeRefreshSeqByMachine.get(e)===t?(this.setState({machineRuntimes:{...this.getState().machineRuntimes,[n.machineId]:n}}),n):void 0}catch(n){this.runtimeRefreshSeqByMachine.get(e)===t&&this.browserErrors.report(j(e),String(n));return}}async selectInitialMachine(e,t){let n=e.find(e=>e.id===(t??`local`));if(n===void 0)return this.localMachine(e);if(n.kind!==`remote`)return n;let r=await this.safeRemoteHealth(n);return this.setState({machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r}}),r.ok||this.browserErrors.report(j(n.id),C(`ui.piWebApp.isUnavailableReconnecting`,`{machineName} is unavailable. Reconnecting…`,{machineName:n.name})),n}async safeRemoteHealth(e){try{return await Xt.health(e.id)}catch(t){return{machineId:e.id,ok:!1,checkedAt:new Date().toISOString(),status:`offline`,error:t instanceof Error?t.message:String(t)}}}localMachine(e){return e.find(e=>e.id===`local`)??e[0]}async refreshMachineHealthFor(e){let t=await Promise.allSettled(e.map(e=>Xt.health(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...n}})}async refreshMachineRuntimeFor(e){let t=await Promise.allSettled(e.map(e=>Xt.runtime(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...n}})}};function ti(e,t){let n={...e,name:t.name};return t.nameOverride===void 0?delete n.nameOverride:n.nameOverride=t.nameOverride,t.reportedName===void 0?delete n.reportedName:n.reportedName=t.reportedName,n}function ni(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function ri(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}function ii(e,t){return t?.()??{machineId:e.selectedMachine?.id??`local`,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,...e.selectedSession===void 0||Reflect.get(e.selectedSession,`clientPendingStart`)!==!0?{sessionId:e.selectedSession?.id}:{}}}var ai=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new Ur,this.api=n.api??Bt}refresh(e){return this.refreshes.request(e,async()=>{let t=this.getState().machineStatusSnapshots[e],n=await this.api.machineStatus(e),r=this.getState().machineStatusSnapshots[e];(r===t||r===void 0||r.epochId===n.epochId)&&this.apply(e,n)})}apply(e,t){let n=this.getState().machineStatusSnapshots;oi(n[e],t)&&this.setState({machineStatusSnapshots:{...n,[e]:t}})}};function oi(e,t){return e===void 0||e.epochId!==t.epochId||t.revision>e.revision}function si(e){switch(e.kind){case`projects`:return JSON.stringify([e.kind,e.machineId]);case`workspaces`:return JSON.stringify([e.kind,e.machineId,e.projectId]);case`sessionPins`:return JSON.stringify([e.kind,e.machineId,e.projectId,e.workspaceId])}}var ci=class{constructor(e,t={}){this.port=e,this.options=t,this.states=new Map}ids(e){return[...this.state(e).snapshot?.ids??[]]}pending(e){return this.state(e).pending>0}ensure(e){let t=this.state(e);if(t.ensuring)return t.ensuring;if(t.snapshot)return Promise.resolve();let n=this.load(e);return t.ensuring=n,n.finally(()=>{t.ensuring=void 0}).catch(()=>void 0),n}load(e){return e={...e},this.enqueue(e,async t=>{t.snapshot=await this.port.load(e)})}async refreshSessionPins(e){await Promise.all([...this.states.values()].filter(({scope:t})=>t.kind===`sessionPins`&&t.machineId===e).map(({scope:e})=>this.load(e)))}mutate(e,t){return e={...e},this.enqueue(e,async n=>{n.snapshot??=await this.port.load(e);let r=n.snapshot,i=[...t([...r.ids])];if(!(i.length===r.ids.length&&i.every((e,t)=>e===r.ids[t])))try{n.snapshot=await this.port.save(e,i,r.revision)}catch(t){n.snapshot=void 0;try{n.snapshot=await this.port.load(e)}catch(t){this.options.onError?.(e,t)}throw t}})}state(e){let t=si(e),n=this.states.get(t);return n||(n={scope:{...e},snapshot:void 0,tail:Promise.resolve(),ensuring:void 0,pending:0},this.states.set(t,n)),n}enqueue(e,t){e={...e};let n=this.state(e);n.pending++,this.options.onChange?.(e);let r=n.tail.then(async()=>{try{await t(n)}catch(t){throw this.options.onError?.(e,t),t}finally{n.pending--,this.options.onChange?.(e)}});return n.tail=r.catch(()=>void 0),r}};function li(e){let t=`api/machines/${encodeURIComponent(e.machineId)}/navigation/projects`;switch(e.kind){case`projects`:return t;case`workspaces`:return`${t}/${encodeURIComponent(e.projectId)}/workspaces`;case`sessionPins`:return`${t}/${encodeURIComponent(e.projectId)}/workspaces/${encodeURIComponent(e.workspaceId)}/session-pins`}}function ui(e){if(!di(e))throw Error(`Invalid navigation order response`);let t=e.ids,n=e.revision;if(!Array.isArray(t)||!t.every(e=>typeof e==`string`&&e.trim()!==``)||new Set(t).size!==t.length||typeof n!=`number`||!Number.isSafeInteger(n)||n<0)throw Error(`Invalid navigation order response: ids and revision are required`);return{ids:[...t],revision:n}}function di(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var fi={load:e=>h(li(e),ui,{cache:`no-store`}),save:(e,t,n)=>{let r={ids:[...t],revision:n};return h(li(e),ui,{method:`PUT`,body:JSON.stringify(r)})}};function pi(e,t){let n=new Map;for(let e of t)n.has(e)||n.set(e,n.size);return[...e].sort((e,t)=>(n.get(e.id)??1/0)-(n.get(t.id)??1/0))}function mi(e,t,n,r,i){let a=[...new Set([...e,...t])];if(n===r||!t.includes(n)||!t.includes(r))return a;let o=a.filter(e=>e!==n),s=o.indexOf(r);return o.splice(s+ +(i===`after`),0,n),o}var hi={workspaceNotFound:x(`Workspace not found: {id}`,`Requested workspace identifier is unavailable during navigation`),sessionNotFound:x(`Session not found: {id}`,`Requested session identifier is unavailable during workspace navigation`),projectNotFound:x(`Project not found`,`Workspace refresh cannot find the requested project`),degraded:x(`Workspace authority is degraded`,`Workspace provider is unavailable and supplied no diagnostic detail`),trustUnavailable:x(`Cannot save trust choice for project {id}: main workspace unavailable`,`The newly added project's trust choice cannot be saved without its main workspace`)},gi=w.registerMessages(`core.projectWorkspaceFeedback`,hi),_i=class extends Error{constructor(e){super(),this.displayMessage=e}get message(){return this.displayMessage()}};function vi(e,t,n){n instanceof _i?e.reportLocalized(t,()=>String(n)):e.report(t,String(n))}var yi=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.loadErrors=new Map,this.api=r.api??Xt,this.onProjectsApplied=r.onProjectsApplied,this.navigateToProject=r.navigateToProject,this.captureNavigation=r.captureNavigation,this.browserErrors=new Ar(e,t)}managementEntryProject(e){let t=this.getState();if(!(e.machineId!==`local`||N(t)!==`local`||e.projectId!==void 0||e.workspaceId!==void 0||e.sessionId!==void 0||t.isLoadingProjects||this.loadErrors.has(`local`)||t.projects.length!==1))return t.projects[0]}async loadProjects(){let e=N(this.getState());this.loadErrors.delete(e),this.setState({isLoadingProjects:!0});try{let t=await this.api.projects(e);if(N(this.getState())!==e)return;let n=new Set(t.map(e=>e.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([e])=>n.has(e)));this.setState({projects:t,workspacesByProjectId:r}),this.onProjectsApplied?.(e)}catch(t){this.loadErrors.set(e,String(t)),this.browserErrors.report(j(e),String(t))}finally{N(this.getState())===e&&this.setState({isLoadingProjects:!1})}}async addProject(e,t,n){if(e.trim()===``)return;let r=N(this.getState()),i=bi(this.getState(),this.captureNavigation),a;try{a=await this.api.addProject(e.trim(),void 0,t,r)}catch(e){this.browserErrors.report(j(r),String(e));return}try{if(N(this.getState())===r){let e=this.getState().projects;this.setState({projects:[...e.filter(e=>e.id!==a.id),a],projectDialogOpen:!1}),this.onProjectsApplied?.(r)}if(n?.changed===!0&&await this.applyTrustChoice(a,n.trusted,r),N(this.getState())!==r)return;this.navigateToProject===void 0?await this.workspaces.selectProject(a):await this.navigateToProject(a,{expected:i})}catch(e){vi(this.browserErrors,xr(r,a.id),e)}}async applyTrustChoice(e,t,n){let r=(await(this.api.workspaces??Xt.workspaces)(e.id,n)).find(t=>t.projectId===e.id&&t.isMain);if(r===void 0)throw new _i(()=>gi.t(`trustUnavailable`,{id:e.id}));await(this.api.setWorkspaceTrust??Xt.setWorkspaceTrust)(e.id,r.id,t,n)}async closeProject(e){let t=N(this.getState());try{if(await this.api.closeProject(e,t),N(this.getState())!==t)return;this.workspaces.forgetProject(e);let n=this.getState();if(this.setState({projects:n.projects.filter(t=>t.id!==e)}),this.onProjectsApplied?.(t),n.selectedProject?.id!==e)return;let r=bi(this.getState(),this.captureNavigation);this.navigateToProject===void 0?this.workspaces.clearSelection():await this.navigateToProject(void 0,{expected:r})}catch(n){this.browserErrors.report(xr(t,e),String(n))}}};function bi(e,t){return t?.()??{machineId:N(e),projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,...e.selectedSession===void 0||Reflect.get(e.selectedSession,`clientPendingStart`)!==!0?{sessionId:e.selectedSession?.id}:{}}}var xi=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.machineGeneration=0,this.activityMachineGeneration=-1,this.projectTopologyGeneration=0,this.nextCwdActivation=0,this.observedActiveCwds=new Set,this.cwdActivations=new Map,this.attemptedCwdActivations=new Map,this.api=n.api??Et,this.onError=n.onError}handleActivityApplied(e){return N(this.getState())===e?(this.activityMachineGeneration=this.machineGeneration,this.reconcile(e)):Promise.resolve()}handleProjectsApplied(e){return N(this.getState())!==e||(this.projectTopologyGeneration+=1,this.attemptedCwdActivations.clear(),this.activePass=void 0,this.activityMachineGeneration!==this.machineGeneration)?Promise.resolve():this.reconcile(e)}handleSelectedMachineChanged(){this.machineGeneration+=1,this.projectTopologyGeneration+=1,this.observedActiveCwds.clear(),this.cwdActivations.clear(),this.attemptedCwdActivations.clear(),this.activePass=void 0}reconcile(e){let t=this.getState();if(N(t)!==e)return Promise.resolve();let n=this.syncActiveCwds(t),r=new Map([...n].filter(([e,n])=>!Si(t.projects,t.workspacesByProjectId,e)&&this.attemptedCwdActivations.get(e)!==n)),i=this.activePass;if(i!==void 0)return(i.machineGeneration!==this.machineGeneration||i.projectTopologyGeneration!==this.projectTopologyGeneration||[...r].some(([e,t])=>i.cwdActivations.get(e)!==t))&&(i.trailingRequested=!0),i.promise;if(r.size===0||t.projects.length===0)return Promise.resolve();let a={machineGeneration:this.machineGeneration,projectTopologyGeneration:this.projectTopologyGeneration,machineId:e,projects:t.projects.map(e=>({id:e.id,path:e.path,startingWorkspaces:t.workspacesByProjectId[e.id]})),cwdActivations:r,trailingRequested:!1,promise:Promise.resolve()};return this.activePass=a,a.promise=this.runPass(a),a.promise}async runPass(e){if(await Promise.all(e.projects.map(async t=>{try{let n=await this.api.workspaces(t.id,e.machineId);this.applyProjectWorkspaces(e,t,n)}catch(n){this.isPassScopeCurrent(e)&&this.reportError({machineId:e.machineId,projectId:t.id,error:n})}})),this.activePass!==e)return;let t=this.getState(),n=this.syncActiveCwds(t);for(let[r,i]of e.cwdActivations)n.get(r)===i&&!Si(t.projects,t.workspacesByProjectId,r)&&this.attemptedCwdActivations.set(r,i);let r=e.trailingRequested;this.activePass=void 0,r&&await this.reconcile(N(this.getState()))}applyProjectWorkspaces(e,t,n){if(this.activePass!==e||!this.isPassScopeCurrent(e))return;let r=this.getState();r.projects.find(e=>e.id===t.id)?.path===t.path&&r.workspacesByProjectId[t.id]===t.startingWorkspaces&&this.setState({workspacesByProjectId:{...r.workspacesByProjectId,[t.id]:n}})}isPassScopeCurrent(e){return e.machineGeneration===this.machineGeneration&&e.projectTopologyGeneration===this.projectTopologyGeneration&&N(this.getState())===e.machineId}syncActiveCwds(e){let t=new Set(Object.values(e.workspaceActivities).filter(Rr).map(e=>e.cwd));for(let e of this.observedActiveCwds)t.has(e)||(this.cwdActivations.delete(e),this.attemptedCwdActivations.delete(e));for(let e of t)this.observedActiveCwds.has(e)||(this.nextCwdActivation+=1,this.cwdActivations.set(e,this.nextCwdActivation),this.attemptedCwdActivations.delete(e));return this.observedActiveCwds=t,new Map([...t].map(e=>[e,this.cwdActivations.get(e)??0]))}reportError(e){if(this.onError!==void 0)try{this.onError(e)}catch{}}};function Si(e,t,n){return e.some(e=>zr(e,t[e.id]??[],n))}var Ci={checkFailed:x(`PI WEB update check failed: {detail}`,`Manual update check failure; detail is an untranslated registry diagnostic`),checkSkipped:x(`PI WEB update check was skipped because remote version checks are disabled by offline/version-check settings`,`Manual update check is disabled by gateway configuration`)},wi=w.registerMessages(`core.piWebStatus`,Ci),Ti=class extends Error{constructor(e){super(),this.displayMessage=e}get message(){return this.displayMessage()}},Ei=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??ln,this.onRefreshError=n.onRefreshError??(()=>void 0)}async refresh(){let e=N(this.getState());if(this.pendingUpdateCheck?.machineId===e)return;let t=++this.requestSequence;try{let n=await this.api.piWebStatus(e);this.isCurrent(e,t)&&this.setState({piWebStatus:n})}catch(n){if(!this.isCurrent(e,t))return;this.setState({piWebStatus:void 0}),this.onRefreshError(e,n)}}checkForUpdates(){let e=N(this.getState()),t=this.pendingUpdateCheck;if(t?.machineId===e)return t.promise;let n=++this.requestSequence,r=this.api.checkForUpdates(e).then(t=>{this.isCurrent(e,n)&&(this.setState({piWebStatus:t}),Di(t))}).catch(t=>{if(this.isCurrent(e,n))throw t}).finally(()=>{this.pendingUpdateCheck?.requestSequence===n&&(this.pendingUpdateCheck=void 0)});return this.pendingUpdateCheck={machineId:e,requestSequence:n,promise:r},r}isCurrent(e,t){return N(this.getState())===e&&t===this.requestSequence}};function Di(e){let t=e.release.error;if(t!==void 0)throw new Ti(()=>wi.t(`checkFailed`,{detail:t}));if(e.release.skipped===!0)throw new Ti(()=>wi.t(`checkSkipped`))}function Oi(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}var ki=`pi-web:cached-new-sessions:v1`,Ai=`browserCachedNew`,ji=`local`;function Mi(e,t=ji,n=Oi()){if(e.messageCount!==0||e.archived===!0)return;let r=Ri(n).filter(n=>n.id!==e.id||n.machineId!==t);zi([Ni(e,t),...r],n)}function Ni(e,t=ji){return{...e,browserCachedNew:!0,machineId:t}}function Pi(e,t=ji,n=Oi()){zi(Ri(n).filter(n=>n.id!==e||n.machineId!==t),n)}function Fi(e,t,n=ji,r=Oi()){let i=new Set(t.map(e=>e.id)),a=Ri(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&zi(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function Ii(e){return e!==void 0&&Vi(e)&&e.browserCachedNew===!0}function Li(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.persisted===void 0?{}:{persisted:e.persisted},...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},...e.agentSubsession===!0?{agentSubsession:!0}:{},...`machineId`in e&&typeof e.machineId==`string`?{machineId:e.machineId}:{machineId:ji},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Ri(e=Oi()){try{let t=e?.getItem(ki);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>Bi(e)):[]}catch{return[]}}function zi(e,t=Oi()){try{e.length===0?t?.removeItem(ki):t?.setItem(ki,JSON.stringify(e))}catch{}}function Bi(e){if(!Hi(e))return[];let t=Ui(e,`id`),n=Ui(e,`path`),r=Ui(e,`cwd`),i=Ui(e,`created`),a=Ui(e,`modified`),o=Ui(e,`firstMessage`),s=Gi(e,`messageCount`);if(t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||s!==0)return[];let c=Wi(e,`name`),l=Wi(e,`parentSessionPath`),u=Wi(e,`machineId`)??ji;return[{id:t,path:n,cwd:r,...c===void 0?{}:{name:c},created:i,modified:a,messageCount:s,firstMessage:o,...l===void 0?{}:{parentSessionPath:l},...e.agentSubsession===!0?{agentSubsession:!0}:{},machineId:u,browserCachedNew:!0}]}function Vi(e){return Ai in e}function Hi(e){return typeof e==`object`&&!!e}function Ui(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Wi(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function Gi(e,t){let n=e[t];return typeof n==`number`?n:void 0}var Ki={replacement:()=>`edit text replacement`,edits:e=>`${String(e)} edit${e===1?``:`s`}`,items:e=>`${String(e)} item${e===1?``:`s`}`,object:()=>`object`};function qi(e){return!Xi(e)||typeof e.command==`string`||typeof e.path==`string`?{}:{summaryPresentation:{kind:`arguments`,args:e}}}function Ji(e,t=Ki){if(!Xi(e))return Zi(e);let n=e.command;if(typeof n==`string`)return n;let r=e.path;if(typeof r==`string`)return r;if(typeof e.oldText==`string`&&typeof e.newText==`string`)return t.replacement();let i=e.edits;return Array.isArray(i)?t.edits(i.length):Object.entries(e).filter(([,e])=>e!=null).slice(0,3).map(([e,n])=>`${e}: ${Yi(n,t)}`).join(` · `)}function Yi(e,t){return typeof e==`string`?e.length>80?`${e.slice(0,77)}…`:e:typeof e==`number`||typeof e==`boolean`?String(e):Array.isArray(e)?t.items(e.length):typeof e==`object`&&e?t.object():``}function Xi(e){return typeof e==`object`&&!!e}function Zi(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}function Qi(e,t){let n=[];return e.forEach((e,r)=>{let i=ra(e);i.every(e=>e.parts.length===0)&&I(e,`role`)!==void 0&&n.at(-1)?.parts.at(-1)?.type===`askUserQuestion`&&(i=[{...i[0]??ea({role:pa(I(e,`role`)),parts:[]},e),parts:[{type:`empty`}]}]),n.push(...i.map(e=>t===void 0?e:{...e,transcriptIndex:t+r}))}),Sa(n).filter(e=>e.parts.length>0)}function $i(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function ea(e,t){let n=la(t),r=I(t,`entryId`),i=I(t,`streamId`);return n===void 0&&r===void 0&&i===void 0?e:{...e,...i===void 0?{}:{streamId:i},...n===void 0?{}:{meta:n},...r===void 0||r===``?{}:{entryId:r}}}function ta(e,t,n){if(n===``)return e;let r=e.at(-1),i=r?.parts.at(-1);return r?.role===t&&i?.type===`text`?[...e.slice(0,-1),{...r,parts:[...r.parts.slice(0,-1),{type:`text`,text:i.text+n}]}]:r?.role===t?[...e.slice(0,-1),{...r,parts:[...r.parts,{type:`text`,text:n}]}]:[...e,$i(t,n)]}function na(e,t){if(t===``)return e;let n=e.at(-1),r=n?.parts.at(-1);return n?.role===`assistant`&&r?.type===`thinking`?[...e.slice(0,-1),{...n,parts:[...n.parts.slice(0,-1),{type:`thinking`,text:r.text+t}]}]:n?.role===`assistant`?[...e.slice(0,-1),{...n,parts:[...n.parts,{type:`thinking`,text:t}]}]:[...e,{role:`assistant`,parts:[{type:`thinking`,text:t}]}]}function ra(e){if(I(e,`role`)===`custom`&&ka(e,`display`)===!1)return[];if(aa(e))return e.parts.some(e=>I(e,`type`)===`image`)?[{...e,parts:e.parts.flatMap(e=>I(e,`type`)===`image`?ha(e):[e])}]:[e];if(I(e,`role`)===`bashExecution`)return[ea(fa(e),e)];let t=I(e,`role`),n=pa(t),r=Oa(e,`content`),i=ma(r,e),a=I(e,`customType`);if(t===`custom`&&a!==void 0){let t=Oa(e,`details`);return[ea({role:`system`,parts:[{type:`customMessage`,customType:a,content:r,...t===void 0?{}:{details:t},parts:i.filter(e=>e.type!==`empty`)}]},e)]}let o=t===`toolResult`?va(I(e,`toolName`)??``,Oa(e,`details`)):void 0,s=t===`toolResult`?_a(I(e,`toolName`)??``,Oa(e,`details`),ka(e,`isError`)===!0):void 0,c=[...t===`toolResult`&&!i.some(e=>e.type===`toolResult`)?[ba(i.flatMap(e=>e.type===`text`?[e.text]:[]).join(`
30
+ </div>`}var mr={},hr=ot(class extends Ce{constructor(){super(...arguments),this.ot=mr}render(e,t){return t()}update(e,[t,n]){if(Array.isArray(t)){if(Array.isArray(this.ot)&&this.ot.length===t.length&&t.every((e,t)=>e===this.ot[t]))return fn}else if(this.ot===t)return fn;return this.ot=Array.isArray(t)?Array.from(t):t,this.render(t,n)}});function gr(e,t=`local`,n=m()){let r=typeof e==`string`?`${vr(t)}/sessions/${encodeURIComponent(e)}/events`:ft(e,t),i=re(r,void 0,n);return new WebSocket(ee(i))}function _r(e=`local`,t=m()){let n=re(`${vr(e)}/events`,void 0,t);return new WebSocket(ee(n))}function vr(e){return`api/machines/${encodeURIComponent(e)}`}function yr(){return{sessions:[],sessionSearchQuery:``,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``,sessionSearchTarget:void 0,clientQueuedSessionMessages:{},startingSessionCount:0,selectedNotificationInbox:void 0,treeDialog:void 0,error:``}}function br(){return{machines:[],selectedMachine:void 0,isLoadingMachines:!1,machineStatuses:{},machineRuntimes:{},machineStatusSnapshots:{},projects:[],workspaces:[],sessions:[],sessionSearchQuery:``,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``,sessionSearchTarget:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,sendingPrompts:{},clientQueuedSessionMessages:{},startingSessionCount:0,isLoadingProjects:!1,isLoadingWorkspaces:!1,selectedProject:void 0,selectedWorkspace:void 0,selectedSession:void 0,status:void 0,activity:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],sessionStatuses:{},sessionActivities:{},workspaceActivities:{},machineActivities:{},selectedNotificationInbox:void 0,workspacesByProjectId:{},workspaceDeletionRuns:{},commandDialog:void 0,pendingTreeActions:[],treeDialog:void 0,modelDialog:void 0,thinkingDialog:void 0,themeDialog:void 0,authDialog:void 0,actionPaletteOpen:!1,projectDialogOpen:!1,machineDialogOpen:!1,workspaceTool:void 0,mainView:`chat`,piWebStatus:void 0,browserErrors:{},error:``}}function j(e){return{kind:`machine`,machineId:e}}function xr(e,t){return{kind:`project`,machineId:e,projectId:t}}function Sr(e,t,n){return{kind:`workspace`,machineId:e,projectId:t,workspaceId:n}}function Cr(e,t,n={}){return{kind:`session`,machineId:e,sessionId:t,...n.cwd===void 0?{}:{cwd:n.cwd},...n.projectId===void 0?{}:{projectId:n.projectId},...n.workspaceId===void 0?{}:{workspaceId:n.workspaceId}}}function wr(e){switch(e.kind){case`global`:return`global`;case`machine`:return JSON.stringify([e.kind,e.machineId]);case`project`:return JSON.stringify([e.kind,e.machineId,e.projectId]);case`workspace`:return JSON.stringify([e.kind,e.machineId,e.projectId,e.workspaceId]);case`session`:return JSON.stringify([e.kind,e.machineId,e.sessionId,e.cwd,e.projectId,e.workspaceId])}}function Tr(e,t,n,r){return{...e,[wr(t)]:{scope:t,message:n,...r===void 0?{}:{recovery:r}}}}function Er(e,t,n){let r=wr(t),i=e[r];return i===void 0||n!==void 0&&i.message!==n?e:Object.fromEntries(Object.entries(e).filter(([e])=>e!==r))}function Dr(e,t){let n=Object.fromEntries(Object.entries(e).filter(([,e])=>!Nr(e.scope,t)));return Object.keys(n).length===Object.keys(e).length?e:n}function Or(e){let t=e.selectedSession;return{machineId:e.selectedMachine?.id??`local`,...e.selectedProject===void 0?{}:{projectId:e.selectedProject.id},...e.selectedWorkspace===void 0?{}:{workspaceId:e.selectedWorkspace.id},...t===void 0?{}:{sessionId:t.id,cwd:t.cwd}}}function kr(e,t){return Object.values(e).filter(e=>jr(e.scope,t)).sort((e,t)=>Mr(e.scope)-Mr(t.scope)||wr(e.scope).localeCompare(wr(t.scope)))}var Ar=class{constructor(e,t){this.getState=e,this.setState=t}report(e,t,n){this.setState({browserErrors:Tr(this.getState().browserErrors,e,t,n)})}reportLocalized(e,t,n){let r=t();this.setState({browserErrors:{...this.getState().browserErrors,[wr(e)]:{scope:e,message:r,displayMessage:t,...n===void 0?{}:{recovery:n}}}})}captureRecovery(e,t){let n=this.getState().browserErrors[wr(e)];return n?.recovery===t?n:void 0}clearRecovered(e){e?.recovery!==void 0&&this.getState().browserErrors[wr(e.scope)]===e&&this.clear(e.scope)}clear(e,t){let n=this.getState().browserErrors,r=Er(n,e,t);r!==n&&this.setState({browserErrors:r})}discard(e){let t=Dr(this.getState().browserErrors,e);t!==this.getState().browserErrors&&this.setState({browserErrors:t})}};function jr(e,t){return e.kind===`global`?!0:e.machineId===t.machineId?e.kind===`machine`?!0:e.kind===`project`?e.projectId===t.projectId:e.kind===`workspace`?e.projectId===t.projectId&&e.workspaceId===t.workspaceId:e.sessionId===t.sessionId&&(e.cwd===void 0||e.cwd===t.cwd)&&(e.projectId===void 0||e.projectId===t.projectId)&&(e.workspaceId===void 0||e.workspaceId===t.workspaceId):!1}function Mr(e){switch(e.kind){case`global`:return 0;case`machine`:return 1;case`project`:return 2;case`workspace`:return 3;case`session`:return 4}}function Nr(e,t){return t.kind===`global`?!0:e.kind===`global`||e.machineId!==t.machineId?!1:t.kind===`machine`?!0:t.kind===`project`?e.kind!==`machine`&&e.projectId===t.projectId:t.kind===`workspace`?e.kind===`workspace`?e.projectId===t.projectId&&e.workspaceId===t.workspaceId:e.kind===`session`&&e.projectId===t.projectId&&e.workspaceId===t.workspaceId:e.kind===`session`&&e.sessionId===t.sessionId&&(t.cwd===void 0||e.cwd===t.cwd)}function Pr(e,t){return t?.phase===`active`&&t.startup!==!0||e?.isStreaming===!0||e?.isBashRunning===!0||e?.isCompacting===!0||(e?.pendingMessageCount??0)>0}var Fr=`workspace.delete`,Ir=`pi.operation`,Lr=`target.workspaceId`;function Rr(e){return e!==void 0&&(e.hasSessionActivity||e.hasTerminalActivity)}function zr(e,t,n){return t.some(t=>t.projectId===e.id&&t.path===n)||n===e.path||n.startsWith(`${e.path}/`)}function Br(e){return Vr(Object.values(e??{}))}function Vr(e){if(e.some(e=>e.hasSessionActivity))return`session`;if(e.some(e=>e.hasTerminalActivity))return`terminal`}function Hr(e,t){return`${e}:${t}`}function M(e,t){return`${e}:${t}`}function N(e){return e.selectedMachine?.id??`local`}var Ur=class{constructor(e=0){if(this.debounceMs=e,this.pendingByKey=new Map,!Number.isInteger(e)||e<0)throw Error(`debounceMs must be a non-negative integer`)}request(e,t){let n=this.pendingByKey.get(e);if(n!==void 0)return n.latestRefresh=t,n.phase===`running`?n.trailing=!0:this.rescheduleDebounce(n),n.promise;let r={promise:Promise.resolve(),latestRefresh:t,phase:`debouncing`,trailing:!1,debounceTimer:void 0,finishDebounce:void 0};return r.promise=Promise.resolve().then(async()=>{let t,n;do{r.trailing=!1,r.phase=`debouncing`,this.debounceMs>0&&await this.waitForDebounce(r),r.phase=`running`;let e=r.latestRefresh;n=!1;try{await e()}catch(e){t=e,n=!0}}while(this.hasTrailingRequest(r));if(this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e),n)throw t}).finally(()=>{this.cancelDebounce(r),this.pendingByKey.get(e)===r&&this.pendingByKey.delete(e)}),this.pendingByKey.set(e,r),r.promise}hasTrailingRequest(e){return e.trailing}waitForDebounce(e){return new Promise(t=>{e.finishDebounce=t,this.rescheduleDebounce(e)})}rescheduleDebounce(e){e.finishDebounce!==void 0&&(e.debounceTimer!==void 0&&globalThis.clearTimeout(e.debounceTimer),e.debounceTimer=globalThis.setTimeout(()=>{let t=e.finishDebounce;e.debounceTimer=void 0,e.finishDebounce=void 0,e.phase=`running`,t?.()},this.debounceMs))}cancelDebounce(e){e.debounceTimer!==void 0&&globalThis.clearTimeout(e.debounceTimer),e.debounceTimer=void 0,e.finishDebounce=void 0}},Wr=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new Ur,this.api=n.api??Rt,this.onActivityApplied=n.onActivityApplied}refresh(e=N(this.getState())){return this.refreshes.request(e,async()=>{this.applyMachineActivitySnapshot(e,Gr(await this.api.workspaceActivity(e)))})}applyWorkspaceActivity(e,t=N(this.getState())){let n=this.getState(),r=N(n)===t,i=Kr(n.machineActivities[t]??(r?n.workspaceActivities:{}),e);this.setState({machineActivities:{...n.machineActivities,[t]:i},...r?{workspaceActivities:i}:{}}),this.onActivityApplied?.(t)}applyMachineActivitySnapshot(e,t){let n=this.getState();this.setState({machineActivities:{...n.machineActivities,[e]:t},...N(n)===e?{workspaceActivities:t}:{}}),this.onActivityApplied?.(e)}};function Gr(e){let t={};for(let n of e.workspaces)Rr(n)&&(t[n.cwd]=n);return t}function Kr(e,t){let n={...e};return Rr(t)?(n[t.cwd]=t,n):Object.fromEntries(Object.entries(n).filter(([e])=>e!==t.cwd))}var qr={close:x(`Close`,`Dismiss the authentication dialog`),cancel:x(`Cancel`,`Cancel authentication or return from the starting step`),submit:x(`Submit`,`Submit the current provider prompt response`),methodTitle:x(`Configure provider authentication`,`Title of the provider authentication method chooser`),subscription:x(`Use a subscription`,`Authentication method using a provider subscription`),subscriptionDetail:x(`ChatGPT Plus/Pro, Claude Pro/Max, or GitHub Copilot`,`Examples of supported subscriptions; product names stay unchanged`),credentials:x(`Use provider credentials`,`Authentication method using an API key or other provider credentials`),credentialsDetail:x(`Configure an API key or provider-specific credentials in the active Pi-compatible profile's auth.json`,`Instructions for configuring provider credentials; auth.json is a literal filename`),selectProvider:x(`Select provider authentication`,`Provider chooser title when no authentication method was specified`),selectSubscription:x(`Select subscription provider`,`Provider chooser title for subscription authentication`),selectCredentials:x(`Select credential provider`,`Provider chooser title for credential authentication`),removeTitle:x(`Remove stored provider authentication`,`Stored-credential removal dialog title`),mcpAuthentication:x(`MCP authentication`,`MCP authentication dialog title before an operation is known`),mcpLogin:x(`MCP login`,`MCP sign-in chooser title`),mcpLogout:x(`MCP logout`,`MCP sign-out chooser title`),mcpLoginProvider:x(`MCP login: {provider}`,`Title when signing in to a named MCP server`),mcpLogoutProvider:x(`MCP logout: {provider}`,`Title when signing out of a named MCP server`),loginProvider:x(`Login to {provider}`,`Provider authentication dialog title`),startMcpLogin:x(`Sign in to an MCP server`,`Starting MCP sign-in dialog title`),startMcpLogout:x(`Sign out of an MCP server`,`Starting MCP sign-out dialog title`),startingMcp:x(`Starting MCP authentication…`,`Status while the host starts MCP authentication`),search:x(`Search providers`,`Accessible name and placeholder of provider search`),noCredentials:x(`No stored credentials. Environment variables and models.json settings are unchanged.`,`Empty stored-credential list; models.json is a literal filename`),noProviders:x(`No providers available.`,`Empty provider chooser`),noMatches:x(`No matching providers`,`Provider search has no matches`),approveBrowser:x(`Approve access in your browser, then return here.`,`MCP browser approval instructions`),authorizationLink:x(`Open this authorization link:`,`Instructions before a provider authorization URL`),authorizationPage:x(`Open authorization page`,`MCP browser authorization link label`),enterCode:x(`Enter code: <codeTag>{code}</codeTag>`,`Device authorization code instructions; codeTag tag wraps the unchanged code`),cancellationRequested:x(`Cancellation requested. Waiting for Pi to finish…`,`MCP cancellation may still be in progress`),finished:x(`Operation finished`,`MCP operation has ended, without claiming authentication succeeded`),waiting:x(`Waiting for Pi…`,`MCP authentication is awaiting the host`),startingLogin:x(`Starting login flow…`,`Provider authentication is starting`),logoutWarning:x(`Logout removes Pi’s saved credentials. It does not disable the server or revoke access at the provider. Other sessions using those credentials are also affected.`,`MCP logout consequences`),reusedCredentials:x(`No browser authorization was requested. Pi may have reused existing credentials; read its result below.`,`MCP completed without a browser authorization step`),cancelWarning:x(`Pi may already be completing authentication. Credentials may have been saved if approval happened before cancellation.`,`MCP cancellation race warning`),mcpPasteNote:x(`If the redirect page cannot load after approval, copy the full URL from your browser’s address bar and paste it below.`,`MCP manual redirect fallback instructions`),remotePasteNote:x(`After you approve, the redirect page will probably fail to load — that is expected. Copy the full URL from your browser's address bar and paste it below.`,`Remote provider manual redirect instructions`),messages:x(`Authentication messages`,`Accessible name for unchanged provider/host progress messages`),related:x(`Related information`,`Accessible name for provider-supplied links`),failed:x(`Authentication failed`,`Fallback status when a failed flow has no provider error`),cancelled:x(`Authentication cancelled`,`Fallback status when a cancelled flow has no provider error`),typeSubscription:x(`subscription`,`Authentication type in provider details`),typeCredentials:x(`credentials`,`Authentication type in provider details`),providerDetail:x(`{provider} · {type}`,`Provider identifier and localized authentication type; complete provider detail line`),configured:x(`✓ configured`,`Provider credential source badge: stored`),environment:x(`✓ env`,`Provider credential source badge: environment, without a variable label`),environmentLabel:x(`✓ env: {label}`,`Provider credential source badge with unchanged environment variable label`),runtime:x(`✓ runtime`,`Provider credential source badge: runtime`),customKey:x(`✓ custom key`,`Provider credential source badge: fallback key`),modelsKey:x(`✓ models.json key`,`Provider credential source badge: key in literal file models.json`),modelsCommand:x(`✓ models.json command`,`Provider credential source badge: command in literal file models.json`),selectSession:x(`Select a session to authenticate MCP servers.`,`Authentication cannot start without an active session`),noStoredProvider:x(`No stored credentials for {provider}`,`Requested provider has no stored credentials`),providerNotFound:x(`Auth provider not found: {provider}`,`Requested provider identifier was not found`)},P=w.registerMessages(`core.auth`,qr),Jr=class{constructor(e,t,n,r){this.getState=e,this.setState=t,this.applyStatus=n,this.oauthOperationGeneration=0,this.pollGeneration=0,this.api=r.api??Xt,this.pollIntervalMs=r.pollIntervalMs??1e3,this.scope=r.scope,this.browserErrors=new Ar(e,t)}dispose(){this.oauthOperationGeneration+=1,this.stopPolling()}handleSlashCommand(e){let t=Qr(e);return t!==void 0&&(t.command===`login`?this.openLogin(t.providerId):this.openLogout(t.providerId),!0)}async openLogin(e){this.advanceAuthOperation();let t=this.captureTarget();t!==void 0&&(e!==void 0&&e!==``?await this.openLoginProvider(e,t):this.setState({authDialog:{step:`method`,target:t}}))}async openMcpAuth(e,t,n){let r=this.getState(),i=n?.session??(r.selectedSession?.archived===!0?void 0:r.selectedSession),a=n?.machineId??N(r);if(i===void 0){this.browserErrors.reportLocalized(j(a),()=>P.t(`selectSession`));return}let o=this.advanceAuthOperation(),s={machineId:a},c={id:i.id,cwd:i.cwd};this.setState({authDialog:{step:`starting`,target:s,mcpSession:c,mode:e,title:e===`login`?C(`ui.mcp.signInTitle`,`Sign in to an MCP server`):C(`ui.mcp.signOutTitle`,`Sign out of an MCP server`)}}),await this.startFlow(()=>t===void 0?this.api.startMcpAuth(c,e,a):this.api.startMcpAuth(c,e,a,t),s,o,c)}async chooseLoginMethod(e){let t=this.getState().authDialog;if(t?.step!==`method`)return;let n=this.oauthOperationGeneration;try{let{providers:r}=await this.api.authProviders({mode:`login`,authType:e,...Xr(t.target)});if(n!==this.oauthOperationGeneration||this.getState().authDialog!==t)return;this.setState({authDialog:{step:`providers`,mode:`login`,authType:e,providers:r,target:t.target}})}catch(e){if(n!==this.oauthOperationGeneration||this.getState().authDialog!==t)return;this.browserErrors.report(j(t.target.machineId),String(e))}}async selectLoginProvider(e,t){let n=this.getState().authDialog;if(n?.step!==`providers`)return;let r=n.providers.find(n=>n.id===e&&(t===void 0||n.authType===t));r!==void 0&&(r.authType===`oauth`||r.loginFlow===`interactive`?await this.startOAuth(r,n.target):this.setState({authDialog:{step:`apiKey`,provider:r,value:``,target:n.target}}))}updateApiKey(e){let t=this.getState().authDialog;if(t?.step!==`apiKey`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,value:e}})}async saveApiKey(){let e=this.getState().authDialog;if(e?.step!==`apiKey`)return;let t=e.value.trim();if(t===``){this.setState({authDialog:{...e,error:C(`ui.shared.daf147632ea6`,`API key is required`)}});return}let n={...e};delete n.error,this.setState({authDialog:{...n,saving:!0}});let r=this.oauthOperationGeneration;try{let n=e.target;if(await this.api.saveApiKey(e.provider.id,t,n),r!==this.oauthOperationGeneration)return;this.closeDialog(),this.refreshStatus(n)}catch(t){if(r!==this.oauthOperationGeneration)return;this.setState({authDialog:{...e,saving:!1,error:String(t)}})}}async openLogout(e){let t=this.advanceAuthOperation(),n=this.captureTarget();if(n!==void 0)try{let{providers:r}=await this.api.authProviders({mode:`logout`,...Xr(n)});if(t!==this.oauthOperationGeneration)return;if(e!==void 0&&e!==``){let t=r.find(t=>t.id===e);t===void 0?this.browserErrors.reportLocalized(j(n.machineId),()=>P.t(`noStoredProvider`,{provider:e})):await this.logoutProviderForTarget(t.id,n);return}this.setState({authDialog:{step:`logout`,providers:r,target:n}})}catch(e){if(t!==this.oauthOperationGeneration)return;this.browserErrors.report(j(n.machineId),String(e))}}async logoutProvider(e){let t=this.getState().authDialog;t?.step===`logout`&&t.providers.find(t=>t.id===e)!==void 0&&await this.logoutProviderForTarget(e,t.target)}async logoutProviderForTarget(e,t){let n=this.advanceAuthOperation();try{if(await this.api.logoutProvider(e,t),n!==this.oauthOperationGeneration)return;this.closeDialog(),this.refreshStatus(t)}catch(e){if(n!==this.oauthOperationGeneration)return;this.browserErrors.report(j(t.machineId),String(e))}}updateOAuthInput(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n={...t};delete n.error,this.setState({authDialog:{...n,inputValue:e}})}async respondOAuth(e){let t=this.getState().authDialog;if(t?.step!==`oauth`)return;let n=t.flow.prompt??t.flow.select;if(n===void 0)return;let r=this.oauthOperationGeneration,i=t.flow.flowId,a=n.requestId;if(this.inFlightResponse?.generation===r&&this.inFlightResponse.flowId===i&&this.inFlightResponse.requestId===a)return;let o={generation:r,flowId:i,requestId:a};this.inFlightResponse=o;let s=e??t.inputValue??``,c={...t};delete c.error,this.setState({authDialog:{...c,responding:!0}});try{let e=t.flow.target===`mcp`?await this.api.respondMcpAuthFlow(i,a,s,t.target.machineId):await this.api.respondOAuthFlow(i,a,s,t.target),n=this.currentOAuthDialog(r,i);if(e.flowId!==i||n===void 0||!Yr(n.target,t.target)||Zr(n.flow)!==a)return;this.updateOAuthFlow(e,t.target)}catch(e){let t=this.currentOAuthDialog(r,i);if(t===void 0||Zr(t.flow)!==a)return;this.setState({authDialog:{...t,responding:!1,error:String(e)}})}finally{this.inFlightResponse===o&&(this.inFlightResponse=void 0)}}async cancelOAuth(){let e=this.getState().authDialog;if(e?.step!==`oauth`){this.closeDialog();return}let t=e.flow.flowId,n=e.target;if(e.flow.target===`mcp`){if(e.flow.status!==`running`){this.closeDialog();return}if(e.flow.cancelRequested===!0)return;let r=this.advanceAuthOperation();this.setState({authDialog:{...e,flow:{...e.flow,cancelRequested:!0}}});try{let e=await this.api.cancelMcpAuthFlow(t,n.machineId);this.currentOAuthDialog(r,t)!==void 0&&(this.updateOAuthFlow(e,n),e.status===`running`&&this.startPolling(t,n))}catch(e){let i=this.currentOAuthDialog(r,t);i!==void 0&&(this.setState({authDialog:{...i,flow:{...i.flow,cancelRequested:!1},error:String(e)}}),this.startPolling(t,n))}}else{this.closeDialog();try{await this.api.cancelOAuthFlow(t,n)}catch{}}}closeDialog(){this.advanceAuthOperation(),this.setState({authDialog:void 0})}async openLoginProvider(e,t){let n=this.oauthOperationGeneration;try{let{providers:r}=await this.api.authProviders({mode:`login`,...Xr(t)});if(n!==this.oauthOperationGeneration)return;let i=r.filter(t=>t.id===e);if(i.length===0){this.browserErrors.reportLocalized(j(t.machineId),()=>P.t(`providerNotFound`,{provider:e}));return}if(i.length>1){this.setState({authDialog:{step:`providers`,mode:`login`,providers:i,target:t}});return}let a=i[0];if(a===void 0)return;a.authType===`oauth`||a.loginFlow===`interactive`?await this.startOAuth(a,t):this.setState({authDialog:{step:`apiKey`,provider:a,value:``,target:t}})}catch(e){if(n!==this.oauthOperationGeneration)return;this.browserErrors.report(j(t.machineId),String(e))}}async startOAuth(e,t){let n=this.advanceAuthOperation();await this.startFlow(()=>e.authType===`oauth`?this.api.startOAuthLogin(e.id,t):this.api.startInteractiveApiKeyLogin(e.id,t),t,n)}async startFlow(e,t,n,r){if(n===this.oauthOperationGeneration)try{let i=await e();if(n!==this.oauthOperationGeneration){if(i.status===`running`)try{i.target===`mcp`?await this.api.cancelMcpAuthFlow(i.flowId,t.machineId):await this.api.cancelOAuthFlow(i.flowId,t)}catch{}return}this.updateOAuthFlow(i,t,r),i.status===`running`&&this.startPolling(i.flowId,t)}catch(e){if(n!==this.oauthOperationGeneration)return;let r=this.getState().authDialog;r?.step===`starting`?this.setState({authDialog:{...r,error:String(e)}}):this.browserErrors.report(j(t.machineId),String(e))}}updateOAuthFlow(e,t,n){let r=this.getState().authDialog;if(n??=e.target===`mcp`&&(r?.step===`oauth`||r?.step===`starting`)?r.mcpSession:void 0,e.status===`complete`&&e.target!==`mcp`){this.stopPolling(),this.closeDialog(),this.refreshStatus(t);return}e.status!==`running`&&(this.oauthOperationGeneration+=1,this.stopPolling(),e.target===`mcp`&&n!==void 0&&this.refreshMcpStatus(t.machineId,n));let i=r?.step===`oauth`&&r.flow.flowId===e.flowId?r.inputValue??``:``,a=r?.step===`oauth`?Zr(r.flow):void 0,o=Zr(e),s=a!==void 0&&a===o,c=s?i:``,l=s&&r?.step===`oauth`?r.responding===!0:!1;this.setState({authDialog:{step:`oauth`,flow:e,inputValue:c,responding:l,target:t,...n===void 0?{}:{mcpSession:n}}})}startPolling(e,t){this.stopPolling();let n=this.oauthOperationGeneration,r=this.pollGeneration;this.pollTimer=window.setInterval(()=>{this.poll(e,t,n,r)},this.pollIntervalMs)}stopPolling(){this.pollGeneration+=1,this.pollTimer!==void 0&&(window.clearInterval(this.pollTimer),this.pollTimer=void 0)}async poll(e,t,n,r){if(r!==this.pollGeneration)return;let i=this.currentOAuthDialog(n,e);if(i===void 0||!Yr(i.target,t)){this.stopPolling();return}let a=Zr(i.flow);try{let o=i.flow.target===`mcp`?await this.api.mcpAuthFlow(e,i.target.machineId):await this.api.oauthFlow(e,i.target),s=this.currentOAuthDialog(n,e);if(o.flowId!==e||r!==this.pollGeneration||s===void 0||!Yr(s.target,t)||Zr(s.flow)!==a)return;this.updateOAuthFlow(o,i.target)}catch(i){let o=this.currentOAuthDialog(n,e);if(r!==this.pollGeneration||o===void 0||!Yr(o.target,t)||Zr(o.flow)!==a)return;this.stopPolling(),this.setState({authDialog:{...o,error:String(i)}})}}currentOAuthDialog(e,t){if(e!==this.oauthOperationGeneration)return;let n=this.getState().authDialog;return n?.step===`oauth`&&n.flow.flowId===t?n:void 0}advanceAuthOperation(){return this.oauthOperationGeneration+=1,this.stopPolling(),this.oauthOperationGeneration}async refreshStatus(e){let t=this.selectedSessionForMachine(e.machineId);if(t!==void 0&&this.targetStillSelected(e))try{let n=await this.api.status(t,e.machineId),r=this.selectedSessionForMachine(e.machineId);if(!this.targetStillSelected(e)||r?.id!==t.id||r.cwd!==t.cwd)return;this.applyStatus(n)}catch{}}async refreshMcpStatus(e,t){let n=()=>{let n=this.selectedSessionForMachine(e);return n?.id===t.id&&n.cwd===t.cwd};if(n())try{let r=await this.api.status(t,e);n()&&this.applyStatus(r)}catch{}}selectedSessionForMachine(e){let t=this.getState();if(N(t)!==e)return;let n=t.selectedSession;if(n!==void 0&&n.archived!==!0)return n}captureTarget(){let e=this.getState(),t=e.selectedMachine,n={machineId:N(e),...t?.kind===void 0?{}:{machineKind:t.kind}};if(this.scope===`management`)return n;let r=e.selectedProject;if(r===void 0)this.browserErrors.report(j(n.machineId),C(`client.authController.select.a.project.before.configuring.provider.authentication.a2a76e`,`Select a project before configuring provider authentication.`));else return{...n,projectId:r.id,projectName:r.name}}targetStillSelected(e){return N(this.getState())===e.machineId?e.projectId===void 0||this.getState().selectedProject?.id===e.projectId:!1}};function Yr(e,t){return e.machineId===t.machineId&&e.projectId===t.projectId}function Xr(e){return e.projectId===void 0?{machineId:e.machineId}:{machineId:e.machineId,projectId:e.projectId,...e.projectName===void 0?{}:{projectName:e.projectName}}}function Zr(e){return e.prompt?.requestId??e.select?.requestId}function Qr(e){let t=e.trim(),n=/^\/(login|logout)(?:\s+(\S+))?\s*$/u.exec(t);if(n===null)return;let r=n[1];if(r!==`login`&&r!==`logout`)return;let i=n[2];return i===void 0||i===``?{command:r}:{command:r,providerId:i}}var $r={editTitle:x(`Edit local display name`,`Machine name editing dialog title`),addTitle:x(`Add machine`,`Machine registration dialog title and action`),closeEdit:x(`Close edit local display name`,`Close editing dialog`),closeAdd:x(`Close add machine`,`Close registration dialog`),urlLabel:x(`Remote PI WEB URL`,`Machine address label`),urlHelp:x(`Enter the reachable base URL first, including http:// or https://.`,`Machine address guidance; protocols are literal`),nameLabel:x(`Local display name (optional)`,`Optional machine alias label`),nameHelp:x(`Only changes the name shown here. Leave blank to use the remote machine’s name.`,`Machine alias guidance`),tokenLabel:x(`Bearer token (optional)`,`Optional authentication token label`),tokenPlaceholder:x(`Leave blank if the remote machine does not require one`,`Token input placeholder`),tokenHelp:x(`If the remote machine requires a token, paste it without the “Bearer” prefix.`,`Token guidance; Bearer is a literal authentication scheme`),intro:x(`After you enter a URL, you can add an optional local display name and bearer token.`,`Machine registration first-step guidance`),cancel:x(`Cancel`,`Cancel machine dialog`),saving:x(`Saving…`,`Machine alias save in progress`),adding:x(`Adding…`,`Machine registration in progress`),save:x(`Save name`,`Save local machine alias`),urlRequired:x(`Remote PI WEB URL is required.`,`Missing machine address validation`),urlInvalid:x(`Enter a valid URL including http:// or https://.`,`Malformed machine address validation`),urlProtocol:x(`Use an http:// or https:// URL.`,`Unsupported machine address protocol validation`),urlCredentials:x(`Do not include credentials in the machine URL.`,`Credentials in machine address validation`),urlQuery:x(`Do not include a query string or fragment.`,`Machine address query or fragment validation`),online:x(`online`,`Machine connection status`),offline:x(`offline`,`Machine connection status`),error:x(`error`,`Machine connection status`),unknown:x(`unknown`,`Machine connection status`),local:x(`Local Pi Web`,`Local machine subtitle`),remote:x(`Remote Pi Web`,`Remote machine subtitle without an address`),unread:x(`Unread sessions on this machine`,`Machine activity accessible description`),terminal:x(`Machine terminal active`,`Machine activity accessible description`),active:x(`Machine active`,`Machine activity accessible description`),actions:x(`Machine actions`,`Machine actions tooltip`),edit:x(`Edit display name`,`Edit machine alias menu action`),remove:x(`Remove`,`Remove remote machine menu action`),machines:x(`Machines`,`Machine navigation heading`),machine:x(`Machine`,`Machine switcher kicker`),noSelection:x(`No machine selected`,`Machine navigation empty selection`),otherTerminal:x(`Terminal active on other machines`,`Other machines activity accessible description`),otherActive:x(`Other machines active`,`Other machines activity accessible description`),otherUnread:x(`Unread sessions on other machines`,`Other machines unread accessible description`),cannotRemove:x(`The local machine cannot be removed.`,`Attempt to delete the local machine`),actionsFor:x(`Actions for {name}`,`Machine-specific actions accessible label`),removeNamed:x(`Remove {name}`,`Machine-specific removal tooltip`),subtitle:x(`{location} · {status}`,`Machine address or localized fallback and translated connection status`),identity:x(`{name} · {location} · {status}`,`Machine switcher identity tooltip`),switch:x(`Machine: {name}. {status}. Switch machine.`,`Machine switcher accessible label`),reconnecting:x(`{name} is unavailable; reconnecting…`,`Selected remote machine connection notice`),refreshFailed:x(`Settings saved, but refreshing the machine name failed: {error}`,`Machine identity refresh failure; error is unchanged backend detail`)},F=w.registerMessages(`core.machines`,$r),ei=class{constructor(e,t,n,r,i={}){this.getState=e,this.setState=t,this.updateUrl=n,this.projects=r,this.runtimeRefreshSeqByMachine=new Map,this.identityRevisionByMachine=new Map,this.pendingIdentityEdits=new Set,this.navigateToMachine=i.navigateToMachine,this.captureNavigation=i.captureNavigation,this.browserErrors=new Ar(e,t)}async loadMachines(e){this.setState({error:``,isLoadingMachines:!0});try{let t=await Xt.machines(),n=await this.selectInitialMachine(t,e),r=new Set(t.map(e=>e.id));for(let e of Object.values(this.getState().browserErrors))e.scope.kind!==`global`&&!r.has(e.scope.machineId)&&this.browserErrors.discard(j(e.scope.machineId));return this.setState({machines:t,selectedMachine:n,machineActivities:ri(this.getState().machineActivities,r),machineRuntimes:ri(this.getState().machineRuntimes,r),machineStatusSnapshots:ri(this.getState().machineStatusSnapshots,r)}),this.refreshMachineHealthFor(t),this.refreshMachineRuntimeFor(t),!0}catch(t){return this.setState({error:String(t)}),this.browserErrors.report(j(e??`local`),String(t)),!1}finally{this.setState({isLoadingMachines:!1})}}async selectMachine(e,t={}){this.getState().selectedMachine?.id!==e.id&&(this.setState({selectedMachine:e,projects:[],workspaces:[],isLoadingWorkspaces:!1,selectedProject:void 0,workspaceResolution:void 0,selectedWorkspace:void 0,selectedSession:void 0,messages:[],messagePageStart:0,messagePageTotal:0,status:void 0,activity:void 0,sessionStatuses:{},sessionActivities:{},sendingPrompts:{},workspaceActivities:{},workspacesByProjectId:{},workspaceDeletionRuns:{},...yr()}),t.updateUrl!==!1&&this.updateUrl(),await this.projects.loadProjects(),this.refreshMachineHealth(e.id),this.refreshMachineRuntime(e.id))}async addMachine(e){let t=ii(this.getState(),this.captureNavigation);this.setState({error:``});try{let n=await Xt.addMachine(e);return this.setState({machines:[...this.getState().machines.filter(e=>e.id!==n.id),n]}),this.navigateToMachine===void 0?await this.selectMachine(n):await this.navigateToMachine(n,{expected:t}),n}catch(e){this.setState({error:String(e)});return}}async refreshMachineIdentity(e){if(this.pendingIdentityEdits.has(e)||!this.getState().machines.some(t=>t.id===e))return;let t=this.invalidateMachineIdentity(e);try{let n=await Xt.machine(e);if(t!==this.identityRevisionByMachine.get(e))return;let r=this.getState(),i=r.machines.map(t=>t.id===e?ti(t,n):t);this.setState({machines:i,...r.selectedMachine===void 0?{}:{selectedMachine:i.find(e=>e.id===r.selectedMachine?.id)??r.selectedMachine}})}catch(n){if(t===this.identityRevisionByMachine.get(e)){let t=String(n);this.browserErrors.reportLocalized(j(e),()=>F.t(`refreshFailed`,{error:t}))}}}async updateMachine(e,t){let n=this.invalidateMachineIdentity(e);this.pendingIdentityEdits.add(e),this.setState({error:``});try{let r=await Xt.updateMachine(e,{name:t});if(n!==this.identityRevisionByMachine.get(e))return;let i=this.getState();if(!i.machines.some(t=>t.id===e))return;let a=i.machines.map(t=>t.id===e?ti(t,r):t);return this.setState({machines:a,...i.selectedMachine?.id===e?{selectedMachine:a.find(t=>t.id===e)}:{}}),r}catch(t){n===this.identityRevisionByMachine.get(e)&&this.setState({error:String(t)});return}finally{n===this.identityRevisionByMachine.get(e)&&(this.pendingIdentityEdits.delete(e),this.invalidateMachineIdentity(e))}}invalidateMachineIdentity(e){let t=(this.identityRevisionByMachine.get(e)??0)+1;return this.identityRevisionByMachine.set(e,t),t}async deleteMachine(e=this.getState().selectedMachine,t={}){if(e!==void 0){if(e.kind===`local`)this.browserErrors.reportLocalized(j(e.id),()=>F.t(`cannotRemove`));else try{await Xt.deleteMachine(e.id),this.invalidateMachineIdentity(e.id),this.pendingIdentityEdits.delete(e.id);let n=this.getState().machines.filter(t=>t.id!==e.id),r=n.find(e=>e.id===`local`)??n[0];if(this.browserErrors.discard(j(e.id)),this.setState({machines:n,machineStatuses:ni(this.getState().machineStatuses,e.id),machineRuntimes:ni(this.getState().machineRuntimes,e.id),machineActivities:ni(this.getState().machineActivities,e.id),machineStatusSnapshots:ni(this.getState().machineStatusSnapshots,e.id)}),this.getState().selectedMachine?.id===e.id&&r!==void 0){if(t.selectFallback===!1)return r;let e=ii(this.getState(),this.captureNavigation);return this.navigateToMachine===void 0?await this.selectMachine(r):await this.navigateToMachine(r,{expected:e}),r}return}catch(t){this.browserErrors.report(j(e.id),String(t));return}}}async refreshMachineHealth(e=this.getState().selectedMachine?.id??`local`){try{let t=await Xt.health(e);return this.setState({machineStatuses:{...this.getState().machineStatuses,[t.machineId]:t}}),t}catch(t){this.browserErrors.report(j(e),String(t));return}}async refreshMachineRuntime(e=this.getState().selectedMachine?.id??`local`){let t=(this.runtimeRefreshSeqByMachine.get(e)??0)+1;this.runtimeRefreshSeqByMachine.set(e,t);try{let n=await Xt.runtime(e,!0);return this.runtimeRefreshSeqByMachine.get(e)===t?(this.setState({machineRuntimes:{...this.getState().machineRuntimes,[n.machineId]:n}}),n):void 0}catch(n){this.runtimeRefreshSeqByMachine.get(e)===t&&this.browserErrors.report(j(e),String(n));return}}async selectInitialMachine(e,t){let n=e.find(e=>e.id===(t??`local`));if(n===void 0)return this.localMachine(e);if(n.kind!==`remote`)return n;let r=await this.safeRemoteHealth(n);return this.setState({machineStatuses:{...this.getState().machineStatuses,[r.machineId]:r}}),r.ok||this.browserErrors.report(j(n.id),C(`ui.piWebApp.isUnavailableReconnecting`,`{machineName} is unavailable. Reconnecting…`,{machineName:n.name})),n}async safeRemoteHealth(e){try{return await Xt.health(e.id)}catch(t){return{machineId:e.id,ok:!1,checkedAt:new Date().toISOString(),status:`offline`,error:t instanceof Error?t.message:String(t)}}}localMachine(e){return e.find(e=>e.id===`local`)??e[0]}async refreshMachineHealthFor(e){let t=await Promise.allSettled(e.map(e=>Xt.health(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineStatuses:{...this.getState().machineStatuses,...n}})}async refreshMachineRuntimeFor(e){let t=await Promise.allSettled(e.map(e=>Xt.runtime(e.id))),n=Object.fromEntries(t.flatMap(e=>e.status===`fulfilled`?[[e.value.machineId,e.value]]:[]));Object.keys(n).length>0&&this.setState({machineRuntimes:{...this.getState().machineRuntimes,...n}})}};function ti(e,t){let n={...e,name:t.name};return t.nameOverride===void 0?delete n.nameOverride:n.nameOverride=t.nameOverride,t.reportedName===void 0?delete n.reportedName:n.reportedName=t.reportedName,n}function ni(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function ri(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>t.has(e)))}function ii(e,t){return t?.()??{machineId:e.selectedMachine?.id??`local`,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,...e.selectedSession===void 0||Reflect.get(e.selectedSession,`clientPendingStart`)!==!0?{sessionId:e.selectedSession?.id}:{}}}var ai=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.refreshes=new Ur,this.api=n.api??Bt}refresh(e){return this.refreshes.request(e,async()=>{let t=this.getState().machineStatusSnapshots[e],n=await this.api.machineStatus(e),r=this.getState().machineStatusSnapshots[e];(r===t||r===void 0||r.epochId===n.epochId)&&this.apply(e,n)})}apply(e,t){let n=this.getState().machineStatusSnapshots;oi(n[e],t)&&this.setState({machineStatusSnapshots:{...n,[e]:t}})}};function oi(e,t){return e===void 0||e.epochId!==t.epochId||t.revision>e.revision}function si(e){switch(e.kind){case`projects`:return JSON.stringify([e.kind,e.machineId]);case`workspaces`:return JSON.stringify([e.kind,e.machineId,e.projectId]);case`sessionPins`:return JSON.stringify([e.kind,e.machineId,e.projectId,e.workspaceId])}}var ci=class{constructor(e,t={}){this.port=e,this.options=t,this.states=new Map}reset(){let e=[...this.states.values()].map(e=>e.scope);this.states.clear();for(let t of e)this.options.onChange?.(t)}ids(e){return[...this.state(e).snapshot?.ids??[]]}pending(e){return this.state(e).pending>0}ensure(e){let t=this.state(e);if(t.ensuring)return t.ensuring;if(t.snapshot)return Promise.resolve();let n=this.load(e);return t.ensuring=n,n.finally(()=>{t.ensuring=void 0}).catch(()=>void 0),n}load(e){return e={...e},this.enqueue(e,async t=>{t.snapshot=await this.port.load(e)})}async refreshSessionPins(e){await Promise.all([...this.states.values()].filter(({scope:t})=>t.kind===`sessionPins`&&t.machineId===e).map(({scope:e})=>this.load(e)))}mutate(e,t){return e={...e},this.enqueue(e,async n=>{if(n.snapshot??=await this.port.load(e),this.states.get(si(e))!==n)return;let r=n.snapshot,i=[...t([...r.ids])];if(!(i.length===r.ids.length&&i.every((e,t)=>e===r.ids[t])))try{n.snapshot=await this.port.save(e,i,r.revision)}catch(t){if(this.states.get(si(e))!==n)return;n.snapshot=void 0;try{n.snapshot=await this.port.load(e)}catch(t){this.options.onError?.(e,t)}throw t}})}state(e){let t=si(e),n=this.states.get(t);return n||(n={scope:{...e},snapshot:void 0,tail:Promise.resolve(),ensuring:void 0,pending:0},this.states.set(t,n)),n}enqueue(e,t){e={...e};let n=this.state(e);n.pending++,this.options.onChange?.(e);let r=n.tail.then(async()=>{if(this.states.get(si(e))===n)try{await t(n)}catch(t){throw this.states.get(si(e))===n&&this.options.onError?.(e,t),t}finally{n.pending--,this.states.get(si(e))===n&&this.options.onChange?.(e)}});return n.tail=r.catch(()=>void 0),r}};function li(e){let t=`api/machines/${encodeURIComponent(e.machineId)}/navigation/projects`;switch(e.kind){case`projects`:return t;case`workspaces`:return`${t}/${encodeURIComponent(e.projectId)}/workspaces`;case`sessionPins`:return`${t}/${encodeURIComponent(e.projectId)}/workspaces/${encodeURIComponent(e.workspaceId)}/session-pins`}}function ui(e){if(!di(e))throw Error(`Invalid navigation order response`);let t=e.ids,n=e.revision;if(!Array.isArray(t)||!t.every(e=>typeof e==`string`&&e.trim()!==``)||new Set(t).size!==t.length||typeof n!=`number`||!Number.isSafeInteger(n)||n<0)throw Error(`Invalid navigation order response: ids and revision are required`);return{ids:[...t],revision:n}}function di(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var fi={load:e=>h(li(e),ui,{cache:`no-store`}),save:(e,t,n)=>{let r={ids:[...t],revision:n};return h(li(e),ui,{method:`PUT`,body:JSON.stringify(r)})}};function pi(e,t){let n=new Map;for(let e of t)n.has(e)||n.set(e,n.size);return[...e].sort((e,t)=>(n.get(e.id)??1/0)-(n.get(t.id)??1/0))}function mi(e,t,n,r,i){let a=[...new Set([...e,...t])];if(n===r||!t.includes(n)||!t.includes(r))return a;let o=a.filter(e=>e!==n),s=o.indexOf(r);return o.splice(s+ +(i===`after`),0,n),o}var hi={workspaceNotFound:x(`Workspace not found: {id}`,`Requested workspace identifier is unavailable during navigation`),sessionNotFound:x(`Session not found: {id}`,`Requested session identifier is unavailable during workspace navigation`),projectNotFound:x(`Project not found`,`Workspace refresh cannot find the requested project`),degraded:x(`Workspace authority is degraded`,`Workspace provider is unavailable and supplied no diagnostic detail`),trustUnavailable:x(`Cannot save trust choice for project {id}: main workspace unavailable`,`The newly added project's trust choice cannot be saved without its main workspace`)},gi=w.registerMessages(`core.projectWorkspaceFeedback`,hi),_i=class extends Error{constructor(e){super(),this.displayMessage=e}get message(){return this.displayMessage()}};function vi(e,t,n){n instanceof _i?e.reportLocalized(t,()=>String(n)):e.report(t,String(n))}var yi=class{constructor(e,t,n,r={}){this.getState=e,this.setState=t,this.workspaces=n,this.loadErrors=new Map,this.api=r.api??Xt,this.onProjectsApplied=r.onProjectsApplied,this.navigateToProject=r.navigateToProject,this.captureNavigation=r.captureNavigation,this.browserErrors=new Ar(e,t)}managementEntryProject(e){let t=this.getState();if(!(e.machineId!==`local`||N(t)!==`local`||e.projectId!==void 0||e.workspaceId!==void 0||e.sessionId!==void 0||t.isLoadingProjects||this.loadErrors.has(`local`)||t.projects.length!==1))return t.projects[0]}async loadProjects(){let e=N(this.getState());this.loadErrors.delete(e),this.setState({isLoadingProjects:!0});try{let t=await this.api.projects(e);if(N(this.getState())!==e)return;let n=new Set(t.map(e=>e.id)),r=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([e])=>n.has(e)));this.setState({projects:t,workspacesByProjectId:r}),this.onProjectsApplied?.(e)}catch(t){this.loadErrors.set(e,String(t)),this.browserErrors.report(j(e),String(t))}finally{N(this.getState())===e&&this.setState({isLoadingProjects:!1})}}async addProject(e,t,n){if(e.trim()===``)return;let r=N(this.getState()),i=bi(this.getState(),this.captureNavigation),a;try{a=await this.api.addProject(e.trim(),void 0,t,r)}catch(e){this.browserErrors.report(j(r),String(e));return}try{if(N(this.getState())===r){let e=this.getState().projects;this.setState({projects:[...e.filter(e=>e.id!==a.id),a],projectDialogOpen:!1}),this.onProjectsApplied?.(r)}if(n?.changed===!0&&await this.applyTrustChoice(a,n.trusted,r),N(this.getState())!==r)return;this.navigateToProject===void 0?await this.workspaces.selectProject(a):await this.navigateToProject(a,{expected:i})}catch(e){vi(this.browserErrors,xr(r,a.id),e)}}async applyTrustChoice(e,t,n){let r=(await(this.api.workspaces??Xt.workspaces)(e.id,n)).find(t=>t.projectId===e.id&&t.isMain);if(r===void 0)throw new _i(()=>gi.t(`trustUnavailable`,{id:e.id}));await(this.api.setWorkspaceTrust??Xt.setWorkspaceTrust)(e.id,r.id,t,n)}async closeProject(e){let t=N(this.getState());try{if(await this.api.closeProject(e,t),N(this.getState())!==t)return;this.workspaces.forgetProject(e);let n=this.getState();if(this.setState({projects:n.projects.filter(t=>t.id!==e)}),this.onProjectsApplied?.(t),n.selectedProject?.id!==e)return;let r=bi(this.getState(),this.captureNavigation);this.navigateToProject===void 0?this.workspaces.clearSelection():await this.navigateToProject(void 0,{expected:r})}catch(n){this.browserErrors.report(xr(t,e),String(n))}}};function bi(e,t){return t?.()??{machineId:N(e),projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,...e.selectedSession===void 0||Reflect.get(e.selectedSession,`clientPendingStart`)!==!0?{sessionId:e.selectedSession?.id}:{}}}var xi=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.machineGeneration=0,this.activityMachineGeneration=-1,this.projectTopologyGeneration=0,this.nextCwdActivation=0,this.observedActiveCwds=new Set,this.cwdActivations=new Map,this.attemptedCwdActivations=new Map,this.api=n.api??Et,this.onError=n.onError}handleActivityApplied(e){return N(this.getState())===e?(this.activityMachineGeneration=this.machineGeneration,this.reconcile(e)):Promise.resolve()}handleProjectsApplied(e){return N(this.getState())!==e||(this.projectTopologyGeneration+=1,this.attemptedCwdActivations.clear(),this.activePass=void 0,this.activityMachineGeneration!==this.machineGeneration)?Promise.resolve():this.reconcile(e)}handleSelectedMachineChanged(){this.machineGeneration+=1,this.projectTopologyGeneration+=1,this.observedActiveCwds.clear(),this.cwdActivations.clear(),this.attemptedCwdActivations.clear(),this.activePass=void 0}reconcile(e){let t=this.getState();if(N(t)!==e)return Promise.resolve();let n=this.syncActiveCwds(t),r=new Map([...n].filter(([e,n])=>!Si(t.projects,t.workspacesByProjectId,e)&&this.attemptedCwdActivations.get(e)!==n)),i=this.activePass;if(i!==void 0)return(i.machineGeneration!==this.machineGeneration||i.projectTopologyGeneration!==this.projectTopologyGeneration||[...r].some(([e,t])=>i.cwdActivations.get(e)!==t))&&(i.trailingRequested=!0),i.promise;if(r.size===0||t.projects.length===0)return Promise.resolve();let a={machineGeneration:this.machineGeneration,projectTopologyGeneration:this.projectTopologyGeneration,machineId:e,projects:t.projects.map(e=>({id:e.id,path:e.path,startingWorkspaces:t.workspacesByProjectId[e.id]})),cwdActivations:r,trailingRequested:!1,promise:Promise.resolve()};return this.activePass=a,a.promise=this.runPass(a),a.promise}async runPass(e){if(await Promise.all(e.projects.map(async t=>{try{let n=await this.api.workspaces(t.id,e.machineId);this.applyProjectWorkspaces(e,t,n)}catch(n){this.isPassScopeCurrent(e)&&this.reportError({machineId:e.machineId,projectId:t.id,error:n})}})),this.activePass!==e)return;let t=this.getState(),n=this.syncActiveCwds(t);for(let[r,i]of e.cwdActivations)n.get(r)===i&&!Si(t.projects,t.workspacesByProjectId,r)&&this.attemptedCwdActivations.set(r,i);let r=e.trailingRequested;this.activePass=void 0,r&&await this.reconcile(N(this.getState()))}applyProjectWorkspaces(e,t,n){if(this.activePass!==e||!this.isPassScopeCurrent(e))return;let r=this.getState();r.projects.find(e=>e.id===t.id)?.path===t.path&&r.workspacesByProjectId[t.id]===t.startingWorkspaces&&this.setState({workspacesByProjectId:{...r.workspacesByProjectId,[t.id]:n}})}isPassScopeCurrent(e){return e.machineGeneration===this.machineGeneration&&e.projectTopologyGeneration===this.projectTopologyGeneration&&N(this.getState())===e.machineId}syncActiveCwds(e){let t=new Set(Object.values(e.workspaceActivities).filter(Rr).map(e=>e.cwd));for(let e of this.observedActiveCwds)t.has(e)||(this.cwdActivations.delete(e),this.attemptedCwdActivations.delete(e));for(let e of t)this.observedActiveCwds.has(e)||(this.nextCwdActivation+=1,this.cwdActivations.set(e,this.nextCwdActivation),this.attemptedCwdActivations.delete(e));return this.observedActiveCwds=t,new Map([...t].map(e=>[e,this.cwdActivations.get(e)??0]))}reportError(e){if(this.onError!==void 0)try{this.onError(e)}catch{}}};function Si(e,t,n){return e.some(e=>zr(e,t[e.id]??[],n))}var Ci={checkFailed:x(`PI WEB update check failed: {detail}`,`Manual update check failure; detail is an untranslated registry diagnostic`),checkSkipped:x(`PI WEB update check was skipped because remote version checks are disabled by offline/version-check settings`,`Manual update check is disabled by gateway configuration`)},wi=w.registerMessages(`core.piWebStatus`,Ci),Ti=class extends Error{constructor(e){super(),this.displayMessage=e}get message(){return this.displayMessage()}},Ei=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.requestSequence=0,this.api=n.api??ln,this.onRefreshError=n.onRefreshError??(()=>void 0)}async refresh(){let e=N(this.getState());if(this.pendingUpdateCheck?.machineId===e)return;let t=++this.requestSequence;try{let n=await this.api.piWebStatus(e);this.isCurrent(e,t)&&this.setState({piWebStatus:n})}catch(n){if(!this.isCurrent(e,t))return;this.setState({piWebStatus:void 0}),this.onRefreshError(e,n)}}checkForUpdates(){let e=N(this.getState()),t=this.pendingUpdateCheck;if(t?.machineId===e)return t.promise;let n=++this.requestSequence,r=this.api.checkForUpdates(e).then(t=>{this.isCurrent(e,n)&&(this.setState({piWebStatus:t}),Di(t))}).catch(t=>{if(this.isCurrent(e,n))throw t}).finally(()=>{this.pendingUpdateCheck?.requestSequence===n&&(this.pendingUpdateCheck=void 0)});return this.pendingUpdateCheck={machineId:e,requestSequence:n,promise:r},r}isCurrent(e,t){return N(this.getState())===e&&t===this.requestSequence}};function Di(e){let t=e.release.error;if(t!==void 0)throw new Ti(()=>wi.t(`checkFailed`,{detail:t}));if(e.release.skipped===!0)throw new Ti(()=>wi.t(`checkSkipped`))}function Oi(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}var ki=`pi-web:cached-new-sessions:v1`,Ai=`browserCachedNew`,ji=`local`;function Mi(e,t=ji,n=Oi()){if(e.messageCount!==0||e.archived===!0)return;let r=Ri(n).filter(n=>n.id!==e.id||n.machineId!==t);zi([Ni(e,t),...r],n)}function Ni(e,t=ji){return{...e,browserCachedNew:!0,machineId:t}}function Pi(e,t=ji,n=Oi()){zi(Ri(n).filter(n=>n.id!==e||n.machineId!==t),n)}function Fi(e,t,n=ji,r=Oi()){let i=new Set(t.map(e=>e.id)),a=Ri(r),o=a.filter(e=>e.machineId!==n||!i.has(e.id));return o.length!==a.length&&zi(o,r),[...o.filter(t=>t.machineId===n&&t.cwd===e),...t]}function Ii(e){return e!==void 0&&Vi(e)&&e.browserCachedNew===!0}function Li(e){return{id:e.id,path:e.path,cwd:e.cwd,...e.persisted===void 0?{}:{persisted:e.persisted},...e.name===void 0?{}:{name:e.name},created:e.created,modified:e.modified,messageCount:e.messageCount,firstMessage:e.firstMessage,...e.parentSessionPath===void 0?{}:{parentSessionPath:e.parentSessionPath},...e.agentSubsession===!0?{agentSubsession:!0}:{},...`machineId`in e&&typeof e.machineId==`string`?{machineId:e.machineId}:{machineId:ji},...e.archived===!0?{archived:!0}:{},...e.archivedAt===void 0?{}:{archivedAt:e.archivedAt}}}function Ri(e=Oi()){try{let t=e?.getItem(ki);if(t==null||t===``)return[];let n=JSON.parse(t);return Array.isArray(n)?n.flatMap(e=>Bi(e)):[]}catch{return[]}}function zi(e,t=Oi()){try{e.length===0?t?.removeItem(ki):t?.setItem(ki,JSON.stringify(e))}catch{}}function Bi(e){if(!Hi(e))return[];let t=Ui(e,`id`),n=Ui(e,`path`),r=Ui(e,`cwd`),i=Ui(e,`created`),a=Ui(e,`modified`),o=Ui(e,`firstMessage`),s=Gi(e,`messageCount`);if(t===void 0||n===void 0||r===void 0||i===void 0||a===void 0||o===void 0||s!==0)return[];let c=Wi(e,`name`),l=Wi(e,`parentSessionPath`),u=Wi(e,`machineId`)??ji;return[{id:t,path:n,cwd:r,...c===void 0?{}:{name:c},created:i,modified:a,messageCount:s,firstMessage:o,...l===void 0?{}:{parentSessionPath:l},...e.agentSubsession===!0?{agentSubsession:!0}:{},machineId:u,browserCachedNew:!0}]}function Vi(e){return Ai in e}function Hi(e){return typeof e==`object`&&!!e}function Ui(e,t){let n=e[t];return typeof n==`string`?n:void 0}function Wi(e,t){let n=e[t];return n===void 0||typeof n!=`string`?void 0:n}function Gi(e,t){let n=e[t];return typeof n==`number`?n:void 0}var Ki={replacement:()=>`edit text replacement`,edits:e=>`${String(e)} edit${e===1?``:`s`}`,items:e=>`${String(e)} item${e===1?``:`s`}`,object:()=>`object`};function qi(e){return!Xi(e)||typeof e.command==`string`||typeof e.path==`string`?{}:{summaryPresentation:{kind:`arguments`,args:e}}}function Ji(e,t=Ki){if(!Xi(e))return Zi(e);let n=e.command;if(typeof n==`string`)return n;let r=e.path;if(typeof r==`string`)return r;if(typeof e.oldText==`string`&&typeof e.newText==`string`)return t.replacement();let i=e.edits;return Array.isArray(i)?t.edits(i.length):Object.entries(e).filter(([,e])=>e!=null).slice(0,3).map(([e,n])=>`${e}: ${Yi(n,t)}`).join(` · `)}function Yi(e,t){return typeof e==`string`?e.length>80?`${e.slice(0,77)}…`:e:typeof e==`number`||typeof e==`boolean`?String(e):Array.isArray(e)?t.items(e.length):typeof e==`object`&&e?t.object():``}function Xi(e){return typeof e==`object`&&!!e}function Zi(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}function Qi(e,t){let n=[];return e.forEach((e,r)=>{let i=ra(e);i.every(e=>e.parts.length===0)&&I(e,`role`)!==void 0&&n.at(-1)?.parts.at(-1)?.type===`askUserQuestion`&&(i=[{...i[0]??ea({role:pa(I(e,`role`)),parts:[]},e),parts:[{type:`empty`}]}]),n.push(...i.map(e=>t===void 0?e:{...e,transcriptIndex:t+r}))}),Sa(n).filter(e=>e.parts.length>0)}function $i(e,t){return{role:e,parts:[{type:`text`,text:t}]}}function ea(e,t){let n=la(t),r=I(t,`entryId`),i=I(t,`streamId`);return n===void 0&&r===void 0&&i===void 0?e:{...e,...i===void 0?{}:{streamId:i},...n===void 0?{}:{meta:n},...r===void 0||r===``?{}:{entryId:r}}}function ta(e,t,n){if(n===``)return e;let r=e.at(-1),i=r?.parts.at(-1);return r?.role===t&&i?.type===`text`?[...e.slice(0,-1),{...r,parts:[...r.parts.slice(0,-1),{type:`text`,text:i.text+n}]}]:r?.role===t?[...e.slice(0,-1),{...r,parts:[...r.parts,{type:`text`,text:n}]}]:[...e,$i(t,n)]}function na(e,t){if(t===``)return e;let n=e.at(-1),r=n?.parts.at(-1);return n?.role===`assistant`&&r?.type===`thinking`?[...e.slice(0,-1),{...n,parts:[...n.parts.slice(0,-1),{type:`thinking`,text:r.text+t}]}]:n?.role===`assistant`?[...e.slice(0,-1),{...n,parts:[...n.parts,{type:`thinking`,text:t}]}]:[...e,{role:`assistant`,parts:[{type:`thinking`,text:t}]}]}function ra(e){if(I(e,`role`)===`custom`&&ka(e,`display`)===!1)return[];if(aa(e))return e.parts.some(e=>I(e,`type`)===`image`)?[{...e,parts:e.parts.flatMap(e=>I(e,`type`)===`image`?ha(e):[e])}]:[e];if(I(e,`role`)===`bashExecution`)return[ea(fa(e),e)];let t=I(e,`role`),n=pa(t),r=Oa(e,`content`),i=ma(r,e),a=I(e,`customType`);if(t===`custom`&&a!==void 0){let t=Oa(e,`details`);return[ea({role:`system`,parts:[{type:`customMessage`,customType:a,content:r,...t===void 0?{}:{details:t},parts:i.filter(e=>e.type!==`empty`)}]},e)]}let o=t===`toolResult`?va(I(e,`toolName`)??``,Oa(e,`details`)):void 0,s=t===`toolResult`?_a(I(e,`toolName`)??``,Oa(e,`details`),ka(e,`isError`)===!0):void 0,c=[...t===`toolResult`&&!i.some(e=>e.type===`toolResult`)?[ba(i.flatMap(e=>e.type===`text`?[e.text]:[]).join(`
31
31
  `),e),...i.filter(e=>e.type===`image`)]:i,...o===void 0?[]:[o],...s===void 0?[]:[s]],l=n===`user`?oa(c):void 0;if(l!==void 0)return l.map(t=>ea(t,e));let u=ca(e);if(n===`tool`)return[ea({role:n,parts:c,...u===void 0?{}:{source:u}},e)];let d=c.filter(e=>e.type!==`empty`),f=n===`assistant`&&d.length>0&&d.every(e=>e.type===`skillRead`)?`skill`:n,p=d.length>0?[ea({role:f,parts:d,...u===void 0?{}:{source:u}},e)]:[],m=ia(e);return m===void 0?p:[...p,ea(m,e)]}function ia(e){if(I(e,`role`)!==`assistant`||I(e,`stopReason`)!==`error`)return;let t=I(e,`errorMessage`)?.trim();return{role:`system`,parts:[{type:`text`,text:`Model response failed: ${t===void 0||t===``?`The model returned an error.`:t}`,presentation:{kind:`modelError`,detail:t??``}}]}}function aa(e){let t=I(e,`role`);return(t===`user`||t===`assistant`||t===`tool`||t===`system`||t===`bash`||t===`skill`)&&Array.isArray(Oa(e,`parts`))}function oa(e){if(e.length!==1||e[0]?.type!==`text`)return;let t=sa(e[0].text);if(t!==void 0)return[{role:`user`,parts:[{type:`skillInvocation`,name:t.name,location:t.location,content:t.content}]},...t.userMessage===void 0?[]:[{role:`user`,parts:[{type:`text`,text:t.userMessage}]}]]}function sa(e){let t=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/.exec(e);if(t===null)return;let n=t[4]?.trim();return{name:t[1]??`skill`,location:t[2]??``,content:t[3]??``,...n===void 0||n===``?{}:{userMessage:n}}}function ca(e){let t=I(e,`source`);if(t===`compaction`||t===`branch_summary`)return t}function la(e){let t=ua(Oa(e,`timestamp`)),n=da(e),r=I(e,`thinkingLevel`);if(t!==void 0||n!==void 0||r!==void 0&&r!==``)return{...t===void 0?{}:{timestamp:t},...n===void 0?{}:{model:n},...r===void 0||r===``?{}:{thinkingLevel:r}}}function ua(e){if(typeof e==`number`&&Number.isFinite(e))return new Date(e).toISOString();if(typeof e!=`string`||e===``)return;let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():void 0}function da(e){if(I(e,`role`)!==`assistant`)return;let t=I(e,`provider`),n=I(e,`model`),r=I(e,`responseModel`);if(t!==void 0&&t!==``||n!==void 0&&n!==``||r!==void 0&&r!==``)return{...t===void 0||t===``?{}:{provider:t},...n===void 0||n===``?{}:{id:n},...r===void 0||r===``?{}:{responseId:r}}}function fa(e){let t=I(e,`command`)??``,n=ka(e,`excludeFromContext`)===!0?[`excluded from context`,``,`$ ${t}`]:[`$ ${t}`],r=Oa(e,`output`);r!=null&&n.push(``,ja(r));let i=Oa(e,`exitCode`);i!=null&&n.push(``,`exit ${ja(i)}`),ka(e,`cancelled`)===!0&&n.push(``,`cancelled`),ka(e,`truncated`)===!0&&n.push(``,`output truncated`);let a=I(e,`fullOutputPath`);return a!==void 0&&a!==``&&n.push(``,`full output: ${a}`),{role:`bash`,parts:[{type:`text`,text:n.join(`
32
32
  `),presentation:{kind:`bash`,command:t,excluded:ka(e,`excludeFromContext`)===!0,cancelled:ka(e,`cancelled`)===!0,truncated:ka(e,`truncated`)===!0,...r==null?{}:{output:ja(r)},...i==null?{}:{exitCode:ja(i)},...a===void 0||a===``?{}:{fullOutputPath:a}}}]}}function pa(e){return e===`assistant`?`assistant`:e===`user`?`user`:e===`toolResult`?`tool`:`system`}function ma(e,t){let n=ga(t);if(n!==void 0)return[n];if(typeof e==`string`){let n=I(t,`displayText`);return e===``?[]:[{type:`text`,text:e,...n===void 0?{}:{displayText:n}}]}return Array.isArray(e)?e.flatMap(e=>{let t=I(e,`type`),n=I(e,`text`),r=I(e,`displayText`),i=r===void 0?{}:{displayText:r};if(t===`text`)return n!==void 0&&n!==``?[{type:`text`,text:n,...i}]:[];if(t===`thinking`){let t=I(e,`thinking`)??n;return t!==void 0&&t!==``?[{type:`thinking`,text:t,...i}]:[]}if(t===`toolCall`){let t=I(e,`name`)??`tool`,n=Oa(e,`arguments`),r=I(e,`id`),i=t===`read`?xa(I(n,`path`)):void 0;return i===void 0?[{type:`toolCall`,...r===void 0?{}:{toolCallId:r},toolName:t,summary:Ji(n),...qi(n),...n===void 0?{}:{args:n}}]:[{type:`skillRead`,...i,...r===void 0?{}:{toolCallId:r}}]}return t===`image`?ha(e):Ea(e)}).map(e=>e.type===`text`&&I(t,`role`)===`toolResult`?ba(e.text,t):e):Ea(e)}function ha(e){let t=I(e,`mimeType`),n=Oa(e,`mediaId`),r=ct(Oa(e,`width`),Oa(e,`height`));if(n!==void 0){let i=Aa(e,`byteSize`);if(Wt(n)&&t!==void 0&&/^image\/[a-z0-9][a-z0-9.+-]*$/iu.test(t)&&i!==void 0&&Number.isSafeInteger(i)&&i>=0)return[{type:`image`,mediaId:n,mimeType:t,byteSize:i,...r}]}else{let n=I(e,`data`);if(n!==void 0&&n!==``&&t!==void 0&&t!==``)return[{type:`image`,mimeType:t,data:n,...r}]}return[{type:`text`,text:`[image]`,presentation:{kind:`imagePlaceholder`}}]}function ga(e){if(I(e,`role`)===`custom`&&I(e,`customType`)===`pi-web.ask.answers`)return ya(Oa(e,`details`))}function _a(e,t,n){if(!(e!==`ask_user`||n))try{return{type:`askUserQuestion`,ask:yt(Oa(t,`ask`))}}catch{return}}function va(e,t){if(e===`ask_user`)return ya(Oa(t,`superseded`))}function ya(e){try{return{type:`askUserRecord`,outcome:Ut(e)}}catch{return}}function ba(e,t){let n=I(t,`toolCallId`),r=Oa(t,`content`),i=Oa(t,`details`);return{type:`toolResult`,...n===void 0?{}:{toolCallId:n},toolName:I(t,`toolName`)??`tool`,text:e,...r===void 0?{}:{content:r},...i===void 0?{}:{details:i},isError:ka(t,`isError`)===!0}}function xa(e){if(e===void 0||e===``)return;let t=e.replace(/\\/g,`/`);if(!t.endsWith(`/SKILL.md`)&&t!==`SKILL.md`)return;let n=t.split(`/`).at(-2);if(n!==void 0&&n!==``)return{name:n,path:e}}function Sa(e){let t=[],n=new Map;for(let r of e){let e=[],i={...r.streamId===void 0?{}:{streamId:r.streamId},...r.entryId===void 0?{}:{entryId:r.entryId},...r.transcriptIndex===void 0?{}:{transcriptIndex:r.transcriptIndex},...r.source===void 0?{}:{source:r.source},...r.meta===void 0?{}:{meta:r.meta}},a=()=>{e.length!==0&&(t.push({role:r.role,parts:e,...i}),e=[])};for(let o of r.parts)if(o.type===`toolCall`){a();let e=Ca(o),r=t.length;t.push({role:`tool`,parts:[e],...i}),e.toolCallId!==void 0&&n.set(e.toolCallId,{lineIndex:r,partIndex:0})}else{if(o.type===`toolResult`){let i=o.toolCallId===void 0?void 0:n.get(o.toolCallId);if(i!==void 0&&wa(t,i,o,r.meta)){n.delete(o.toolCallId??``),t.at(-1)?.parts.at(-1)?.type===`askUserQuestion`&&!r.parts.some(e=>e.type===`askUserQuestion`||e.type===`askUserRecord`)&&e.push({type:`toolResultBoundary`,...o.toolCallId===void 0?{}:{toolCallId:o.toolCallId}});continue}}o.type===`askUserQuestion`||o.type===`askUserRecord`?(a(),t.push({role:r.role,parts:[o],...i})):e.push(o)}a()}return t}function Ca(e){return{type:`toolExecution`,...e.toolCallId===void 0?{}:{toolCallId:e.toolCallId},toolName:e.toolName,summary:e.summary,...e.summaryPresentation===void 0?{}:{summaryPresentation:e.summaryPresentation},...e.args===void 0?{}:{args:e.args},status:`pending`}}function wa(e,t,n,r){let i=e[t.lineIndex],a=i?.parts[t.partIndex];if(i===void 0||a?.type!==`toolExecution`)return!1;let o=Ta(n.details)??a.preview,s={...a,status:n.isError?`error`:`success`,resultText:n.text,...n.content===void 0?{}:{content:n.content},...n.details===void 0?{}:{details:n.details},...o===void 0?{}:{preview:o}};return e[t.lineIndex]={...i,parts:[...i.parts.slice(0,t.partIndex),s,...i.parts.slice(t.partIndex+1)],...r===void 0?{}:{meta:r}},!0}function Ta(e){let t=Oa(e,`preview`);if(!Da(t))return;let n=I(t,`diff`),r=I(t,`error`),i=Aa(t,`firstChangedLine`);if(n!==void 0||r!==void 0||i!==void 0)return{...n===void 0?{}:{diff:n},...r===void 0?{}:{error:r},...i===void 0?{}:{firstChangedLine:i}}}function Ea(e){return e==null?[]:typeof e==`object`?[{type:`text`,text:Ji(e),presentation:{kind:`arguments`,args:e}}]:[{type:`text`,text:ja(e)}]}function Da(e){return typeof e==`object`&&!!e}function Oa(e,t){return Da(e)?e[t]:void 0}function I(e,t){let n=Oa(e,t);return typeof n==`string`?n:void 0}function ka(e,t){let n=Oa(e,t);return typeof n==`boolean`?n:void 0}function Aa(e,t){let n=Oa(e,t);return typeof n==`number`&&Number.isFinite(n)?n:void 0}function ja(e){return e==null?``:typeof e==`string`?e:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?String(e):``}var Ma={forkCancelled:x(`Fork cancelled`,`Built-in session command feedback. Keep slash commands and PI WEB unchanged.`),forked:x(`Session forked`,`Built-in session command feedback. Keep slash commands and PI WEB unchanged.`),nameUsage:x(`Usage: /name '<session name>'`,`Built-in session command feedback. Keep slash commands and PI WEB unchanged.`),requestExpired:x(`Command request expired`,`Built-in session command feedback. Keep slash commands and PI WEB unchanged.`),reloadActive:x(`Cannot reload while the session is active. Stop current activity before reloading.`,`Built-in session command feedback. Keep slash commands and PI WEB unchanged.`),reloadUnavailable:x(`/reload is not available for this session runtime.`,`Built-in session command feedback. Keep slash commands and PI WEB unchanged.`),reloaded:x(`Session runtime resources reloaded. Extensions, skills, prompt templates, themes, and context/system prompt files are refreshed for this session. Reload the browser page separately for PI WEB browser plugin changes.`,`Built-in session command feedback. Keep slash commands and PI WEB unchanged.`),cloneEmpty:x(`Cannot clone: no current session entry`,`Built-in session command feedback. Keep slash commands and PI WEB unchanged.`),cloneCancelled:x(`Clone cancelled`,`Built-in session command feedback. Keep slash commands and PI WEB unchanged.`),cloned:x(`Session cloned`,`Built-in session command feedback. Keep slash commands and PI WEB unchanged.`),forkEmpty:x(`No user messages to fork from`,`Built-in session command feedback. Keep slash commands and PI WEB unchanged.`),forkSelect:x(`Fork from message`,`Built-in session command feedback. Keep slash commands and PI WEB unchanged.`),treeActive:x(`Cannot open the session tree while the session is active. Stop current activity and try /tree again.`,`Built-in session command feedback. Keep slash commands and PI WEB unchanged.`),treeEmpty:x(`Cannot navigate an empty session tree.`,`Built-in session command feedback. Keep slash commands and PI WEB unchanged.`),treeUnavailable:x(`Session tree navigation is not available with this Pi runtime.`,`Built-in session command feedback. Keep slash commands and PI WEB unchanged.`),navigationActive:x(`Cannot run commands while session tree navigation is active. Stop or finish the navigation first.`,`Built-in session command feedback. Keep slash commands and PI WEB unchanged.`),unknown:x(`Unknown command: /{command}`,`Command name is an unchanged identifier`),notImplemented:x(`/{command} is not implemented in the web UI yet`,`Command name is an unchanged identifier`),named:x(`Session named: {name}`,`User-provided session name is unchanged`),reloadFailed:x(`Reload failed: {detail}`,`Detail is an untranslated runtime diagnostic`),treeFailed:x(`Unable to open the session tree: {detail}`,`Detail is an untranslated runtime diagnostic`),replacementActive:x(`{command, select, fork {Cannot fork while the session is active. Stop current activity before forking.} other {Cannot clone while the session is active. Stop current activity before cloning.}}`,`Blocked session replacement; command is fork or clone`),stats:x(`Session: {sessionId}
33
33
  Messages: {totalMessages, number} ({userMessages, number} user, {assistantMessages, number} assistant)
@@ -52,7 +52,7 @@ Cost: {cost}`,`Session statistics. ID is raw; cost is regional USD with four fra
52
52
  `)+1,r=e.slice(n),i=vc(r,`@ `),a=vc(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 vc(e,t){for(let n=e.lastIndexOf(t);n>=0;n=e.lastIndexOf(t,n-1))if(n===0||yc(e[n-1]))return n;return-1}function yc(e){return e===` `||e===` `}function bc(e){let t=e.trimStart();if(t.startsWith(`!@`))return{kind:`file`};if(t.startsWith(`!`))return{kind:`shell`,excludeFromContext:t.startsWith(`!!`)};if(Cc(e).startsWith(`/`))return{kind:`command`};let n=uc(e);return n?.kind===`file`?{kind:`file`}:n?.kind===`model`?{kind:`model`}:{kind:`normal`}}function xc(e){return bc(e).kind===`shell`}function Sc(e,t){return e.kind===t.kind?e.kind===`shell`&&t.kind===`shell`?e.excludeFromContext===t.excludeFromContext:!0:!1}function Cc(e){let t=Math.max(e.lastIndexOf(` `),e.lastIndexOf(`
53
53
  `))+1;return e.slice(t)}var wc=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,a){this.close(),this.machineId=r,this.session=e,this.onEvent=t,this.onReconnect=n,this.onInitialOpen=i,this.onConnectionState=a,this.shouldReconnect=!0,this.open()}setHandler(e){this.onEvent=e}reconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.socket;this.socket=void 0,Mc(e),this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Mc(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.onInitialOpen=void 0,this.onConnectionState=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=gr(e,this.machineId,this.scope);t.binaryType=`arraybuffer`,this.socket=t,this.onConnectionState?.(`connecting`),t.onopen=()=>{if(this.socket!==t)return;this.reconnectDelay=500;let e=this.hasOpened;this.hasOpened=!0,this.onConnectionState?.(`open`),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.onConnectionState?.(`connecting`),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=Ec(await jc(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))}},Tc=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()}reconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.socket;this.socket=void 0,Mc(e),this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Mc(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId=`local`}open(){if(!this.shouldReconnect)return;let e=_r(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=Dc(await jc(e));this.socket===t&&n!==void 0&&this.onEvent?.(n)}};function Ec(e){let t=Ac(e);if(t===`notifications.inbox`)return kc(()=>vt(e));if(t===`dialog.opened`)return kc(()=>gt(e));if(t===`dialog.closed`)return kc(()=>pt(e));let n=kc(()=>un(e));return n===void 0?void 0:Oc(n,e)}function Dc(e){if(Ac(e)===`notices.updated`)return kc(()=>St(e));if(Ac(e)===`sessions.unread`)return kc(()=>lt(e));if(Ac(e)===`session.startup`)return kc(()=>wt(e));if(typeof e==`object`&&e){if(Ac(e)===`terminal.created`||Ac(e)===`terminal.exited`){if(!(`terminal`in e))return;let t=kc(()=>ht(e.terminal));return t===void 0?void 0:{type:Ac(e)===`terminal.created`?`terminal.created`:`terminal.exited`,terminal:t}}if(Ac(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(Ac(e)===`workspace.activity`){if(!(`activity`in e))return;let t=kc(()=>Dt(e.activity));return t===void 0?void 0:{type:`workspace.activity`,activity:t}}}return kc(()=>bt(e))}function Oc(e,t){return typeof t!=`object`||!t||!(`seq`in t)?e:typeof t.seq==`number`?{...e,seq:t.seq}:e}function kc(e){try{return e()}catch{return}}function Ac(e){if(typeof e!=`object`||!e||!(`type`in e))return``;let t=e.type;return typeof t==`string`?t:``}async function jc(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 Mc(e){e!==void 0&&(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING?e.onopen=()=>{e.close()}:e.close())}function Nc(e){return e?.ok===!0}function Pc(e){return{authoritative:Nc(e)}}function Fc(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||Ii(e)?`transient`:n.authoritative===!0?`unknown`:`persisted`}function Ic(e,t,n){return e!==void 0&&e.archived!==!0&&Fc(e,t,n)===`persisted`}function Lc(e,t,n){return e!==void 0&&e.archived!==!0&&Fc(e,t,n)===`transient`}function Rc(){try{return typeof sessionStorage>`u`?void 0:sessionStorage}catch{return}}var zc=class{constructor(e,t,n=Rc()){this.storageKey=e,this.storage=n,this.values=new Map;for(let[r,i]of Vc(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 Bc(e){return typeof e==`string`&&e!==``?e:void 0}function Vc(e,t,n){try{let r=n?.getItem(e);if(r==null||r===``)return[];let i=JSON.parse(r);if(!Hc(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 Hc(e){return!Uc(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 Uc(e){return typeof e==`object`&&!!e}var Wc=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)}},Gc=`pi-web:session-selection:v1`,Kc=class{constructor(e=Rc()){this.sessionIdsByCwd=new zc(Gc,Bc,e)}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}};function qc(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 Jc(e,t){return t?.archived===!0&&!e.some(e=>e.archived!==!0)}function Yc(e,t,n){return Xc(e,[t],n)}function Xc(e,t,n){let r=new Set(t);return e.map(e=>r.has(e.id)?{...e,archived:!0,archivedAt:n}:e)}function Zc(e,t,n){return Qc(e,t,[n])}function Qc(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 $c=/timed out|operation was aborted|request cancelled/i;function el(e){return e instanceof ne&&(e.status===504||e.status===499)||e instanceof Error&&$c.test(e.message)}function tl(e){return el(e)?C(`ui.main.634a1618e706`,`The session daemon request timed out. The conversation is still running.`):e instanceof Error?e.message:String(e)}var nl=[500,1500,3e3],rl=Symbol(`retired-read`);async function il(e,t,n,r=!0){let i=()=>n?.aborted!==!0&&t(),a=0;for(;i();)try{let t=await al(e(),n);return t!==rl&&i()?t:void 0}catch(e){if(n?.aborted===!0||r&&!t())return;let i=nl[a];if(!r||!(e instanceof d)||i===void 0)throw e;let o;try{await al(new Promise(e=>{o=setTimeout(e,i)}),n)}finally{o!==void 0&&clearTimeout(o)}a+=1}}function al(e,t){if(t===void 0)return e;let n=()=>void 0,r=new Promise(e=>{n=()=>{e(rl)},t.addEventListener(`abort`,n,{once:!0}),t.aborted&&n()});return Promise.race([e,r]).finally(()=>{t.removeEventListener(`abort`,n)})}var ol={newSession:x(`New session`,`Temporary session row name before backend creation completes`),creating:x(`Creating session`,`Pending session startup activity label`),waiting:x(`Waiting for the backend session to be ready`,`Pending session startup detail without queued sends`),queued:x(`{count, plural, one {# queued message will send when the backend session is ready} other {# queued messages will send when the backend session is ready}}`,`Startup detail showing locally retained sends`),failed:x(`Session creation failed`,`Failed pending session activity label`),failedDetail:x(`{count, plural, =0 {{detail}} one {{detail} · # queued message kept below} other {{detail} · # queued messages kept below}}`,`Failed startup detail; detail is an untranslated runtime diagnostic`),startFailure:x(`Failed to start session: {detail}`,`Startup failure banner; detail is an untranslated diagnostic`),queueUnavailable:x(`The backend session is not ready for queued sends. Copy your message before discarding this failed start.`,`Recovery guidance when sending to a failed temporary session`),commandInput:x(`Queued command “{command}” needs input; open the session and run it again.`,`Queued command needs an interactive response; command is raw user input`),navigationChanged:x(`Session started, but its navigation changed before selection completed. Select it from the session list.`,`Started session could not be selected because navigation changed`),selectionChanged:x(`Session started, but its selection changed before navigation completed. Select it from the session list.`,`Started session selection changed during navigation`),selectionFailure:x(`Session started, but it could not be selected: {detail}`,`Started session navigation failed; detail is an untranslated diagnostic`),attachments:x(`[{count, plural, one {# attachment queued} other {# attachments queued}}]`,`Queued attachment preview without filenames`),namedAttachments:x(`[{count, plural, one {# attachment queued} other {# attachments queued}}: {names}{remaining, plural, =0 {} other {, +# more}}]`,`Queued attachment preview; names are raw filenames, at most three, remaining counts omitted filenames`),promptAttachments:x(`{text}
54
54
 
55
- {attachments}`,`Queued prompt preview with attachment summary; text is raw user content`)},sl=w.registerMessages(`core.pendingSession`,ol),cl=class extends Error{constructor(e){super(),this.displayMessage=e}get message(){return this.displayMessage()}toString(){return this.message}},ll={archiveFailure:x(`Archive failed: {detail}`,`Bulk archive request failed; detail is an untranslated runtime diagnostic`),deleteFailure:x(`Delete failed: {detail}`,`Bulk delete request failed; detail is an untranslated runtime diagnostic`),archivePartialFailure:x(`Archive failed for {count, plural, one {# session} other {# sessions}}: {details}`,`Bulk archive partial failures; details contain raw session identifiers and runtime diagnostics`),deletePartialFailure:x(`Delete failed for {count, plural, one {# session} other {# sessions}}: {details}`,`Bulk delete partial failures; details contain raw session identifiers and runtime diagnostics`),sessionListRefresh:x(`The session list could not be refreshed. Check your connection and retry.`,`Workspace session-list network recovery exhausted`),conversationRefresh:x(`The conversation could not be refreshed. Check your connection and retry.`,`Selected conversation network recovery exhausted`)},ul=w.registerMessages(`core.sessionFeedback`,ll),dl=class extends Error{constructor(e){super(),this.displayMessage=e}get message(){return this.displayMessage()}toString(){return this.message}},fl=100,pl=500,ml=5e3,hl=[`machine`,`project`,`workspace`,`session`],gl=[`machine`,`project`,`workspace`,`session`],_l=class{constructor(e,t,n,r=new Wc,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.sessionConnectionOpen=!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 Ur,this.workspaceSessionRefreshes=new Ur,this.socket=i.socket??new wc,this.api=i.api??Xt,this.transcripts=i.transcripts??new sc,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 Ar(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.searchAbort?.abort(),this.searchAbort=void 0,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}))},ml))}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.sessionConnectionOpen=!1,this.setState({selectedSession:void 0,conversationSync:void 0,conversationRefreshedAt: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();Jc(this.automaticSessionCandidates(e.sessions),e.selectedSession)&&await this.clearSessionAfterNavigation(this.navigationSelection())}async startSession(e){let t=this.getState().selectedWorkspace;if(!t)return;let n=N(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?.(hl);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=N(this.getState())){try{let n=await this.api.pinned(e,t);if(N(this.getState())!==t||this.getState().selectedWorkspace?.path!==e)return;this.setState({pinnedSessionIds:n.sessionIds})}catch{N(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=N(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(N(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(N(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=N(t);this.searchSeq+=1;let i=this.searchSeq;this.searchAbort?.abort(),this.searchAbort=void 0,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){let a=new AbortController;this.searchAbort=a;try{let o=await this.api.searchContent(r,t,i,{signal:a.signal}),s=this.getState();if(e!==this.searchSeq||N(s)!==i||s.selectedWorkspace?.id!==n||s.selectedWorkspace.path!==r||s.sessionSearchQuery.trim()!==t)return;this.setState({sessionSearchResults:o,isSearchingSessions:!1})}catch(t){let a=this.getState();if(e!==this.searchSeq||N(a)!==i||a.selectedWorkspace?.id!==n||a.selectedWorkspace.path!==r)return;this.setState({sessionSearchResults:{results:[],matchCount:0,truncated:!1},isSearchingSessions:!1,sessionSearchError:String(t)})}finally{this.searchAbort===a&&(this.searchAbort=void 0)}}preferredSession(e,t,n){if(go(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 qc(t,{targetSessionId:n});let r=p()?t.filter(e=>!Ii(e)):t,i=this.sessionSelection.latestSessionId(this.workspaceSelectionKey(e));return i!==void 0&&i!==``&&r.some(e=>e.id===i)?qc(r,{latestSessionId:i}):qc(this.automaticSessionCandidates(r))}canReuseSelectedSession(){return!this.disposed&&Ll(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?.(gl);await this.selectSession(e,{updateUrl:!1,navigation:t})}async selectSession(e,t){if(this.disposed||!Ll(t?.navigation))return;if(this.retireReadRecoveries([`session`]),wl(e)){this.selectClientPendingStartSession(e,t);return}let n=N(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.sessionConnectionOpen=!1,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,conversationSync:e.archived===!0?void 0:`catching-up`,conversationRefreshedAt: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(Cr(n,e.id,r),`session-refresh`),s=await this.api.messages(e,{limit:fl},n),c=this.getState().selectedSession;if(i!==this.selectionSeq||N(this.getState())!==n||c?.id!==e.id||c.cwd!==e.cwd||c.path!==e.path||c.archived!==e.archived||!Ll(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,()=>{this.isCurrentSessionSelection(e.id,n,i)&&this.isSelectedSessionScope(e,n)&&this.refreshSelectedSession(e.id,{recoverNetwork:!0})},t=>{this.isCurrentSessionSelection(e.id,n,i)&&this.updateSubscriptionState(t)}),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)||!Ll(t?.navigation))return;this.refreshAvailableThinkingLevels(),this.onSelectedSessionReady?.({machineId:n,session:e}),t?.updateUrl!==!1&&this.updateUrl()}catch(a){let o=Ll(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(Ii(e)&&Il(a)){await this.recreateCachedNewSession(e,t,i,r);return}if(this.reportSessionError(e,n,a,r),t?.propagateRefreshError===!0)throw a}finally{let r=Ll(t?.navigation);i===this.selectionSeq&&r&&(this.selectedSessionJoinNavigation=void 0),s&&!Ll(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=N(e),r=this.captureSessionErrorOwner(t),i=this.selectionSeq,a=M(n,t.id),o=this.transcripts.historyRevision(a),s=()=>{let e=this.getState();return!this.disposed&&i===this.selectionSeq&&N(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:fl},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&&(!Eo(a,{machineId:N(o),sessionId:s.id,cwd:s.cwd})||wl(s)))return!1;let c=e.trim(),l=n!==void 0&&n.length>0,u=a!==void 0;if(wl(s))return!l&&c.startsWith(`/`)?this.enqueuePendingSessionSend(s,{type:`command`,text:e}):!l&&xc(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&&xc(e))return await this.runShell(e),!1;let d=N(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:bl(n,e)})}async runShell(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;if(wl(t)){this.enqueuePendingSessionSend(t,{type:`shell`,text:e});return}let n=N(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(wl(t)){this.enqueuePendingSessionSend(t,{type:`command`,text:e});return}let n=N(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===``||!Ic(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let r=N(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||N(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:C(`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=n===void 0?this.captureSessionErrorOwner(e):this.captureSessionErrorOwner(e,n.originWorkspace);this.reportSessionError(e,e.machineId,new cl(()=>sl.t(`queueUnavailable`)),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=El(e.id,n.queuedSends.length);this.setState({clientQueuedSessionMessages:{...i.clientQueuedSessionMessages,[e.id]:[...a,Ol(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=>hc(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,$i(`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,$i(`system`,tl(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,new cl(()=>sl.t(`commandInput`,{command:t})),i),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,$i(`system`,tl(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?bl(t.clientQueuedSessionMessages,e):{...t.clientQueuedSessionMessages,[e]:r}})}async respondToCommand(e,t){let n=this.getState().selectedSession;if(!n)return;let r=N(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||wl(r))return;let i=N(n),a=this.selectionSeq,o=this.captureSessionErrorOwner(r),s;try{if(s=await this.api.runCommand(r,`/tree`,i),s.type!==`tree`)throw`message`in s?s.presentation===void 0?Error(s.message):new Fa(s.presentation):new Zn(`historyUnavailable`);if(!s.tree.nodes.some(t=>t.id===e))throw new Zn(`messageUnavailable`)}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||wl(a))throw new Zn(`treeUnavailable`);let o={...a},s=N(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,()=>{this.setTreeActionPending(l,!1)}),i}catch(e){throw this.reportSessionError(o,s,e,c),e}finally{this.setTreeActionPending(l,!1)}}async applySessionTreeNavigationResult(e,t,n,r,i){if(n.cancelled||this.disposed)return;if(this.hasDraftIdentityConflict(e,t)){this.reportSessionError(e,t,C(`client.sessionController.queueContextChanged`,`The conversation context changed before the result returned. The current draft was preserved.`));return}let a=M(t,e.id),o=n.editorText;if(o!==void 0&&No(a,o),this.transcripts.discard(a),!this.isSelectedSessionScope(e,t))return;this.clearPendingUpdates();let s=this.selectionSeq,c=()=>this.isCurrentSessionSelection(e.id,t,s)&&this.isSelectedSessionScope(e,t),l=(async()=>{o!==void 0&&c()&&(await this.replacePromptEditorText?.({machineId:t,sessionId:e.id,text:o,isCurrent:c}),c()&&i?.())})(),[u,d]=await Promise.allSettled([l,this.requestSelectedSessionRefresh({session:e,machineId:t,selectionSeq:s,errorOwner:this.captureSessionErrorOwner(e)})]);if(c()){if(u.status===`rejected`)throw u.reason;if(d.status===`rejected`)throw d.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||wl(i))throw new Zn(`treeUnavailable`);let a={...i},o=N(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=M(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&&No(M(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||wl(t))return;let n=N(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 p()?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);No(M(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=N(e);t!==void 0&&this.isSelectedSessionIdentity(t.id,n)&&(this.transcripts.discard(M(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(Lc(e,t,n)){await this.deleteCachedNewSession(e);return}if(!Ic(e,t,n))return;let r=N(this.getState()),i=this.captureSessionErrorOwner(e);try{await this.api.archive(e,r,this.archiveScopeProjectId());let t=this.getState(),n=Yc(t.sessions,e.id,new Date().toISOString()),i=Zc(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||!Ic(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=N(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=Xc(i.sessions,r,new Date().toISOString()),o=Qc(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=jl(e).filter(e=>Ic(e,this.statusForSession(e),t));if(n.length===0)return;let r=N(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=Xc(t.sessions,e,s??new Date().toISOString()),r=Qc(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(`archive`,t,r,i,a,o)}catch(e){this.reportWorkspaceOrSessionError(i,a,r,new dl(()=>ul.t(`archiveFailure`,{detail:Nl(e)})),o)}}async deleteArchivedSessions(e){let t=jl(e).filter(e=>e.archived===!0);if(t.length===0)return;let n=N(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(`delete`,o,n,r,i,a)}catch(e){this.reportWorkspaceOrSessionError(r,i,n,new dl(()=>ul.t(`deleteFailure`,{detail:Nl(e)})),a)}}async archiveSessionBatch(e,t){let n=await this.api.archiveMany(e,t,this.archiveScopeProjectId());return{succeededIds:n.archivedSessionIds,failures:Ml(n.failures),generatedAt:n.generatedAt}}async deleteArchivedSessionBatch(e,t){let n=await this.api.deleteArchivedMany(e,t,this.archiveScopeProjectId());return{succeededIds:n.deletedSessionIds,failures:Ml(n.failures)}}async applySessionCleanupResult(e,t=N(this.getState())){if(N(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=Xc(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:xl(t.sessionStatuses,a),sessionActivities:xl(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=Qc(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=N(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&&Ll(i)&&N(this.getState())===e&&this.getState().selectedWorkspace?.id===n.id&&this.getState().selectedWorkspace?.projectId===n.projectId&&this.getState().selectedWorkspace?.path===n.path,o=Sr(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 il(i,a,s.signal,t?.recoverNetwork===!0)}finally{this.workspaceReadRecoveries.delete(s)}if(c===void 0||!a())return;this.browserErrors.clearRecovered(r);let l=Fi(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){if(d.archived!==!0&&p.archived===!0){let e=Zc(this.automaticSessionCandidates(u),d.id,d.id);e.type===`select`?await this.selectSessionAfterNavigation(e.session,f):e.type===`clear`&&await this.clearSessionAfterNavigation(f)}else d.archived===!0&&p.archived!==!0?await this.selectSessionAfterNavigation(p,f):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 d){this.browserErrors.reportLocalized(o,()=>ul.t(`sessionListRefresh`),`workspace-sessions-refresh`);return}if(el(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||!Lc(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=wl(e)?this.pendingSessionStarts.get(e.id):void 0;t===void 0?this.api.stop(e,N(this.getState())).catch(()=>{}):(t.discarded=!0,t.queuedSends=[]),Pi(e.id,N(this.getState())),Po(this.sessionCacheKey(e.id)),Bo(this.sessionCacheKey(e.id));let n=this.getState(),r=n.sessions.filter(t=>t.id!==e.id);if(this.setState({sessions:r,sessionStatuses:bl(n.sessionStatuses,e.id),sessionActivities:yl(n.sessionActivities,e.id),sendingPrompts:bl(n.sendingPrompts,e.id),clientQueuedSessionMessages:bl(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=N(this.getState()),n=this.captureSessionErrorOwner(e),r=this.selectionSeq,i=this.beginNavigationOperation?.(gl);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;return this.replaceSession(a),o&&await this.selectSession(a,{updateUrl:!1,...i===void 0?{}:{navigation:i}}),a}async reloadSession(e=this.getState().selectedSession){if(e===void 0||!Ic(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=N(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.reloadSession(e,t),this.transcripts.discard(M(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=N(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.detachParent(e,t);let n=this.getState();if(this.disposed||N(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=N(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=N(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=N(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=N(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=N(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=N(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=N(this.getState()),i=this.captureSessionErrorOwner(n);try{let i=await this.api.setModel(n,e,t,r);if(N(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=N(this.getState()),r=this.captureSessionErrorOwner(t);try{let r=await this.api.cycleModel(t,e,n);if(N(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=N(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=N(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=N(this.getState()),r=this.captureSessionErrorOwner(t);try{let r=await this.api.setThinkingLevel(t,e,n);if(N(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=N(this.getState()),n=this.captureSessionErrorOwner(e);try{let n=await this.api.cycleThinkingLevel(e,t);if(N(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||wl(i))return;let a={...i},o=N(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(C(`client.sessionController.queueResponseMismatch`,`The queue response belongs to a different conversation.`));if(!this.canMutateQueueMessage(a,o))throw Error(C(`client.sessionController.queueActionsUnavailable`,`Queued message actions are no longer available.`));if(this.hasDraftIdentityConflict(a,o))throw Error(C(`client.sessionController.queueContextChanged`,`The conversation context changed before the result returned. The current draft was preserved.`));e===`edit`&&(No(M(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||wl(t))return;let n=N(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||wl(n))return;let r=N(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(wl(r)){await this.closePendingStartDialog(r,e,t);return}let i=N(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||wl(r))return;let i=N(n),a=this.captureSessionErrorOwner(r),o=this.selectionSeq;try{let n=await t(r,i);Jo(M(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=N(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.abort(e,t)}catch(r){this.reportSessionError(e,t,r,n)}}resumeSelectedSession(e){if(e?.reconnect!==!1){let e=this.sessionConnectionOpen;if(this.socket.reconnect(),e)return Promise.resolve()}return this.refreshSelectedSession(void 0,{recoverNetwork:!0})}updateSubscriptionState(e){this.sessionConnectionOpen=e===`open`,!this.sessionConnectionOpen&&this.getState().conversationRefreshedAt!==void 0&&this.setState({conversationSync:`stale`})}refreshSelectedSession(e=this.getState().selectedSession?.id,t){let n=this.getState().selectedSession;if(e===void 0||n?.id!==e||this.selectedSessionLoadDeferred||n.archived===!0||wl(n))return Promise.resolve();let r=N(this.getState()),i={session:n,machineId:r,selectionSeq:this.selectionSeq,errorOwner:this.captureSessionErrorOwner(n),...t?.recoverNetwork===!0?{recoverNetwork:!0}:{}},a=this.selectedReadGeneration,o=this.getState().conversationSync;return t?.silent!==!0&&o!==`stale`&&o!==`interrupted`&&this.setState({conversationSync:`catching-up`}),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 d?this.browserErrors.reportLocalized(Cr(i.machineId,i.session.id,i.errorOwner),()=>ul.t(`conversationRefresh`),`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=M(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 il(()=>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)}}).catch(e=>{throw r()&&this.setState({conversationSync:`interrupted`}),e})}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,l=this.browserErrors.captureRecovery(Cr(e.machineId,e.session.id,e.errorOwner),`session-refresh`),u=!1,d=()=>{if(!u&&(u=!0,this.refreshEventBuffer===i&&(this.refreshEventBuffer=void 0),n()))for(let e of i.events){if(!n())break;this.applyEvent(e)}};r?.addEventListener(`abort`,d,{once:!0});try{let o=await this.transcriptSnapshot(e.session,{limit:fl,...r===void 0?{}:{signal:r},timeoutMs:1e4},e.machineId);if(!n()||this.transcripts.historyRevision(t)!==a)return;this.browserErrors.clearRecovered(l);let{page:u,status:d}=o;if(this.preserveBufferedDialogOutcomes(i,o.seq),!this.isUnchangedSelectedRefresh(e,t,u,d,o)){let n=this.transcripts.mergeSnapshot(t,u),r=this.transcripts.seedStreamingPartial(n.messages,o.partial);this.streamWatermark={sessionId:e.session.id,seq:o.seq},this.setState({...n,messages:r,status:d,activity:this.getState().sessionActivities[e.session.id]}),this.applyStatus(d),this.lastAppliedSelectedRefresh={selectionSeq:e.selectionSeq,partialJson:vl(o)}}s=this.transcripts.historyRevision(t),c=d}catch(t){if(r?.aborted===!0&&t===r.reason&&!this.isCurrentRefreshTarget(e))return;throw t}finally{r?.removeEventListener(`abort`,d),d()}this.transcripts.historyRevision(t)===s&&n()&&(this.setState({conversationSync:this.sessionConnectionOpen?`checked`:`stale`,conversationRefreshedAt:Date.now()}),o?.(c),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)||vl(i)!==a.partialJson||!Qs(this.transcripts.rawHistoryPage(t),n)||JSON.stringify(r)!==JSON.stringify(this.getState().status)?!1:this.getState().sessionActivities[r.sessionId]?.phase!==`active`||Pr(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&&Ll(e.navigation)}isCurrentSessionSelection(e,t,n){return n===this.selectionSeq&&this.isSelectedSessionIdentity(e,t)}isCurrentRestoreOperation(e,t,n){return t===this.selectionSeq&&N(this.getState())===e&&Ll(n)}isSelectedSessionIdentity(e,t){if(this.disposed)return!1;let n=this.getState(),r=n.selectedSession;return N(n)===t&&r?.id===e&&r.archived!==!0&&!wl(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 N(n)===t&&r?.id===e.id&&(r.cwd!==e.cwd||r.path!==e.path)}reportSessionError(e,t,n,r={cwd:e.cwd}){let i=Cr(t,e.id,r);n instanceof Zn||n instanceof cl||n instanceof dl||n instanceof Fa?this.browserErrors.reportLocalized(i,()=>String(n)):this.browserErrors.report(i,tl(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){let r=Sr(t,e.projectId,e.id);n instanceof dl?this.browserErrors.reportLocalized(r,()=>String(n)):this.browserErrors.report(r,tl(n))}applyBulkSessionFailures(e,t,n,r,i,a){t.length!==0&&this.reportWorkspaceOrSessionError(r,i,n,new dl(()=>ul.t(e===`archive`?`archivePartialFailure`:`deletePartialFailure`,{count:t.length,details: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 M(N(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 Pc(e.machineRuntimes[N(e)])}workspaceSelectionKey(e){return`${N(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:N(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,get name(){return sl.t(`newSession`)},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:El(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);this.sessionConnectionOpen=!1;let i=t?.activity??n.sessionActivities[e.id]??(r===void 0?void 0:El(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,conversationSync:void 0,conversationRefreshedAt:void 0,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){Po(M(n.machineId,e)),Bo(M(n.machineId,e)),this.setState({clientQueuedSessionMessages:bl(this.getState().clientQueuedSessionMessages,e)}),this.applyReleasedCreatedSessions(i,n.machineId),this.api.stop(t,n.machineId).catch(()=>{});return}Mi(t,n.machineId),Fo(M(n.machineId,e),M(n.machineId,t.id)),Vo(M(n.machineId,e),M(n.machineId,t.id));let a=Ni(t,n.machineId),o=this.captureSessionErrorOwner(t,n.originWorkspace);if(!this.isCurrentPendingStart(n)){this.setState({clientQueuedSessionMessages:bl(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:Cl(s.sessions,e,a),sessionActivities:yl(s.sessionActivities,e),sendingPrompts:Sl(s.sendingPrompts,e,a.id),clientQueuedSessionMessages:Sl(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&&!Ll(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||!Ll(n)?void 0:()=>sl.t(`navigationChanged`))}catch(n){let r=Nl(n);this.clearUnreconciledPendingSelection(e,t,()=>sl.t(`selectionFailure`,{detail:r}))}else try{if(await this.selectSession(t,{updateUrl:!1,navigation:n}),!Ll(n)){this.clearUnreconciledPendingSelection(e,t);return}if(this.getState().selectedSession?.id!==t.id){this.clearUnreconciledPendingSelection(e,t,()=>sl.t(`selectionChanged`));return}this.updateUrl(e.pendingUrlPublished?{replace:!0}:void 0)}catch(n){let r=Nl(n);this.clearUnreconciledPendingSelection(e,t,()=>sl.t(`selectionFailure`,{detail:r}))}}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.reportLocalized(Sr(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=[],Pi(e.tempId,e.machineId);let t=M(e.machineId,e.tempId);Po(t),Bo(t);let n=this.getState(),r=n.selectedSession?.id===e.tempId;if(this.setState({sessions:n.sessions.filter(t=>t.id!==e.tempId),sessionStatuses:bl(n.sessionStatuses,e.tempId),sessionActivities:yl(n.sessionActivities,e.tempId),sendingPrompts:bl(n.sendingPrompts,e.tempId),clientQueuedSessionMessages:bl(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=Nl(t),s=new cl(()=>sl.t(`startFailure`,{detail:o}));if(!a){this.browserErrors.reportLocalized(Sr(n.machineId,n.originWorkspace.projectId,n.originWorkspace.id),()=>s.message);return}let c=this.getState(),l=Dl(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 N(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||N(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=>wl(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=N(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)||!Ll(t?.navigation))return;Mi(r,i),Fo(M(i,e.id),M(i,r.id)),Vo(M(i,e.id),M(i,r.id)),Pi(e.id,i);let o=Ni(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(!Ii(e))return;let t=this.getState().sessions.find(t=>t.id===e.id)??e;this.replaceSession(Li(t))}async applyCommandResult(e,t){if(e.type===`select`){this.setState({commandDialog:{...e,get title(){return e.presentation===void 0?e.title:Pa(e.presentation)}}});return}if(e.type===`tree`){this.setState({treeDialog:e.tree});return}let n=e.message;if(n!==void 0&&n!==``&&this.setState({messages:[...this.getState().messages,{role:e.type===`unsupported`?`system`:`tool`,parts:[{type:`text`,text:n,...e.presentation===void 0?{}:{presentation:e.presentation}}]}]}),e.type!==`done`||e.session===void 0)return;e.promptDraft!==void 0&&No(this.sessionCacheKey(e.session.id),e.promptDraft);let r=this.getState().selectedSession,i=[e.session,...this.getState().sessions.filter(t=>t.id!==e.session?.id)];this.setState({sessions:i,...r?.id===e.session.id?{selectedSession:e.session}:{}}),r?.id!==e.session.id&&this.navigationSelectionMatchesState(t)&&(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=N(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`&&!Pr(e);this.setState({sessionStatuses:{...t.sessionStatuses,[e.sessionId]:e},...Pl(t,e.sessionId,e.messageCount),...r?{sessionActivities:yl(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(N(this.getState()),e);return}if(e.type===`command.output`&&this.notifications?.shouldFilterLegacyNotification(N(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(Fl(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`?El(t.tempId,t.queuedSends.length):Tl(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=N(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:pl},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&&N(this.getState())===t&&this.getState().selectedSession?.id===e}};function vl(e){return JSON.stringify(e.partial??null)}function yl(e,t){return bl(e,t)}function bl(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function xl(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 Sl(e,t,n){if(t===n||!(t in e))return e;let r=e[t];return r===void 0?e:{...bl(e,t),[n]:r}}function Cl(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 wl(e){return e!==void 0&&`clientPendingStart`in e&&e.clientPendingStart===!0}function Tl(e,t){return{sessionId:t,phase:e.phase,label:e.label,...e.detail===void 0?{}:{detail:e.detail},...e.startupPresentation===void 0?{}:{startupPresentation:e.startupPresentation},...e.runtimePresentation===void 0?{}:{runtimePresentation:e.runtimePresentation},at:e.at}}function El(e,t=0){return{sessionId:e,phase:`active`,get label(){return sl.t(`creating`)},get detail(){return t>0?sl.t(`queued`,{count:t}):sl.t(`waiting`)},at:new Date().toISOString()}}function Dl(e,t,n=0){return{sessionId:e,phase:`error`,get label(){return sl.t(`failed`)},get detail(){return sl.t(`failedDetail`,{detail:t,count:n})},at:new Date().toISOString()}}function Ol(e){if(e.type===`prompt`){let t=e.attachments?.length??0;return{kind:e.streamingBehavior===`steer`?`steer`:`followUp`,get text(){return kl(e.text,e.attachments)},...t>0?{hasAttachments:!0,attachmentCount:t}:{}}}return{kind:`followUp`,text:e.text}}function kl(e,t){let n=Al(t);return n===void 0?e:e.trim()===``?n:sl.t(`promptAttachments`,{text:e,attachments:n})}function Al(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;return t.length===0?sl.t(`attachments`,{count:n}):sl.t(`namedAttachments`,{count:n,names:t.slice(0,3).join(`, `),remaining:Math.max(0,t.length-3)})}function jl(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 Ml(e){return e.map(e=>`${e.sessionId}: ${e.error}`)}function Nl(e){return e instanceof Error?e.message:String(e)}function Pl(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 Fl(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`||e.type===`shell.chunk`}function Il(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`session not found`)||t.includes(C(`session.notFound`,`Session not found`))}function Ll(e){return e===void 0||e.isCurrent()}var Rl=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=Pr(t.status),a.statusActive||(a.activityActive=!1)):a.activityActive=Pr(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 zl(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 Bl={compactionCancelled:x(kt.compactionCancelled,`Notification after manual compaction is cancelled`),automaticCompactionCancelled:x(kt.automaticCompactionCancelled,`Notification after automatic compaction is cancelled`),compactionFailed:x(kt.compactionFailed,`Compaction failure notification; provider diagnostics are separate and unchanged`),dismissFailed:x(`Failed to dismiss notification: {detail}`,`Notification dismissal failure; detail is an untranslated runtime diagnostic`),dismissAllFailed:x(`Failed to dismiss session notifications: {detail}`,`Clear notification inbox failure; detail is an untranslated runtime diagnostic`),info:x(`Info`,`Informational notification severity`),warning:x(`Warning`,`Warning notification severity`),error:x(`Error`,`Error notification severity`),announcement:x(`{severity, select, error {Error notification received.} warning {Warning notification received.} other {Info notification received.}}`,`Live announcement of a new notification, without reading its user-supplied message`),heading:x(`Notifications ({count, number})`,`Session notification tray heading`),dismissEmpty:x(`{severity, select, error {Dismiss error notification} warning {Dismiss warning notification} other {Dismiss info notification}}`,`Dismiss accessible name when the notification message is empty`),dismiss:x(`Dismiss notification: {summary}`,`Dismiss accessible name; summary is unchanged notification content`),overflow:x(`{count, plural, one {# older notification not shown.} other {# older notifications not shown.}}`,`Notifications discarded because the inbox reached its limit`),truncated:x(`Message truncated at {limit, number} KiB.`,`Notification message byte limit`),expand:x(`Expand notifications`,`Expand notification tray`),collapse:x(`Collapse notifications`,`Collapse notification tray`),clearAll:x(`Clear all notifications`,`Clear notification tray accessible name`),clear:x(`Clear`,`Clear notification tray button`),dismissTitle:x(`Dismiss notification`,`Dismiss notification button tooltip`)},Vl=w.registerMessages(`core.sessionNotifications`,Bl),Hl={order:0,overflowWatermark:0};function Ul(e){return{...e,status:`loading`,catalogRevision:0,notifications:[],dismissThrough:Hl,optimisticDismissedIds:[],announcements:[]}}function Wl(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&&au(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 Gl(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)return{value:e??Ul(t),needsRefresh:!1,changed:!1};if(e===void 0||!au(e,t))return{value:su(t),needsRefresh:!0,changed:!0};if(e.daemonInstanceId!==n.daemonInstanceId)return{value:su(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(!cu(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 Kl(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=uu(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,...du(lu(r)),dismissThrough:e.dismissThrough,pendingDismissedIds:t,dismissAllPending:n!==void 0,announcements:e.announcements}}function ql(e){return Vl.t(e)}function Jl(e){return Vl.t(`announcement`,{severity:e.severity})}function Yl(e){return e.retainedCount+e.discardedCount}function Xl(e){return Vl.t(`heading`,{count:Yl(e)})}function Zl(e){return e.presentation===void 0?e.message:Vl.t(e.presentation.kind)}function Ql(e){let t=Zl(e).replace(/\s+/gu,` `).trim();if(t===``)return Vl.t(`dismissEmpty`,{severity:e.severity});let n=Array.from(t),r=n.length<=80?t:`${n.slice(0,79).join(``).trimEnd()}…`;return Vl.t(`dismiss`,{summary:r})}function $l(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 eu(e){return JSON.stringify([e.machineId,e.cwd,e.sessionId])}function tu(e,t){return e.has(eu(t))}function nu(e,t,n){let r=new Set(e),i=eu(t);return n?r.add(i):r.delete(i),r}function ru(e){return Vl.t(`overflow`,{count:e})}function iu(e){if(!e.truncated)return;let t=rn/1024;return Vl.t(`truncated`,{limit:t})}function au(e,t){return e.machineId===t.machineId&&e.sessionId===t.sessionId&&e.cwd===t.cwd}function ou(e,t){if(e===`error`||t===`error`)return`error`;if(e===`warning`||t===`warning`)return`warning`;if(e===`info`||t===`info`)return`info`}function su(e){return{...Ul(e),status:`stale`}}function cu(e,t){return e.length===t.retainedCount&&lu(e)===t.highestSeverity}function lu(e){let t;for(let n of e)t=ou(t,n.severity);return t}function uu(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 du(e){return e===void 0?{}:{highestSeverity:e}}var fu=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??Xt,this.browserErrors=new Ar(e,t),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:Ul(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=Gl(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=Kl(t);if(t===void 0||n===void 0||this.dismissAllPending||this.dismissingNotificationIds.has(e)||!n.notifications.some(t=>t.id===e))return;let r=pu(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){if(this.isCurrentTarget(r,i)){this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)}));let n=hu(t);this.browserErrors.reportLocalized(Cr(r.machineId,r.sessionId,{cwd:r.cwd}),()=>Vl.t(`dismissFailed`,{detail:n})),await this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId)}}finally{this.dismissingNotificationIds.delete(e)}}async dismissAll(){let e=this.getState().selectedNotificationInbox,t=Kl(e);if(e===void 0||t===void 0||this.dismissAllPending||t.retainedCount+t.discardedCount===0)return;let n=pu(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){if(this.isCurrentTarget(n,r)){this.patchSelectedOverlay(n,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t});let t=hu(e);this.browserErrors.reportLocalized(Cr(n.machineId,n.sessionId,{cwd:n.cwd}),()=>Vl.t(`dismissAllFailed`,{detail:t})),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||mu(i,t,r)?Wl(i,t,r):i;for(let r of[...n.events].sort((e,t)=>e.summary.inboxRevision-t.summary.inboxRevision)){let n=Gl(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&&au(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||!au(r,e))return;if(!this.machineSupportsNotifications(e.machineId)||!this.machineIsReachable(e.machineId)){this.setState({selectedNotificationInbox:{...n(r),status:`stale`}});return}let i=mu(r,e,t)?Wl(r,e,t):r;this.setState({selectedNotificationInbox:n(i)})}patchSelectedOverlay(e,t){let n=this.getState().selectedNotificationInbox;n!==void 0&&au(n,e)&&this.setState({selectedNotificationInbox:t(n)})}ensureSelectedProjection(e){let t=this.getState().selectedNotificationInbox;t!==void 0&&au(t,e)||this.setState({selectedNotificationInbox:Ul(e)})}scheduleSelectedRefresh(e){queueMicrotask(()=>{!this.disposed&&this.selectedTarget!==void 0&&au(this.selectedTarget,e)&&this.refreshSelectedSession({id:e.sessionId,cwd:e.cwd},e.machineId)})}markSelectedStale(e){let t=this.getState().selectedNotificationInbox;t!==void 0&&au(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&&au(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 pu(e){return{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd}}function mu(e,t,n){return!au(e,t)||e.daemonInstanceId!==n.daemonInstanceId||e.summary===void 0||n.summary.inboxRevision>=e.summary.inboxRevision}function hu(e){return e instanceof Error?e.message:String(e)}function gu(e){return e?.status!==`folder`}var _u=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)}},vu=`pi-web:workspace-selection:v1`,yu=class{constructor(e=Rc()){this.workspaceIdsByProject=new zc(vu,Bc,e)}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}};function bu(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 xu=50,Su=[`machine`,`project`,`workspace`,`session`],Cu=class{constructor(e,t,n,r,i=new _u,a={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessions=r,this.workspaceSelection=i,this.workspaceListRequests=new Map,this.api=a.api??Xt,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 Ar(e,t),this.topologyRefreshes=new Ur(a.topologyRefreshDebounceMs??xu)}clearSelection(e){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,workspaceResolution:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...yr()}),e?.updateUrl!==!1&&this.updateUrl()}forgetProject(e){let t=N(this.getState());this.browserErrors.discard(xr(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?.(Su);if(!this.navigationIsCurrent(n)||!Tu(t))return;let r=N(this.getState()),i=xr(r,e.id);this.sessions.clearActiveSession(),this.setState({selectedProject:e,workspaceResolution:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...yr()});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)||!Tu(t)||N(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 ku(o);let c=bu(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!==``){let e=t.workspaceId;return this.browserErrors.reportLocalized(i,()=>gi.t(`workspaceNotFound`,{id:e})),()=>gi.t(`workspaceNotFound`,{id:e})}t?.updateUrl!==!1&&this.navigationIsCurrent(n)&&this.updateUrl()}catch(a){return this.navigationIsCurrent(n)&&Tu(t)&&N(this.getState())===r&&this.getState().selectedProject?.id===e.id&&this.setState({isLoadingWorkspaces:!1}),t?.signal?.aborted!==!0&&vi(this.browserErrors,i,a),Au(a)}}async selectWorkspace(e,t){let n=t?.navigation??this.beginNavigationOperation?.(Su);if(!this.navigationIsCurrent(n)||!Tu(t))return;let r=N(this.getState()),i=Sr(r,e.projectId,e.id);this.workspaceSelection.rememberWorkspace({...e,projectId:Hr(r,e.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:e,isLoadingWorkspaces:!1,...yr()});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=Fi(e.path,a,r);if(!this.navigationIsCurrent(n)||!Tu(t)||N(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)||!Tu(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!==``){let e=t.sessionId;return this.browserErrors.reportLocalized(i,()=>gi.t(`sessionNotFound`,{id:e})),()=>gi.t(`sessionNotFound`,{id:e})}else t?.updateUrl!==!1&&this.updateUrl()}catch(e){return t?.signal?.aborted!==!0&&vi(this.browserErrors,i,e),Au(e)}}async refreshProjectWorkspaces(e,t=N(this.getState()),n){return(await this.refreshProjectWorkspaceList(e,t,n)).workspaces}async refreshProjectWorkspaceList(e,t,n){if(!Tu(n))return{workspaces:[],isCurrent:()=>!1};let r=this.getState().projects.find(t=>t.id===e);if(r===void 0)throw new _i(()=>gi.t(`projectNotFound`));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()&&Tu(n)&&N(this.getState())===t){if(this.getState().selectedProject?.id===r.id&&this.setState({workspaceResolution:a}),a.status===`degraded`)throw ku(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=N(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()||N(i)!==n||i.selectedProject?.id!==t.id)return;if(this.setState({workspaceResolution:r}),r.status===`degraded`)throw ku(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=N(this.getState()),r){if(!Tu(r))return;let i=this.beginNavigationOperation?.(Su),{workspaces:a,isCurrent:o}=await this.refreshProjectWorkspaceList(e,n,r);if(!o()||!this.navigationIsCurrent(i)||!Tu(r))return;let s=this.getState();if(N(s)!==n||s.selectedProject?.id!==e||s.selectedWorkspace?.id!==t)return;let c=wu(this.getState(),this.captureNavigation),l=Eu(a);this.navigateToWorkspace===void 0?l===void 0?this.navigationIsCurrent(i)&&Tu(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||Du(e,n)))return{selectedWorkspace:n}}navigationIsCurrent(e){return e===void 0||e.isCurrent()}};function wu(e,t){return t?.()??{machineId:N(e),projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,...e.selectedSession===void 0||Reflect.get(e.selectedSession,`clientPendingStart`)!==!0?{sessionId:e.selectedSession?.id}:{}}}function Tu(e){return e?.signal?.aborted!==!0&&e?.isCurrent?.()!==!1}function Eu(e){return e.find(e=>e.isMain)??e[0]}function Du(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)=>Du(e,t[n]));if(!Ou(e)||!Ou(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&Du(e[n],t[n]))}function Ou(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ku(e){let t=e.diagnostics.map(({message:e})=>e).join(`; `);return t?Error(t):new _i(()=>gi.t(`degraded`))}function Au(e){return e instanceof _i?()=>String(e):String(e)}var ju={unknownView:x(`Unknown view: {view}`,`Requested route view is not supported; raw view identifier stays unchanged`),machineNotFound:x(`Machine not found: {id}`,`Requested route machine is unavailable; identifier stays unchanged`),projectNotFound:x(`Project not found: {id}`,`Requested route project is unavailable; identifier stays unchanged`),remoteMachine:x(`Remote machine`,`Fallback machine name during route reconnection`),reconnecting:x(`{machine} is unavailable; reconnecting…{hasDetail, select, yes { {detail}} other {}}`,`Route reconnection banner; machine name and optional diagnostic stay unchanged`),exhausted:x(`{machine} is still unavailable.{hasDetail, select, yes { {detail}} other {}}`,`Route reconnection attempts exhausted; machine name and optional diagnostic stay unchanged`),loadingProjects:x(`Loading projects…`,`Session area while route projects load`),selectSession:x(`Select or start a session.`,`Session area with a selected workspace but no session`),selectWorkspace:x(`Select a workspace to start a session.`,`Session area with a selected project but no workspace`),addProject:x(`Add a project to start a session.`,`Session area with no projects`),selectProject:x(`Select a project and workspace to start a session.`,`Session area with projects but no selection`)},Mu=w.registerMessages(`core.routeFeedback`,ju),Nu=`core.workspace.files--file`,Pu=`core.workspace.terminal--terminal`,Fu=`pi-web:machine-navigation:v1`,Iu=class{constructor(e=Rc()){this.snapshotsByMachine=new zc(Fu,Vu,e)}latest(e){let t=this.snapshotsByMachine.get(e);return t?.machineId===e?Bu(t):void 0}remember(e){this.snapshotsByMachine.set(e.machineId,Bu(e))}forget(e){this.snapshotsByMachine.delete(e)}};function Lu(e){return{machineId:e,surface:{}}}function Ru(e,t={}){let n=e.selectedWorkspace===void 0?{}:Ya(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 zu(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view}}function Bu(e){let t=e.surface.contributionQuery;return{...e,surface:{...e.surface,...t===void 0?{}:{contributionQuery:Ya(t)}}}}function Vu(e){if(!Ku(e))return;let t=Gu(e,`machineId`);if(t===void 0)return;let n=Gu(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=Uu(Gu(e,`tool`))??r,a=ho(n)??(r===void 0?void 0:`workspace`);return{machineId:t,projectId:Gu(e,`projectId`),workspaceId:Gu(e,`workspaceId`),sessionId:Gu(e,`sessionId`),...i===void 0?{}:{tool:i},...a===void 0?{}:{view:a},surface:Hu(e.surface)}}function Hu(e){if(!Ku(e))return{};let t=Ku(e.contributionQuery)?e.contributionQuery:{},n=Gu(e,`selectedFilePath`),r=Gu(e,`selectedTerminalId`),i=Gu(e,`selectedDiffPath`),a=Ya({...n===void 0?{}:{[Nu]:n},...r===void 0?{}:{[Pu]:r},...i===void 0?{}:{"core.workspace.git--diff":i},...t});return{...Object.keys(a).length===0?{}:{contributionQuery:a}}}function Uu(e){return Wu(e)?e:void 0}function Wu(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Gu(e,t){let n=e[t];return typeof n==`string`&&n!==``?n:void 0}function Ku(e){return typeof e==`object`&&!!e}function qu(e,t,n){if(t!==void 0&&Yu(t.path)===Yu(n.cwd))return{machineId:e,projectId:t.projectId,workspaceId:t.id,root:t.path}}function Ju(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=`${Yu(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 Yu(e){return e.replace(/\/+$/,``)}var Xu={skipPinned:!0,archiveIdleEnabled:!0,archiveIdleDays:`30`,deleteArchivedEnabled:!1,deleteArchivedDays:`90`};function Zu(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,code:`disabled`,error:`Enable at least one cleanup action.`};let t={skipPinned:e.skipPinned,archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){let n=ad(e.archiveIdleDays,`Archive idle sessions after`);if(typeof n!=`number`)return{ok:!1,code:n.code===`required`?`archiveRequired`:`archiveInvalid`,error:n.error};t.archiveIdleDays=n}if(e.deleteArchivedEnabled){let n=ad(e.deleteArchivedDays,`Delete archived sessions after`);if(typeof n!=`number`)return{ok:!1,code:n.code===`required`?`deleteRequired`:`deleteInvalid`,error:n.error};t.deleteArchivedDays=n}return{ok:!0,request:t}}function Qu(e){return JSON.stringify({skipPinned:e?.skipPinned??!1,archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null,projectId:e?.projectId??null})}function $u(e){if(e.canCleanup===!1||e.loading===!0||e.running===!0||e.preview===void 0)return!1;let t=Zu(e.draft);if(!t.ok)return!1;if(e.previewRequest===void 0){if(e.canCleanup!==!0||!ed(e.draft,e.preview))return!1}else if(od(t.request)!==od(e.previewRequest)||(t.request.skipPinned??!1)!==(e.previewRequest.skipPinned??!1))return!1;return td(e.preview)}function ed(e,t){let n=Zu(e);return n.ok?od(n.request)===od(t.thresholds):!1}function td(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function nd(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 rd(e,t){let n=new Set(nd(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 id(e){return C(`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??C(`client.sessionCleanupUi.this.machine.74a83f`,`this machine`)})}function ad(e,t){let n=e.trim();if(n===``)return{code:`required`,error:`${t} must be set.`};let r=Number(n);return!Number.isInteger(r)||r<0?{code:`invalid`,error:`${t} must be a non-negative whole number of days.`}:r}function od(e){return JSON.stringify({archiveIdleDays:e.archiveIdleDays??null,deleteArchivedDays:e.deleteArchivedDays??null})}var sd=new Set,cd=$t+1,ld={unreadCatalog:e=>Tt.unreadCatalog(e),markUnread:(e,t)=>Tt.markUnread(e,t),acknowledgeUnread:(e,t,n,r)=>Tt.acknowledgeUnread(e,t,n,r)},ud=class{constructor(e={}){this.machines=new Map,this.api=e.api??ld,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 sd;let r=new Set;for(let e of t)n.summariesByIdentity.has(gd(e))&&r.add(e.id);return r.size===0?sd:r}isUnread(e,t){return this.machines.get(e)?.projection?.summariesByIdentity.has(gd(t))===!0}applyEvent(e,t){let n=this.machine(e);this.recordObservedEvent(n,t);let r=dd(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)}))}completion(e,t){let n=this.machines.get(e);if(n?.status!==`fresh`||n.projection===void 0)return;let r=n.projection.summariesByIdentity.get(gd(t));return r===void 0?void 0:{catalogId:n.projection.catalogId,sessionId:r.sessionId,cwd:r.cwd,completionOrder:r.completionOrder}}acknowledgeRendered(e,t,n,r){let i=this.completion(e,t);return i?.catalogId!==n.catalogId||i.sessionId!==n.sessionId||i.cwd!==n.cwd||i.completionOrder!==n.completionOrder?Promise.resolve():r===void 0?this.acknowledge(e,t):this.acknowledgeLoaded(e,t,r)}async markUnread(e,t){let n=this.machine(e),r=n.generation,i=this.beginNetworkObservation(n,r);try{let a=await this.api.markUnread(t,e);if(!this.isCurrent(n,r))return;this.applyNetworkSnapshot(n,a,i)&&this.refresh(e)}finally{n.observers.delete(i)}}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(gd(t));if(i===void 0)return Promise.resolve();let a=_d(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(gd(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(gd(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=pd(t),a=`fresh`,o=!1;for(let e of n.events){let t=dd(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>=cd?(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=!hd(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 dd(e,t,n){if(e===void 0){let e=md(n.catalogId);return n.catalogRevision===1?fd(e,`fresh`,n):{projection:e,status:`stale`,requiresRefresh:!0}}if(e.catalogId!==n.catalogId){let e=md(n.catalogId);return n.catalogRevision===1?fd(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?fd(e,t,n):{projection:e,status:`stale`,requiresRefresh:!0}}function fd(e,t,n){let r=new Map(e.summariesByIdentity),i=gd(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 pd(e){return{catalogId:e.catalogId,catalogRevision:e.catalogRevision,summariesByIdentity:new Map(e.sessions.map(e=>[gd(e),{...e}]))}}function md(e){return{catalogId:e,catalogRevision:0,summariesByIdentity:new Map}}function hd(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 gd(e){let t=`id`in e?e.id:e.sessionId;return JSON.stringify([t,e.cwd])}function _d(e,t){return JSON.stringify([e,t.sessionId,t.cwd,t.completionOrder])}var vd={machines:new Set,projects:new Set,workspaces:new Set};function yd(e){let t=xd(e.projectionFor(e.selectedMachineId));return{machines:Sd(e.machineIds,e.projectionFor),projects:wd(e.projects,e.workspacesByProjectId,t),workspaces:Cd(e.workspaces,t)}}function bd(e){return e!==void 0&&e.sessions.length>0}function xd(e){return e===void 0||e.sessions.length===0?Ed:new Set(e.sessions.map(e=>e.cwd))}function Sd(e,t){let n=new Set;for(let r of e)bd(t(r))&&n.add(r);return n}function Cd(e,t){let n=new Set;for(let r of e)t.has(r.path)&&n.add(r.id);return n}function wd(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 Td(e,t){return Dd(e.machines,t.machines)&&Dd(e.projects,t.projects)&&Dd(e.workspaces,t.workspaces)}var Ed=new Set;function Dd(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}var Od=100;function kd(e,t){return e.filter(e=>Md(e,t))}var Ad={snapshot:e=>jt.snapshot(e),dismiss:(e,t,n)=>jt.dismiss(e,t,n)},jd=class{constructor(e={}){this.machines=new Map,this.api=e.api??Ad,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,Nd(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,Nd(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,Nd(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>=Od?(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=!Pd(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 Md(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 Nd(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 Pd(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 Fd(e,t,n,r,i,a,o){Rd(t);let s=t?.mode===`patch`;zd(e,s);let c=e.machineId===void 0?o??(s?n.machineId??`local`:i):Ld(e.machineId)??`local`,l=!s||c!==(n.machineId??`local`),u=Id(e.projectId,l?void 0:n.projectId),d=l||u!==n.projectId,f=Id(e.workspaceId,d?void 0:n.workspaceId),p=d||f!==n.workspaceId,m={machineId:c,projectId:u,workspaceId:f,sessionId:Id(e.sessionId,p?void 0:n.sessionId),tool:Id(e.tool,l?void 0:n.tool),view:Id(e.view,s?n.view:void 0)},h=Ya(p?{}:r);if(e.query!==void 0){if(!Bd(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=Xa(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 Id(e,t){return e===void 0?t:Ld(e)}function Ld(e){return e===null||e===``?void 0:e}function Rd(e){if(e!==void 0){if(!Bd(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 zd(e,t){if(!Bd(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 Bd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Vd={title:x(`Clean up sessions`,`Session cleanup dialog title and accessible name`),eyebrow:x(`Sessions`,`Small heading above cleanup dialog title`),closeCleanup:x(`Close cleanup`,`Close cleanup dialog tooltip and accessible name`),intro:x(`Choose cleanup rules for the selected machine, then preview the affected projects before making changes.`,`Cleanup dialog introduction`),rulesStep:x(`1. Choose cleanup rules`,`First cleanup step heading`),reviewStep:x(`2. Review cleanup`,`Second cleanup step heading`),reviewIntro:x(`Choose which projects to clean up.`,`Cleanup review step introduction`),summaryEstimates:x(`Estimated counts — matching sessions may change`,`Review summary: cleanup rechecks eligibility when it runs`),summaryPinsProtected:x(`Pinned sessions protected`,`Review summary when pinned sessions are excluded from cleanup`),summaryPinsIncluded:x(`Pinned sessions included`,`Review warning when eligible pinned sessions can be archived or deleted, not merely unpinned`),summaryBusy:x(`Busy sessions skipped`,`Review summary: sessions with active work are always excluded`),back:x(`Back`,`Return to cleanup rules without changing sessions`),archiveSummary:x(`Archive after {days, plural, one {# inactive day} other {# inactive days}}`,`Compact archive rule on cleanup review`),deleteSummary:x(`Delete permanently after {days, plural, one {# day in archive} other {# days in archive}}`,`Compact deletion rule and irreversibility warning on cleanup review`),rules:x(`Cleanup rules`,`Heading for cleanup eligibility controls`),skipPinned:x(`Skip pinned sessions`,`Checkbox protecting pinned sessions from archiving and deletion`),pinnedHint:x(`Pinned sessions will not be archived or deleted. Sessions with active work are always skipped.`,`Explanation of default cleanup protections`),busyHint:x(`Sessions with active work are always skipped.`,`Cleanup protection when pinned sessions are included`),skippedPinned:x(`{count, plural, one {# pinned session was skipped.} other {# pinned sessions were skipped.}}`,`Cleanup preview pinned-session exclusion count`),cancel:x(`Cancel`,`Dismiss cleanup before completion`),close:x(`Close`,`Dismiss completed cleanup`),preview:x(`Preview cleanup`,`Preview cleanup targets without modifying sessions`),previewing:x(`Previewing…`,`Busy preview button`),run:x(`Run cleanup`,`Execute cleanup action and enabled button tooltip`),running:x(`Running…`,`Busy cleanup execution button`),runningHint:x(`Cleanup is running. Closing this dialog will not stop it.`,`Live status explaining that closing does not cancel cleanup`),noTargetsTitle:x(`No sessions to clean up`,`Disabled run button tooltip when the preview has no eligible sessions`),selectRequiredTitle:x(`Select at least one project to run cleanup`,`Disabled run button tooltip when no projects are selected`),previewRequiredTitle:x(`Preview cleanup before running it`,`Disabled run button tooltip when preview is missing or stale`),selectRequired:x(`Select at least one project to run cleanup.`,`Validation when selected projects contain no cleanup targets`),previewRequired:x(`Preview cleanup before running it.`,`Validation when preview is missing or stale`),archiveEnabled:x(`Archive idle sessions`,`Accessible name of archive-action checkbox`),deleteEnabled:x(`Delete old archived sessions`,`Accessible name of permanent-delete-action checkbox`),archiveThreshold:x(`Idle days before archiving`,`Accessible name of archive threshold number input`),deleteThreshold:x(`Archived days before deletion`,`Accessible name of deletion threshold number input`),archiveRule:x(`Days since last activity`,`Label for the archive threshold number input`),deleteRule:x(`Days since archiving`,`Label for the permanent-deletion threshold number input`),warning:x(`<strong>Deletion is permanent.</strong> Cleanup only deletes sessions that are already archived.`,`Destructive cleanup warning; strong tag emphasizes irreversibility`),stale:x(`Cleanup rules changed. Preview again before running cleanup.`,`Status when cleanup rules differ from preview`),previewLabel:x(`Cleanup preview`,`Accessible name of cleanup preview section`),empty:x(`No sessions match these rules. Try a shorter time range or different cleanup options.`,`Empty cleanup preview`),tableLabel:x(`Cleanup projects table`,`Accessible name of horizontally scrollable cleanup table`),cleanupColumn:x(`Clean up`,`Column heading for project selection checkboxes`),pathColumn:x(`Project or workspace`,`Column heading for unchanged filesystem paths`),archiveColumn:x(`Archive`,`Column heading for archive counts`),deleteColumn:x(`Delete`,`Column heading for permanent deletion counts`),totals:x(`Estimated totals`,`Table footer heading for estimated cleanup counts in selected projects`),skipped:x(`{count, plural, one {# busy session was skipped.} other {# busy sessions were skipped.}}`,`Cleanup preview busy-session exclusion count`),selectionLabel:x(`Project selection`,`Accessible name of preview project-selection controls`),selection:x(`{selected, number} of {total, number} projects selected`,`Number of selected projects out of preview projects`),selectAll:x(`Select all`,`Select all preview projects`),deselectAll:x(`Deselect all`,`Deselect all preview projects`),selectProject:x(`Clean up {path}`,`Project checkbox accessible name; path is an unchanged filesystem path`),resultLabel:x(`Cleanup result`,`Accessible name of cleanup result section`),complete:x(`Cleanup complete`,`Heading after successful cleanup`),result:x(`{archived, plural, one {Archived # session} other {Archived # sessions}}; {deleted, plural, one {permanently deleted # archived session.} other {permanently deleted # archived sessions.}}`,`Complete cleanup result sentence with both action counts`),confirm:x(`{archive, plural, =0 {{delete, plural, =0 {Run cleanup?} one {Run cleanup and permanently delete # archived session?} other {Run cleanup and permanently delete # archived sessions?}}} one {{delete, plural, =0 {Run cleanup and archive {archive, number} idle session?} one {Run cleanup and archive {archive, number} idle session and permanently delete # archived session?} other {Run cleanup and archive {archive, number} idle session and permanently delete # archived sessions?}}} other {{delete, plural, =0 {Run cleanup and archive {archive, number} idle sessions?} one {Run cleanup and archive {archive, number} idle sessions and permanently delete # archived session?} other {Run cleanup and archive {archive, number} idle sessions and permanently delete # archived sessions?}}}}
55
+ {attachments}`,`Queued prompt preview with attachment summary; text is raw user content`)},sl=w.registerMessages(`core.pendingSession`,ol),cl=class extends Error{constructor(e){super(),this.displayMessage=e}get message(){return this.displayMessage()}toString(){return this.message}},ll={archiveFailure:x(`Archive failed: {detail}`,`Bulk archive request failed; detail is an untranslated runtime diagnostic`),deleteFailure:x(`Delete failed: {detail}`,`Bulk delete request failed; detail is an untranslated runtime diagnostic`),archivePartialFailure:x(`Archive failed for {count, plural, one {# session} other {# sessions}}: {details}`,`Bulk archive partial failures; details contain raw session identifiers and runtime diagnostics`),deletePartialFailure:x(`Delete failed for {count, plural, one {# session} other {# sessions}}: {details}`,`Bulk delete partial failures; details contain raw session identifiers and runtime diagnostics`),sessionListRefresh:x(`The session list could not be refreshed. Check your connection and retry.`,`Workspace session-list network recovery exhausted`),conversationRefresh:x(`The conversation could not be refreshed. Check your connection and retry.`,`Selected conversation network recovery exhausted`)},ul=w.registerMessages(`core.sessionFeedback`,ll),dl=class extends Error{constructor(e){super(),this.displayMessage=e}get message(){return this.displayMessage()}toString(){return this.message}},fl=100,pl=500,ml=5e3,hl=[`machine`,`project`,`workspace`,`session`],gl=[`machine`,`project`,`workspace`,`session`],_l=class{constructor(e,t,n,r=new Wc,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.sessionConnectionOpen=!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 Ur,this.workspaceSessionRefreshes=new Ur,this.socket=i.socket??new wc,this.api=i.api??Xt,this.transcripts=i.transcripts??new sc,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 Ar(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.searchAbort?.abort(),this.searchAbort=void 0,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}))},ml))}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.sessionConnectionOpen=!1,this.setState({selectedSession:void 0,conversationSync:void 0,conversationRefreshedAt: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();Jc(this.automaticSessionCandidates(e.sessions),e.selectedSession)&&await this.clearSessionAfterNavigation(this.navigationSelection())}async startSession(e){let t=this.getState().selectedWorkspace;if(!t)return;let n=N(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?.(hl);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)}}searchSessions(e){let t=this.getState(),n=t.selectedWorkspace,r=N(t);this.searchSeq+=1;let i=this.searchSeq;this.searchAbort?.abort(),this.searchAbort=void 0,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){let a=new AbortController;this.searchAbort=a;try{let o=await this.api.searchContent(r,t,i,{signal:a.signal}),s=this.getState();if(e!==this.searchSeq||N(s)!==i||s.selectedWorkspace?.id!==n||s.selectedWorkspace.path!==r||s.sessionSearchQuery.trim()!==t)return;this.setState({sessionSearchResults:o,isSearchingSessions:!1})}catch(t){let a=this.getState();if(e!==this.searchSeq||N(a)!==i||a.selectedWorkspace?.id!==n||a.selectedWorkspace.path!==r)return;this.setState({sessionSearchResults:{results:[],matchCount:0,truncated:!1},isSearchingSessions:!1,sessionSearchError:String(t)})}finally{this.searchAbort===a&&(this.searchAbort=void 0)}}preferredSession(e,t,n){if(go(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 qc(t,{targetSessionId:n});let r=p()?t.filter(e=>!Ii(e)):t,i=this.sessionSelection.latestSessionId(this.workspaceSelectionKey(e));return i!==void 0&&i!==``&&r.some(e=>e.id===i)?qc(r,{latestSessionId:i}):qc(this.automaticSessionCandidates(r))}canReuseSelectedSession(){return!this.disposed&&Ll(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?.(gl);await this.selectSession(e,{updateUrl:!1,navigation:t})}async selectSession(e,t){if(this.disposed||!Ll(t?.navigation))return;if(this.retireReadRecoveries([`session`]),wl(e)){this.selectClientPendingStartSession(e,t);return}let n=N(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.sessionConnectionOpen=!1,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,conversationSync:e.archived===!0?void 0:`catching-up`,conversationRefreshedAt: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(Cr(n,e.id,r),`session-refresh`),s=await this.api.messages(e,{limit:fl},n),c=this.getState().selectedSession;if(i!==this.selectionSeq||N(this.getState())!==n||c?.id!==e.id||c.cwd!==e.cwd||c.path!==e.path||c.archived!==e.archived||!Ll(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,()=>{this.isCurrentSessionSelection(e.id,n,i)&&this.isSelectedSessionScope(e,n)&&this.refreshSelectedSession(e.id,{recoverNetwork:!0})},t=>{this.isCurrentSessionSelection(e.id,n,i)&&this.updateSubscriptionState(t)}),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)||!Ll(t?.navigation))return;this.refreshAvailableThinkingLevels(),this.onSelectedSessionReady?.({machineId:n,session:e}),t?.updateUrl!==!1&&this.updateUrl()}catch(a){let o=Ll(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(Ii(e)&&Il(a)){await this.recreateCachedNewSession(e,t,i,r);return}if(this.reportSessionError(e,n,a,r),t?.propagateRefreshError===!0)throw a}finally{let r=Ll(t?.navigation);i===this.selectionSeq&&r&&(this.selectedSessionJoinNavigation=void 0),s&&!Ll(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=N(e),r=this.captureSessionErrorOwner(t),i=this.selectionSeq,a=M(n,t.id),o=this.transcripts.historyRevision(a),s=()=>{let e=this.getState();return!this.disposed&&i===this.selectionSeq&&N(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:fl},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&&(!Eo(a,{machineId:N(o),sessionId:s.id,cwd:s.cwd})||wl(s)))return!1;let c=e.trim(),l=n!==void 0&&n.length>0,u=a!==void 0;if(wl(s))return!l&&c.startsWith(`/`)?this.enqueuePendingSessionSend(s,{type:`command`,text:e}):!l&&xc(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&&xc(e))return await this.runShell(e),!1;let d=N(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:bl(n,e)})}async runShell(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;if(wl(t)){this.enqueuePendingSessionSend(t,{type:`shell`,text:e});return}let n=N(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(wl(t)){this.enqueuePendingSessionSend(t,{type:`command`,text:e});return}let n=N(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===``||!Ic(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let r=N(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||N(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:C(`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=n===void 0?this.captureSessionErrorOwner(e):this.captureSessionErrorOwner(e,n.originWorkspace);this.reportSessionError(e,e.machineId,new cl(()=>sl.t(`queueUnavailable`)),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=El(e.id,n.queuedSends.length);this.setState({clientQueuedSessionMessages:{...i.clientQueuedSessionMessages,[e.id]:[...a,Ol(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=>hc(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,$i(`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,$i(`system`,tl(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,new cl(()=>sl.t(`commandInput`,{command:t})),i),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,$i(`system`,tl(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?bl(t.clientQueuedSessionMessages,e):{...t.clientQueuedSessionMessages,[e]:r}})}async respondToCommand(e,t){let n=this.getState().selectedSession;if(!n)return;let r=N(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||wl(r))return;let i=N(n),a=this.selectionSeq,o=this.captureSessionErrorOwner(r),s;try{if(s=await this.api.runCommand(r,`/tree`,i),s.type!==`tree`)throw`message`in s?s.presentation===void 0?Error(s.message):new Fa(s.presentation):new Zn(`historyUnavailable`);if(!s.tree.nodes.some(t=>t.id===e))throw new Zn(`messageUnavailable`)}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||wl(a))throw new Zn(`treeUnavailable`);let o={...a},s=N(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,()=>{this.setTreeActionPending(l,!1)}),i}catch(e){throw this.reportSessionError(o,s,e,c),e}finally{this.setTreeActionPending(l,!1)}}async applySessionTreeNavigationResult(e,t,n,r,i){if(n.cancelled||this.disposed)return;if(this.hasDraftIdentityConflict(e,t)){this.reportSessionError(e,t,C(`client.sessionController.queueContextChanged`,`The conversation context changed before the result returned. The current draft was preserved.`));return}let a=M(t,e.id),o=n.editorText;if(o!==void 0&&No(a,o),this.transcripts.discard(a),!this.isSelectedSessionScope(e,t))return;this.clearPendingUpdates();let s=this.selectionSeq,c=()=>this.isCurrentSessionSelection(e.id,t,s)&&this.isSelectedSessionScope(e,t),l=(async()=>{o!==void 0&&c()&&(await this.replacePromptEditorText?.({machineId:t,sessionId:e.id,text:o,isCurrent:c}),c()&&i?.())})(),[u,d]=await Promise.allSettled([l,this.requestSelectedSessionRefresh({session:e,machineId:t,selectionSeq:s,errorOwner:this.captureSessionErrorOwner(e)})]);if(c()){if(u.status===`rejected`)throw u.reason;if(d.status===`rejected`)throw d.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||wl(i))throw new Zn(`treeUnavailable`);let a={...i},o=N(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=M(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&&No(M(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||wl(t))return;let n=N(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 p()?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);No(M(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=N(e);t!==void 0&&this.isSelectedSessionIdentity(t.id,n)&&(this.transcripts.discard(M(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(Lc(e,t,n)){await this.deleteCachedNewSession(e);return}if(!Ic(e,t,n))return;let r=N(this.getState()),i=this.captureSessionErrorOwner(e);try{await this.api.archive(e,r,this.archiveScopeProjectId());let t=this.getState(),n=Yc(t.sessions,e.id,new Date().toISOString()),i=Zc(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||!Ic(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=N(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=Xc(i.sessions,r,new Date().toISOString()),o=Qc(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=jl(e).filter(e=>Ic(e,this.statusForSession(e),t));if(n.length===0)return;let r=N(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=Xc(t.sessions,e,s??new Date().toISOString()),r=Qc(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(`archive`,t,r,i,a,o)}catch(e){this.reportWorkspaceOrSessionError(i,a,r,new dl(()=>ul.t(`archiveFailure`,{detail:Nl(e)})),o)}}async deleteArchivedSessions(e){let t=jl(e).filter(e=>e.archived===!0);if(t.length===0)return;let n=N(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 t=new Set(e),n=this.getState(),r=n.sessions.filter(e=>!t.has(e.id));if(this.setState({sessions:r}),n.selectedSession!==void 0&&t.has(n.selectedSession.id)){let e=this.navigationSelection(),t=this.automaticSessionCandidates(r),n=t.find(e=>e.archived!==!0)??t[0];n===void 0?await this.clearSessionAfterNavigation(e):await this.selectSessionAfterNavigation(n,e)}}this.applyBulkSessionFailures(`delete`,o,n,r,i,a)}catch(e){this.reportWorkspaceOrSessionError(r,i,n,new dl(()=>ul.t(`deleteFailure`,{detail:Nl(e)})),a)}}async archiveSessionBatch(e,t){let n=await this.api.archiveMany(e,t,this.archiveScopeProjectId());return{succeededIds:n.archivedSessionIds,failures:Ml(n.failures),generatedAt:n.generatedAt}}async deleteArchivedSessionBatch(e,t){let n=await this.api.deleteArchivedMany(e,t,this.archiveScopeProjectId());return{succeededIds:n.deletedSessionIds,failures:Ml(n.failures)}}async applySessionCleanupResult(e,t=N(this.getState())){if(N(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=Xc(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:xl(t.sessionStatuses,a),sessionActivities:xl(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=Qc(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=N(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&&Ll(i)&&N(this.getState())===e&&this.getState().selectedWorkspace?.id===n.id&&this.getState().selectedWorkspace?.projectId===n.projectId&&this.getState().selectedWorkspace?.path===n.path,o=Sr(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 il(i,a,s.signal,t?.recoverNetwork===!0)}finally{this.workspaceReadRecoveries.delete(s)}if(c===void 0||!a())return;this.browserErrors.clearRecovered(r);let l=Fi(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});let f=this.navigationSelection();if(d===void 0)return;let p=u.find(e=>e.id===d.id);if(p!==void 0){if(d.archived!==!0&&p.archived===!0){let e=Zc(this.automaticSessionCandidates(u),d.id,d.id);e.type===`select`?await this.selectSessionAfterNavigation(e.session,f):e.type===`clear`&&await this.clearSessionAfterNavigation(f)}else d.archived===!0&&p.archived!==!0?await this.selectSessionAfterNavigation(p,f):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 d){this.browserErrors.reportLocalized(o,()=>ul.t(`sessionListRefresh`),`workspace-sessions-refresh`);return}if(el(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||!Lc(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=wl(e)?this.pendingSessionStarts.get(e.id):void 0;t===void 0?this.api.stop(e,N(this.getState())).catch(()=>{}):(t.discarded=!0,t.queuedSends=[]),Pi(e.id,N(this.getState())),Po(this.sessionCacheKey(e.id)),Bo(this.sessionCacheKey(e.id));let n=this.getState(),r=n.sessions.filter(t=>t.id!==e.id);if(this.setState({sessions:r,sessionStatuses:bl(n.sessionStatuses,e.id),sessionActivities:yl(n.sessionActivities,e.id),sendingPrompts:bl(n.sendingPrompts,e.id),clientQueuedSessionMessages:bl(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=N(this.getState()),n=this.captureSessionErrorOwner(e),r=this.selectionSeq,i=this.beginNavigationOperation?.(gl);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;return this.replaceSession(a),o&&await this.selectSession(a,{updateUrl:!1,...i===void 0?{}:{navigation:i}}),a}async reloadSession(e=this.getState().selectedSession){if(e===void 0||!Ic(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=N(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.reloadSession(e,t),this.transcripts.discard(M(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=N(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.detachParent(e,t);let n=this.getState();if(this.disposed||N(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=N(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=N(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=N(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=N(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=N(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=N(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=N(this.getState()),i=this.captureSessionErrorOwner(n);try{let i=await this.api.setModel(n,e,t,r);if(N(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=N(this.getState()),r=this.captureSessionErrorOwner(t);try{let r=await this.api.cycleModel(t,e,n);if(N(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=N(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=N(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=N(this.getState()),r=this.captureSessionErrorOwner(t);try{let r=await this.api.setThinkingLevel(t,e,n);if(N(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=N(this.getState()),n=this.captureSessionErrorOwner(e);try{let n=await this.api.cycleThinkingLevel(e,t);if(N(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||wl(i))return;let a={...i},o=N(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(C(`client.sessionController.queueResponseMismatch`,`The queue response belongs to a different conversation.`));if(!this.canMutateQueueMessage(a,o))throw Error(C(`client.sessionController.queueActionsUnavailable`,`Queued message actions are no longer available.`));if(this.hasDraftIdentityConflict(a,o))throw Error(C(`client.sessionController.queueContextChanged`,`The conversation context changed before the result returned. The current draft was preserved.`));e===`edit`&&(No(M(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||wl(t))return;let n=N(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||wl(n))return;let r=N(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(wl(r)){await this.closePendingStartDialog(r,e,t);return}let i=N(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||wl(r))return;let i=N(n),a=this.captureSessionErrorOwner(r),o=this.selectionSeq;try{let n=await t(r,i);Jo(M(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=N(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.abort(e,t)}catch(r){this.reportSessionError(e,t,r,n)}}resumeSelectedSession(e){if(e?.reconnect!==!1){let e=this.sessionConnectionOpen;if(this.socket.reconnect(),e)return Promise.resolve()}return this.refreshSelectedSession(void 0,{recoverNetwork:!0})}updateSubscriptionState(e){this.sessionConnectionOpen=e===`open`,!this.sessionConnectionOpen&&this.getState().conversationRefreshedAt!==void 0&&this.setState({conversationSync:`stale`})}refreshSelectedSession(e=this.getState().selectedSession?.id,t){let n=this.getState().selectedSession;if(e===void 0||n?.id!==e||this.selectedSessionLoadDeferred||n.archived===!0||wl(n))return Promise.resolve();let r=N(this.getState()),i={session:n,machineId:r,selectionSeq:this.selectionSeq,errorOwner:this.captureSessionErrorOwner(n),...t?.recoverNetwork===!0?{recoverNetwork:!0}:{}},a=this.selectedReadGeneration,o=this.getState().conversationSync;return t?.silent!==!0&&o!==`stale`&&o!==`interrupted`&&this.setState({conversationSync:`catching-up`}),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 d?this.browserErrors.reportLocalized(Cr(i.machineId,i.session.id,i.errorOwner),()=>ul.t(`conversationRefresh`),`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=M(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 il(()=>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)}}).catch(e=>{throw r()&&this.setState({conversationSync:`interrupted`}),e})}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,l=this.browserErrors.captureRecovery(Cr(e.machineId,e.session.id,e.errorOwner),`session-refresh`),u=!1,d=()=>{if(!u&&(u=!0,this.refreshEventBuffer===i&&(this.refreshEventBuffer=void 0),n()))for(let e of i.events){if(!n())break;this.applyEvent(e)}};r?.addEventListener(`abort`,d,{once:!0});try{let o=await this.transcriptSnapshot(e.session,{limit:fl,...r===void 0?{}:{signal:r},timeoutMs:1e4},e.machineId);if(!n()||this.transcripts.historyRevision(t)!==a)return;this.browserErrors.clearRecovered(l);let{page:u,status:d}=o;if(this.preserveBufferedDialogOutcomes(i,o.seq),!this.isUnchangedSelectedRefresh(e,t,u,d,o)){let n=this.transcripts.mergeSnapshot(t,u),r=this.transcripts.seedStreamingPartial(n.messages,o.partial);this.streamWatermark={sessionId:e.session.id,seq:o.seq},this.setState({...n,messages:r,status:d,activity:this.getState().sessionActivities[e.session.id]}),this.applyStatus(d),this.lastAppliedSelectedRefresh={selectionSeq:e.selectionSeq,partialJson:vl(o)}}s=this.transcripts.historyRevision(t),c=d}catch(t){if(r?.aborted===!0&&t===r.reason&&!this.isCurrentRefreshTarget(e))return;throw t}finally{r?.removeEventListener(`abort`,d),d()}this.transcripts.historyRevision(t)===s&&n()&&(this.setState({conversationSync:this.sessionConnectionOpen?`checked`:`stale`,conversationRefreshedAt:Date.now()}),o?.(c),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)||vl(i)!==a.partialJson||!Qs(this.transcripts.rawHistoryPage(t),n)||JSON.stringify(r)!==JSON.stringify(this.getState().status)?!1:this.getState().sessionActivities[r.sessionId]?.phase!==`active`||Pr(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&&Ll(e.navigation)}isCurrentSessionSelection(e,t,n){return n===this.selectionSeq&&this.isSelectedSessionIdentity(e,t)}isCurrentRestoreOperation(e,t,n){return t===this.selectionSeq&&N(this.getState())===e&&Ll(n)}isSelectedSessionIdentity(e,t){if(this.disposed)return!1;let n=this.getState(),r=n.selectedSession;return N(n)===t&&r?.id===e&&r.archived!==!0&&!wl(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 N(n)===t&&r?.id===e.id&&(r.cwd!==e.cwd||r.path!==e.path)}reportSessionError(e,t,n,r={cwd:e.cwd}){let i=Cr(t,e.id,r);n instanceof Zn||n instanceof cl||n instanceof dl||n instanceof Fa?this.browserErrors.reportLocalized(i,()=>String(n)):this.browserErrors.report(i,tl(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){let r=Sr(t,e.projectId,e.id);n instanceof dl?this.browserErrors.reportLocalized(r,()=>String(n)):this.browserErrors.report(r,tl(n))}applyBulkSessionFailures(e,t,n,r,i,a){t.length!==0&&this.reportWorkspaceOrSessionError(r,i,n,new dl(()=>ul.t(e===`archive`?`archivePartialFailure`:`deletePartialFailure`,{count:t.length,details: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 M(N(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 Pc(e.machineRuntimes[N(e)])}workspaceSelectionKey(e){return`${N(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:N(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,get name(){return sl.t(`newSession`)},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:El(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);this.sessionConnectionOpen=!1;let i=t?.activity??n.sessionActivities[e.id]??(r===void 0?void 0:El(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,conversationSync:void 0,conversationRefreshedAt:void 0,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){Po(M(n.machineId,e)),Bo(M(n.machineId,e)),this.setState({clientQueuedSessionMessages:bl(this.getState().clientQueuedSessionMessages,e)}),this.applyReleasedCreatedSessions(i,n.machineId),this.api.stop(t,n.machineId).catch(()=>{});return}Mi(t,n.machineId),Fo(M(n.machineId,e),M(n.machineId,t.id)),Vo(M(n.machineId,e),M(n.machineId,t.id));let a=Ni(t,n.machineId),o=this.captureSessionErrorOwner(t,n.originWorkspace);if(!this.isCurrentPendingStart(n)){this.setState({clientQueuedSessionMessages:bl(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:Cl(s.sessions,e,a),sessionActivities:yl(s.sessionActivities,e),sendingPrompts:Sl(s.sendingPrompts,e,a.id),clientQueuedSessionMessages:Sl(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&&!Ll(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||!Ll(n)?void 0:()=>sl.t(`navigationChanged`))}catch(n){let r=Nl(n);this.clearUnreconciledPendingSelection(e,t,()=>sl.t(`selectionFailure`,{detail:r}))}else try{if(await this.selectSession(t,{updateUrl:!1,navigation:n}),!Ll(n)){this.clearUnreconciledPendingSelection(e,t);return}if(this.getState().selectedSession?.id!==t.id){this.clearUnreconciledPendingSelection(e,t,()=>sl.t(`selectionChanged`));return}this.updateUrl(e.pendingUrlPublished?{replace:!0}:void 0)}catch(n){let r=Nl(n);this.clearUnreconciledPendingSelection(e,t,()=>sl.t(`selectionFailure`,{detail:r}))}}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.reportLocalized(Sr(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=[],Pi(e.tempId,e.machineId);let t=M(e.machineId,e.tempId);Po(t),Bo(t);let n=this.getState(),r=n.selectedSession?.id===e.tempId;if(this.setState({sessions:n.sessions.filter(t=>t.id!==e.tempId),sessionStatuses:bl(n.sessionStatuses,e.tempId),sessionActivities:yl(n.sessionActivities,e.tempId),sendingPrompts:bl(n.sendingPrompts,e.tempId),clientQueuedSessionMessages:bl(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=Nl(t),s=new cl(()=>sl.t(`startFailure`,{detail:o}));if(!a){this.browserErrors.reportLocalized(Sr(n.machineId,n.originWorkspace.projectId,n.originWorkspace.id),()=>s.message);return}let c=this.getState(),l=Dl(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 N(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||N(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=>wl(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=N(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)||!Ll(t?.navigation))return;Mi(r,i),Fo(M(i,e.id),M(i,r.id)),Vo(M(i,e.id),M(i,r.id)),Pi(e.id,i);let o=Ni(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(!Ii(e))return;let t=this.getState().sessions.find(t=>t.id===e.id)??e;this.replaceSession(Li(t))}async applyCommandResult(e,t){if(e.type===`select`){this.setState({commandDialog:{...e,get title(){return e.presentation===void 0?e.title:Pa(e.presentation)}}});return}if(e.type===`tree`){this.setState({treeDialog:e.tree});return}let n=e.message;if(n!==void 0&&n!==``&&this.setState({messages:[...this.getState().messages,{role:e.type===`unsupported`?`system`:`tool`,parts:[{type:`text`,text:n,...e.presentation===void 0?{}:{presentation:e.presentation}}]}]}),e.type!==`done`||e.session===void 0)return;e.promptDraft!==void 0&&No(this.sessionCacheKey(e.session.id),e.promptDraft);let r=this.getState().selectedSession,i=[e.session,...this.getState().sessions.filter(t=>t.id!==e.session?.id)];this.setState({sessions:i,...r?.id===e.session.id?{selectedSession:e.session}:{}}),r?.id!==e.session.id&&this.navigationSelectionMatchesState(t)&&(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=N(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`&&!Pr(e);this.setState({sessionStatuses:{...t.sessionStatuses,[e.sessionId]:e},...Pl(t,e.sessionId,e.messageCount),...r?{sessionActivities:yl(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(N(this.getState()),e);return}if(e.type===`command.output`&&this.notifications?.shouldFilterLegacyNotification(N(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(Fl(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`?El(t.tempId,t.queuedSends.length):Tl(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=N(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:pl},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&&N(this.getState())===t&&this.getState().selectedSession?.id===e}};function vl(e){return JSON.stringify(e.partial??null)}function yl(e,t){return bl(e,t)}function bl(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function xl(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 Sl(e,t,n){if(t===n||!(t in e))return e;let r=e[t];return r===void 0?e:{...bl(e,t),[n]:r}}function Cl(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 wl(e){return e!==void 0&&`clientPendingStart`in e&&e.clientPendingStart===!0}function Tl(e,t){return{sessionId:t,phase:e.phase,label:e.label,...e.detail===void 0?{}:{detail:e.detail},...e.startupPresentation===void 0?{}:{startupPresentation:e.startupPresentation},...e.runtimePresentation===void 0?{}:{runtimePresentation:e.runtimePresentation},at:e.at}}function El(e,t=0){return{sessionId:e,phase:`active`,get label(){return sl.t(`creating`)},get detail(){return t>0?sl.t(`queued`,{count:t}):sl.t(`waiting`)},at:new Date().toISOString()}}function Dl(e,t,n=0){return{sessionId:e,phase:`error`,get label(){return sl.t(`failed`)},get detail(){return sl.t(`failedDetail`,{detail:t,count:n})},at:new Date().toISOString()}}function Ol(e){if(e.type===`prompt`){let t=e.attachments?.length??0;return{kind:e.streamingBehavior===`steer`?`steer`:`followUp`,get text(){return kl(e.text,e.attachments)},...t>0?{hasAttachments:!0,attachmentCount:t}:{}}}return{kind:`followUp`,text:e.text}}function kl(e,t){let n=Al(t);return n===void 0?e:e.trim()===``?n:sl.t(`promptAttachments`,{text:e,attachments:n})}function Al(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;return t.length===0?sl.t(`attachments`,{count:n}):sl.t(`namedAttachments`,{count:n,names:t.slice(0,3).join(`, `),remaining:Math.max(0,t.length-3)})}function jl(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 Ml(e){return e.map(e=>`${e.sessionId}: ${e.error}`)}function Nl(e){return e instanceof Error?e.message:String(e)}function Pl(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 Fl(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`||e.type===`shell.chunk`}function Il(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`session not found`)||t.includes(C(`session.notFound`,`Session not found`))}function Ll(e){return e===void 0||e.isCurrent()}var Rl=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=Pr(t.status),a.statusActive||(a.activityActive=!1)):a.activityActive=Pr(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 zl(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 Bl={compactionCancelled:x(kt.compactionCancelled,`Notification after manual compaction is cancelled`),automaticCompactionCancelled:x(kt.automaticCompactionCancelled,`Notification after automatic compaction is cancelled`),compactionFailed:x(kt.compactionFailed,`Compaction failure notification; provider diagnostics are separate and unchanged`),dismissFailed:x(`Failed to dismiss notification: {detail}`,`Notification dismissal failure; detail is an untranslated runtime diagnostic`),dismissAllFailed:x(`Failed to dismiss session notifications: {detail}`,`Clear notification inbox failure; detail is an untranslated runtime diagnostic`),info:x(`Info`,`Informational notification severity`),warning:x(`Warning`,`Warning notification severity`),error:x(`Error`,`Error notification severity`),announcement:x(`{severity, select, error {Error notification received.} warning {Warning notification received.} other {Info notification received.}}`,`Live announcement of a new notification, without reading its user-supplied message`),heading:x(`Notifications ({count, number})`,`Session notification tray heading`),dismissEmpty:x(`{severity, select, error {Dismiss error notification} warning {Dismiss warning notification} other {Dismiss info notification}}`,`Dismiss accessible name when the notification message is empty`),dismiss:x(`Dismiss notification: {summary}`,`Dismiss accessible name; summary is unchanged notification content`),overflow:x(`{count, plural, one {# older notification not shown.} other {# older notifications not shown.}}`,`Notifications discarded because the inbox reached its limit`),truncated:x(`Message truncated at {limit, number} KiB.`,`Notification message byte limit`),expand:x(`Expand notifications`,`Expand notification tray`),collapse:x(`Collapse notifications`,`Collapse notification tray`),clearAll:x(`Clear all notifications`,`Clear notification tray accessible name`),clear:x(`Clear`,`Clear notification tray button`),dismissTitle:x(`Dismiss notification`,`Dismiss notification button tooltip`)},Vl=w.registerMessages(`core.sessionNotifications`,Bl),Hl={order:0,overflowWatermark:0};function Ul(e){return{...e,status:`loading`,catalogRevision:0,notifications:[],dismissThrough:Hl,optimisticDismissedIds:[],announcements:[]}}function Wl(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&&au(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 Gl(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)return{value:e??Ul(t),needsRefresh:!1,changed:!1};if(e===void 0||!au(e,t))return{value:su(t),needsRefresh:!0,changed:!0};if(e.daemonInstanceId!==n.daemonInstanceId)return{value:su(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(!cu(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 Kl(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=uu(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,...du(lu(r)),dismissThrough:e.dismissThrough,pendingDismissedIds:t,dismissAllPending:n!==void 0,announcements:e.announcements}}function ql(e){return Vl.t(e)}function Jl(e){return Vl.t(`announcement`,{severity:e.severity})}function Yl(e){return e.retainedCount+e.discardedCount}function Xl(e){return Vl.t(`heading`,{count:Yl(e)})}function Zl(e){return e.presentation===void 0?e.message:Vl.t(e.presentation.kind)}function Ql(e){let t=Zl(e).replace(/\s+/gu,` `).trim();if(t===``)return Vl.t(`dismissEmpty`,{severity:e.severity});let n=Array.from(t),r=n.length<=80?t:`${n.slice(0,79).join(``).trimEnd()}…`;return Vl.t(`dismiss`,{summary:r})}function $l(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 eu(e){return JSON.stringify([e.machineId,e.cwd,e.sessionId])}function tu(e,t){return e.has(eu(t))}function nu(e,t,n){let r=new Set(e),i=eu(t);return n?r.add(i):r.delete(i),r}function ru(e){return Vl.t(`overflow`,{count:e})}function iu(e){if(!e.truncated)return;let t=rn/1024;return Vl.t(`truncated`,{limit:t})}function au(e,t){return e.machineId===t.machineId&&e.sessionId===t.sessionId&&e.cwd===t.cwd}function ou(e,t){if(e===`error`||t===`error`)return`error`;if(e===`warning`||t===`warning`)return`warning`;if(e===`info`||t===`info`)return`info`}function su(e){return{...Ul(e),status:`stale`}}function cu(e,t){return e.length===t.retainedCount&&lu(e)===t.highestSeverity}function lu(e){let t;for(let n of e)t=ou(t,n.severity);return t}function uu(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 du(e){return e===void 0?{}:{highestSeverity:e}}var fu=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??Xt,this.browserErrors=new Ar(e,t),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:Ul(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=Gl(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=Kl(t);if(t===void 0||n===void 0||this.dismissAllPending||this.dismissingNotificationIds.has(e)||!n.notifications.some(t=>t.id===e))return;let r=pu(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){if(this.isCurrentTarget(r,i)){this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)}));let n=hu(t);this.browserErrors.reportLocalized(Cr(r.machineId,r.sessionId,{cwd:r.cwd}),()=>Vl.t(`dismissFailed`,{detail:n})),await this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId)}}finally{this.dismissingNotificationIds.delete(e)}}async dismissAll(){let e=this.getState().selectedNotificationInbox,t=Kl(e);if(e===void 0||t===void 0||this.dismissAllPending||t.retainedCount+t.discardedCount===0)return;let n=pu(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){if(this.isCurrentTarget(n,r)){this.patchSelectedOverlay(n,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t});let t=hu(e);this.browserErrors.reportLocalized(Cr(n.machineId,n.sessionId,{cwd:n.cwd}),()=>Vl.t(`dismissAllFailed`,{detail:t})),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||mu(i,t,r)?Wl(i,t,r):i;for(let r of[...n.events].sort((e,t)=>e.summary.inboxRevision-t.summary.inboxRevision)){let n=Gl(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&&au(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||!au(r,e))return;if(!this.machineSupportsNotifications(e.machineId)||!this.machineIsReachable(e.machineId)){this.setState({selectedNotificationInbox:{...n(r),status:`stale`}});return}let i=mu(r,e,t)?Wl(r,e,t):r;this.setState({selectedNotificationInbox:n(i)})}patchSelectedOverlay(e,t){let n=this.getState().selectedNotificationInbox;n!==void 0&&au(n,e)&&this.setState({selectedNotificationInbox:t(n)})}ensureSelectedProjection(e){let t=this.getState().selectedNotificationInbox;t!==void 0&&au(t,e)||this.setState({selectedNotificationInbox:Ul(e)})}scheduleSelectedRefresh(e){queueMicrotask(()=>{!this.disposed&&this.selectedTarget!==void 0&&au(this.selectedTarget,e)&&this.refreshSelectedSession({id:e.sessionId,cwd:e.cwd},e.machineId)})}markSelectedStale(e){let t=this.getState().selectedNotificationInbox;t!==void 0&&au(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&&au(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 pu(e){return{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd}}function mu(e,t,n){return!au(e,t)||e.daemonInstanceId!==n.daemonInstanceId||e.summary===void 0||n.summary.inboxRevision>=e.summary.inboxRevision}function hu(e){return e instanceof Error?e.message:String(e)}function gu(e){return e?.status!==`folder`}var _u=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)}},vu=`pi-web:workspace-selection:v1`,yu=class{constructor(e=Rc()){this.workspaceIdsByProject=new zc(vu,Bc,e)}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}};function bu(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 xu=50,Su=[`machine`,`project`,`workspace`,`session`],Cu=class{constructor(e,t,n,r,i=new _u,a={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessions=r,this.workspaceSelection=i,this.workspaceListRequests=new Map,this.api=a.api??Xt,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 Ar(e,t),this.topologyRefreshes=new Ur(a.topologyRefreshDebounceMs??xu)}clearSelection(e){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,workspaceResolution:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...yr()}),e?.updateUrl!==!1&&this.updateUrl()}forgetProject(e){let t=N(this.getState());this.browserErrors.discard(xr(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?.(Su);if(!this.navigationIsCurrent(n)||!Tu(t))return;let r=N(this.getState()),i=xr(r,e.id);this.sessions.clearActiveSession(),this.setState({selectedProject:e,workspaceResolution:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...yr()});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)||!Tu(t)||N(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 ku(o);let c=bu(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!==``){let e=t.workspaceId;return this.browserErrors.reportLocalized(i,()=>gi.t(`workspaceNotFound`,{id:e})),()=>gi.t(`workspaceNotFound`,{id:e})}t?.updateUrl!==!1&&this.navigationIsCurrent(n)&&this.updateUrl()}catch(a){return this.navigationIsCurrent(n)&&Tu(t)&&N(this.getState())===r&&this.getState().selectedProject?.id===e.id&&this.setState({isLoadingWorkspaces:!1}),t?.signal?.aborted!==!0&&vi(this.browserErrors,i,a),Au(a)}}async selectWorkspace(e,t){let n=t?.navigation??this.beginNavigationOperation?.(Su);if(!this.navigationIsCurrent(n)||!Tu(t))return;let r=N(this.getState()),i=Sr(r,e.projectId,e.id);this.workspaceSelection.rememberWorkspace({...e,projectId:Hr(r,e.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:e,isLoadingWorkspaces:!1,...yr()});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=Fi(e.path,a,r);if(!this.navigationIsCurrent(n)||!Tu(t)||N(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)||!Tu(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!==``){let e=t.sessionId;return this.browserErrors.reportLocalized(i,()=>gi.t(`sessionNotFound`,{id:e})),()=>gi.t(`sessionNotFound`,{id:e})}else t?.updateUrl!==!1&&this.updateUrl()}catch(e){return t?.signal?.aborted!==!0&&vi(this.browserErrors,i,e),Au(e)}}async refreshProjectWorkspaces(e,t=N(this.getState()),n){return(await this.refreshProjectWorkspaceList(e,t,n)).workspaces}async refreshProjectWorkspaceList(e,t,n){if(!Tu(n))return{workspaces:[],isCurrent:()=>!1};let r=this.getState().projects.find(t=>t.id===e);if(r===void 0)throw new _i(()=>gi.t(`projectNotFound`));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()&&Tu(n)&&N(this.getState())===t){if(this.getState().selectedProject?.id===r.id&&this.setState({workspaceResolution:a}),a.status===`degraded`)throw ku(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=N(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()||N(i)!==n||i.selectedProject?.id!==t.id)return;if(this.setState({workspaceResolution:r}),r.status===`degraded`)throw ku(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=N(this.getState()),r){if(!Tu(r))return;let i=this.beginNavigationOperation?.(Su),{workspaces:a,isCurrent:o}=await this.refreshProjectWorkspaceList(e,n,r);if(!o()||!this.navigationIsCurrent(i)||!Tu(r))return;let s=this.getState();if(N(s)!==n||s.selectedProject?.id!==e||s.selectedWorkspace?.id!==t)return;let c=wu(this.getState(),this.captureNavigation),l=Eu(a);this.navigateToWorkspace===void 0?l===void 0?this.navigationIsCurrent(i)&&Tu(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||Du(e,n)))return{selectedWorkspace:n}}navigationIsCurrent(e){return e===void 0||e.isCurrent()}};function wu(e,t){return t?.()??{machineId:N(e),projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,...e.selectedSession===void 0||Reflect.get(e.selectedSession,`clientPendingStart`)!==!0?{sessionId:e.selectedSession?.id}:{}}}function Tu(e){return e?.signal?.aborted!==!0&&e?.isCurrent?.()!==!1}function Eu(e){return e.find(e=>e.isMain)??e[0]}function Du(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)=>Du(e,t[n]));if(!Ou(e)||!Ou(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&Du(e[n],t[n]))}function Ou(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ku(e){let t=e.diagnostics.map(({message:e})=>e).join(`; `);return t?Error(t):new _i(()=>gi.t(`degraded`))}function Au(e){return e instanceof _i?()=>String(e):String(e)}var ju={unknownView:x(`Unknown view: {view}`,`Requested route view is not supported; raw view identifier stays unchanged`),machineNotFound:x(`Machine not found: {id}`,`Requested route machine is unavailable; identifier stays unchanged`),projectNotFound:x(`Project not found: {id}`,`Requested route project is unavailable; identifier stays unchanged`),remoteMachine:x(`Remote machine`,`Fallback machine name during route reconnection`),reconnecting:x(`{machine} is unavailable; reconnecting…{hasDetail, select, yes { {detail}} other {}}`,`Route reconnection banner; machine name and optional diagnostic stay unchanged`),exhausted:x(`{machine} is still unavailable.{hasDetail, select, yes { {detail}} other {}}`,`Route reconnection attempts exhausted; machine name and optional diagnostic stay unchanged`),loadingProjects:x(`Loading projects…`,`Session area while route projects load`),selectSession:x(`Select or start a session.`,`Session area with a selected workspace but no session`),selectWorkspace:x(`Select a workspace to start a session.`,`Session area with a selected project but no workspace`),addProject:x(`Add a project to start a session.`,`Session area with no projects`),selectProject:x(`Select a project and workspace to start a session.`,`Session area with projects but no selection`)},Mu=w.registerMessages(`core.routeFeedback`,ju),Nu=`core.workspace.files--file`,Pu=`core.workspace.terminal--terminal`,Fu=`pi-web:machine-navigation:v1`,Iu=class{constructor(e=Rc()){this.snapshotsByMachine=new zc(Fu,Vu,e)}latest(e){let t=this.snapshotsByMachine.get(e);return t?.machineId===e?Bu(t):void 0}remember(e){this.snapshotsByMachine.set(e.machineId,Bu(e))}forget(e){this.snapshotsByMachine.delete(e)}};function Lu(e){return{machineId:e,surface:{}}}function Ru(e,t={}){let n=e.selectedWorkspace===void 0?{}:Ya(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 zu(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view}}function Bu(e){let t=e.surface.contributionQuery;return{...e,surface:{...e.surface,...t===void 0?{}:{contributionQuery:Ya(t)}}}}function Vu(e){if(!Ku(e))return;let t=Gu(e,`machineId`);if(t===void 0)return;let n=Gu(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=Uu(Gu(e,`tool`))??r,a=ho(n)??(r===void 0?void 0:`workspace`);return{machineId:t,projectId:Gu(e,`projectId`),workspaceId:Gu(e,`workspaceId`),sessionId:Gu(e,`sessionId`),...i===void 0?{}:{tool:i},...a===void 0?{}:{view:a},surface:Hu(e.surface)}}function Hu(e){if(!Ku(e))return{};let t=Ku(e.contributionQuery)?e.contributionQuery:{},n=Gu(e,`selectedFilePath`),r=Gu(e,`selectedTerminalId`),i=Gu(e,`selectedDiffPath`),a=Ya({...n===void 0?{}:{[Nu]:n},...r===void 0?{}:{[Pu]:r},...i===void 0?{}:{"core.workspace.git--diff":i},...t});return{...Object.keys(a).length===0?{}:{contributionQuery:a}}}function Uu(e){return Wu(e)?e:void 0}function Wu(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Gu(e,t){let n=e[t];return typeof n==`string`&&n!==``?n:void 0}function Ku(e){return typeof e==`object`&&!!e}function qu(e,t,n){if(t!==void 0&&Yu(t.path)===Yu(n.cwd))return{machineId:e,projectId:t.projectId,workspaceId:t.id,root:t.path}}function Ju(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=`${Yu(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 Yu(e){return e.replace(/\/+$/,``)}var Xu={skipPinned:!0,archiveIdleEnabled:!0,archiveIdleDays:`30`,deleteArchivedEnabled:!1,deleteArchivedDays:`90`};function Zu(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,code:`disabled`,error:`Enable at least one cleanup action.`};let t={skipPinned:e.skipPinned,archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){let n=ad(e.archiveIdleDays,`Archive idle sessions after`);if(typeof n!=`number`)return{ok:!1,code:n.code===`required`?`archiveRequired`:`archiveInvalid`,error:n.error};t.archiveIdleDays=n}if(e.deleteArchivedEnabled){let n=ad(e.deleteArchivedDays,`Delete archived sessions after`);if(typeof n!=`number`)return{ok:!1,code:n.code===`required`?`deleteRequired`:`deleteInvalid`,error:n.error};t.deleteArchivedDays=n}return{ok:!0,request:t}}function Qu(e){return JSON.stringify({skipPinned:e?.skipPinned??!1,archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null,projectId:e?.projectId??null})}function $u(e){if(e.canCleanup===!1||e.loading===!0||e.running===!0||e.preview===void 0)return!1;let t=Zu(e.draft);if(!t.ok)return!1;if(e.previewRequest===void 0){if(e.canCleanup!==!0||!ed(e.draft,e.preview))return!1}else if(od(t.request)!==od(e.previewRequest)||(t.request.skipPinned??!1)!==(e.previewRequest.skipPinned??!1))return!1;return td(e.preview)}function ed(e,t){let n=Zu(e);return n.ok?od(n.request)===od(t.thresholds):!1}function td(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function nd(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 rd(e,t){let n=new Set(nd(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 id(e){return C(`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??C(`client.sessionCleanupUi.this.machine.74a83f`,`this machine`)})}function ad(e,t){let n=e.trim();if(n===``)return{code:`required`,error:`${t} must be set.`};let r=Number(n);return!Number.isInteger(r)||r<0?{code:`invalid`,error:`${t} must be a non-negative whole number of days.`}:r}function od(e){return JSON.stringify({archiveIdleDays:e.archiveIdleDays??null,deleteArchivedDays:e.deleteArchivedDays??null})}var sd=new Set,cd=$t+1,ld={unreadCatalog:e=>Tt.unreadCatalog(e),markUnread:(e,t)=>Tt.markUnread(e,t),acknowledgeUnread:(e,t,n,r)=>Tt.acknowledgeUnread(e,t,n,r)},ud=class{constructor(e={}){this.machines=new Map,this.api=e.api??ld,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 sd;let r=new Set;for(let e of t)n.summariesByIdentity.has(gd(e))&&r.add(e.id);return r.size===0?sd:r}isUnread(e,t){return this.machines.get(e)?.projection?.summariesByIdentity.has(gd(t))===!0}applyEvent(e,t){let n=this.machine(e);this.recordObservedEvent(n,t);let r=dd(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)}))}completion(e,t){let n=this.machines.get(e);if(n?.status!==`fresh`||n.projection===void 0)return;let r=n.projection.summariesByIdentity.get(gd(t));return r===void 0?void 0:{catalogId:n.projection.catalogId,sessionId:r.sessionId,cwd:r.cwd,completionOrder:r.completionOrder}}acknowledgeRendered(e,t,n,r){let i=this.completion(e,t);return i?.catalogId!==n.catalogId||i.sessionId!==n.sessionId||i.cwd!==n.cwd||i.completionOrder!==n.completionOrder?Promise.resolve():r===void 0?this.acknowledge(e,t):this.acknowledgeLoaded(e,t,r)}async markUnread(e,t){let n=this.machine(e),r=n.generation,i=this.beginNetworkObservation(n,r);try{let a=await this.api.markUnread(t,e);if(!this.isCurrent(n,r))return;this.applyNetworkSnapshot(n,a,i)&&this.refresh(e)}finally{n.observers.delete(i)}}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(gd(t));if(i===void 0)return Promise.resolve();let a=_d(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(gd(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(gd(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=pd(t),a=`fresh`,o=!1;for(let e of n.events){let t=dd(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>=cd?(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=!hd(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 dd(e,t,n){if(e===void 0){let e=md(n.catalogId);return n.catalogRevision===1?fd(e,`fresh`,n):{projection:e,status:`stale`,requiresRefresh:!0}}if(e.catalogId!==n.catalogId){let e=md(n.catalogId);return n.catalogRevision===1?fd(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?fd(e,t,n):{projection:e,status:`stale`,requiresRefresh:!0}}function fd(e,t,n){let r=new Map(e.summariesByIdentity),i=gd(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 pd(e){return{catalogId:e.catalogId,catalogRevision:e.catalogRevision,summariesByIdentity:new Map(e.sessions.map(e=>[gd(e),{...e}]))}}function md(e){return{catalogId:e,catalogRevision:0,summariesByIdentity:new Map}}function hd(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 gd(e){let t=`id`in e?e.id:e.sessionId;return JSON.stringify([t,e.cwd])}function _d(e,t){return JSON.stringify([e,t.sessionId,t.cwd,t.completionOrder])}var vd={machines:new Set,projects:new Set,workspaces:new Set};function yd(e){let t=xd(e.projectionFor(e.selectedMachineId));return{machines:Sd(e.machineIds,e.projectionFor),projects:wd(e.projects,e.workspacesByProjectId,t),workspaces:Cd(e.workspaces,t)}}function bd(e){return e!==void 0&&e.sessions.length>0}function xd(e){return e===void 0||e.sessions.length===0?Ed:new Set(e.sessions.map(e=>e.cwd))}function Sd(e,t){let n=new Set;for(let r of e)bd(t(r))&&n.add(r);return n}function Cd(e,t){let n=new Set;for(let r of e)t.has(r.path)&&n.add(r.id);return n}function wd(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 Td(e,t){return Dd(e.machines,t.machines)&&Dd(e.projects,t.projects)&&Dd(e.workspaces,t.workspaces)}var Ed=new Set;function Dd(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}var Od=100;function kd(e,t){return e.filter(e=>Md(e,t))}var Ad={snapshot:e=>jt.snapshot(e),dismiss:(e,t,n)=>jt.dismiss(e,t,n)},jd=class{constructor(e={}){this.machines=new Map,this.api=e.api??Ad,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,Nd(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,Nd(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,Nd(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>=Od?(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=!Pd(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 Md(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 Nd(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 Pd(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 Fd(e,t,n,r,i,a,o){Rd(t);let s=t?.mode===`patch`;zd(e,s);let c=e.machineId===void 0?o??(s?n.machineId??`local`:i):Ld(e.machineId)??`local`,l=!s||c!==(n.machineId??`local`),u=Id(e.projectId,l?void 0:n.projectId),d=l||u!==n.projectId,f=Id(e.workspaceId,d?void 0:n.workspaceId),p=d||f!==n.workspaceId,m={machineId:c,projectId:u,workspaceId:f,sessionId:Id(e.sessionId,p?void 0:n.sessionId),tool:Id(e.tool,l?void 0:n.tool),view:Id(e.view,s?n.view:void 0)},h=Ya(p?{}:r);if(e.query!==void 0){if(!Bd(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=Xa(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 Id(e,t){return e===void 0?t:Ld(e)}function Ld(e){return e===null||e===``?void 0:e}function Rd(e){if(e!==void 0){if(!Bd(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 zd(e,t){if(!Bd(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 Bd(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Vd={title:x(`Clean up sessions`,`Session cleanup dialog title and accessible name`),eyebrow:x(`Sessions`,`Small heading above cleanup dialog title`),closeCleanup:x(`Close cleanup`,`Close cleanup dialog tooltip and accessible name`),intro:x(`Choose cleanup rules for the selected machine, then preview the affected projects before making changes.`,`Cleanup dialog introduction`),rulesStep:x(`1. Choose cleanup rules`,`First cleanup step heading`),reviewStep:x(`2. Review cleanup`,`Second cleanup step heading`),reviewIntro:x(`Choose which projects to clean up.`,`Cleanup review step introduction`),summaryEstimates:x(`Estimated counts — matching sessions may change`,`Review summary: cleanup rechecks eligibility when it runs`),summaryPinsProtected:x(`Pinned sessions protected`,`Review summary when pinned sessions are excluded from cleanup`),summaryPinsIncluded:x(`Pinned sessions included`,`Review warning when eligible pinned sessions can be archived or deleted, not merely unpinned`),summaryBusy:x(`Busy sessions skipped`,`Review summary: sessions with active work are always excluded`),back:x(`Back`,`Return to cleanup rules without changing sessions`),archiveSummary:x(`Archive after {days, plural, one {# inactive day} other {# inactive days}}`,`Compact archive rule on cleanup review`),deleteSummary:x(`Delete permanently after {days, plural, one {# day in archive} other {# days in archive}}`,`Compact deletion rule and irreversibility warning on cleanup review`),rules:x(`Cleanup rules`,`Heading for cleanup eligibility controls`),skipPinned:x(`Skip pinned sessions`,`Checkbox protecting pinned sessions from archiving and deletion`),pinnedHint:x(`Pinned sessions will not be archived or deleted. Sessions with active work are always skipped.`,`Explanation of default cleanup protections`),busyHint:x(`Sessions with active work are always skipped.`,`Cleanup protection when pinned sessions are included`),skippedPinned:x(`{count, plural, one {# pinned session was skipped.} other {# pinned sessions were skipped.}}`,`Cleanup preview pinned-session exclusion count`),cancel:x(`Cancel`,`Dismiss cleanup before completion`),close:x(`Close`,`Dismiss completed cleanup`),preview:x(`Preview cleanup`,`Preview cleanup targets without modifying sessions`),previewing:x(`Previewing…`,`Busy preview button`),run:x(`Run cleanup`,`Execute cleanup action and enabled button tooltip`),running:x(`Running…`,`Busy cleanup execution button`),runningHint:x(`Cleanup is running. Closing this dialog will not stop it.`,`Live status explaining that closing does not cancel cleanup`),noTargetsTitle:x(`No sessions to clean up`,`Disabled run button tooltip when the preview has no eligible sessions`),selectRequiredTitle:x(`Select at least one project to run cleanup`,`Disabled run button tooltip when no projects are selected`),previewRequiredTitle:x(`Preview cleanup before running it`,`Disabled run button tooltip when preview is missing or stale`),selectRequired:x(`Select at least one project to run cleanup.`,`Validation when selected projects contain no cleanup targets`),previewRequired:x(`Preview cleanup before running it.`,`Validation when preview is missing or stale`),archiveEnabled:x(`Archive idle sessions`,`Accessible name of archive-action checkbox`),deleteEnabled:x(`Delete old archived sessions`,`Accessible name of permanent-delete-action checkbox`),archiveThreshold:x(`Idle days before archiving`,`Accessible name of archive threshold number input`),deleteThreshold:x(`Archived days before deletion`,`Accessible name of deletion threshold number input`),archiveRule:x(`Days since last activity`,`Label for the archive threshold number input`),deleteRule:x(`Days since archiving`,`Label for the permanent-deletion threshold number input`),warning:x(`<strong>Deletion is permanent.</strong> Cleanup only deletes sessions that are already archived.`,`Destructive cleanup warning; strong tag emphasizes irreversibility`),stale:x(`Cleanup rules changed. Preview again before running cleanup.`,`Status when cleanup rules differ from preview`),previewLabel:x(`Cleanup preview`,`Accessible name of cleanup preview section`),empty:x(`No sessions match these rules. Try a shorter time range or different cleanup options.`,`Empty cleanup preview`),tableLabel:x(`Cleanup projects table`,`Accessible name of horizontally scrollable cleanup table`),cleanupColumn:x(`Clean up`,`Column heading for project selection checkboxes`),pathColumn:x(`Project or workspace`,`Column heading for unchanged filesystem paths`),archiveColumn:x(`Archive`,`Column heading for archive counts`),deleteColumn:x(`Delete`,`Column heading for permanent deletion counts`),totals:x(`Estimated totals`,`Table footer heading for estimated cleanup counts in selected projects`),skipped:x(`{count, plural, one {# busy session was skipped.} other {# busy sessions were skipped.}}`,`Cleanup preview busy-session exclusion count`),selectionLabel:x(`Project selection`,`Accessible name of preview project-selection controls`),selection:x(`{selected, number} of {total, number} projects selected`,`Number of selected projects out of preview projects`),selectAll:x(`Select all`,`Select all preview projects`),deselectAll:x(`Deselect all`,`Deselect all preview projects`),selectProject:x(`Clean up {path}`,`Project checkbox accessible name; path is an unchanged filesystem path`),resultLabel:x(`Cleanup result`,`Accessible name of cleanup result section`),complete:x(`Cleanup complete`,`Heading after successful cleanup`),result:x(`{archived, plural, one {Archived # session} other {Archived # sessions}}; {deleted, plural, one {permanently deleted # archived session.} other {permanently deleted # archived sessions.}}`,`Complete cleanup result sentence with both action counts`),confirm:x(`{archive, plural, =0 {{delete, plural, =0 {Run cleanup?} one {Run cleanup and permanently delete # archived session?} other {Run cleanup and permanently delete # archived sessions?}}} one {{delete, plural, =0 {Run cleanup and archive {archive, number} idle session?} one {Run cleanup and archive {archive, number} idle session and permanently delete # archived session?} other {Run cleanup and archive {archive, number} idle session and permanently delete # archived sessions?}}} other {{delete, plural, =0 {Run cleanup and archive {archive, number} idle sessions?} one {Run cleanup and archive {archive, number} idle sessions and permanently delete # archived session?} other {Run cleanup and archive {archive, number} idle sessions and permanently delete # archived sessions?}}}}
56
56
 
57
57
  These counts are estimates. Eligible sessions and counts may change before cleanup runs.
58
58
 
@@ -762,7 +762,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
762
762
  .workspace-trust-error { color: var(--pi-danger, #c0392b); line-height: 1.3; }
763
763
 
764
764
  }
765
- `]}};g([y({attribute:!1})],mj.prototype,`workspaces`,void 0),g([y()],mj.prototype,`machineId`,void 0),g([y({type:Boolean})],mj.prototype,`managementMode`,void 0),g([y({type:Boolean,reflect:!0,attribute:`tree-layout`})],mj.prototype,`treeLayout`,void 0),g([y({attribute:!1})],mj.prototype,`selectedChildren`,void 0),g([y({attribute:!1})],mj.prototype,`selected`,void 0),g([y({type:Boolean,reflect:!0})],mj.prototype,`collapsible`,void 0),g([y({type:Boolean,reflect:!0})],mj.prototype,`collapsed`,void 0),g([y({attribute:!1})],mj.prototype,`workspaceLabelItems`,void 0),g([y({attribute:!1})],mj.prototype,`activities`,void 0),g([y({attribute:!1})],mj.prototype,`deletingWorkspaceIds`,void 0),g([y({attribute:!1})],mj.prototype,`unreadWorkspaceIds`,void 0),g([y({attribute:!1})],mj.prototype,`statusSnapshot`,void 0),g([y({attribute:!1})],mj.prototype,`onSelect`,void 0),g([y({attribute:!1})],mj.prototype,`onDelete`,void 0),g([y({attribute:!1})],mj.prototype,`onMove`,void 0),g([y({attribute:!1})],mj.prototype,`onToggleCollapsed`,void 0),g([y({attribute:!1})],mj.prototype,`onFocusPreviousSection`,void 0),g([y({attribute:!1})],mj.prototype,`onFocusNextSection`,void 0),g([y({attribute:!1})],mj.prototype,`onCancelKeyboardNavigation`,void 0),g([v()],mj.prototype,`openMenuWorkspaceId`,void 0),g([v()],mj.prototype,`copiedDetailKey`,void 0),g([v()],mj.prototype,`trustByWorkspaceId`,void 0),g([v()],mj.prototype,`branchCollapsed`,void 0),mj=g([_(`workspace-list`)],mj);function hj(e){let t=e.branch??e.label;return e.isMain?U.t(`mainLabel`,{label:t}):t}function gj(e){return`workspace-menu-${encodeURIComponent(e)}`}function _j(e){return e.slice(-8)}function vj(e){return e.map((e,t)=>D`${t===0?null:D`<span class="session-label-separator" aria-hidden="true">·</span>`}${yj(e)}`)}function yj(e){if(e.type===`render`)return D`<span class="session-label-render">${e.render()}</span>`;if(e.type===`link`&&bj(e.href)){let t=e.target??`_blank`;return D`<a class="session-label-item" href=${e.href} title=${e.title??e.text} target=${t} rel=${t===`_blank`?`noopener noreferrer`:E}>${e.text}</a>`}return D`<span class="session-label-item" title=${e.title??e.text}>${e.text}</span>`}function bj(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 xj(e){return e.replace(/[/\\]+$/u,``)}var Sj={sessions:x(`Sessions`,`Session list section heading`),loadingSessions:x(`Loading sessions…`,`Session navigation while the selected project's sessions load`),pinned:x(`Pinned`,`Pinned session group heading`),recent:x(`Recent`,`Unpinned session group heading`),archived:x(`Archived`,`Archived session group heading`),noSelection:x(`No session selected`,`Collapsed session list summary`),unread:x(`{count, number} unread`,`Unread session count`),closeCurrentSelection:x(`Close current session selection`,`Exit bulk selection of current sessions`),selectCurrent:x(`Select current sessions`,`Enter bulk selection of current sessions`),closeArchivedSelection:x(`Close archived session selection`,`Exit bulk selection of archived sessions`),selectArchived:x(`Select archived sessions`,`Enter bulk selection of archived sessions`),cleanupPreview:x(`Preview session cleanup`,`Open session cleanup dialog`),cleanup:x(`Clean up`,`Open session cleanup dialog button`),startAnother:x(`Start another session`,`New session button while others are starting`),start:x(`Start a new session`,`New session button`),starting:x(`{count, plural, one {Starting session…} other {Starting # sessions…}}`,`Pending session creation status`),waiting:x(`{count, plural, one {Waiting for the new session to be created} other {Waiting for new sessions to be created}}`,`Pending session creation explanation`),archive:x(`Archive`,`Archive selected session(s)`),markRead:x(`Mark read`,`Mark selected sessions read`),delete:x(`Delete`,`Permanently delete session(s)`),deleteSelectedTitle:x(`Permanently delete selected archived sessions`,`Destructive bulk action tooltip`),selectAll:x(`Select all`,`Select all sessions in this section`),clearSelected:x(`Clear selected ({count, number})`,`Clear session selection; count includes hidden subsessions`),selectSession:x(`Select {label}`,`Session checkbox accessible name; label is user content`),sessionMeta:x(`{state, select, creating {creating · } error {error · } new {new · } archived {read-only · } other {}}{count, plural, one {# message} other {# messages}}`,`Session state and message count; state is creating/error/new/archived/other`),actions:x(`Session actions`,`Open session action menu`),agentSubsessions:x(`Agent subsessions ({count, number})`,`Expand or collapse child sessions created by agents`),sendingSubsession:x(`Sending subsession message`,`Subsession activity accessibility label`),activeSubsessions:x(`Agent subsessions active`,`Subsession activity accessibility label`),unreadSubsession:x(`Unread subsession activity`,`Subsession unread accessibility label`),restoreTitle:x(`Restore session`,`Restore archived session tooltip`),restore:x(`Restore`,`Restore archived session button`),deleteArchivedTitle:x(`Permanently delete archived session`,`Destructive archived session action tooltip`),deleteArchived:x(`Delete archived session`,`Destructive archived session action`),deleteTransient:x(`Delete transient new session`,`Remove unsaved new session tooltip`),markReadTitle:x(`Mark session as read`,`Mark session as read tooltip`),markAsRead:x(`Mark as read`,`Mark session as read action`),markUnreadTitle:x(`Mark session as unread`,`Mark session as unread tooltip`),markAsUnread:x(`Mark as unread`,`Mark session as unread action`),archiveTitle:x(`Archive session`,`Archive session tooltip`),archiveDescendantsTitle:x(`Archive this session and its descendants`,`Archive a session subtree tooltip`),archiveDescendants:x(`Archive with descendants ({count, number})`,`Archive subtree action with descendant count`),detach:x(`Detach from parent`,`Detach a session from its parent`),stopBeforeReload:x(`Stop current session activity before reloading from disk`,`Disabled reload action tooltip`),reloadTitle:x(`Reload session from disk without refreshing Pi runtime resources`,`Reload action tooltip`),reload:x(`Reload from disk`,`Reload session action`),pin:x(`Pin session`,`Pin session action`),unpin:x(`Unpin session`,`Unpin session action`),moveUp:x(`Move up`,`Move pinned session earlier`),moveDown:x(`Move down`,`Move pinned session later`),missingParent:x(`parent unavailable`,`Orphan session marker accessible name`),missingParentTitle:x(`Parent session is not available in this workspace`,`Orphan session marker tooltip`),depth:x(`depth {count, number}`,`Session tree nesting depth badge`),confirmArchive:x(`Archive “{label}” and {count, plural, one {# descendant session} other {# descendant sessions}}?`,`Native archive confirmation; label is unchanged session content`),confirmDelete:x(`Permanently delete archived session “{label}”? This cannot be undone.`,`Native destructive confirmation; label is unchanged session content`),confirmDeleteSelected:x(`Permanently delete {count, plural, one {# selected archived session} other {# selected archived sessions}}? This cannot be undone.`,`Native bulk destructive confirmation`),sending:x(`Sending message`,`Session activity accessibility label`),active:x(`Session active`,`Session activity accessibility label`),unreadActivity:x(`Unread session activity`,`Session unread accessibility label`)},W=w.registerMessages(`core.sessionNavigation`,Sj);function Cj(e){return`session-menu-${encodeURIComponent(e)}`}function wj(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?_j(e.id):e.firstMessage}var Tj=C(`client.parentSessionLocation.no.parent.session.available.in.this.workspace.cbd17a`,`No parent session available in this workspace`),Ej=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 VA(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.loading=!1,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=C(`ui.appNavigationPanel.updateAndRestartPiWebOnThisMachine2`,`Update and restart Pi-Web on this machine before deleting archived sessions.`),this.cleanupUnavailableMessage=C(`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,this.autoExpandedForSelection=!1,o.createController(this),new S(this)}sessionTree(){if(this.treeCache?.sessions!==this.sessions||this.treeCache.pinnedSessionIds!==this.pinnedSessionIds){let e=Jj(this.sessions,this.pinnedSessionIds),t=new Set(e.map(e=>e.session.id)),n=Yj(this.sessions.filter(e=>e.archived===!0&&!t.has(e.id)),this.pinnedSessionIds);this.treeCache={sessions:this.sessions,pinnedSessionIds:this.pinnedSessionIds,currentRows:e,currentAgentGroups:tM(e),archivedAgentGroups:tM(n),currentSelectableSessions:e.map(e=>e.session).filter(e=>Aj(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=Zj(e.currentRows,this.pinnedSessionIds),n=[...this.pinnedRootIds.filter(e=>t.has(e)),...t],r=$j(rM(e.currentRows,this.expandedAgentParents,e.currentAgentGroups),n),i=r.rows,a=rM(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:eM(i,e.currentAgentGroups),archivedAgentOffsets:eM(a,e.archivedAgentGroups),currentSelectableSessions:i.map(e=>e.session).filter(e=>Aj(e)===`current`),archivedSessions:a.map(e=>e.session)}}return this.visibleTreeCache}automaticSessionCandidates(e){return nM(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=Wj(a,this.statuses[a.id],this.activities[a.id],this.sending[a.id]===!0,this.sessionFlags),u=[l,s?.kind,c?.kind],d=u.includes(`intervention-required`)?`intervention-required`:u.includes(`sending`)?`sending`:l??s?.kind??c?.kind,f=Kj(a,this.unreadSessionIds)||s?.unread===!0||c?.unread===!0;(d!==void 0||f)&&r.set(o,{kind:d,unread:f})}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,Aj(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),Aj(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){this.autoExpandedForSelection=!1,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(`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),this.shouldRevealSelectedRow(e)&&this.revealSelectedAgentRow();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.archivedExpanded=!0,this.autoExpandedForSelection=!0),(e.has(`selected`)||e.has(`sessions`)||e.has(`pinnedSessionIds`))&&this.expandVisibleLimitForSelected()}shouldUpdate(e){if(e.size===0)return!0;for(let[t,n]of e)if(!Ej.has(String(t))&&!(t===`sessions`&&Nj(n,this.sessions))&&!(t===`selected`&&Fj(n,this.selected))&&((t===`statuses`||t===`activities`)&&this.sessionTree().currentAgentGroups.parentByAgentId.size>0||!(t===`statuses`&&Ij(n,this.statuses,this.activities,this.sending,this.sessions,this.authoritativeSessionPersistence,`status`))&&!(t===`activities`&&Ij(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,(this.autoExpandedForSelection||this.shouldRevealSelectedRow(e))&&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,XA(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??=Mj(this.sessions));let c=Dj(t,this.unreadSessionIds),l=n.slice(0,this.currentVisibleLimit),u=l.map(e=>e.session).filter(e=>Aj(e)===`current`),d=r.slice(0,this.archivedVisibleLimit),f=d.map(e=>e.session);return D`
765
+ `]}};g([y({attribute:!1})],mj.prototype,`workspaces`,void 0),g([y()],mj.prototype,`machineId`,void 0),g([y({type:Boolean})],mj.prototype,`managementMode`,void 0),g([y({type:Boolean,reflect:!0,attribute:`tree-layout`})],mj.prototype,`treeLayout`,void 0),g([y({attribute:!1})],mj.prototype,`selectedChildren`,void 0),g([y({attribute:!1})],mj.prototype,`selected`,void 0),g([y({type:Boolean,reflect:!0})],mj.prototype,`collapsible`,void 0),g([y({type:Boolean,reflect:!0})],mj.prototype,`collapsed`,void 0),g([y({attribute:!1})],mj.prototype,`workspaceLabelItems`,void 0),g([y({attribute:!1})],mj.prototype,`activities`,void 0),g([y({attribute:!1})],mj.prototype,`deletingWorkspaceIds`,void 0),g([y({attribute:!1})],mj.prototype,`unreadWorkspaceIds`,void 0),g([y({attribute:!1})],mj.prototype,`statusSnapshot`,void 0),g([y({attribute:!1})],mj.prototype,`onSelect`,void 0),g([y({attribute:!1})],mj.prototype,`onDelete`,void 0),g([y({attribute:!1})],mj.prototype,`onMove`,void 0),g([y({attribute:!1})],mj.prototype,`onToggleCollapsed`,void 0),g([y({attribute:!1})],mj.prototype,`onFocusPreviousSection`,void 0),g([y({attribute:!1})],mj.prototype,`onFocusNextSection`,void 0),g([y({attribute:!1})],mj.prototype,`onCancelKeyboardNavigation`,void 0),g([v()],mj.prototype,`openMenuWorkspaceId`,void 0),g([v()],mj.prototype,`copiedDetailKey`,void 0),g([v()],mj.prototype,`trustByWorkspaceId`,void 0),g([v()],mj.prototype,`branchCollapsed`,void 0),mj=g([_(`workspace-list`)],mj);function hj(e){let t=e.branch??e.label;return e.isMain?U.t(`mainLabel`,{label:t}):t}function gj(e){return`workspace-menu-${encodeURIComponent(e)}`}function _j(e){return e.slice(-8)}function vj(e){return e.map((e,t)=>D`${t===0?null:D`<span class="session-label-separator" aria-hidden="true">·</span>`}${yj(e)}`)}function yj(e){if(e.type===`render`)return D`<span class="session-label-render">${e.render()}</span>`;if(e.type===`link`&&bj(e.href)){let t=e.target??`_blank`;return D`<a class="session-label-item" href=${e.href} title=${e.title??e.text} target=${t} rel=${t===`_blank`?`noopener noreferrer`:E}>${e.text}</a>`}return D`<span class="session-label-item" title=${e.title??e.text}>${e.text}</span>`}function bj(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 xj(e){return e.replace(/[/\\]+$/u,``)}var Sj={sessions:x(`Sessions`,`Session list section heading`),loadingSessions:x(`Loading sessions…`,`Session navigation while the selected project's sessions load`),pinned:x(`Pinned`,`Pinned session group heading`),recent:x(`Recent`,`Unpinned session group heading`),archived:x(`Archived`,`Archived session group heading`),noSelection:x(`No session selected`,`Collapsed session list summary`),unread:x(`{count, number} unread`,`Unread session count`),closeCurrentSelection:x(`Close current session selection`,`Exit bulk selection of current sessions`),selectCurrent:x(`Select current sessions`,`Enter bulk selection of current sessions`),closeArchivedSelection:x(`Close archived session selection`,`Exit bulk selection of archived sessions`),selectArchived:x(`Select archived sessions`,`Enter bulk selection of archived sessions`),cleanupPreview:x(`Preview session cleanup`,`Open session cleanup dialog`),cleanup:x(`Clean up`,`Open session cleanup dialog button`),startAnother:x(`Start another session`,`New session button while others are starting`),start:x(`Start a new session`,`New session button`),starting:x(`{count, plural, one {Starting session…} other {Starting # sessions…}}`,`Pending session creation status`),waiting:x(`{count, plural, one {Waiting for the new session to be created} other {Waiting for new sessions to be created}}`,`Pending session creation explanation`),archive:x(`Archive`,`Archive selected session(s)`),markRead:x(`Mark read`,`Mark selected sessions read`),delete:x(`Delete`,`Permanently delete session(s)`),deleteSelectedTitle:x(`Permanently delete selected archived sessions`,`Destructive bulk action tooltip`),selectAll:x(`Select all`,`Select all sessions in this section`),clearSelected:x(`Clear selected ({count, number})`,`Clear session selection; count includes hidden subsessions`),selectSession:x(`Select {label}`,`Session checkbox accessible name; label is user content`),sessionMeta:x(`{state, select, creating {creating · } error {error · } new {new · } archived {read-only · } other {}}{count, plural, one {# message} other {# messages}}`,`Session state and message count; state is creating/error/new/archived/other`),actions:x(`Session actions`,`Open session action menu`),agentSubsessions:x(`Agent subsessions ({count, number})`,`Expand or collapse child sessions created by agents`),sendingSubsession:x(`Sending subsession message`,`Subsession activity accessibility label`),activeSubsessions:x(`Agent subsessions active`,`Subsession activity accessibility label`),unreadSubsession:x(`Unread subsession activity`,`Subsession unread accessibility label`),restoreTitle:x(`Restore session`,`Restore archived session tooltip`),restore:x(`Restore`,`Restore archived session button`),deleteArchivedTitle:x(`Permanently delete archived session`,`Destructive archived session action tooltip`),deleteArchived:x(`Delete archived session`,`Destructive archived session action`),deleteTransient:x(`Delete transient new session`,`Remove unsaved new session tooltip`),markReadTitle:x(`Mark session as read`,`Mark session as read tooltip`),markAsRead:x(`Mark as read`,`Mark session as read action`),markUnreadTitle:x(`Mark session as unread`,`Mark session as unread tooltip`),markAsUnread:x(`Mark as unread`,`Mark session as unread action`),archiveTitle:x(`Archive session`,`Archive session tooltip`),archiveDescendantsTitle:x(`Archive this session and its descendants`,`Archive a session subtree tooltip`),archiveDescendants:x(`Archive with descendants ({count, number})`,`Archive subtree action with descendant count`),detach:x(`Detach from parent`,`Detach a session from its parent`),stopBeforeReload:x(`Stop current session activity before reloading from disk`,`Disabled reload action tooltip`),reloadTitle:x(`Reload session from disk without refreshing Pi runtime resources`,`Reload action tooltip`),reload:x(`Reload from disk`,`Reload session action`),pin:x(`Pin session`,`Pin session action`),unpin:x(`Unpin session`,`Unpin session action`),moveUp:x(`Move up`,`Move pinned session earlier`),moveDown:x(`Move down`,`Move pinned session later`),missingParent:x(`parent unavailable`,`Orphan session marker accessible name`),missingParentTitle:x(`Parent session is not available in this workspace`,`Orphan session marker tooltip`),depth:x(`depth {count, number}`,`Session tree nesting depth badge`),confirmArchive:x(`Archive “{label}” and {count, plural, one {# descendant session} other {# descendant sessions}}?`,`Native archive confirmation; label is unchanged session content`),confirmDelete:x(`Permanently delete archived session “{label}”? This cannot be undone.`,`Native destructive confirmation; label is unchanged session content`),confirmDeleteSelected:x(`Permanently delete {count, plural, one {# selected archived session} other {# selected archived sessions}}? This cannot be undone.`,`Native bulk destructive confirmation`),sending:x(`Sending message`,`Session activity accessibility label`),active:x(`Session active`,`Session activity accessibility label`),unreadActivity:x(`Unread session activity`,`Session unread accessibility label`)},W=w.registerMessages(`core.sessionNavigation`,Sj);function Cj(e){return`session-menu-${encodeURIComponent(e)}`}function wj(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?_j(e.id):e.firstMessage}var Tj=C(`client.parentSessionLocation.no.parent.session.available.in.this.workspace.cbd17a`,`No parent session available in this workspace`),Ej=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 VA(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.loading=!1,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=C(`ui.appNavigationPanel.updateAndRestartPiWebOnThisMachine2`,`Update and restart Pi-Web on this machine before deleting archived sessions.`),this.cleanupUnavailableMessage=C(`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,this.autoExpandedForSelection=!1,o.createController(this),new S(this)}sessionTree(){if(this.treeCache?.sessions!==this.sessions||this.treeCache.pinnedSessionIds!==this.pinnedSessionIds){let e=Jj(this.sessions,this.pinnedSessionIds),t=new Set(e.map(e=>e.session.id)),n=Yj(this.sessions.filter(e=>e.archived===!0&&!t.has(e.id)),this.pinnedSessionIds);this.treeCache={sessions:this.sessions,pinnedSessionIds:this.pinnedSessionIds,currentRows:e,currentAgentGroups:nM(e),archivedAgentGroups:nM(n),currentSelectableSessions:e.map(e=>e.session).filter(e=>Aj(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=Qj(e.currentRows,this.pinnedSessionIds),n=[...this.pinnedRootIds.filter(e=>t.has(e)),...t],r=eM(iM(e.currentRows,this.expandedAgentParents,e.currentAgentGroups),n),i=r.rows,a=iM(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:tM(i,e.currentAgentGroups),archivedAgentOffsets:tM(a,e.archivedAgentGroups),currentSelectableSessions:i.map(e=>e.session).filter(e=>Aj(e)===`current`),archivedSessions:a.map(e=>e.session)}}return this.visibleTreeCache}automaticSessionCandidates(e){return rM(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=Wj(a,this.statuses[a.id],this.activities[a.id],this.sending[a.id]===!0,this.sessionFlags),u=[l,s?.kind,c?.kind],d=u.includes(`intervention-required`)?`intervention-required`:u.includes(`sending`)?`sending`:l??s?.kind??c?.kind,f=Kj(a,this.unreadSessionIds)||s?.unread===!0||c?.unread===!0;(d!==void 0||f)&&r.set(o,{kind:d,unread:f})}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,Aj(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),Aj(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){this.autoExpandedForSelection=!1,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(`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),this.shouldRevealSelectedRow(e)&&this.revealSelectedAgentRow();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.archivedExpanded=!0,this.autoExpandedForSelection=!0),(e.has(`selected`)||e.has(`sessions`)||e.has(`pinnedSessionIds`))&&this.expandVisibleLimitForSelected()}shouldUpdate(e){if(e.size===0)return!0;for(let[t,n]of e)if(!Ej.has(String(t))&&!(t===`sessions`&&Nj(n,this.sessions))&&!(t===`selected`&&Fj(n,this.selected))&&((t===`statuses`||t===`activities`)&&this.sessionTree().currentAgentGroups.parentByAgentId.size>0||!(t===`statuses`&&Ij(n,this.statuses,this.activities,this.sending,this.sessions,this.authoritativeSessionPersistence,`status`))&&!(t===`activities`&&Ij(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,(this.autoExpandedForSelection||this.shouldRevealSelectedRow(e))&&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,XA(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??=Mj(this.sessions));let c=Dj(t,this.unreadSessionIds),l=n.slice(0,this.currentVisibleLimit),u=l.map(e=>e.session).filter(e=>Aj(e)===`current`),d=r.slice(0,this.archivedVisibleLimit),f=d.map(e=>e.session);return D`
766
766
  <section data-ui-context="sessions" data-collapsed=${String(this.collapsed)}>
767
767
  ${this.renderHeading(e.currentRows.length+e.archivedRows.length,t,c)}
768
768
  ${this.collapsed?null:D`
@@ -966,7 +966,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
966
966
  .session-checkbox { position: absolute; top: 9px; inset-inline-start: calc(24px + var(--depth, 0) * 16px + var(--agent-offset, 0px)); z-index: 2; margin: 0; }
967
967
 
968
968
  }
969
- `]}};g([y({attribute:!1})],G.prototype,`scopeKey`,void 0),g([y({attribute:!1})],G.prototype,`sessions`,void 0),g([y({attribute:!1})],G.prototype,`pinnedSessionIds`,void 0),g([y({type:Boolean})],G.prototype,`loading`,void 0),g([y({attribute:!1})],G.prototype,`pinnedRootIds`,void 0),g([y({attribute:!1})],G.prototype,`onMovePin`,void 0),g([y({attribute:!1})],G.prototype,`statuses`,void 0),g([y({attribute:!1})],G.prototype,`activities`,void 0),g([y({attribute:!1})],G.prototype,`sessionFlags`,void 0),g([y({attribute:!1})],G.prototype,`sending`,void 0),g([y({attribute:!1})],G.prototype,`unreadSessionIds`,void 0),g([y({attribute:!1})],G.prototype,`selected`,void 0),g([y({attribute:!1})],G.prototype,`sessionLabelItems`,void 0),g([y({type:Number})],G.prototype,`startingCount`,void 0),g([y({type:Boolean})],G.prototype,`canStart`,void 0),g([y({type:Boolean})],G.prototype,`canDeleteArchived`,void 0),g([y({type:Boolean})],G.prototype,`canReload`,void 0),g([y({type:Boolean})],G.prototype,`canCleanup`,void 0),g([y({type:Boolean})],G.prototype,`authoritativeSessionPersistence`,void 0),g([y({type:String})],G.prototype,`archivedDeleteUnavailableMessage`,void 0),g([y({type:String})],G.prototype,`cleanupUnavailableMessage`,void 0),g([y({type:Boolean,reflect:!0})],G.prototype,`collapsible`,void 0),g([y({type:Boolean,reflect:!0})],G.prototype,`collapsed`,void 0),g([y({type:Boolean,attribute:`external-scroll`})],G.prototype,`externalScroll`,void 0),g([y({attribute:!1})],G.prototype,`onSelect`,void 0),g([y({attribute:!1})],G.prototype,`onSearch`,void 0),g([y({attribute:!1})],G.prototype,`onTogglePin`,void 0),g([y({attribute:!1})],G.prototype,`onStart`,void 0),g([y({attribute:!1})],G.prototype,`onToggleCollapsed`,void 0),g([y({attribute:!1})],G.prototype,`onArchivedCollapsed`,void 0),g([y({attribute:!1})],G.prototype,`onFocusPreviousSection`,void 0),g([y({attribute:!1})],G.prototype,`onFocusNextSection`,void 0),g([y({attribute:!1})],G.prototype,`onCancelKeyboardNavigation`,void 0),g([y({attribute:!1})],G.prototype,`onArchive`,void 0),g([y({attribute:!1})],G.prototype,`onArchiveWithDescendants`,void 0),g([y({attribute:!1})],G.prototype,`onArchiveMany`,void 0),g([y({attribute:!1})],G.prototype,`onRestore`,void 0),g([y({attribute:!1})],G.prototype,`onDelete`,void 0),g([y({attribute:!1})],G.prototype,`onDeleteArchived`,void 0),g([y({attribute:!1})],G.prototype,`onDeleteArchivedMany`,void 0),g([y({attribute:!1})],G.prototype,`onRename`,void 0),g([y({attribute:!1})],G.prototype,`onDetachParent`,void 0),g([y({attribute:!1})],G.prototype,`onMarkRead`,void 0),g([y({attribute:!1})],G.prototype,`onMarkUnread`,void 0),g([y({attribute:!1})],G.prototype,`onMarkReadMany`,void 0),g([y({attribute:!1})],G.prototype,`onReload`,void 0),g([y({attribute:!1})],G.prototype,`onCleanup`,void 0),g([v()],G.prototype,`openMenuSessionId`,void 0),g([v()],G.prototype,`archivedExpanded`,void 0),g([v()],G.prototype,`selectionScopes`,void 0),g([v()],G.prototype,`selectedSessionIds`,void 0),g([v()],G.prototype,`currentVisibleLimit`,void 0),g([v()],G.prototype,`archivedVisibleLimit`,void 0),g([Te(`.list-body`)],G.prototype,`listBody`,void 0),g([v()],G.prototype,`expandedAgentParents`,void 0),G=g([_(`session-list`)],G);function Dj(e,t){return t.size===0?0:e.filter(e=>Kj(e,t)).length}function Oj(e){let t=globalThis.prompt(C(`ui.sessionList.renameSession`,`Rename session`),wj(e))?.trim();return t===void 0||t===``?void 0:t}function kj(e,t,n){return Ic(e,t,n)}function Aj(e){return e.archived===!0?`archived`:`current`}function jj(e,t){let n=new Set(t);return new Set([...e].filter(e=>!n.has(e)))}function Mj(e){let t=new Map;for(let n of e){if(n.parentSessionPath===void 0)continue;let e=xj(n.parentSessionPath),r=t.get(e)??[];r.push(n),t.set(e,r)}let n=(e,r)=>{let i=xj(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(xj(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 Nj(e,t){return!Array.isArray(e)||e.length!==t.length?!1:t.every((t,n)=>Pj(t)===Pj(e[n]))}function Pj(e){return Rj(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 Fj(e,t){return e===void 0||t===void 0?e===t:Pj(e)===Pj(t)}function Ij(e,t,n,r,i,a,o){if(!zj(e))return!1;for(let s of i){let i=Bj(o===`status`?e:n,s.id),c=Bj(o===`status`?t:n,s.id),l=Vj(o===`activity`?e:n,s.id),u=Vj(o===`activity`?t:n,s.id);if(Lj(s,i,l,r[s.id]===!0,a)!==Lj(s,c,u,r[s.id]===!0,a))return!1}return!0}function Lj(e,t,n,r,i){return JSON.stringify([Wj(e,t,n,r),n?.phase,Fc(e,t,{authoritative:i})])}function Rj(e){return zj(e)&&typeof e.id==`string`&&typeof e.path==`string`}function zj(e){return typeof e==`object`&&!!e}function Bj(e,t){if(!zj(e))return;let n=e[t];return Hj(n)?n:void 0}function Vj(e,t){if(!zj(e))return;let n=e[t];return Uj(n)?n:void 0}function Hj(e){return zj(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)&&zj(e.tokens)&&typeof e.cost==`number`}function Uj(e){return zj(e)&&typeof e.sessionId==`string`&&(e.phase===`active`||e.phase===`idle`||e.phase===`error`)&&typeof e.label==`string`&&typeof e.at==`string`}function Wj(e,t,n,r,i){if(!(Ii(e)||e.archived===!0))return(i===void 0?(t?.sessionId===e.id?t.interventionRequired:void 0)??e.interventionRequired:i[e.id]?.[Zt.interventionRequired]===!0)===!0?`intervention-required`:r?`sending`:Gj(e,t,n,i)?`session`:void 0}function Gj(e,t,n,r){return r===void 0?Pr(t,n):r[e.id]?.[Zt.working]===!0}function Kj(e,t){return Ii(e)||e.archived===!0?!1:t.has(e.id)}function qj(e){return new Map(e.map(e=>[xj(e.path),e]))}function Jj(e,t=[]){let n=qj(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:xj(t.parentSessionPath),i=new Set([xj(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:xj(t.parentSessionPath)}}return Yj(e.filter(e=>r.has(e.id)),t)}function Yj(e,t=[]){let n=qj(e),r=new Map,i=[];for(let t of e){let e=t.parentSessionPath,a=e===void 0?void 0:n.get(xj(e));if(a===void 0){i.push(t);continue}let o=xj(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)=>[xj(e.path),t])),s=new Map,c=(e,t)=>{if(a.has(e.id))return!0;let n=xj(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(xj(e.path))??0)-(o.get(xj(t.path))??0):r},u=[],d=(e,t,i)=>{let a=xj(e.path);if(i.has(a))return;let o=e.parentSessionPath;u.push({session:e,depth:t,hasMissingParent:o!==void 0&&!n.has(xj(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 Xj(e,t){let n=Jj([...e],t);return $j(n,[...Zj(n,t)]).pinnedRootIds}function Zj(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 Qj(e){return e.depth===0&&!e.hasMissingParent&&e.session.parentSessionPath===void 0&&e.session.archived!==!0}function $j(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&&Qj(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 eM(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 tM(e){let t=qj(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(xj(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 nM(e,t={}){if(t.collapsed===!0)return[];let n=t.expandedAgentParents??new Set,r=Jj(e),i=new Set(rM(r,n).map(e=>e.session.id));if(t.archivedExpanded===!0){let t=new Set(r.map(e=>e.session.id)),a=Yj(e.filter(e=>e.archived===!0&&!t.has(e.id)));for(let e of rM(a,n))i.add(e.session.id)}return e.filter(e=>i.has(e.id))}function rM(e,t,n=tM(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 iM={info:`M12 8h.01M11 12h1v5M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0`,archive:`M3 3h18v4H3zM5 7v14h14V7M10 11h4`,delete:`M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7M14 10v7`,check:`M5 12l4 4L19 6`,warning:`M12 3 2 21h20L12 3zM12 9v5M12 18h.01`},aM=class extends O{constructor(){super(),this.canCleanup=!0,this.unavailableMessage=C(`ui.sessionCleanupDialog.updateAndRestartPiWebOnThisMachine`,`Update and restart Pi-Web on this machine before cleaning up sessions.`),this.loading=!1,this.running=!1,this.error=``,this.step=`rules`,this.draft={...Xu},o.createController(this),new S(this)}willUpdate(e){e.has(`preview`)&&(this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd),this.preview!==void 0&&(this.step=`review`))}updated(e){if(e.has(`step`)&&e.get(`step`)!==void 0||e.has(`result`)&&this.result!==void 0){(this.shadowRoot?.querySelector(`#step-heading, .result h2`))?.focus();let e=this.shadowRoot?.querySelector(`.body`);e!=null&&(e.scrollTop=0)}}render(){let e=this.step===`review`&&this.preview!==void 0,t=this.result!==void 0;return D`
969
+ `]}};g([y({attribute:!1})],G.prototype,`scopeKey`,void 0),g([y({attribute:!1})],G.prototype,`sessions`,void 0),g([y({attribute:!1})],G.prototype,`pinnedSessionIds`,void 0),g([y({type:Boolean})],G.prototype,`loading`,void 0),g([y({attribute:!1})],G.prototype,`pinnedRootIds`,void 0),g([y({attribute:!1})],G.prototype,`onMovePin`,void 0),g([y({attribute:!1})],G.prototype,`statuses`,void 0),g([y({attribute:!1})],G.prototype,`activities`,void 0),g([y({attribute:!1})],G.prototype,`sessionFlags`,void 0),g([y({attribute:!1})],G.prototype,`sending`,void 0),g([y({attribute:!1})],G.prototype,`unreadSessionIds`,void 0),g([y({attribute:!1})],G.prototype,`selected`,void 0),g([y({attribute:!1})],G.prototype,`sessionLabelItems`,void 0),g([y({type:Number})],G.prototype,`startingCount`,void 0),g([y({type:Boolean})],G.prototype,`canStart`,void 0),g([y({type:Boolean})],G.prototype,`canDeleteArchived`,void 0),g([y({type:Boolean})],G.prototype,`canReload`,void 0),g([y({type:Boolean})],G.prototype,`canCleanup`,void 0),g([y({type:Boolean})],G.prototype,`authoritativeSessionPersistence`,void 0),g([y({type:String})],G.prototype,`archivedDeleteUnavailableMessage`,void 0),g([y({type:String})],G.prototype,`cleanupUnavailableMessage`,void 0),g([y({type:Boolean,reflect:!0})],G.prototype,`collapsible`,void 0),g([y({type:Boolean,reflect:!0})],G.prototype,`collapsed`,void 0),g([y({type:Boolean,attribute:`external-scroll`})],G.prototype,`externalScroll`,void 0),g([y({attribute:!1})],G.prototype,`onSelect`,void 0),g([y({attribute:!1})],G.prototype,`onSearch`,void 0),g([y({attribute:!1})],G.prototype,`onTogglePin`,void 0),g([y({attribute:!1})],G.prototype,`onStart`,void 0),g([y({attribute:!1})],G.prototype,`onToggleCollapsed`,void 0),g([y({attribute:!1})],G.prototype,`onArchivedCollapsed`,void 0),g([y({attribute:!1})],G.prototype,`onFocusPreviousSection`,void 0),g([y({attribute:!1})],G.prototype,`onFocusNextSection`,void 0),g([y({attribute:!1})],G.prototype,`onCancelKeyboardNavigation`,void 0),g([y({attribute:!1})],G.prototype,`onArchive`,void 0),g([y({attribute:!1})],G.prototype,`onArchiveWithDescendants`,void 0),g([y({attribute:!1})],G.prototype,`onArchiveMany`,void 0),g([y({attribute:!1})],G.prototype,`onRestore`,void 0),g([y({attribute:!1})],G.prototype,`onDelete`,void 0),g([y({attribute:!1})],G.prototype,`onDeleteArchived`,void 0),g([y({attribute:!1})],G.prototype,`onDeleteArchivedMany`,void 0),g([y({attribute:!1})],G.prototype,`onRename`,void 0),g([y({attribute:!1})],G.prototype,`onDetachParent`,void 0),g([y({attribute:!1})],G.prototype,`onMarkRead`,void 0),g([y({attribute:!1})],G.prototype,`onMarkUnread`,void 0),g([y({attribute:!1})],G.prototype,`onMarkReadMany`,void 0),g([y({attribute:!1})],G.prototype,`onReload`,void 0),g([y({attribute:!1})],G.prototype,`onCleanup`,void 0),g([v()],G.prototype,`openMenuSessionId`,void 0),g([v()],G.prototype,`archivedExpanded`,void 0),g([v()],G.prototype,`selectionScopes`,void 0),g([v()],G.prototype,`selectedSessionIds`,void 0),g([v()],G.prototype,`currentVisibleLimit`,void 0),g([v()],G.prototype,`archivedVisibleLimit`,void 0),g([Te(`.list-body`)],G.prototype,`listBody`,void 0),g([v()],G.prototype,`expandedAgentParents`,void 0),G=g([_(`session-list`)],G);function Dj(e,t){return t.size===0?0:e.filter(e=>Kj(e,t)).length}function Oj(e){let t=globalThis.prompt(C(`ui.sessionList.renameSession`,`Rename session`),wj(e))?.trim();return t===void 0||t===``?void 0:t}function kj(e,t,n){return Ic(e,t,n)}function Aj(e){return e.archived===!0?`archived`:`current`}function jj(e,t){let n=new Set(t);return new Set([...e].filter(e=>!n.has(e)))}function Mj(e){let t=new Map;for(let n of e){if(n.parentSessionPath===void 0)continue;let e=xj(n.parentSessionPath),r=t.get(e)??[];r.push(n),t.set(e,r)}let n=(e,r)=>{let i=xj(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(xj(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 Nj(e,t){return!Array.isArray(e)||e.length!==t.length?!1:t.every((t,n)=>Pj(t)===Pj(e[n]))}function Pj(e){return Rj(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 Fj(e,t){return e===void 0||t===void 0?e===t:Pj(e)===Pj(t)}function Ij(e,t,n,r,i,a,o){if(!zj(e))return!1;for(let s of i){let i=Bj(o===`status`?e:n,s.id),c=Bj(o===`status`?t:n,s.id),l=Vj(o===`activity`?e:n,s.id),u=Vj(o===`activity`?t:n,s.id);if(Lj(s,i,l,r[s.id]===!0,a)!==Lj(s,c,u,r[s.id]===!0,a))return!1}return!0}function Lj(e,t,n,r,i){return JSON.stringify([Wj(e,t,n,r),n?.phase,Fc(e,t,{authoritative:i})])}function Rj(e){return zj(e)&&typeof e.id==`string`&&typeof e.path==`string`}function zj(e){return typeof e==`object`&&!!e}function Bj(e,t){if(!zj(e))return;let n=e[t];return Hj(n)?n:void 0}function Vj(e,t){if(!zj(e))return;let n=e[t];return Uj(n)?n:void 0}function Hj(e){return zj(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)&&zj(e.tokens)&&typeof e.cost==`number`}function Uj(e){return zj(e)&&typeof e.sessionId==`string`&&(e.phase===`active`||e.phase===`idle`||e.phase===`error`)&&typeof e.label==`string`&&typeof e.at==`string`}function Wj(e,t,n,r,i){if(!(Ii(e)||e.archived===!0))return(i===void 0?(t?.sessionId===e.id?t.interventionRequired:void 0)??e.interventionRequired:i[e.id]?.[Zt.interventionRequired]===!0)===!0?`intervention-required`:r?`sending`:Gj(e,t,n,i)?`session`:void 0}function Gj(e,t,n,r){return r===void 0?Pr(t,n):r[e.id]?.[Zt.working]===!0}function Kj(e,t){return Ii(e)||e.archived===!0?!1:t.has(e.id)}function qj(e){return new Map(e.map(e=>[xj(e.path),e]))}function Jj(e,t=[]){let n=qj(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:xj(t.parentSessionPath),i=new Set([xj(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:xj(t.parentSessionPath)}}return Yj(e.filter(e=>r.has(e.id)),t)}function Yj(e,t=[]){let n=qj(e),r=new Map,i=[];for(let t of e){let e=t.parentSessionPath,a=e===void 0?void 0:n.get(xj(e));if(a===void 0){i.push(t);continue}let o=xj(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)=>[xj(e.path),t])),s=new Map,c=(e,t)=>{if(a.has(e.id))return!0;let n=xj(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(xj(e.path))??0)-(o.get(xj(t.path))??0):r},u=[],d=(e,t,i)=>{let a=xj(e.path);if(i.has(a))return;let o=e.parentSessionPath;u.push({session:e,depth:t,hasMissingParent:o!==void 0&&!n.has(xj(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 Xj(e,t){let n=Jj([...e],t);return eM(n,[...Qj(n,t)]).pinnedRootIds}function Zj(e,t){let n=Jj([...e],t),r=new Map,i;for(let e of n)e.depth===0&&(i=e.session.id),i!==void 0&&r.set(e.session.id,i);return eM(n,t.flatMap(e=>r.get(e)??[])).pinnedRootIds}function Qj(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 $j(e){return e.depth===0&&!e.hasMissingParent&&e.session.parentSessionPath===void 0&&e.session.archived!==!0}function eM(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&&$j(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 tM(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 nM(e){let t=qj(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(xj(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 rM(e,t={}){if(t.collapsed===!0)return[];let n=t.expandedAgentParents??new Set,r=Jj(e),i=new Set(iM(r,n).map(e=>e.session.id));if(t.archivedExpanded===!0){let t=new Set(r.map(e=>e.session.id)),a=Yj(e.filter(e=>e.archived===!0&&!t.has(e.id)));for(let e of iM(a,n))i.add(e.session.id)}return e.filter(e=>i.has(e.id))}function iM(e,t,n=nM(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 aM={info:`M12 8h.01M11 12h1v5M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0`,archive:`M3 3h18v4H3zM5 7v14h14V7M10 11h4`,delete:`M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7M14 10v7`,check:`M5 12l4 4L19 6`,warning:`M12 3 2 21h20L12 3zM12 9v5M12 18h.01`},oM=class extends O{constructor(){super(),this.canCleanup=!0,this.unavailableMessage=C(`ui.sessionCleanupDialog.updateAndRestartPiWebOnThisMachine`,`Update and restart Pi-Web on this machine before cleaning up sessions.`),this.loading=!1,this.running=!1,this.error=``,this.step=`rules`,this.draft={...Xu},o.createController(this),new S(this)}willUpdate(e){e.has(`preview`)&&(this.selectedProjectCwds=this.preview?.projects.map(e=>e.cwd),this.preview!==void 0&&(this.step=`review`))}updated(e){if(e.has(`step`)&&e.get(`step`)!==void 0||e.has(`result`)&&this.result!==void 0){(this.shadowRoot?.querySelector(`#step-heading, .result h2`))?.focus();let e=this.shadowRoot?.querySelector(`.body`);e!=null&&(e.scrollTop=0)}}render(){let e=this.step===`review`&&this.preview!==void 0,t=this.result!==void 0;return D`
970
970
  <modal-surface .onClose=${()=>{this.onClose?.()}} .label=${L.t(`title`)}>
971
971
  <header class="ui-dialog-header">
972
972
  <h1 class="ui-dialog-title">${L.t(`title`)}</h1>
@@ -1002,20 +1002,20 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1002
1002
  `}renderForm(){let e=this.loading||this.running;return D`
1003
1003
  <fieldset aria-label=${L.t(`rules`)} ?disabled=${e}>
1004
1004
  <div class="cleanup-rule">
1005
- <label class="ui-checkbox-field"><input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:oM(e)})}}>${L.t(`archiveEnabled`)}</label>
1005
+ <label class="ui-checkbox-field"><input type="checkbox" .checked=${this.draft.archiveIdleEnabled} @change=${e=>{this.updateDraft({archiveIdleEnabled:sM(e)})}}>${L.t(`archiveEnabled`)}</label>
1006
1006
  <div class="threshold-field">
1007
1007
  <label for="archive-days">${L.t(`archiveRule`)}</label>
1008
- <input id="archive-days" class="ui-input days" aria-label=${L.t(`archiveThreshold`)} type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${e||!this.draft.archiveIdleEnabled} @input=${e=>{this.updateDraft({archiveIdleDays:sM(e)})}}>
1008
+ <input id="archive-days" class="ui-input days" aria-label=${L.t(`archiveThreshold`)} type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.archiveIdleDays} ?disabled=${e||!this.draft.archiveIdleEnabled} @input=${e=>{this.updateDraft({archiveIdleDays:cM(e)})}}>
1009
1009
  </div>
1010
1010
  </div>
1011
1011
  <div class="cleanup-rule">
1012
- <label class="ui-checkbox-field"><input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:oM(e)})}}>${L.t(`deleteEnabled`)}</label>
1012
+ <label class="ui-checkbox-field"><input type="checkbox" .checked=${this.draft.deleteArchivedEnabled} @change=${e=>{this.updateDraft({deleteArchivedEnabled:sM(e)})}}>${L.t(`deleteEnabled`)}</label>
1013
1013
  <div class="threshold-field">
1014
1014
  <label for="delete-days">${L.t(`deleteRule`)}</label>
1015
- <input id="delete-days" class="ui-input days" aria-label=${L.t(`deleteThreshold`)} type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${e||!this.draft.deleteArchivedEnabled} @input=${e=>{this.updateDraft({deleteArchivedDays:sM(e)})}}>
1015
+ <input id="delete-days" class="ui-input days" aria-label=${L.t(`deleteThreshold`)} type="number" min="0" step="1" inputmode="numeric" .value=${this.draft.deleteArchivedDays} ?disabled=${e||!this.draft.deleteArchivedEnabled} @input=${e=>{this.updateDraft({deleteArchivedDays:cM(e)})}}>
1016
1016
  </div>
1017
1017
  </div>
1018
- <label class="ui-checkbox-field"><input id="skip-pinned" type="checkbox" .checked=${this.draft.skipPinned} @change=${e=>{this.updateDraft({skipPinned:oM(e)})}}>${L.t(`skipPinned`)}</label>
1018
+ <label class="ui-checkbox-field"><input id="skip-pinned" type="checkbox" .checked=${this.draft.skipPinned} @change=${e=>{this.updateDraft({skipPinned:sM(e)})}}>${L.t(`skipPinned`)}</label>
1019
1019
  <p class="hint">${L.t(this.draft.skipPinned?`pinnedHint`:`busyHint`)}</p>
1020
1020
  </fieldset>
1021
1021
  ${this.draft.deleteArchivedEnabled?D`<p class="warning">${L.rich(`warning`,{strong:e=>D`<strong>${e}</strong>`})}</p>`:null}
@@ -1047,7 +1047,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1047
1047
  ${this.renderSkipped(e)}
1048
1048
  </section>
1049
1049
  `}renderSummaryItem(e,t,n=`default`){return D`<li class=${`summary-${n}`}>
1050
- <svg aria-hidden="true" focusable="false" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d=${iM[e]} /></svg>
1050
+ <svg aria-hidden="true" focusable="false" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d=${aM[e]} /></svg>
1051
1051
  <span>${t}</span>
1052
1052
  </li>`}renderSkipped(e){return D`
1053
1053
  ${e.skippedPinnedSessionIds===void 0||e.skippedPinnedSessionIds.length===0?null:D`<p class="hint">${L.t(`skippedPinned`,{count:e.skippedPinnedSessionIds.length})}</p>`}
@@ -1061,7 +1061,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1061
1061
  ${t.length===0?D`<p class="hint" role="status">${L.t(`selectRequired`)}</p>`:null}
1062
1062
  `}renderProjectRow(e,t){return D`
1063
1063
  <tr class=${t?``:`unselected`}>
1064
- <td class="select-cell"><input type="checkbox" aria-label=${L.t(`selectProject`,{path:e.cwd})} .checked=${t} ?disabled=${this.loading||this.running} @change=${t=>{this.setProjectSelected(e.cwd,oM(t))}}></td>
1064
+ <td class="select-cell"><input type="checkbox" aria-label=${L.t(`selectProject`,{path:e.cwd})} .checked=${t} ?disabled=${this.loading||this.running} @change=${t=>{this.setProjectSelected(e.cwd,sM(t))}}></td>
1065
1065
  <th title=${e.cwd} dir="auto">${e.cwd}</th>
1066
1066
  <td>${w.number(e.archiveCount)}</td>
1067
1067
  <td>${w.number(e.deleteCount)}</td>
@@ -1114,7 +1114,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1114
1114
  thead th:nth-child(3), thead th:nth-child(4) { width: 44px; }
1115
1115
  th, td { padding: 8px 4px; }
1116
1116
  }
1117
- `]}};g([y({type:Boolean})],aM.prototype,`canCleanup`,void 0),g([y({type:String})],aM.prototype,`unavailableMessage`,void 0),g([y({attribute:!1})],aM.prototype,`preview`,void 0),g([y({attribute:!1})],aM.prototype,`previewRequest`,void 0),g([y({attribute:!1})],aM.prototype,`result`,void 0),g([y({type:Boolean})],aM.prototype,`loading`,void 0),g([y({type:Boolean})],aM.prototype,`running`,void 0),g([y({type:String})],aM.prototype,`error`,void 0),g([y({attribute:!1})],aM.prototype,`errorMessage`,void 0),g([y({attribute:!1})],aM.prototype,`onPreview`,void 0),g([y({attribute:!1})],aM.prototype,`onRun`,void 0),g([y({attribute:!1})],aM.prototype,`onClose`,void 0),g([v()],aM.prototype,`step`,void 0),g([v()],aM.prototype,`draft`,void 0),g([v()],aM.prototype,`formError`,void 0),g([v()],aM.prototype,`selectedProjectCwds`,void 0),aM=g([_(`session-cleanup-dialog`)],aM);function oM(e){return e.target instanceof HTMLInputElement&&e.target.checked}function sM(e){return e.target instanceof HTMLInputElement?e.target.value:``}var cM=class extends O{constructor(){super(),this.query=``,this.searching=!1,this.error=``,o.createController(this)}render(){let e=this.query.trim()!==``;return D`
1117
+ `]}};g([y({type:Boolean})],oM.prototype,`canCleanup`,void 0),g([y({type:String})],oM.prototype,`unavailableMessage`,void 0),g([y({attribute:!1})],oM.prototype,`preview`,void 0),g([y({attribute:!1})],oM.prototype,`previewRequest`,void 0),g([y({attribute:!1})],oM.prototype,`result`,void 0),g([y({type:Boolean})],oM.prototype,`loading`,void 0),g([y({type:Boolean})],oM.prototype,`running`,void 0),g([y({type:String})],oM.prototype,`error`,void 0),g([y({attribute:!1})],oM.prototype,`errorMessage`,void 0),g([y({attribute:!1})],oM.prototype,`onPreview`,void 0),g([y({attribute:!1})],oM.prototype,`onRun`,void 0),g([y({attribute:!1})],oM.prototype,`onClose`,void 0),g([v()],oM.prototype,`step`,void 0),g([v()],oM.prototype,`draft`,void 0),g([v()],oM.prototype,`formError`,void 0),g([v()],oM.prototype,`selectedProjectCwds`,void 0),oM=g([_(`session-cleanup-dialog`)],oM);function sM(e){return e.target instanceof HTMLInputElement&&e.target.checked}function cM(e){return e.target instanceof HTMLInputElement?e.target.value:``}var lM=class extends O{constructor(){super(),this.query=``,this.searching=!1,this.error=``,o.createController(this)}render(){let e=this.query.trim()!==``;return D`
1118
1118
  <modal-surface .onClose=${()=>{this.onClose?.()}} .initialFocus=${`input`} .label=${C(`ui.sessionSearchDialog.searchSessionContent`,`Search session content`)}>
1119
1119
  <header class="ui-dialog-header">
1120
1120
  <div>
@@ -1126,7 +1126,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1126
1126
  <div class="body">
1127
1127
  <label class="search-field">
1128
1128
  <span aria-hidden="true">⌕</span>
1129
- <input type="search" aria-label=${C(`ui.sessionSearchDialog.searchUserQuestionsOrAiAnswers`,`Search user questions or AI answers`)} .value=${this.query} @input=${e=>{this.onSearch?.(fM(e))}}>
1129
+ <input type="search" aria-label=${C(`ui.sessionSearchDialog.searchUserQuestionsOrAiAnswers`,`Search user questions or AI answers`)} .value=${this.query} @input=${e=>{this.onSearch?.(pM(e))}}>
1130
1130
  ${this.searching?D`<span class="spinner" aria-label=${C(`ui.sessionSearchDialog.searching`,`Searching`)}></span>`:null}
1131
1131
  </label>
1132
1132
  ${this.renderStatus(e)}
@@ -1142,7 +1142,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1142
1142
  ${e.results.map(e=>D`
1143
1143
  <section class="session-group">
1144
1144
  <div class="session-heading">
1145
- <strong dir="auto">${dM(e.session)}</strong>
1145
+ <strong dir="auto">${fM(e.session)}</strong>
1146
1146
  <span>${C(`ui.sessionSearchDialog.matchCount`,`{count} matches`,{count:e.matches.length})}</span>
1147
1147
  </div>
1148
1148
  ${e.matches.map(t=>this.renderMatch(e.session,t))}
@@ -1153,7 +1153,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1153
1153
  <button class="match-row ui-selection-option" @click=${()=>{this.onSelect?.(e,t)}}>
1154
1154
  <span class="match-meta"><span class=${`role ${t.role}`}>${n}</span></span>
1155
1155
  <span class="excerpts" dir="auto">
1156
- ${t.excerpts.map(e=>D`<span class="excerpt">${lM(e)}</span>`)}
1156
+ ${t.excerpts.map(e=>D`<span class="excerpt">${uM(e)}</span>`)}
1157
1157
  </span>
1158
1158
  <span class="jump" aria-hidden="true">→</span>
1159
1159
  </button>
@@ -1198,7 +1198,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1198
1198
  .body { padding: 12px; }
1199
1199
  .match-row { padding-left: 10px; }
1200
1200
  }
1201
- `}};g([y({type:String})],cM.prototype,`query`,void 0),g([y({attribute:!1})],cM.prototype,`response`,void 0),g([y({type:Boolean})],cM.prototype,`searching`,void 0),g([y({type:String})],cM.prototype,`error`,void 0),g([y({attribute:!1})],cM.prototype,`onSearch`,void 0),g([y({attribute:!1})],cM.prototype,`onSelect`,void 0),g([y({attribute:!1})],cM.prototype,`onClose`,void 0),cM=g([_(`session-search-dialog`)],cM);function lM(e){return D`${uM(e).map(e=>e.highlighted?D`<mark>${e.text}</mark>`:e.text)}`}function uM(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 dM(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?_j(e.id):e.firstMessage}function fM(e){return e.target instanceof HTMLInputElement?e.target.value:``}var pM={title:x(`Navigate session tree`,`Full-screen session history dialog title and accessible name`),eyebrow:x(`Conversation history`,`Small heading above the session tree dialog title`),close:x(`Close session tree`,`Close session tree dialog button tooltip and accessible name`),intro:x(`Select the history entry where you would like to continue.`,`Instruction above selectable conversation history entries`),markers:x(`Session tree markers`,`Accessible name of the active-path and active-leaf legend`),activePath:x(`Active path`,`Legend and badge for entries on the current conversation branch`),activeLeaf:x(`Active leaf`,`Legend and badge for the last entry on the current conversation branch`),empty:x(`This session does not contain any selectable history entries.`,`Empty state when conversation history contains no selectable entries`),history:x(`Complete session history`,`Accessible name of the complete conversation history tree`),noChildren:x(`No child entries`,`Tooltip on a history entry without child entries`),collapse:x(`Collapse branch`,`Tooltip for folding a branch of the history tree`),expand:x(`Expand branch`,`Tooltip for unfolding a branch of the history tree`),selected:x(`Selected entry`,`Heading above the chosen history entry`),choose:x(`Choose how to continue`,`Heading on the operation confirmation step`),unavailableEntry:x(`The selected history entry is no longer available.`,`Warning when the selected history entry has disappeared`),operation:x(`How would you like to continue?`,`Legend for same-session continuation versus creating a new session`),continueOption:x(`Continue in this session`,`Radio option: keep the session file and branch from the chosen entry`),continueDescription:x(`Branch from the selected entry in this session file and keep its other branches.`,`Explanation of same-session continuation; existing branches are preserved`),forkOption:x(`Fork into a new session`,`Radio option: create and switch to a separate session`),forkDescription:x(`Create and switch to a separate session file while leaving the original unchanged.`,`Explanation of creating a new session; the original is preserved`),summary:x(`Abandoned branch summary`,`Legend for options to summarize the context being left behind`),none:x(`No summary`,`Radio option: do not summarize the abandoned branch`),noneDescription:x(`Switch branches without adding a summary entry.`,`Explanation of switching branches without generating a summary`),default:x(`Summarize`,`Radio option: generate the default abandoned-branch summary`),defaultDescription:x(`Ask Pi to summarize the context being left behind.`,`Explanation of default summary; Pi is the agent name`),custom:x(`Summarize with custom focus`,`Radio option: summarize with user-provided focus instructions`),customDescription:x(`Guide Pi toward the details that matter for the new branch.`,`Explanation of guiding the summary toward relevant details; Pi is the agent name`),customFocus:x(`Custom summary focus`,`Label for the summary-focus instructions textarea`),sideEffectsTitle:x(`Conversation context only.`,`Emphasized warning: tree actions only affect conversation context`),sideEffects:x(`Continuing or forking does not undo filesystem changes, shell commands, tool calls, or other side effects.`,`Warning that session continuation and forking cannot undo external side effects`),forkUser:x(`The new session will branch before this user message, and its text will return to the prompt editor as the new session draft.`,`Fork behavior for a user message: branch before it and restore its text as a draft`),forkOther:x(`The new session will include this entry and all history leading to it.`,`Fork behavior for non-user entries: include the chosen entry and earlier history`),continueUser:x(`This message’s text will return to the prompt editor for optional editing and resubmission in this session.`,`Continuation behavior for user or custom messages: restore text to the prompt editor`),continueOther:x(`The prompt editor will be empty after continuing from this entry in this session.`,`Continuation behavior for other entries: leave the prompt editor empty`),cancel:x(`Cancel`,`Dismiss the session tree without taking an action`),next:x(`Next`,`Advance from history selection to operation confirmation`),back:x(`Back`,`Return from operation confirmation to history selection`),cancelling:x(`Cancelling…`,`Busy button label while a summarization cancellation request is pending`),cancelSummary:x(`Cancel summarization`,`Cancel an in-flight abandoned-branch summarization`),continueAction:x(`Continue from here`,`Submit same-session continuation from the selected history entry`),forkAction:x(`Fork into new session`,`Submit creation of a new session from the selected history entry`),forking:x(`Forking…`,`Busy label while creating a new session`),continuing:x(`Continuing…`,`Busy label while continuing without a summary`),summarizing:x(`Summarizing…`,`Busy label while generating an abandoned-branch summary`),navigationUnavailable:x(`Session tree navigation is unavailable. Close and reopen /tree, then try again.`,`Client navigation callback is unavailable; /tree is a literal slash command`),summaryCancelled:x(`Summarization cancelled. Your selected history entry is unchanged.`,`Status after cancelled summarization; the selected history entry remains unchanged`),navigationCancelled:x(`Navigation cancelled. Your selected history entry is unchanged.`,`Status after cancelled navigation; the selected history entry remains unchanged`),forkUnavailable:x(`Fork from the session tree is unavailable. Close and reopen /tree, then try again.`,`Client fork callback is unavailable; /tree is a literal slash command`),forkCancelled:x(`Fork cancelled. No new session was created; your selected history entry is unchanged.`,`Status after cancelled fork; no session was created and selection remains unchanged`),abortUnavailable:x(`Summarization cannot be cancelled from this client.`,`Error when the client cannot cancel summarization`),aborting:x(`Cancelling summarization…`,`Live status while a summarization cancellation request is pending`),kind_user:x(`User`,`Session history entry kind: user`),kind_assistant:x(`Assistant`,`Session history entry kind: assistant`),kind_tool_result:x(`Tool result`,`Session history entry kind: tool-result`),kind_bash:x(`Shell`,`Session history entry kind: bash`),kind_custom_message:x(`Custom message`,`Session history entry kind: custom-message`),kind_compaction:x(`Compaction`,`Session history entry kind: compaction`),kind_branch_summary:x(`Branch summary`,`Session history entry kind: branch-summary`),kind_model_change:x(`Model`,`Session history entry kind: model-change`),kind_thinking_level_change:x(`Thinking`,`Session history entry kind: thinking-level-change`),kind_session_info:x(`Session info`,`Session history entry kind: session-info`),kind_label:x(`Label`,`Session history entry kind: label`),kind_custom:x(`Custom`,`Session history entry kind: custom`),kind_other:x(`Other`,`Session history entry kind: other`),navigationFailed:x(`Could not navigate session history: {error}`,`Session tree failure; error is an untranslated diagnostic from the backend or callback`),abortFailed:x(`Could not cancel summarization: {error}`,`Session tree failure; error is an untranslated diagnostic from the backend or callback`),forkFailed:x(`Could not fork session history: {error}`,`Fork failure; error is an untranslated diagnostic`),required:x(`Enter custom summary focus instructions.`,`Custom summary validation: blank instructions`),tooLong:x(`Custom summary focus must be {max, number} characters or fewer.`,`Custom summary validation: maximum length`),characterCount:x(`{count, number} / {max, number}`,`Custom summary instruction length and maximum character count`)},K=w.registerMessages(`core.sessionTree`,pM),mM={image:x(`[image]`,`Image placeholder in a history preview, not a marker parsed from user text`),message:x(`Message`,`History preview when a message role is unavailable`),"user-message":x(`User message`,`History preview for an empty user message`),"assistant-response":x(`Assistant response`,`History preview for an empty assistant response`),"assistant-error":x(`Assistant error`,`History preview for an assistant response that failed`),"assistant-aborted":x(`Assistant response aborted`,`History preview for an aborted assistant response`),"hidden-custom-message":x(`Hidden custom message`,`History preview for a hidden extension message; its content is never sent to the browser`),"compaction-summary":x(`Compaction summary`,`History preview when the compaction summary is empty`),"branch-summary":x(`Branch summary`,`History preview when the branch summary is empty`),shell:x(`{hasValue, select, yes {Shell: {value}} other {Shell command}}`,`History shell command preview; value is an untranslated command`),model:x(`{hasValue, select, yes {Model: {value}} other {Model changed}}`,`History model change; value is an untranslated provider/model identifier`),"thinking-level":x(`{hasValue, select, yes {Thinking level: {value}} other {Thinking level changed}}`,`History thinking change; value is the stored level identifier`),"session-name":x(`{hasValue, select, yes {Session name: {value}} other {Session info changed}}`,`History name change; value is an untranslated user name`),label:x(`{hasValue, select, yes {Label: {value}} other {Label removed}}`,`History label change; value is an untranslated user label`),"custom-entry":x(`{hasValue, select, yes {Custom entry: {value}} other {Custom entry}}`,`History extension entry; value is an untranslated extension type identifier`),entry:x(`{hasValue, select, yes {Entry: {value}} other {Other session entry}}`,`History unknown entry; value is an untranslated SDK entry type`),toolCalls:x(`Tool call: {names}`,`History assistant tool calls; names is a locale-formatted list of untranslated tool identifiers`),toolResult:x(`{error, select, yes {Tool error} other {Tool result}}{hasName, select, yes { ({name})} other {}}{hasContent, select, yes {: {content}} other {}}`,`Complete history tool result preview. Name is a raw tool identifier; content contains raw text and localized image placeholders. Both may be absent.`),customMessage:x(`Custom message{hasName, select, yes { ({name})} other {}}{hasContent, select, yes {: {content}} other {}}`,`Complete visible extension message preview. Name is a raw custom type; content contains raw text and localized image placeholders. Both may be absent.`)},hM=w.registerMessages(`core.sessionTreeSummary`,mM);function gM(e){let t=e.summaryPresentation;if(t===void 0)return e.summary;let n=e=>e.map(e=>e.type===`text`?e.text:hM.t(`image`)).join(` `),r;switch(t.type){case`status`:r=hM.t(t.status);break;case`content`:r=n(t.parts)||hM.t(t.fallback);break;case`named`:r=hM.t(t.field,{hasValue:t.value===void 0?`no`:`yes`,value:t.value??``});break;case`assistant-tools`:r=hM.t(`toolCalls`,{names:w.list(t.names)});break;case`tool-result`:r=hM.t(`toolResult`,{error:t.isError?`yes`:`no`,hasName:t.toolName===void 0?`no`:`yes`,name:t.toolName??``,hasContent:t.parts.length>0?`yes`:`no`,content:n(t.parts)});break;case`custom-message`:r=hM.t(`customMessage`,{hasName:t.customType===void 0?`no`:`yes`,name:t.customType??``,hasContent:t.parts.length>0?`yes`:`no`,content:n(t.parts)})}if(r.length<=360)return r;let i=359,a=r.charCodeAt(i-1);return a>=55296&&a<=56319&&--i,`${r.slice(0,i)}…`}function _M(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=CM(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:wM(d,r),activeLeafId:d}}function vM(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 yM(e){return e.activeLeafId===null?e.orderedIds.at(-1):e.activeLeafId}function bM(e,t,n){let r=vM(e,t.foldedIds).map(e=>e.node.id),i=TM(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 xM(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 SM(e,t,n){return e===`none`||e==="default"?{ok:!0,choice:{mode:e}}:t.trim()===``?{ok:!1,error:n?.(`required`)??`Enter custom summary focus instructions.`}:t.length>1e4?{ok:!1,error:n?.(`tooLong`)??`Custom summary focus must be 10000 characters or fewer.`}:{ok:!0,choice:{mode:`custom`,instructions:t.trim()}}}function CM(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 wM(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 TM(e,t){return t!==void 0&&e.includes(t)?t:e.at(-1)}var EM={nodes:[],activeLeafId:null,activePathIds:[]},DM=8,OM={user:{label:`kind_user`,tone:`user`,bookkeeping:!1},assistant:{label:`kind_assistant`,tone:`assistant`,bookkeeping:!1},"tool-result":{label:`kind_tool_result`,tone:`tool`,bookkeeping:!1},bash:{label:`kind_bash`,tone:`shell`,bookkeeping:!1},"custom-message":{label:`kind_custom_message`,tone:`context`,bookkeeping:!1},compaction:{label:`kind_compaction`,tone:`context`,bookkeeping:!1},"branch-summary":{label:`kind_branch_summary`,tone:`context`,bookkeeping:!1},"model-change":{label:`kind_model_change`,tone:`metadata`,bookkeeping:!0},"thinking-level-change":{label:`kind_thinking_level_change`,tone:`metadata`,bookkeeping:!0},"session-info":{label:`kind_session_info`,tone:`metadata`,bookkeeping:!0},label:{label:`kind_label`,tone:`metadata`,bookkeeping:!0},custom:{label:`kind_custom`,tone:`metadata`,bookkeeping:!0},other:{label:`kind_other`,tone:`metadata`,bookkeeping:!0}},kM=class extends O{constructor(){super(),this.tree=EM,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=_M(EM),this.operationGeneration=0,o.createController(this),new S(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 D`
1201
+ `}};g([y({type:String})],lM.prototype,`query`,void 0),g([y({attribute:!1})],lM.prototype,`response`,void 0),g([y({type:Boolean})],lM.prototype,`searching`,void 0),g([y({type:String})],lM.prototype,`error`,void 0),g([y({attribute:!1})],lM.prototype,`onSearch`,void 0),g([y({attribute:!1})],lM.prototype,`onSelect`,void 0),g([y({attribute:!1})],lM.prototype,`onClose`,void 0),lM=g([_(`session-search-dialog`)],lM);function uM(e){return D`${dM(e).map(e=>e.highlighted?D`<mark>${e.text}</mark>`:e.text)}`}function dM(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 fM(e){return e.name!==void 0&&e.name!==``?e.name:e.firstMessage===``?_j(e.id):e.firstMessage}function pM(e){return e.target instanceof HTMLInputElement?e.target.value:``}var mM={title:x(`Navigate session tree`,`Full-screen session history dialog title and accessible name`),eyebrow:x(`Conversation history`,`Small heading above the session tree dialog title`),close:x(`Close session tree`,`Close session tree dialog button tooltip and accessible name`),intro:x(`Select the history entry where you would like to continue.`,`Instruction above selectable conversation history entries`),markers:x(`Session tree markers`,`Accessible name of the active-path and active-leaf legend`),activePath:x(`Active path`,`Legend and badge for entries on the current conversation branch`),activeLeaf:x(`Active leaf`,`Legend and badge for the last entry on the current conversation branch`),empty:x(`This session does not contain any selectable history entries.`,`Empty state when conversation history contains no selectable entries`),history:x(`Complete session history`,`Accessible name of the complete conversation history tree`),noChildren:x(`No child entries`,`Tooltip on a history entry without child entries`),collapse:x(`Collapse branch`,`Tooltip for folding a branch of the history tree`),expand:x(`Expand branch`,`Tooltip for unfolding a branch of the history tree`),selected:x(`Selected entry`,`Heading above the chosen history entry`),choose:x(`Choose how to continue`,`Heading on the operation confirmation step`),unavailableEntry:x(`The selected history entry is no longer available.`,`Warning when the selected history entry has disappeared`),operation:x(`How would you like to continue?`,`Legend for same-session continuation versus creating a new session`),continueOption:x(`Continue in this session`,`Radio option: keep the session file and branch from the chosen entry`),continueDescription:x(`Branch from the selected entry in this session file and keep its other branches.`,`Explanation of same-session continuation; existing branches are preserved`),forkOption:x(`Fork into a new session`,`Radio option: create and switch to a separate session`),forkDescription:x(`Create and switch to a separate session file while leaving the original unchanged.`,`Explanation of creating a new session; the original is preserved`),summary:x(`Abandoned branch summary`,`Legend for options to summarize the context being left behind`),none:x(`No summary`,`Radio option: do not summarize the abandoned branch`),noneDescription:x(`Switch branches without adding a summary entry.`,`Explanation of switching branches without generating a summary`),default:x(`Summarize`,`Radio option: generate the default abandoned-branch summary`),defaultDescription:x(`Ask Pi to summarize the context being left behind.`,`Explanation of default summary; Pi is the agent name`),custom:x(`Summarize with custom focus`,`Radio option: summarize with user-provided focus instructions`),customDescription:x(`Guide Pi toward the details that matter for the new branch.`,`Explanation of guiding the summary toward relevant details; Pi is the agent name`),customFocus:x(`Custom summary focus`,`Label for the summary-focus instructions textarea`),sideEffectsTitle:x(`Conversation context only.`,`Emphasized warning: tree actions only affect conversation context`),sideEffects:x(`Continuing or forking does not undo filesystem changes, shell commands, tool calls, or other side effects.`,`Warning that session continuation and forking cannot undo external side effects`),forkUser:x(`The new session will branch before this user message, and its text will return to the prompt editor as the new session draft.`,`Fork behavior for a user message: branch before it and restore its text as a draft`),forkOther:x(`The new session will include this entry and all history leading to it.`,`Fork behavior for non-user entries: include the chosen entry and earlier history`),continueUser:x(`This message’s text will return to the prompt editor for optional editing and resubmission in this session.`,`Continuation behavior for user or custom messages: restore text to the prompt editor`),continueOther:x(`The prompt editor will be empty after continuing from this entry in this session.`,`Continuation behavior for other entries: leave the prompt editor empty`),cancel:x(`Cancel`,`Dismiss the session tree without taking an action`),next:x(`Next`,`Advance from history selection to operation confirmation`),back:x(`Back`,`Return from operation confirmation to history selection`),cancelling:x(`Cancelling…`,`Busy button label while a summarization cancellation request is pending`),cancelSummary:x(`Cancel summarization`,`Cancel an in-flight abandoned-branch summarization`),continueAction:x(`Continue from here`,`Submit same-session continuation from the selected history entry`),forkAction:x(`Fork into new session`,`Submit creation of a new session from the selected history entry`),forking:x(`Forking…`,`Busy label while creating a new session`),continuing:x(`Continuing…`,`Busy label while continuing without a summary`),summarizing:x(`Summarizing…`,`Busy label while generating an abandoned-branch summary`),navigationUnavailable:x(`Session tree navigation is unavailable. Close and reopen /tree, then try again.`,`Client navigation callback is unavailable; /tree is a literal slash command`),summaryCancelled:x(`Summarization cancelled. Your selected history entry is unchanged.`,`Status after cancelled summarization; the selected history entry remains unchanged`),navigationCancelled:x(`Navigation cancelled. Your selected history entry is unchanged.`,`Status after cancelled navigation; the selected history entry remains unchanged`),forkUnavailable:x(`Fork from the session tree is unavailable. Close and reopen /tree, then try again.`,`Client fork callback is unavailable; /tree is a literal slash command`),forkCancelled:x(`Fork cancelled. No new session was created; your selected history entry is unchanged.`,`Status after cancelled fork; no session was created and selection remains unchanged`),abortUnavailable:x(`Summarization cannot be cancelled from this client.`,`Error when the client cannot cancel summarization`),aborting:x(`Cancelling summarization…`,`Live status while a summarization cancellation request is pending`),kind_user:x(`User`,`Session history entry kind: user`),kind_assistant:x(`Assistant`,`Session history entry kind: assistant`),kind_tool_result:x(`Tool result`,`Session history entry kind: tool-result`),kind_bash:x(`Shell`,`Session history entry kind: bash`),kind_custom_message:x(`Custom message`,`Session history entry kind: custom-message`),kind_compaction:x(`Compaction`,`Session history entry kind: compaction`),kind_branch_summary:x(`Branch summary`,`Session history entry kind: branch-summary`),kind_model_change:x(`Model`,`Session history entry kind: model-change`),kind_thinking_level_change:x(`Thinking`,`Session history entry kind: thinking-level-change`),kind_session_info:x(`Session info`,`Session history entry kind: session-info`),kind_label:x(`Label`,`Session history entry kind: label`),kind_custom:x(`Custom`,`Session history entry kind: custom`),kind_other:x(`Other`,`Session history entry kind: other`),navigationFailed:x(`Could not navigate session history: {error}`,`Session tree failure; error is an untranslated diagnostic from the backend or callback`),abortFailed:x(`Could not cancel summarization: {error}`,`Session tree failure; error is an untranslated diagnostic from the backend or callback`),forkFailed:x(`Could not fork session history: {error}`,`Fork failure; error is an untranslated diagnostic`),required:x(`Enter custom summary focus instructions.`,`Custom summary validation: blank instructions`),tooLong:x(`Custom summary focus must be {max, number} characters or fewer.`,`Custom summary validation: maximum length`),characterCount:x(`{count, number} / {max, number}`,`Custom summary instruction length and maximum character count`)},K=w.registerMessages(`core.sessionTree`,mM),hM={image:x(`[image]`,`Image placeholder in a history preview, not a marker parsed from user text`),message:x(`Message`,`History preview when a message role is unavailable`),"user-message":x(`User message`,`History preview for an empty user message`),"assistant-response":x(`Assistant response`,`History preview for an empty assistant response`),"assistant-error":x(`Assistant error`,`History preview for an assistant response that failed`),"assistant-aborted":x(`Assistant response aborted`,`History preview for an aborted assistant response`),"hidden-custom-message":x(`Hidden custom message`,`History preview for a hidden extension message; its content is never sent to the browser`),"compaction-summary":x(`Compaction summary`,`History preview when the compaction summary is empty`),"branch-summary":x(`Branch summary`,`History preview when the branch summary is empty`),shell:x(`{hasValue, select, yes {Shell: {value}} other {Shell command}}`,`History shell command preview; value is an untranslated command`),model:x(`{hasValue, select, yes {Model: {value}} other {Model changed}}`,`History model change; value is an untranslated provider/model identifier`),"thinking-level":x(`{hasValue, select, yes {Thinking level: {value}} other {Thinking level changed}}`,`History thinking change; value is the stored level identifier`),"session-name":x(`{hasValue, select, yes {Session name: {value}} other {Session info changed}}`,`History name change; value is an untranslated user name`),label:x(`{hasValue, select, yes {Label: {value}} other {Label removed}}`,`History label change; value is an untranslated user label`),"custom-entry":x(`{hasValue, select, yes {Custom entry: {value}} other {Custom entry}}`,`History extension entry; value is an untranslated extension type identifier`),entry:x(`{hasValue, select, yes {Entry: {value}} other {Other session entry}}`,`History unknown entry; value is an untranslated SDK entry type`),toolCalls:x(`Tool call: {names}`,`History assistant tool calls; names is a locale-formatted list of untranslated tool identifiers`),toolResult:x(`{error, select, yes {Tool error} other {Tool result}}{hasName, select, yes { ({name})} other {}}{hasContent, select, yes {: {content}} other {}}`,`Complete history tool result preview. Name is a raw tool identifier; content contains raw text and localized image placeholders. Both may be absent.`),customMessage:x(`Custom message{hasName, select, yes { ({name})} other {}}{hasContent, select, yes {: {content}} other {}}`,`Complete visible extension message preview. Name is a raw custom type; content contains raw text and localized image placeholders. Both may be absent.`)},gM=w.registerMessages(`core.sessionTreeSummary`,hM);function _M(e){let t=e.summaryPresentation;if(t===void 0)return e.summary;let n=e=>e.map(e=>e.type===`text`?e.text:gM.t(`image`)).join(` `),r;switch(t.type){case`status`:r=gM.t(t.status);break;case`content`:r=n(t.parts)||gM.t(t.fallback);break;case`named`:r=gM.t(t.field,{hasValue:t.value===void 0?`no`:`yes`,value:t.value??``});break;case`assistant-tools`:r=gM.t(`toolCalls`,{names:w.list(t.names)});break;case`tool-result`:r=gM.t(`toolResult`,{error:t.isError?`yes`:`no`,hasName:t.toolName===void 0?`no`:`yes`,name:t.toolName??``,hasContent:t.parts.length>0?`yes`:`no`,content:n(t.parts)});break;case`custom-message`:r=gM.t(`customMessage`,{hasName:t.customType===void 0?`no`:`yes`,name:t.customType??``,hasContent:t.parts.length>0?`yes`:`no`,content:n(t.parts)})}if(r.length<=360)return r;let i=359,a=r.charCodeAt(i-1);return a>=55296&&a<=56319&&--i,`${r.slice(0,i)}…`}function vM(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=wM(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:TM(d,r),activeLeafId:d}}function yM(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 bM(e){return e.activeLeafId===null?e.orderedIds.at(-1):e.activeLeafId}function xM(e,t,n){let r=yM(e,t.foldedIds).map(e=>e.node.id),i=EM(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 SM(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 CM(e,t,n){return e===`none`||e==="default"?{ok:!0,choice:{mode:e}}:t.trim()===``?{ok:!1,error:n?.(`required`)??`Enter custom summary focus instructions.`}:t.length>1e4?{ok:!1,error:n?.(`tooLong`)??`Custom summary focus must be 10000 characters or fewer.`}:{ok:!0,choice:{mode:`custom`,instructions:t.trim()}}}function wM(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 TM(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 EM(e,t){return t!==void 0&&e.includes(t)?t:e.at(-1)}var DM={nodes:[],activeLeafId:null,activePathIds:[]},OM=8,kM={user:{label:`kind_user`,tone:`user`,bookkeeping:!1},assistant:{label:`kind_assistant`,tone:`assistant`,bookkeeping:!1},"tool-result":{label:`kind_tool_result`,tone:`tool`,bookkeeping:!1},bash:{label:`kind_bash`,tone:`shell`,bookkeeping:!1},"custom-message":{label:`kind_custom_message`,tone:`context`,bookkeeping:!1},compaction:{label:`kind_compaction`,tone:`context`,bookkeeping:!1},"branch-summary":{label:`kind_branch_summary`,tone:`context`,bookkeeping:!1},"model-change":{label:`kind_model_change`,tone:`metadata`,bookkeeping:!0},"thinking-level-change":{label:`kind_thinking_level_change`,tone:`metadata`,bookkeeping:!0},"session-info":{label:`kind_session_info`,tone:`metadata`,bookkeeping:!0},label:{label:`kind_label`,tone:`metadata`,bookkeeping:!0},custom:{label:`kind_custom`,tone:`metadata`,bookkeeping:!0},other:{label:`kind_other`,tone:`metadata`,bookkeeping:!0}},AM=class extends O{constructor(){super(),this.tree=DM,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=vM(DM),this.operationGeneration=0,o.createController(this),new S(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 D`
1202
1202
  <modal-surface
1203
1203
  .label=${K.t(`title`)}
1204
1204
  .initialFocus=${this.selectedId===void 0?`.close-button`:`[data-tree-node-id][tabindex='0']`}
@@ -1216,7 +1216,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1216
1216
  ${this.step===`tree`?this.renderTreeStep():this.renderActionStep()}
1217
1217
  ${this.renderFooter()}
1218
1218
  </modal-surface>
1219
- `}renderTreeStep(){let e=vM(this.model,this.foldedIds);return D`
1219
+ `}renderTreeStep(){let e=yM(this.model,this.foldedIds);return D`
1220
1220
  <div class="body tree-step">
1221
1221
  <div class="tree-intro">
1222
1222
  <p>${K.t(`intro`)}</p>
@@ -1235,7 +1235,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1235
1235
  </div>
1236
1236
  `}
1237
1237
  </div>
1238
- `}renderTreeRow(e){let t=e.node.id===this.selectedId,n=e.childIds.length>0&&!this.foldedIds.has(e.node.id),r=MM(e.node.kind),i=[`tree-row`,t?`selected`:``,e.activePath?`active-path`:``,e.activeLeaf?`active-leaf`:``,r.bookkeeping?`bookkeeping`:``].filter(e=>e!==``).join(` `),a=AM(e.branchDepth);return D`
1238
+ `}renderTreeRow(e){let t=e.node.id===this.selectedId,n=e.childIds.length>0&&!this.foldedIds.has(e.node.id),r=NM(e.node.kind),i=[`tree-row`,t?`selected`:``,e.activePath?`active-path`:``,e.activeLeaf?`active-leaf`:``,r.bookkeeping?`bookkeeping`:``].filter(e=>e!==``).join(` `),a=jM(e.branchDepth);return D`
1239
1239
  <div
1240
1240
  class=${i}
1241
1241
  style=${`--tree-indent: ${String(a*16)}px; --tree-indent-mobile: ${String(a*12)}px;`}
@@ -1263,9 +1263,9 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1263
1263
  </span>
1264
1264
  </span>
1265
1265
  <span class="entry">
1266
- <span class="summary" dir="auto">${gM(e.node)}</span>
1266
+ <span class="summary" dir="auto">${_M(e.node)}</span>
1267
1267
  ${e.node.label===void 0?null:D`<span class="label" dir="auto" title=${e.node.label}>${e.node.label}</span>`}
1268
- ${e.node.timestamp===void 0?null:D`<time datetime=${e.node.timestamp}>${PM(e.node.timestamp)}</time>`}
1268
+ ${e.node.timestamp===void 0?null:D`<time datetime=${e.node.timestamp}>${FM(e.node.timestamp)}</time>`}
1269
1269
  </span>
1270
1270
  </div>
1271
1271
  `}renderKindBadge(e){return D`<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=this.validateSummaryChoice();return D`
@@ -1277,8 +1277,8 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1277
1277
  </div>
1278
1278
  ${e===void 0?D`<div class="empty">${K.t(`unavailableEntry`)}</div>`:D`
1279
1279
  <div class="selected-entry">
1280
- ${this.renderKindBadge(MM(e.kind))}
1281
- <strong dir="auto">${gM(e)}</strong>
1280
+ ${this.renderKindBadge(NM(e.kind))}
1281
+ <strong dir="auto">${_M(e)}</strong>
1282
1282
  <p>${this.selectedEntryDescription(e.kind)}</p>
1283
1283
  </div>
1284
1284
  `}
@@ -1317,7 +1317,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1317
1317
  ${this.error===``?null:D`<div class="dialog-error" role="alert">${this.error()}</div>`}
1318
1318
  </div>
1319
1319
  </div>
1320
- `}validateSummaryChoice(){return SM(this.summaryMode,this.customInstructions,e=>e===`required`?K.t(`required`):K.t(`tooLong`,{max:Yt}))}selectedEntryDescription(e){return this.operation===`fork`?e===`user`?K.t(`forkUser`):K.t(`forkOther`):jM(e)?K.t(`continueUser`):K.t(`continueOther`)}renderOperationOption(e,t,n){return D`
1320
+ `}validateSummaryChoice(){return CM(this.summaryMode,this.customInstructions,e=>e===`required`?K.t(`required`):K.t(`tooLong`,{max:Yt}))}selectedEntryDescription(e){return this.operation===`fork`?e===`user`?K.t(`forkUser`):K.t(`forkOther`):MM(e)?K.t(`continueUser`):K.t(`continueOther`)}renderOperationOption(e,t,n){return D`
1321
1321
  <label class=${`choice-option${this.operation===e?` selected`:``}`}>
1322
1322
  <input
1323
1323
  type="radio"
@@ -1356,7 +1356,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1356
1356
  ${this.primaryActionLabel()}
1357
1357
  </button>
1358
1358
  </footer>
1359
- `}resetTree(){this.operationGeneration+=1,this.model=_M(this.tree),this.selectedId=yM(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=xM(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=w.direction===`rtl`?e.key===`ArrowLeft`?`ArrowRight`:e.key===`ArrowRight`?`ArrowLeft`:e.key:e.key,n=bM(this.model,{selectedId:this.selectedId,foldedIds:this.foldedIds},t);n.handled&&(e.preventDefault(),e.stopPropagation(),n.action===`confirm`?this.continueToAction():(this.selectedId=n.selectedId,this.foldedIds=n.foldedIds,this.pendingFocus=`tree`))}continueToAction(){!this.busy&&this.selectedId!==void 0&&this.model.nodesById.has(this.selectedId)&&(this.validateSummaryChoice().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`?K.t(`forking`):this.summaryMode===`none`?K.t(`continuing`):K.t(`summarizing`):this.operation===`continue`?K.t(`continueAction`):K.t(`forkAction`)}submitSelectedOperation(){return this.operation===`continue`?this.submitNavigation():this.submitFork()}async submitNavigation(){if(this.busy||this.selectedId===void 0)return;let e=this.validateSummaryChoice();if(!e.ok){this.error=``,this.statusMessage=``,this.pendingFocus=`custom`,this.requestUpdate();return}let t=this.onNavigate;if(t===void 0){this.error=()=>K.t(`navigationUnavailable`);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?K.t(`summaryCancelled`):K.t(`navigationCancelled`),this.pendingFocus=`tree`}catch(e){if(r!==this.operationGeneration)return;this.busy=!1,this.aborting=!1,this.statusMessage=``,this.error=()=>K.t(`navigationFailed`,{error:NM(e)})}}async submitFork(){if(this.busy||this.selectedId===void 0)return;let e=this.onFork;if(e===void 0){this.error=()=>K.t(`forkUnavailable`);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=()=>K.t(`forkCancelled`),this.pendingFocus=`operation`}catch(e){if(n!==this.operationGeneration)return;this.busy=!1,this.statusMessage=``,this.error=()=>K.t(`forkFailed`,{error:NM(e)})}}async abortNavigation(){if(!this.busy||this.summaryMode===`none`||this.aborting)return;let e=this.onAbort;if(e===void 0){this.error=()=>K.t(`abortUnavailable`);return}let t=this.operationGeneration;this.aborting=!0,this.error=``,this.statusMessage=()=>K.t(`aborting`);try{await e()}catch(e){if(t!==this.operationGeneration)return;this.aborting=!1,this.statusMessage=``,this.error=()=>K.t(`abortFailed`,{error:NM(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`
1359
+ `}resetTree(){this.operationGeneration+=1,this.model=vM(this.tree),this.selectedId=bM(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=SM(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=w.direction===`rtl`?e.key===`ArrowLeft`?`ArrowRight`:e.key===`ArrowRight`?`ArrowLeft`:e.key:e.key,n=xM(this.model,{selectedId:this.selectedId,foldedIds:this.foldedIds},t);n.handled&&(e.preventDefault(),e.stopPropagation(),n.action===`confirm`?this.continueToAction():(this.selectedId=n.selectedId,this.foldedIds=n.foldedIds,this.pendingFocus=`tree`))}continueToAction(){!this.busy&&this.selectedId!==void 0&&this.model.nodesById.has(this.selectedId)&&(this.validateSummaryChoice().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`?K.t(`forking`):this.summaryMode===`none`?K.t(`continuing`):K.t(`summarizing`):this.operation===`continue`?K.t(`continueAction`):K.t(`forkAction`)}submitSelectedOperation(){return this.operation===`continue`?this.submitNavigation():this.submitFork()}async submitNavigation(){if(this.busy||this.selectedId===void 0)return;let e=this.validateSummaryChoice();if(!e.ok){this.error=``,this.statusMessage=``,this.pendingFocus=`custom`,this.requestUpdate();return}let t=this.onNavigate;if(t===void 0){this.error=()=>K.t(`navigationUnavailable`);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?K.t(`summaryCancelled`):K.t(`navigationCancelled`),this.pendingFocus=`tree`}catch(e){if(r!==this.operationGeneration)return;this.busy=!1,this.aborting=!1,this.statusMessage=``,this.error=()=>K.t(`navigationFailed`,{error:PM(e)})}}async submitFork(){if(this.busy||this.selectedId===void 0)return;let e=this.onFork;if(e===void 0){this.error=()=>K.t(`forkUnavailable`);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=()=>K.t(`forkCancelled`),this.pendingFocus=`operation`}catch(e){if(n!==this.operationGeneration)return;this.busy=!1,this.statusMessage=``,this.error=()=>K.t(`forkFailed`,{error:PM(e)})}}async abortNavigation(){if(!this.busy||this.summaryMode===`none`||this.aborting)return;let e=this.onAbort;if(e===void 0){this.error=()=>K.t(`abortUnavailable`);return}let t=this.operationGeneration;this.aborting=!0,this.error=``,this.statusMessage=()=>K.t(`aborting`);try{await e()}catch(e){if(t!==this.operationGeneration)return;this.aborting=!1,this.statusMessage=``,this.error=()=>K.t(`abortFailed`,{error:PM(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`
1360
1360
  @layer pi-web-base {
1361
1361
  :host { position: fixed; inset: 0; color: var(--pi-text); font: 14px var(--pi-font, system-ui, sans-serif); }
1362
1362
  header, footer, .confirmation-card { overflow-wrap: anywhere; }
@@ -1467,7 +1467,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1467
1467
  }
1468
1468
 
1469
1469
  }
1470
- `}};g([y({attribute:!1})],kM.prototype,`tree`,void 0),g([y({attribute:!1})],kM.prototype,`onNavigate`,void 0),g([y({attribute:!1})],kM.prototype,`onFork`,void 0),g([y({attribute:!1})],kM.prototype,`onAbort`,void 0),g([y({attribute:!1})],kM.prototype,`onCancel`,void 0),g([v()],kM.prototype,`selectedId`,void 0),g([v()],kM.prototype,`foldedIds`,void 0),g([v()],kM.prototype,`step`,void 0),g([v()],kM.prototype,`operation`,void 0),g([v()],kM.prototype,`summaryMode`,void 0),g([v()],kM.prototype,`customInstructions`,void 0),g([v()],kM.prototype,`busy`,void 0),g([v()],kM.prototype,`aborting`,void 0),g([v()],kM.prototype,`error`,void 0),g([v()],kM.prototype,`statusMessage`,void 0),kM=g([_(`session-tree-navigator`)],kM);function AM(e){return Math.min(Math.max(0,e),DM)}function jM(e){return e===`user`||e===`custom-message`}function MM(e){let t=OM[e];return{...t,label:K.t(t.label)}}function NM(e){return e instanceof Error?e.message:String(e)}function PM(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:w.date(t,{dateStyle:`medium`,timeStyle:`short`})}var FM=T`
1470
+ `}};g([y({attribute:!1})],AM.prototype,`tree`,void 0),g([y({attribute:!1})],AM.prototype,`onNavigate`,void 0),g([y({attribute:!1})],AM.prototype,`onFork`,void 0),g([y({attribute:!1})],AM.prototype,`onAbort`,void 0),g([y({attribute:!1})],AM.prototype,`onCancel`,void 0),g([v()],AM.prototype,`selectedId`,void 0),g([v()],AM.prototype,`foldedIds`,void 0),g([v()],AM.prototype,`step`,void 0),g([v()],AM.prototype,`operation`,void 0),g([v()],AM.prototype,`summaryMode`,void 0),g([v()],AM.prototype,`customInstructions`,void 0),g([v()],AM.prototype,`busy`,void 0),g([v()],AM.prototype,`aborting`,void 0),g([v()],AM.prototype,`error`,void 0),g([v()],AM.prototype,`statusMessage`,void 0),AM=g([_(`session-tree-navigator`)],AM);function jM(e){return Math.min(Math.max(0,e),OM)}function MM(e){return e===`user`||e===`custom-message`}function NM(e){let t=kM[e];return{...t,label:K.t(t.label)}}function PM(e){return e instanceof Error?e.message:String(e)}function FM(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:w.date(t,{dateStyle:`medium`,timeStyle:`short`})}var IM=T`
1471
1471
  @layer pi-web-base {
1472
1472
  :host { display: flex; flex-direction: column; flex: 1 1 auto; min-width: 0; min-height: 0; isolation: isolate; }
1473
1473
  :host([hidden]) { display: none; }
@@ -1485,7 +1485,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1485
1485
  @media (prefers-reduced-motion: reduce) { .dot { animation: none; } }
1486
1486
  @keyframes pulse { 0%, 100% { transform: scale(.75); opacity: .55; } 50% { transform: scale(1.2); opacity: 1; } }
1487
1487
  }
1488
- `,IM={sending:x(`Sending your message…`,`Conversation activity while a prompt is being sent`),compacting:x(`compacting`,`Conversation status while compacting history`),bash:x(`bash`,`Conversation status while running a shell command`),running:x(`running`,`Conversation status while the agent is working`),queued:x(`queued`,`Conversation status while messages are queued`),startup:x(`{intent, select, create {Creating session} other {Opening session}}: {stage, select, runtime {Starting the Pi session} other {Loading session extensions}}{refreshing, select, yes { · provider model lists are refreshing} other {}}`,`Complete startup progress. A provider catalog refresh is concurrent, not necessarily the cause of waiting. Intent selects creating/opening; stage selects runtime construction/extension loading.`),summary:x(`{label}: {detail}`,`Conversation activity summary; label and detail can be raw runtime-provided text`)},LM={compacting:x(b.compacting,`Session runtime activity: compacting`),duplicateQueuedMessage:x(b.duplicateQueuedMessage,`Session runtime activity: duplicate queued message ignored`),steeringQueued:x(b.steeringQueued,`Session runtime activity: steering queued`),messageQueued:x(b.messageQueued,`Session runtime activity: message queued`),promptAccepted:x(b.promptAccepted,`Session runtime activity: prompt accepted`),error:x(b.error,`Session runtime activity: error`),queuedDuringCompaction:x(b.queuedDuringCompaction,`Session runtime activity: message queued during compaction`),runningBash:x(b.runningBash,`Session runtime activity: running bash`),bashComplete:x(b.bashComplete,`Session runtime activity: bash complete`),bashFailed:x(b.bashFailed,`Session runtime activity: bash failed`),summarizingBranch:x(b.summarizingBranch,`Session runtime activity: summarizing branch`),navigatingTree:x(b.navigatingTree,`Session runtime activity: navigating session tree`),branchSummaryAborted:x(b.branchSummaryAborted,`Session runtime activity: branch summary aborted`),treeNavigationCancelled:x(b.treeNavigationCancelled,`Session runtime activity: tree navigation cancelled`),treeNavigated:x(b.treeNavigated,`Session runtime activity: session tree navigated`),treeNavigationFailed:x(b.treeNavigationFailed,`Session runtime activity: tree navigation failed`),forking:x(b.forking,`Session runtime activity: forking session from entry`),forkCancelled:x(b.forkCancelled,`Session runtime activity: fork cancelled`),forked:x(b.forked,`Session runtime activity: session forked`),forkFailed:x(b.forkFailed,`Session runtime activity: fork failed`),reloading:x(b.reloading,`Session runtime activity: reloading resources`),reloaded:x(b.reloaded,`Session runtime activity: resources reloaded`),reloadFailed:x(b.reloadFailed,`Session runtime activity: reload failed`),stopped:x(b.stopped,`Session runtime activity: stopped`),stopFailed:x(b.stopFailed,`Session runtime activity: stop failed`),extensionError:x(b.extensionError,`Session runtime activity: extension error`),extensionCallbackFailed:x(b.extensionCallbackFailed,`Session runtime activity: extension callback failed`),compactionCancelled:x(b.compactionCancelled,`Session runtime activity: compaction cancelled`),compactionComplete:x(b.compactionComplete,`Session runtime activity: compaction complete`),compactionFailed:x(b.compactionFailed,`Session runtime activity: compaction failed`),updatingSession:x(b.updatingSession,`Session runtime activity: updating session`),agentRunning:x(b.agentRunning,`Session runtime activity: agent running`),queued:x(b.queued,`Session runtime activity: queued`),active:x(b.active,`Session runtime activity: active`),idle:x(b.idle,`Session runtime activity: idle`),turnComplete:x(b.turnComplete,`Session runtime activity: turn complete`),messageStarted:x(b.messageStarted,`Session runtime activity: message started`),messageComplete:x(b.messageComplete,`Session runtime activity: message complete`),receivingResponse:x(b.receivingResponse,`Session runtime activity: receiving response`),runningTool:x(b.runningTool,`Session runtime activity: running tool`),toolFailed:x(b.toolFailed,`Session runtime activity: tool failed`),toolComplete:x(b.toolComplete,`Session runtime activity: tool complete`),model:x(`model: {value}`,`Selected model ID; the ID is not translated`),thinking:x(`thinking: {value}`,`Selected thinking-level identifier; the identifier is not translated`),event:x(`runtime event: {value}`,`Unknown runtime event; preserve its event identifier`),compactionCancelledDetail:x(`Compaction cancelled.`,`Manual compaction cancellation detail`),automaticCompactionCancelledDetail:x(`Automatic compaction cancelled.`,`Automatic compaction cancellation detail`),compactionFailedDetail:x(`Couldn’t compact history. Try again.`,`Compaction failure recovery guidance; raw diagnostics remain separate`)},RM=w.registerMessages(`core.conversationLayout`,IM),zM=w.registerMessages(`core.runtimeActivity`,LM);function BM(e,t,n){if(n)return RM.t(`sending`);let r=e===void 0?void 0:e.isCompacting?`compacting`:e.isBashRunning?`bash`:e.isStreaming?`running`:e.pendingMessageCount>0?`queued`:`idle`;if(r===void 0&&(t===void 0||t.phase===`idle`)||r===`idle`&&t?.phase!==`active`)return;if(t===void 0||r!==void 0&&r!==`idle`&&t.phase===`idle`)return r===void 0||r===`idle`?void 0:RM.t(r);let i=t.startupPresentation;if(t.phase===`active`&&i!==void 0&&[`create`,`open`].includes(i.intent)&&[`runtime`,`extensions`].includes(i.stage)&&typeof i.catalogRefreshing==`boolean`)return RM.t(`startup`,{intent:i.intent,stage:i.stage,refreshing:i.catalogRefreshing?`yes`:`no`});let a=mt(t.runtimePresentation),o=t.label,s=t.detail;return a!==void 0&&(o=`value`in a?zM.t(a.kind,{value:a.value}):zM.t(a.kind),`detailKind`in a&&(s=zM.t(`${a.detailKind}Detail`))),s!==void 0&&s!==``?RM.t(`summary`,{label:o,detail:s}):o}var VM=class extends O{constructor(){super(),this.sending=!1,this.visualEffects=!0,this.presentationContext={mode:`normal`},o.createController(this),new S(this,w)}render(){let e=BM(this.status,this.activity,this.sending);return D`
1488
+ `,LM={sending:x(`Sending your message…`,`Conversation activity while a prompt is being sent`),compacting:x(`compacting`,`Conversation status while compacting history`),bash:x(`bash`,`Conversation status while running a shell command`),running:x(`running`,`Conversation status while the agent is working`),queued:x(`queued`,`Conversation status while messages are queued`),startup:x(`{intent, select, create {Creating session} other {Opening session}}: {stage, select, runtime {Starting the Pi session} other {Loading session extensions}}{refreshing, select, yes { · provider model lists are refreshing} other {}}`,`Complete startup progress. A provider catalog refresh is concurrent, not necessarily the cause of waiting. Intent selects creating/opening; stage selects runtime construction/extension loading.`),summary:x(`{label}: {detail}`,`Conversation activity summary; label and detail can be raw runtime-provided text`)},RM={compacting:x(b.compacting,`Session runtime activity: compacting`),duplicateQueuedMessage:x(b.duplicateQueuedMessage,`Session runtime activity: duplicate queued message ignored`),steeringQueued:x(b.steeringQueued,`Session runtime activity: steering queued`),messageQueued:x(b.messageQueued,`Session runtime activity: message queued`),promptAccepted:x(b.promptAccepted,`Session runtime activity: prompt accepted`),error:x(b.error,`Session runtime activity: error`),queuedDuringCompaction:x(b.queuedDuringCompaction,`Session runtime activity: message queued during compaction`),runningBash:x(b.runningBash,`Session runtime activity: running bash`),bashComplete:x(b.bashComplete,`Session runtime activity: bash complete`),bashFailed:x(b.bashFailed,`Session runtime activity: bash failed`),summarizingBranch:x(b.summarizingBranch,`Session runtime activity: summarizing branch`),navigatingTree:x(b.navigatingTree,`Session runtime activity: navigating session tree`),branchSummaryAborted:x(b.branchSummaryAborted,`Session runtime activity: branch summary aborted`),treeNavigationCancelled:x(b.treeNavigationCancelled,`Session runtime activity: tree navigation cancelled`),treeNavigated:x(b.treeNavigated,`Session runtime activity: session tree navigated`),treeNavigationFailed:x(b.treeNavigationFailed,`Session runtime activity: tree navigation failed`),forking:x(b.forking,`Session runtime activity: forking session from entry`),forkCancelled:x(b.forkCancelled,`Session runtime activity: fork cancelled`),forked:x(b.forked,`Session runtime activity: session forked`),forkFailed:x(b.forkFailed,`Session runtime activity: fork failed`),reloading:x(b.reloading,`Session runtime activity: reloading resources`),reloaded:x(b.reloaded,`Session runtime activity: resources reloaded`),reloadFailed:x(b.reloadFailed,`Session runtime activity: reload failed`),stopped:x(b.stopped,`Session runtime activity: stopped`),stopFailed:x(b.stopFailed,`Session runtime activity: stop failed`),extensionError:x(b.extensionError,`Session runtime activity: extension error`),extensionCallbackFailed:x(b.extensionCallbackFailed,`Session runtime activity: extension callback failed`),compactionCancelled:x(b.compactionCancelled,`Session runtime activity: compaction cancelled`),compactionComplete:x(b.compactionComplete,`Session runtime activity: compaction complete`),compactionFailed:x(b.compactionFailed,`Session runtime activity: compaction failed`),updatingSession:x(b.updatingSession,`Session runtime activity: updating session`),agentRunning:x(b.agentRunning,`Session runtime activity: agent running`),queued:x(b.queued,`Session runtime activity: queued`),active:x(b.active,`Session runtime activity: active`),idle:x(b.idle,`Session runtime activity: idle`),turnComplete:x(b.turnComplete,`Session runtime activity: turn complete`),messageStarted:x(b.messageStarted,`Session runtime activity: message started`),messageComplete:x(b.messageComplete,`Session runtime activity: message complete`),receivingResponse:x(b.receivingResponse,`Session runtime activity: receiving response`),runningTool:x(b.runningTool,`Session runtime activity: running tool`),toolFailed:x(b.toolFailed,`Session runtime activity: tool failed`),toolComplete:x(b.toolComplete,`Session runtime activity: tool complete`),model:x(`model: {value}`,`Selected model ID; the ID is not translated`),thinking:x(`thinking: {value}`,`Selected thinking-level identifier; the identifier is not translated`),event:x(`runtime event: {value}`,`Unknown runtime event; preserve its event identifier`),compactionCancelledDetail:x(`Compaction cancelled.`,`Manual compaction cancellation detail`),automaticCompactionCancelledDetail:x(`Automatic compaction cancelled.`,`Automatic compaction cancellation detail`),compactionFailedDetail:x(`Couldn’t compact history. Try again.`,`Compaction failure recovery guidance; raw diagnostics remain separate`)},zM=w.registerMessages(`core.conversationLayout`,LM),BM=w.registerMessages(`core.runtimeActivity`,RM);function VM(e,t,n){if(n)return zM.t(`sending`);let r=e===void 0?void 0:e.isCompacting?`compacting`:e.isBashRunning?`bash`:e.isStreaming?`running`:e.pendingMessageCount>0?`queued`:`idle`;if(r===void 0&&(t===void 0||t.phase===`idle`)||r===`idle`&&t?.phase!==`active`)return;if(t===void 0||r!==void 0&&r!==`idle`&&t.phase===`idle`)return r===void 0||r===`idle`?void 0:zM.t(r);let i=t.startupPresentation;if(t.phase===`active`&&i!==void 0&&[`create`,`open`].includes(i.intent)&&[`runtime`,`extensions`].includes(i.stage)&&typeof i.catalogRefreshing==`boolean`)return zM.t(`startup`,{intent:i.intent,stage:i.stage,refreshing:i.catalogRefreshing?`yes`:`no`});let a=mt(t.runtimePresentation),o=t.label,s=t.detail;return a!==void 0&&(o=`value`in a?BM.t(a.kind,{value:a.value}):BM.t(a.kind),`detailKind`in a&&(s=BM.t(`${a.detailKind}Detail`))),s!==void 0&&s!==``?zM.t(`summary`,{label:o,detail:s}):o}var HM=class extends O{constructor(){super(),this.sending=!1,this.visualEffects=!0,this.presentationContext={mode:`normal`},o.createController(this),new S(this,w)}render(){let e=VM(this.status,this.activity,this.sending);return D`
1489
1489
  <pi-web-ui-presentation region="chat-chrome" .runtime=${this.presentationRuntime} .context=${this.presentationContext}>
1490
1490
  <div class="transcript" slot="transcript"><slot></slot></div>
1491
1491
  <div class="composer-boundary" slot="composer">
@@ -1496,15 +1496,15 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1496
1496
  </div>
1497
1497
  </pi-web-ui-presentation>
1498
1498
  <slot name="status"></slot>
1499
- `}static{this.styles=FM}};g([y({attribute:!1})],VM.prototype,`status`,void 0),g([y({attribute:!1})],VM.prototype,`activity`,void 0),g([y({type:Boolean})],VM.prototype,`sending`,void 0),g([y({type:Boolean})],VM.prototype,`visualEffects`,void 0),g([y({attribute:!1})],VM.prototype,`presentationRuntime`,void 0),g([y({attribute:!1})],VM.prototype,`presentationContext`,void 0),VM=g([_(`conversation-layout`)],VM);var HM={stale:x(`Chat may be out of date.`,`Conversation notice when messages may need refreshing`),interrupted:x(`Could not refresh messages.`,`Conversation notice when a refresh request failed`),retry:x(`Refresh messages`,`Request a fresh conversation snapshot`)},UM=w.registerMessages(`core.conversationSyncNotice`,HM),WM=2e3,GM=class extends O{constructor(){super(),this.showStaleWarning=!1,new S(this),o.createController(this)}connectedCallback(){super.connectedCallback(),this.requestUpdate()}disconnectedCallback(){super.disconnectedCallback(),this.clearStaleWarningTimer(),this.showStaleWarning=!1}willUpdate(){this.state===`stale`?!this.showStaleWarning&&this.staleWarningTimer===void 0&&this.isConnected&&(this.staleWarningTimer=setTimeout(()=>{this.staleWarningTimer=void 0,this.state===`stale`&&(this.showStaleWarning=!0)},WM)):(this.clearStaleWarningTimer(),this.showStaleWarning=this.state===`interrupted`)}clearStaleWarningTimer(){this.staleWarningTimer!==void 0&&clearTimeout(this.staleWarningTimer),this.staleWarningTimer=void 0}render(){return this.state!==`interrupted`&&!(this.state===`stale`&&this.showStaleWarning)?E:D`
1499
+ `}static{this.styles=IM}};g([y({attribute:!1})],HM.prototype,`status`,void 0),g([y({attribute:!1})],HM.prototype,`activity`,void 0),g([y({type:Boolean})],HM.prototype,`sending`,void 0),g([y({type:Boolean})],HM.prototype,`visualEffects`,void 0),g([y({attribute:!1})],HM.prototype,`presentationRuntime`,void 0),g([y({attribute:!1})],HM.prototype,`presentationContext`,void 0),HM=g([_(`conversation-layout`)],HM);var UM={stale:x(`Chat may be out of date.`,`Conversation notice when messages may need refreshing`),interrupted:x(`Could not refresh messages.`,`Conversation notice when a refresh request failed`),retry:x(`Refresh messages`,`Request a fresh conversation snapshot`)},WM=w.registerMessages(`core.conversationSyncNotice`,UM),GM=2e3,KM=class extends O{constructor(){super(),this.showStaleWarning=!1,new S(this),o.createController(this)}connectedCallback(){super.connectedCallback(),this.requestUpdate()}disconnectedCallback(){super.disconnectedCallback(),this.clearStaleWarningTimer(),this.showStaleWarning=!1}willUpdate(){this.state===`stale`?!this.showStaleWarning&&this.staleWarningTimer===void 0&&this.isConnected&&(this.staleWarningTimer=setTimeout(()=>{this.staleWarningTimer=void 0,this.state===`stale`&&(this.showStaleWarning=!0)},GM)):(this.clearStaleWarningTimer(),this.showStaleWarning=this.state===`interrupted`)}clearStaleWarningTimer(){this.staleWarningTimer!==void 0&&clearTimeout(this.staleWarningTimer),this.staleWarningTimer=void 0}render(){return this.state!==`interrupted`&&!(this.state===`stale`&&this.showStaleWarning)?E:D`
1500
1500
  <div class="ui-notice warning" role="status">
1501
- <span>${UM.t(this.state)}</span>
1502
- <button type="button" class="ui-button ui-button--action ui-button--compact" @click=${()=>{this.onRetry?.()}}>${UM.t(`retry`)}</button>
1501
+ <span>${WM.t(this.state)}</span>
1502
+ <button type="button" class="ui-button ui-button--action ui-button--compact" @click=${()=>{this.onRetry?.()}}>${WM.t(`retry`)}</button>
1503
1503
  </div>
1504
1504
  `}static{this.styles=[nt,e,T`
1505
1505
  :host { display: contents; }
1506
1506
  .ui-notice { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
1507
- `]}};g([y({attribute:!1})],GM.prototype,`state`,void 0),g([y({attribute:!1})],GM.prototype,`onRetry`,void 0),g([v()],GM.prototype,`showStaleWarning`,void 0),GM=g([_(`conversation-sync-notice`)],GM);var KM=r(`:host{min-width:0;min-height:0;color:var(--pi-text);font:14px var(--pi-font,system-ui, sans-serif);flex-direction:column;flex:auto;display:flex}:host([collapsed]){flex:none}:host([empty]){display:contents}.notification-tray{background:var(--pi-bg-overlay);flex-direction:column;flex:auto;min-height:0;display:flex}.notification-tray.collapsed{flex:none}.notification-header{z-index:2;box-sizing:border-box;border-bottom:1px solid var(--pi-border-muted);background:var(--pi-bg-overlay);flex-wrap:nowrap;flex:none;justify-content:space-between;align-items:center;gap:8px;min-width:0;min-height:40px;padding:4px 10px;display:flex;position:sticky;top:0}.notification-tray.collapsed .notification-header{border-bottom:0}.notification-header:focus-visible{outline:2px solid var(--pi-accent);outline-offset:-3px}.notification-heading{min-width:0;color:var(--pi-text-bright);text-overflow:ellipsis;white-space:nowrap;flex:auto;font-size:13px;overflow:hidden}.notification-header-actions{flex:none}.notification-icon{fill:none;stroke:currentColor;stroke-width:2px;stroke-linecap:round;stroke-linejoin:round;pointer-events:none;width:17px;height:17px}.notification-disclosure-icon.expanded{transform:rotate(90deg)}.notification-close-icon{width:16px;height:16px}.notification-list{overscroll-behavior-y:contain;box-sizing:border-box;flex:auto;min-height:0;padding:0 10px 5px;overflow-y:auto}.notification-list[hidden]{display:none}.notification-overflow{border-bottom:1px solid var(--pi-border-muted);color:var(--pi-muted);overflow-wrap:anywhere;margin:0;padding:7px 2px;font-size:11px}.notification-row{box-sizing:border-box;border-bottom:1px solid var(--pi-border-muted);min-width:0;min-height:42px;color:var(--pi-text);gap:4px;padding-block:9px;padding-inline:2px 38px;display:grid;position:relative}.notification-row:focus-visible{outline:2px solid var(--pi-accent);outline-offset:-2px}.notification-metadata{min-width:0;color:var(--pi-muted);flex-wrap:wrap;align-items:baseline;gap:5px;font-size:11px;display:flex}.notification-severity{color:var(--pi-muted);font-size:inherit;font-weight:600}.notification-row.warning .notification-severity{color:var(--pi-warning)}.notification-row.error .notification-severity{color:var(--pi-danger)}.notification-message{white-space:pre-wrap;overflow-wrap:anywhere;text-align:start;unicode-bidi:plaintext;margin:0}.notification-message a{color:var(--pi-accent);text-decoration:underline}.notification-message a:focus-visible{outline:2px solid var(--pi-accent);outline-offset:2px}.notification-truncated{color:var(--pi-muted);overflow-wrap:anywhere;margin:0;font-size:11px}.notification-row-dismiss{top:5px;position:absolute;inset-inline-end:0}.notification-disclosure-icon{transform:scaleX(var(--notification-disclosure-direction,1))}:host(:dir(rtl)){--notification-disclosure-direction:-1}.visually-hidden{clip:rect(0 0 0 0)!important;clip-path:inset(50%)!important;white-space:nowrap!important;border:0!important;width:1px!important;height:1px!important;margin:-1px!important;padding:0!important;position:absolute!important;overflow:hidden!important}.notification-live span{display:block}@media (width<=520px){.notification-header{gap:4px;padding-inline:8px}.notification-list{padding-inline:8px}}`);function qM(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 JM(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),D`<a href=${s} target="_blank" rel="noopener noreferrer">${s}</a>`),r=a+s.length}return n.push(e.slice(r)),n}var YM=class extends O{constructor(){super(),this.sessionId=``,this.collapsedNotificationTargetKeys=new Set,o.createController(this),new S(this)}willUpdate(e){let t=e.get(`notificationInbox`),n=this.notificationInbox;(e.has(`sessionId`)||e.has(`notificationInbox`)&&(!qM(t)||n===void 0||eu(t)!==eu(n)))&&(this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0);let r=this.hasVisibleTray();this.toggleAttribute(`empty`,!r),this.toggleAttribute(`collapsed`,r&&n!==void 0&&tu(this.collapsedNotificationTargetKeys,n))}updated(e){e.has(`notificationInbox`)&&this.pendingNotificationFocus!==void 0&&this.focusPendingNotificationTarget()}disconnectedCallback(){this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0,super.disconnectedCallback()}hasVisibleTray(){let e=this.notificationInbox;return e?.sessionId===this.sessionId&&(Yl(e)>0||e.pendingDismissedIds.size>0||e.dismissAllPending||this.retainedEmptyNotificationTrayTargetKey===eu(e))}render(){return D`${this.renderTray()}${this.renderLiveRegions()}`}renderTray(){let e=this.notificationInbox;if(e===void 0||!this.hasVisibleTray())return null;let t=tu(this.collapsedNotificationTargetKeys,e),n=Vl.t(t?`expand`:`collapse`);return D`
1507
+ `]}};g([y({attribute:!1})],KM.prototype,`state`,void 0),g([y({attribute:!1})],KM.prototype,`onRetry`,void 0),g([v()],KM.prototype,`showStaleWarning`,void 0),KM=g([_(`conversation-sync-notice`)],KM);var qM=r(`:host{min-width:0;min-height:0;color:var(--pi-text);font:14px var(--pi-font,system-ui, sans-serif);flex-direction:column;flex:auto;display:flex}:host([collapsed]){flex:none}:host([empty]){display:contents}.notification-tray{background:var(--pi-bg-overlay);flex-direction:column;flex:auto;min-height:0;display:flex}.notification-tray.collapsed{flex:none}.notification-header{z-index:2;box-sizing:border-box;border-bottom:1px solid var(--pi-border-muted);background:var(--pi-bg-overlay);flex-wrap:nowrap;flex:none;justify-content:space-between;align-items:center;gap:8px;min-width:0;min-height:40px;padding:4px 10px;display:flex;position:sticky;top:0}.notification-tray.collapsed .notification-header{border-bottom:0}.notification-header:focus-visible{outline:2px solid var(--pi-accent);outline-offset:-3px}.notification-heading{min-width:0;color:var(--pi-text-bright);text-overflow:ellipsis;white-space:nowrap;flex:auto;font-size:13px;overflow:hidden}.notification-header-actions{flex:none}.notification-icon{fill:none;stroke:currentColor;stroke-width:2px;stroke-linecap:round;stroke-linejoin:round;pointer-events:none;width:17px;height:17px}.notification-disclosure-icon.expanded{transform:rotate(90deg)}.notification-close-icon{width:16px;height:16px}.notification-list{overscroll-behavior-y:contain;box-sizing:border-box;flex:auto;min-height:0;padding:0 10px 5px;overflow-y:auto}.notification-list[hidden]{display:none}.notification-overflow{border-bottom:1px solid var(--pi-border-muted);color:var(--pi-muted);overflow-wrap:anywhere;margin:0;padding:7px 2px;font-size:11px}.notification-row{box-sizing:border-box;border-bottom:1px solid var(--pi-border-muted);min-width:0;min-height:42px;color:var(--pi-text);gap:4px;padding-block:9px;padding-inline:2px 38px;display:grid;position:relative}.notification-row:focus-visible{outline:2px solid var(--pi-accent);outline-offset:-2px}.notification-metadata{min-width:0;color:var(--pi-muted);flex-wrap:wrap;align-items:baseline;gap:5px;font-size:11px;display:flex}.notification-severity{color:var(--pi-muted);font-size:inherit;font-weight:600}.notification-row.warning .notification-severity{color:var(--pi-warning)}.notification-row.error .notification-severity{color:var(--pi-danger)}.notification-message{white-space:pre-wrap;overflow-wrap:anywhere;text-align:start;unicode-bidi:plaintext;margin:0}.notification-message a{color:var(--pi-accent);text-decoration:underline}.notification-message a:focus-visible{outline:2px solid var(--pi-accent);outline-offset:2px}.notification-truncated{color:var(--pi-muted);overflow-wrap:anywhere;margin:0;font-size:11px}.notification-row-dismiss{top:5px;position:absolute;inset-inline-end:0}.notification-disclosure-icon{transform:scaleX(var(--notification-disclosure-direction,1))}:host(:dir(rtl)){--notification-disclosure-direction:-1}.visually-hidden{clip:rect(0 0 0 0)!important;clip-path:inset(50%)!important;white-space:nowrap!important;border:0!important;width:1px!important;height:1px!important;margin:-1px!important;padding:0!important;position:absolute!important;overflow:hidden!important}.notification-live span{display:block}@media (width<=520px){.notification-header{gap:4px;padding-inline:8px}.notification-list{padding-inline:8px}}`);function JM(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 YM(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),D`<a href=${s} target="_blank" rel="noopener noreferrer">${s}</a>`),r=a+s.length}return n.push(e.slice(r)),n}var XM=class extends O{constructor(){super(),this.sessionId=``,this.collapsedNotificationTargetKeys=new Set,o.createController(this),new S(this)}willUpdate(e){let t=e.get(`notificationInbox`),n=this.notificationInbox;(e.has(`sessionId`)||e.has(`notificationInbox`)&&(!JM(t)||n===void 0||eu(t)!==eu(n)))&&(this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0);let r=this.hasVisibleTray();this.toggleAttribute(`empty`,!r),this.toggleAttribute(`collapsed`,r&&n!==void 0&&tu(this.collapsedNotificationTargetKeys,n))}updated(e){e.has(`notificationInbox`)&&this.pendingNotificationFocus!==void 0&&this.focusPendingNotificationTarget()}disconnectedCallback(){this.pendingNotificationFocus=void 0,this.retainedEmptyNotificationTrayTargetKey=void 0,super.disconnectedCallback()}hasVisibleTray(){let e=this.notificationInbox;return e?.sessionId===this.sessionId&&(Yl(e)>0||e.pendingDismissedIds.size>0||e.dismissAllPending||this.retainedEmptyNotificationTrayTargetKey===eu(e))}render(){return D`${this.renderTray()}${this.renderLiveRegions()}`}renderTray(){let e=this.notificationInbox;if(e===void 0||!this.hasVisibleTray())return null;let t=tu(this.collapsedNotificationTargetKeys,e),n=Vl.t(t?`expand`:`collapse`);return D`
1508
1508
  <section class=${`notification-tray${t?` collapsed`:``}`} role="region" aria-labelledby="session-notifications-heading" @focusout=${e=>{this.releaseEmptyNotificationTray(e)}}>
1509
1509
  <header class="notification-header" data-notification-focus="header" tabindex="-1">
1510
1510
  <strong class="notification-heading" id="session-notifications-heading">${Xl(e)}</strong>
@@ -1530,7 +1530,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1530
1530
  <span aria-hidden="true">·</span>
1531
1531
  <time datetime=${t.receivedAt}>${w.time(new Date(t.receivedAt),{timeStyle:`short`})}</time>
1532
1532
  </div>
1533
- <p class="notification-message" dir="auto">${JM(Zl(t),t.truncated)}</p>
1533
+ <p class="notification-message" dir="auto">${YM(Zl(t),t.truncated)}</p>
1534
1534
  ${iu(t)===void 0?null:D`<p class="notification-truncated">${iu(t)}</p>`}
1535
1535
  <button type="button" class="ui-button ui-button--compact ui-button--icon notification-row-dismiss"
1536
1536
  aria-label=${Ql(t)} title=${Vl.t(`dismissTitle`)}
@@ -1543,46 +1543,46 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1543
1543
  </div>
1544
1544
  </section>`}renderLiveRegions(){let e=this.notificationInbox?.sessionId===this.sessionId?this.notificationInbox.announcements:[],t=e.filter(e=>e.severity!==`error`),n=e.filter(e=>e.severity===`error`);return D`
1545
1545
  <div class="visually-hidden notification-live" aria-live="polite" aria-atomic="false">${qe(t,e=>e.id,e=>D`<span data-announcement-id=${e.id}>${Jl(e)}</span>`)}</div>
1546
- <div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${qe(n,e=>e.id,e=>D`<span data-announcement-id=${e.id}>${Jl(e)}</span>`)}</div>`}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=$l(t.notifications,e),r=eu(t);this.pendingNotificationFocus={chatKey:r,focusTarget:n},n.kind===`header`&&(this.retainedEmptyNotificationTrayTargetKey=r),this.onDismissNotification(e)}dismissAllNotifications(){let e=this.notificationInbox;if(e===void 0||this.onDismissAllNotifications===void 0)return;let t=eu(e);this.pendingNotificationFocus={chatKey:t,focusTarget:{kind:`header`}},this.retainedEmptyNotificationTrayTargetKey=t,this.onDismissAllNotifications()}releaseEmptyNotificationTray(e){let t=e.currentTarget,n=e.relatedTarget;if(t instanceof HTMLElement&&n instanceof Node&&t.contains(n)||this.pendingNotificationFocus!==void 0)return;let r=this.notificationInbox;r!==void 0&&this.retainedEmptyNotificationTrayTargetKey===eu(r)&&Yl(r)===0&&(this.retainedEmptyNotificationTrayTargetKey=void 0)}focusPendingNotificationTarget(){let e=this.pendingNotificationFocus;this.pendingNotificationFocus=void 0;let t=this.notificationInbox;if(e!==void 0&&t!==void 0&&eu(t)===e.chatKey){if(e.focusTarget.kind===`notification`){let t=e.focusTarget.notificationId,n=Array.from(this.renderRoot.querySelectorAll(`[data-notification-id]`)).find(e=>e.dataset.notificationId===t);if(n!==void 0){n.focus();return}}Yl(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}}static{this.styles=[e,t,KM]}};g([y()],YM.prototype,`sessionId`,void 0),g([y({attribute:!1})],YM.prototype,`notificationInbox`,void 0),g([y({attribute:!1})],YM.prototype,`onDismissNotification`,void 0),g([y({attribute:!1})],YM.prototype,`onDismissAllNotifications`,void 0),g([v()],YM.prototype,`collapsedNotificationTargetKeys`,void 0),g([v()],YM.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),YM=g([_(`session-notification-tray`)],YM);var XM={modelAuthRemoved:x(`Authentication for {provider}/{model} was removed. Use /model to select another model.`,`Active model lost authentication. Provider/model identifiers and the /model command stay unchanged`),sessionNamingFailed:x(`Session created, but naming failed: {detail}`,`Related session was created successfully but could not be named; detail is an untranslated diagnostic`),modelFailure:x(`{detailed, select, yes {Model response failed: {detail}} other {Model response failed: The model returned an error.}}`,`Model failure notice. Detail is an untranslated provider diagnostic, rendered as plain text`),imagePlaceholder:x(`[image]`,`Placeholder for malformed or unavailable inline image data`),shellExcluded:x(`excluded from context`,`Shell execution omitted from the model context`),shellNoOutput:x(`(no output)`,`Live shell execution completed without output`),shellFailed:x(`Bash command failed`,`Live shell execution failed without a supplied diagnostic`),shellExit:x(`exit {code}`,`Shell exit status; code is a raw process status, not a regional quantity`),shellCancelled:x(`cancelled`,`Shell execution was cancelled`),shellTruncated:x(`output truncated`,`Shell output is incomplete`),shellFullOutput:x(`full output: {path}`,`Location of complete shell output; path is unchanged`),argsReplacement:x(`edit text replacement`,`Summary of a text replacement tool call without a file path`),argsEdits:x(`{count, plural, one {# edit} other {# edits}}`,`Number of edit operations in tool arguments`),argsItems:x(`{count, plural, one {# item} other {# items}}`,`Size of an array in a compact tool argument summary`),argsObject:x(`object`,`Compact summary of an object-valued tool argument`),role:x(`{role, select, user {user} assistant {assistant} tool {tool} system {system} bash {shell} other {skill}}`,`Message role heading; role is user, assistant, tool, system, bash or skill`),toolOutput:x(`{named, select, yes {{name} output} other {tool output}}`,`Tool-image output heading; name is a raw tool identifier`),toolImage:x(`{named, select, yes {{name} output image {index, number} of {total, number}} other {Tool output image {index, number} of {total, number}}}`,`Tool-image accessible description, including its position across all outputs`),sources:x(`Sources ({count, number})`,`Disclosure of tool-image source messages`),output:x(`Output {index, number}`,`Accessible source-message section name`),sourceHeader:x(`{named, select, yes {{name} output · {index, number}} other {tool output · {index, number}}}`,`Numbered tool-image source heading`),groupLabel:x(`{live, select, yes {live events} other {events}}`,`Activity group heading, independent of disclosure state`),groupSummary:x(`{kind, select, compaction {{count, plural, one {# history compaction summary} other {# history compaction summaries}}} branch {{count, plural, one {# branch summary} other {# branch summaries}}} other {{count, plural, one {# event} other {# events}} · {roles}}}`,`Activity group summary; roles is a locale-formatted list of role counts`),roleCount:x(`{role, select, user {{count, number} user} assistant {{count, number} assistant} tool {{count, number} tool} system {{count, number} system} bash {{count, number} shell} other {{count, number} skill}}`,`Count of events of one role in an activity group`),information:x(`Message information`,`Show metadata for this message`),actions:x(`Message actions`,`Message action menu and action toolbar accessible name`),noMetadata:x(`No Pi message metadata available`,`Fallback for a message with no valid timestamp, model or thinking level`),thinking:x(`Thinking`,`Disclosure of raw model thinking text`),skill:x(`[skill]`,`Skill invocation disclosure prefix, followed by a raw skill name`),loadedSkill:x(`Loaded {name}`,`Skill-read status; name is a raw skill identifier`),readSkill:x(`read {path}`,`Skill-read source path; path is not translated`),toolResult:x(`{failed, select, yes {{name} result · Failed} other {{name} result}}`,`Tool-result disclosure; name is a raw tool identifier`)},q=w.registerMessages(`core.chatTranscript`,XM);function ZM(){return dn`
1546
+ <div class="visually-hidden notification-live" aria-live="assertive" aria-atomic="false">${qe(n,e=>e.id,e=>D`<span data-announcement-id=${e.id}>${Jl(e)}</span>`)}</div>`}dismissNotification(e){let t=this.notificationInbox;if(t===void 0||this.onDismissNotification===void 0)return;let n=$l(t.notifications,e),r=eu(t);this.pendingNotificationFocus={chatKey:r,focusTarget:n},n.kind===`header`&&(this.retainedEmptyNotificationTrayTargetKey=r),this.onDismissNotification(e)}dismissAllNotifications(){let e=this.notificationInbox;if(e===void 0||this.onDismissAllNotifications===void 0)return;let t=eu(e);this.pendingNotificationFocus={chatKey:t,focusTarget:{kind:`header`}},this.retainedEmptyNotificationTrayTargetKey=t,this.onDismissAllNotifications()}releaseEmptyNotificationTray(e){let t=e.currentTarget,n=e.relatedTarget;if(t instanceof HTMLElement&&n instanceof Node&&t.contains(n)||this.pendingNotificationFocus!==void 0)return;let r=this.notificationInbox;r!==void 0&&this.retainedEmptyNotificationTrayTargetKey===eu(r)&&Yl(r)===0&&(this.retainedEmptyNotificationTrayTargetKey=void 0)}focusPendingNotificationTarget(){let e=this.pendingNotificationFocus;this.pendingNotificationFocus=void 0;let t=this.notificationInbox;if(e!==void 0&&t!==void 0&&eu(t)===e.chatKey){if(e.focusTarget.kind===`notification`){let t=e.focusTarget.notificationId,n=Array.from(this.renderRoot.querySelectorAll(`[data-notification-id]`)).find(e=>e.dataset.notificationId===t);if(n!==void 0){n.focus();return}}Yl(t)===0&&(this.retainedEmptyNotificationTrayTargetKey=e.chatKey),this.renderRoot.querySelector(`[data-notification-focus='header']`)?.focus()}}static{this.styles=[e,t,qM]}};g([y()],XM.prototype,`sessionId`,void 0),g([y({attribute:!1})],XM.prototype,`notificationInbox`,void 0),g([y({attribute:!1})],XM.prototype,`onDismissNotification`,void 0),g([y({attribute:!1})],XM.prototype,`onDismissAllNotifications`,void 0),g([v()],XM.prototype,`collapsedNotificationTargetKeys`,void 0),g([v()],XM.prototype,`retainedEmptyNotificationTrayTargetKey`,void 0),XM=g([_(`session-notification-tray`)],XM);var ZM={modelAuthRemoved:x(`Authentication for {provider}/{model} was removed. Use /model to select another model.`,`Active model lost authentication. Provider/model identifiers and the /model command stay unchanged`),sessionNamingFailed:x(`Session created, but naming failed: {detail}`,`Related session was created successfully but could not be named; detail is an untranslated diagnostic`),modelFailure:x(`{detailed, select, yes {Model response failed: {detail}} other {Model response failed: The model returned an error.}}`,`Model failure notice. Detail is an untranslated provider diagnostic, rendered as plain text`),imagePlaceholder:x(`[image]`,`Placeholder for malformed or unavailable inline image data`),shellExcluded:x(`excluded from context`,`Shell execution omitted from the model context`),shellNoOutput:x(`(no output)`,`Live shell execution completed without output`),shellFailed:x(`Bash command failed`,`Live shell execution failed without a supplied diagnostic`),shellExit:x(`exit {code}`,`Shell exit status; code is a raw process status, not a regional quantity`),shellCancelled:x(`cancelled`,`Shell execution was cancelled`),shellTruncated:x(`output truncated`,`Shell output is incomplete`),shellFullOutput:x(`full output: {path}`,`Location of complete shell output; path is unchanged`),argsReplacement:x(`edit text replacement`,`Summary of a text replacement tool call without a file path`),argsEdits:x(`{count, plural, one {# edit} other {# edits}}`,`Number of edit operations in tool arguments`),argsItems:x(`{count, plural, one {# item} other {# items}}`,`Size of an array in a compact tool argument summary`),argsObject:x(`object`,`Compact summary of an object-valued tool argument`),role:x(`{role, select, user {user} assistant {assistant} tool {tool} system {system} bash {shell} other {skill}}`,`Message role heading; role is user, assistant, tool, system, bash or skill`),toolOutput:x(`{named, select, yes {{name} output} other {tool output}}`,`Tool-image output heading; name is a raw tool identifier`),toolImage:x(`{named, select, yes {{name} output image {index, number} of {total, number}} other {Tool output image {index, number} of {total, number}}}`,`Tool-image accessible description, including its position across all outputs`),sources:x(`Sources ({count, number})`,`Disclosure of tool-image source messages`),output:x(`Output {index, number}`,`Accessible source-message section name`),sourceHeader:x(`{named, select, yes {{name} output · {index, number}} other {tool output · {index, number}}}`,`Numbered tool-image source heading`),groupLabel:x(`{live, select, yes {live events} other {events}}`,`Activity group heading, independent of disclosure state`),groupSummary:x(`{kind, select, compaction {{count, plural, one {# history compaction summary} other {# history compaction summaries}}} branch {{count, plural, one {# branch summary} other {# branch summaries}}} other {{count, plural, one {# event} other {# events}} · {roles}}}`,`Activity group summary; roles is a locale-formatted list of role counts`),roleCount:x(`{role, select, user {{count, number} user} assistant {{count, number} assistant} tool {{count, number} tool} system {{count, number} system} bash {{count, number} shell} other {{count, number} skill}}`,`Count of events of one role in an activity group`),information:x(`Message information`,`Show metadata for this message`),actions:x(`Message actions`,`Message action menu and action toolbar accessible name`),noMetadata:x(`No Pi message metadata available`,`Fallback for a message with no valid timestamp, model or thinking level`),thinking:x(`Thinking`,`Disclosure of raw model thinking text`),skill:x(`[skill]`,`Skill invocation disclosure prefix, followed by a raw skill name`),loadedSkill:x(`Loaded {name}`,`Skill-read status; name is a raw skill identifier`),readSkill:x(`read {path}`,`Skill-read source path; path is not translated`),toolResult:x(`{failed, select, yes {{name} result · Failed} other {{name} result}}`,`Tool-result disclosure; name is a raw tool identifier`)},q=w.registerMessages(`core.chatTranscript`,ZM);function QM(){return dn`
1547
1547
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1548
1548
  <rect x="3.5" y="3.5" width="17" height="17" rx="2.5"></rect>
1549
1549
  <circle cx="9" cy="9" r="1.6"></circle>
1550
1550
  <path d="m20.5 15.5-4.5-4.5L5.5 20.5"></path>
1551
1551
  </svg>
1552
- `}function QM(){return dn`
1552
+ `}function $M(){return dn`
1553
1553
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1554
1554
  <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>
1555
1555
  <circle cx="12" cy="13.5" r="3.6"></circle>
1556
1556
  </svg>
1557
- `}function $M(){return dn`
1557
+ `}function eN(){return dn`
1558
1558
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1559
1559
  <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>
1560
1560
  </svg>
1561
- `}function eN(){return dn`
1561
+ `}function tN(){return dn`
1562
1562
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1563
1563
  <path d="M21 3 13.5 21l-2-8.5L3 10.5Z"></path>
1564
1564
  <path d="M21 3 11.5 12.5"></path>
1565
1565
  </svg>
1566
- `}function tN(){return dn`
1566
+ `}function nN(){return dn`
1567
1567
  <svg class="prompt-action-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1568
1568
  <path d="M4 7h11"></path>
1569
1569
  <path d="M4 12h7"></path>
1570
1570
  <path d="M4 17h7"></path>
1571
1571
  <path d="m15 14 5 3-5 3z"></path>
1572
1572
  </svg>
1573
- `}function nN(){return eN()}function rN(){return dn`
1573
+ `}function rN(){return tN()}function iN(){return dn`
1574
1574
  <svg class="prompt-action-icon prompt-action-icon-filled" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1575
1575
  <rect x="6.5" y="6.5" width="11" height="11" rx="2"></rect>
1576
1576
  </svg>
1577
- `}function iN(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 dn`<rect class=${l?`gauge-bar gauge-bar-active`:`gauge-bar`} x=${o} y=${c} width=${r} height=${s} rx="1"></rect>`});return dn`
1577
+ `}function aN(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 dn`<rect class=${l?`gauge-bar gauge-bar-active`:`gauge-bar`} x=${o} y=${c} width=${r} height=${s} rx="1"></rect>`});return dn`
1578
1578
  <svg class="prompt-thinking-gauge" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
1579
1579
  ${i}
1580
1580
  </svg>
1581
- `}function aN(e,t,n=(e,t)=>e===`client`?{heading:`Queued until session starts`,detail:`Will send once the backend session is ready`}:{heading:`Queued messages`,detail:`${String(t)} pending`}){return[e.length===0?void 0:{source:`client`,...n(`client`,e.length),messages:e},t.length===0?void 0:{source:`server`,...n(`server`,t.length),messages:t}].filter(e=>e!==void 0)}function oN(e){return Qn(e,e=>R.t(`attachments`,{count:e}))}function sN(e,t,n){return e.source===`server`&&t&&n}function cN(e,t){let n=e.source===`server`?t.unavailable:void 0,r=n===void 0?void 0:n===``?R.t(`unavailable`):n,i=t.pending||n!==void 0;return D`
1581
+ `}function oN(e,t,n=(e,t)=>e===`client`?{heading:`Queued until session starts`,detail:`Will send once the backend session is ready`}:{heading:`Queued messages`,detail:`${String(t)} pending`}){return[e.length===0?void 0:{source:`client`,...n(`client`,e.length),messages:e},t.length===0?void 0:{source:`server`,...n(`server`,t.length),messages:t}].filter(e=>e!==void 0)}function sN(e){return Qn(e,e=>R.t(`attachments`,{count:e}))}function cN(e,t,n){return e.source===`server`&&t&&n}function lN(e,t){let n=e.source===`server`?t.unavailable:void 0,r=n===void 0?void 0:n===``?R.t(`unavailable`):n,i=t.pending||n!==void 0;return D`
1582
1582
  <aside class="queued-messages ui-transcript-surface" aria-live="polite">
1583
1583
  <div class="queued-header">
1584
1584
  <div class="queued-heading"><strong>${e.heading}</strong><small>${e.detail}</small></div>
1585
- ${sN(e,t.canClearServerQueue,t.onClear!==void 0)?D`
1585
+ ${cN(e,t.canClearServerQueue,t.onClear!==void 0)?D`
1586
1586
  <button type="button" class="queued-clear-button ui-button ui-button--icon ui-button--compact" ?disabled=${t.pending} aria-label=${R.t(`clearQueue`)} title=${R.t(`clearQueueTitle`)} @click=${t.onClear}>${Vf()}</button>
1587
1587
  `:E}
1588
1588
  </div>
@@ -1592,12 +1592,12 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1592
1592
  <div class="queued-message-header">
1593
1593
  <div class="queued-message-meta">
1594
1594
  <span class="queued-kind">${R.t(`queueKind`,{kind:n.kind,index:e.messages.slice(0,a+1).filter(e=>e.kind===n.kind).length})}</span>
1595
- ${oN(n)===void 0?E:D`<span class="queued-attachments" title=${R.t(`attachmentsTitle`)}><span aria-hidden="true">${$M()}</span> ${oN(n)}</span>`}
1595
+ ${sN(n)===void 0?E:D`<span class="queued-attachments" title=${R.t(`attachmentsTitle`)}><span aria-hidden="true">${eN()}</span> ${sN(n)}</span>`}
1596
1596
  </div>
1597
1597
  <div class="queued-message-actions ui-toolbar-group">
1598
1598
  <button type="button" class="queued-action ui-button ui-button--icon ui-button--compact" aria-label=${R.t(`copyQueue`)} title=${R.t(`copyTitle`)} @click=${()=>{t.onCopy(n.text)}}>${zf()}</button>
1599
1599
  ${e.source!==`server`||!t.canMutate||t.onAction===void 0?E:D`
1600
- <button type="button" class="queued-action ui-button ui-button--icon ui-button--compact" ?disabled=${i} title=${r??R.t(`switchTitle`,{kind:n.kind})} aria-label=${R.t(`switchQueue`,{kind:n.kind})} @click=${()=>{t.onAction?.(`toggle`,a,e.messages)}}>${n.kind===`steer`?tN():nN()}</button>
1600
+ <button type="button" class="queued-action ui-button ui-button--icon ui-button--compact" ?disabled=${i} title=${r??R.t(`switchTitle`,{kind:n.kind})} aria-label=${R.t(`switchQueue`,{kind:n.kind})} @click=${()=>{t.onAction?.(`toggle`,a,e.messages)}}>${n.kind===`steer`?nN():rN()}</button>
1601
1601
  <button type="button" class="queued-action ui-button ui-button--icon ui-button--compact" ?disabled=${i} aria-label=${R.t(`recall`)} title=${r??R.t(`recallTitle`)} @click=${()=>{t.onAction?.(`edit`,a,e.messages)}}>${Bf()}</button>
1602
1602
  <button type="button" class="queued-action ui-button ui-button--icon ui-button--compact" ?disabled=${i} aria-label=${R.t(`remove`)} title=${r??R.t(`removeTitle`)} @click=${()=>{t.onAction?.(`remove`,a,e.messages)}}>${Vf()}</button>
1603
1603
  `}
@@ -1607,10 +1607,10 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1607
1607
  </div>
1608
1608
  `)}
1609
1609
  </aside>
1610
- `}var lN=ot(class extends Ce{constructor(){super(...arguments),this.key=E}render(e,t){return this.key=e,t}update(e,[t,n]){return t!==this.key&&(Ve(e),this.key=t),n}}),uN=class{constructor(e,t){this.context=e,this.changed=t,this.availability=new Jn,this.entryPending=!1,this.displayPending=new Set,this.generation=0}localizationChanged(){this.availability.invalidate()}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){if(this.error!==void 0&&this.current(this.error)&&this.error.key===e)return this.error.cause instanceof Error?this.error.cause.message:String(this.error.cause)}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=Un(e,t.role),{onEntry:o,onDisplay:s,availability:c}=i,l=r.target===`display`?s===void 0?void 0:()=>s({...c,message:Wn(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,cause: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}};function dN(e){return Ji(e.args,{replacement:()=>q.t(`argsReplacement`),edits:e=>q.t(`argsEdits`,{count:e}),items:e=>q.t(`argsItems`,{count:e}),object:()=>q.t(`argsObject`)})}function fN(e){switch(e.kind){case`commandResult`:return Pa(e);case`modelAuthRemoved`:return q.t(`modelAuthRemoved`,{provider:e.provider,model:e.model});case`sessionNamingFailed`:return q.t(`sessionNamingFailed`,{detail:e.detail});case`arguments`:return dN(e);case`imagePlaceholder`:return q.t(`imagePlaceholder`);case`modelError`:return q.t(`modelFailure`,{detail:e.detail,detailed:e.detail===``?`no`:`yes`});case`liveShell`:{let t=e.excluded?[q.t(`shellExcluded`),``,`$ ${e.command}`]:[`$ ${e.command}`];e.output!==void 0&&t.push(``,e.output);let n=e.completion;if(n!==void 0){let e=[];n.noOutput&&e.push(q.t(`shellNoOutput`)),n.failed&&e.push(n.failureOutput??q.t(`shellFailed`)),n.exitCode!==void 0&&e.push(q.t(`shellExit`,{code:n.exitCode})),n.cancelled&&e.push(q.t(`shellCancelled`)),n.truncated&&e.push(q.t(`shellTruncated`)),n.fullOutputPath!==void 0&&e.push(q.t(`shellFullOutput`,{path:n.fullOutputPath})),e.length>0&&t.push(``,e.join(`
1610
+ `}var uN=ot(class extends Ce{constructor(){super(...arguments),this.key=E}render(e,t){return this.key=e,t}update(e,[t,n]){return t!==this.key&&(Ve(e),this.key=t),n}}),dN=class{constructor(e,t){this.context=e,this.changed=t,this.availability=new Jn,this.entryPending=!1,this.displayPending=new Set,this.generation=0}localizationChanged(){this.availability.invalidate()}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){if(this.error!==void 0&&this.current(this.error)&&this.error.key===e)return this.error.cause instanceof Error?this.error.cause.message:String(this.error.cause)}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=Un(e,t.role),{onEntry:o,onDisplay:s,availability:c}=i,l=r.target===`display`?s===void 0?void 0:()=>s({...c,message:Wn(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,cause: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}};function fN(e){return Ji(e.args,{replacement:()=>q.t(`argsReplacement`),edits:e=>q.t(`argsEdits`,{count:e}),items:e=>q.t(`argsItems`,{count:e}),object:()=>q.t(`argsObject`)})}function pN(e){switch(e.kind){case`commandResult`:return Pa(e);case`modelAuthRemoved`:return q.t(`modelAuthRemoved`,{provider:e.provider,model:e.model});case`sessionNamingFailed`:return q.t(`sessionNamingFailed`,{detail:e.detail});case`arguments`:return fN(e);case`imagePlaceholder`:return q.t(`imagePlaceholder`);case`modelError`:return q.t(`modelFailure`,{detail:e.detail,detailed:e.detail===``?`no`:`yes`});case`liveShell`:{let t=e.excluded?[q.t(`shellExcluded`),``,`$ ${e.command}`]:[`$ ${e.command}`];e.output!==void 0&&t.push(``,e.output);let n=e.completion;if(n!==void 0){let e=[];n.noOutput&&e.push(q.t(`shellNoOutput`)),n.failed&&e.push(n.failureOutput??q.t(`shellFailed`)),n.exitCode!==void 0&&e.push(q.t(`shellExit`,{code:n.exitCode})),n.cancelled&&e.push(q.t(`shellCancelled`)),n.truncated&&e.push(q.t(`shellTruncated`)),n.fullOutputPath!==void 0&&e.push(q.t(`shellFullOutput`,{path:n.fullOutputPath})),e.length>0&&t.push(``,e.join(`
1611
1611
  `))}return t.join(`
1612
1612
  `)}case`bash`:{let t=e.excluded?[q.t(`shellExcluded`),``,`$ ${e.command}`]:[`$ ${e.command}`];return e.output!==void 0&&t.push(``,e.output),e.exitCode!==void 0&&t.push(``,q.t(`shellExit`,{code:e.exitCode})),e.cancelled&&t.push(``,q.t(`shellCancelled`)),e.truncated&&t.push(``,q.t(`shellTruncated`)),e.fullOutputPath!==void 0&&t.push(``,q.t(`shellFullOutput`,{path:e.fullOutputPath})),t.join(`
1613
- `)}}}var pN=class extends O{constructor(){super(),this.expanded=!1,this.popup=new VA(this,()=>this.expanded?{anchor:this.trigger,panel:this.panel,onClose:()=>{this.expanded=!1,this.removeAttribute(`open`)},options:{placement:`inline-start-end`,padding:8}}:void 0),o.createController(this),new S(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 D`
1613
+ `)}}}var mN=class extends O{constructor(){super(),this.expanded=!1,this.popup=new VA(this,()=>this.expanded?{anchor:this.trigger,panel:this.panel,onClose:()=>{this.expanded=!1,this.removeAttribute(`open`)},options:{placement:`inline-start-end`,padding:8}}:void 0),o.createController(this),new S(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 D`
1614
1614
  <button type="button" class="ui-button ui-button--small ui-button--icon ui-popup-trigger"
1615
1615
  aria-label=${q.t(`actions`)} aria-expanded=${String(this.expanded)} aria-controls="actions"
1616
1616
  @click=${()=>{this.toggle()}}><span aria-hidden="true">⋯</span></button>
@@ -1639,22 +1639,22 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1639
1639
  [popover] { transition: none; }
1640
1640
  }
1641
1641
  }
1642
- `]}};g([Te(`button`)],pN.prototype,`trigger`,void 0),g([Te(`[popover]`)],pN.prototype,`panel`,void 0),g([v()],pN.prototype,`expanded`,void 0),pN=g([_(`pi-message-actions-menu`)],pN);function mN(e){let t=Object.entries(e.roles).map(([e,t])=>q.t(`roleCount`,{role:e,count:t}));return q.t(`groupSummary`,{kind:e.kind,count:e.count,roles:w.list(t)})}function hN(e){return q.t(`toolOutput`,{name:e??``,named:e===void 0||e===``?`no`:`yes`})}function gN(e){return e?`msg event-group live`:`msg event-group`}function _N(e){return q.t(`groupLabel`,{live:e?`yes`:`no`})}var vN=class{constructor(){this.slices=new WeakMap}group(e,t=0,n){return this.preserveCustomMessage!==n&&(this.slices=new WeakMap,this.preserveCustomMessage=n),bN(e,t,e=>{let t=this.slices.get(e);return t===void 0&&(t=xN(e,n),this.slices.set(e,t)),t})}};function yN(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 bN(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(),TN(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 xN(e,t=()=>!1){let n=[],r=[];for(let i of e.parts.flatMap(e=>e.type===`customMessage`&&!t(e.customType)?e.parts:[e]))i.type!==`toolResultBoundary`&&i.type!==`empty`&&(DN(e,i)?n:r).push(i);let i={...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:n.length===0?void 0:{role:e.role,parts:n,...i},technical:r.length===0?void 0:{role:r.every(e=>e.type===`skillRead`)?`skill`:e.role,parts:r,...i},toolName:EN(r)}}function SN(e){return!(e.parts.length>0&&(e.role===`tool`&&e.parts.every(e=>e.type===`toolExecution`)||e.parts.every(e=>e.type===`askUserRecord`)))}function CN(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||!SN(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 wN(e,t){if(t!==void 0){let n={};for(let t of e)n[t.role]=(n[t.role]??0)+1;return t({kind:e.every(e=>e.source===`compaction`)?`compaction`:e.every(e=>e.source===`branch_summary`)?`branch`:`events`,count:e.length,roles:n})}if(e.every(e=>e.source===`compaction`))return`${String(e.length)} history compaction ${e.length===1?`summary`:`summaries`}`;if(e.every(e=>e.source===`branch_summary`))return`${String(e.length)} branch ${e.length===1?`summary`:`summaries`}`;let n=e.reduce((e,t)=>(e[t.role]=(e[t.role]??0)+1,e),{}),r={user:C(`client.chatGroups.user.0d0e1a`,`User`),assistant:C(`client.chatGroups.assistant.e5ce5f`,`Assistant`),tool:C(`client.chatGroups.tool.5ca673`,`Tool`),system:C(`client.chatGroups.system.5b50d7`,`System`),bash:C(`client.chatGroups.command.928f87`,`Command`),skill:C(`client.chatGroups.skill.99aea2`,`Skill`)},i=Object.entries(n).map(([e,t])=>`${String(t)} ${r[e]??e}`).join(` · `);return C(`client.chatGroups.events.12f406`,`{value1} events{value2}`,{value1:String(e.length),value2:i===``?``:` · ${i}`})}function TN(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function EN(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function DN(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===`customMessage`||t.type===`text`&&(e.role===`user`||e.role===`assistant`||e.role===`system`||e.role===`bash`)}function ON(e,t,n,r){let i=AN(t),a=SN(t),o=i?`msg tool-execution-shell`:`msg ask-user-record-shell`,s=a&&(t.role===`user`||t.role===`assistant`)?` conversation-message conversation-layout chat-message`:``;return D`
1642
+ `]}};g([Te(`button`)],mN.prototype,`trigger`,void 0),g([Te(`[popover]`)],mN.prototype,`panel`,void 0),g([v()],mN.prototype,`expanded`,void 0),mN=g([_(`pi-message-actions-menu`)],mN);function hN(e){let t=Object.entries(e.roles).map(([e,t])=>q.t(`roleCount`,{role:e,count:t}));return q.t(`groupSummary`,{kind:e.kind,count:e.count,roles:w.list(t)})}function gN(e){return q.t(`toolOutput`,{name:e??``,named:e===void 0||e===``?`no`:`yes`})}function _N(e){return e?`msg event-group live`:`msg event-group`}function vN(e){return q.t(`groupLabel`,{live:e?`yes`:`no`})}var yN=class{constructor(){this.slices=new WeakMap}group(e,t=0,n){return this.preserveCustomMessage!==n&&(this.slices=new WeakMap,this.preserveCustomMessage=n),xN(e,t,e=>{let t=this.slices.get(e);return t===void 0&&(t=SN(e,n),this.slices.set(e,t)),t})}};function bN(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 xN(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(),EN(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 SN(e,t=()=>!1){let n=[],r=[];for(let i of e.parts.flatMap(e=>e.type===`customMessage`&&!t(e.customType)?e.parts:[e]))i.type!==`toolResultBoundary`&&i.type!==`empty`&&(ON(e,i)?n:r).push(i);let i={...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:n.length===0?void 0:{role:e.role,parts:n,...i},technical:r.length===0?void 0:{role:r.every(e=>e.type===`skillRead`)?`skill`:e.role,parts:r,...i},toolName:DN(r)}}function CN(e){return!(e.parts.length>0&&(e.role===`tool`&&e.parts.every(e=>e.type===`toolExecution`)||e.parts.every(e=>e.type===`askUserRecord`)))}function wN(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||!CN(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 TN(e,t){if(t!==void 0){let n={};for(let t of e)n[t.role]=(n[t.role]??0)+1;return t({kind:e.every(e=>e.source===`compaction`)?`compaction`:e.every(e=>e.source===`branch_summary`)?`branch`:`events`,count:e.length,roles:n})}if(e.every(e=>e.source===`compaction`))return`${String(e.length)} history compaction ${e.length===1?`summary`:`summaries`}`;if(e.every(e=>e.source===`branch_summary`))return`${String(e.length)} branch ${e.length===1?`summary`:`summaries`}`;let n=e.reduce((e,t)=>(e[t.role]=(e[t.role]??0)+1,e),{}),r={user:C(`client.chatGroups.user.0d0e1a`,`User`),assistant:C(`client.chatGroups.assistant.e5ce5f`,`Assistant`),tool:C(`client.chatGroups.tool.5ca673`,`Tool`),system:C(`client.chatGroups.system.5b50d7`,`System`),bash:C(`client.chatGroups.command.928f87`,`Command`),skill:C(`client.chatGroups.skill.99aea2`,`Skill`)},i=Object.entries(n).map(([e,t])=>`${String(t)} ${r[e]??e}`).join(` · `);return C(`client.chatGroups.events.12f406`,`{value1} events{value2}`,{value1:String(e.length),value2:i===``?``:` · ${i}`})}function EN(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`image`)}function DN(e){for(let t of e)if((t.type===`toolCall`||t.type===`toolExecution`||t.type===`toolResult`)&&t.toolName!==``)return t.toolName}function ON(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===`customMessage`||t.type===`text`&&(e.role===`user`||e.role===`assistant`||e.role===`system`||e.role===`bash`)}function kN(e,t,n,r){let i=jN(t),a=CN(t),o=i?`msg tool-execution-shell`:`msg ask-user-record-shell`,s=a&&(t.role===`user`||t.role===`assistant`)?` conversation-message conversation-layout chat-message`:``;return D`
1643
1643
  <article class=${`${a?`msg ${t.role}${s}`:o} ui-transcript-surface`} data-speaker=${s===``?E:t.role} data-index=${n} data-scroll-anchor-id=${e.anchors.message(n,t)??E}>
1644
1644
  ${s===``?D`
1645
- ${a?PN(e,t,String(n),n,r):null}
1646
- ${t.parts.map((r,i)=>IN(e,r,t,n,i))}
1645
+ ${a?FN(e,t,String(n),n,r):null}
1646
+ ${t.parts.map((r,i)=>LN(e,r,t,n,i))}
1647
1647
  `:D`
1648
1648
  <div class="conversation-content chat-message-content">
1649
- ${PN(e,t,String(n),n,r,void 0,!0)}
1650
- <div class="conversation-body chat-message-body">${t.parts.map((r,i)=>IN(e,r,t,n,i))}</div>
1649
+ ${FN(e,t,String(n),n,r,void 0,!0)}
1650
+ <div class="conversation-body chat-message-body">${t.parts.map((r,i)=>LN(e,r,t,n,i))}</div>
1651
1651
  </div>
1652
- ${FN(e,t,String(n))}
1652
+ ${IN(e,t,String(n))}
1653
1653
  `}
1654
1654
  </article>
1655
- `}function kN(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=hN(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:()=>q.t(`toolImage`,{name:e.output.toolName??``,named:e.output.toolName===void 0||e.output.toolName===``?`no`:`yes`,index:t+1,total:c.length})}));return D`
1655
+ `}function AN(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=gN(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:()=>q.t(`toolImage`,{name:e.output.toolName??``,named:e.output.toolName===void 0||e.output.toolName===``?`no`:`yes`,index:t+1,total:c.length})}));return D`
1656
1656
  <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)??E}>
1657
- ${r.length===1?PN(e,i.message,String(i.index),i.index,n,s):D`<div class="msg-header"><span class="label">${s}</span></div>`}
1657
+ ${r.length===1?FN(e,i.message,String(i.index),i.index,n,s):D`<div class="msg-header"><span class="label">${s}</span></div>`}
1658
1658
  <div class="tool-image-thumbnails">
1659
1659
  ${l.map((t,n)=>D`
1660
1660
  <pi-web-transcript-image .imagePart=${t.part} .thumbnail=${!0} .description=${t.description}
@@ -1668,44 +1668,44 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1668
1668
  <details class="image-output-sources" ?open=${Ze(o)} @toggle=${t=>{e.disclosure.toggle(a,t,!1)}}>
1669
1669
  <summary class="ui-transcript-disclosure">${q.t(`sources`,{count:r.length})}</summary>
1670
1670
  ${o?r.map((t,r)=>D`<section class="image-output-source" aria-label=${q.t(`output`,{index:r+1})}>
1671
- ${PN(e,t.message,`image-source:${String(t.index)}`,t.index,n,q.t(`sourceHeader`,{name:t.toolName??``,named:t.toolName===void 0||t.toolName===``?`no`:`yes`,index:r+1}))}
1671
+ ${FN(e,t.message,`image-source:${String(t.index)}`,t.index,n,q.t(`sourceHeader`,{name:t.toolName??``,named:t.toolName===void 0||t.toolName===``?`no`:`yes`,index:r+1}))}
1672
1672
  </section>`):E}
1673
1673
  </details>
1674
1674
  `}
1675
1675
  </article>
1676
- `}function AN(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`toolExecution`)}function jN(e,t,n,r,i){let{messages:a,startIndex:o}=t,{open:s,anchor:c,toggle:l}=i;return D`
1677
- <details class=${`${gN(n)} ui-transcript-surface ui-transcript-activity`} data-index=${o} data-scroll-anchor-id=${c??E} ?open=${s} @toggle=${l}>
1676
+ `}function jN(e){return e.role===`tool`&&e.parts.length>0&&e.parts.every(e=>e.type===`toolExecution`)}function MN(e,t,n,r,i){let{messages:a,startIndex:o}=t,{open:s,anchor:c,toggle:l}=i;return D`
1677
+ <details class=${`${_N(n)} ui-transcript-surface ui-transcript-activity`} data-index=${o} data-scroll-anchor-id=${c??E} ?open=${s} @toggle=${l}>
1678
1678
  <summary class="ui-transcript-disclosure ui-transcript-heading">
1679
- <span class="label">${_N(n)}</span>
1680
- <span>${wN(a.map(e=>e.message),mN)}</span>
1679
+ <span class="label">${vN(n)}</span>
1680
+ <span>${TN(a.map(e=>e.message),hN)}</span>
1681
1681
  </summary>
1682
- ${Xe(s?MN(e,t,r):E)}
1682
+ ${Xe(s?NN(e,t,r):E)}
1683
1683
  </details>
1684
- `}function MN(e,{messages:t,startIndex:n},r=new Set){return D`
1684
+ `}function NN(e,{messages:t,startIndex:n},r=new Set){return D`
1685
1685
  <div class="group-body">
1686
1686
  ${t.map(({message:t,index:i},a)=>D`
1687
1687
  <section class=${`group-msg ${t.role} ui-transcript-surface`} data-index=${i} data-scroll-anchor-id=${e.anchors.event(i,t)??E}>
1688
- ${SN(t)?D`<div class="transcript-content">${PN(e,t,`${String(n)}:${String(a)}`,i,r)}</div>`:null}
1689
- ${NN(e,t,i)}
1688
+ ${CN(t)?D`<div class="transcript-content">${FN(e,t,`${String(n)}:${String(a)}`,i,r)}</div>`:null}
1689
+ ${PN(e,t,i)}
1690
1690
  </section>`)}
1691
1691
  </div>
1692
- `}function NN(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=>D`
1692
+ `}function PN(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=>D`
1693
1693
  <div class=${r.section?`transcript-section`:`transcript-content`}>
1694
- ${r.parts.map(({part:r,index:i})=>IN(e,r,t,n,i))}
1694
+ ${r.parts.map(({part:r,index:i})=>LN(e,r,t,n,i))}
1695
1695
  </div>
1696
- `)}function PN(e,t,n,r,i,a,o=!1){let s=e.metadata.label(t),c=e.metadata.expandedKey===n,l=`message-meta-${n}`,u=a===void 0&&(t.role===`user`||t.role===`assistant`),d=a??q.t(`role`,{role:t.role});return D`
1696
+ `)}function FN(e,t,n,r,i,a,o=!1){let s=e.metadata.label(t),c=e.metadata.expandedKey===n,l=`message-meta-${n}`,u=a===void 0&&(t.role===`user`||t.role===`assistant`),d=a??q.t(`role`,{role:t.role});return D`
1697
1697
  <div class=${u?`msg-header conversation-header chat-message-header`:`msg-header`}>
1698
1698
  <span class=${u?`visually-hidden`:`label`}>${d}</span>
1699
1699
  <pi-message-actions-menu>
1700
1700
  <div class="msg-actions-strip">
1701
- ${LN(e,t,n,e.messages[r-e.messageStart]??t,i.has(t))}
1702
- <button type="button" class="msg-meta ui-button ui-button--icon ui-button--small" title=${s} aria-label=${q.t(`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 pN&&r.close()}}>${of(`info`,`msg-info-icon`)}</button>
1701
+ ${RN(e,t,n,e.messages[r-e.messageStart]??t,i.has(t))}
1702
+ <button type="button" class="msg-meta ui-button ui-button--icon ui-button--small" title=${s} aria-label=${q.t(`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 mN&&r.close()}}>${of(`info`,`msg-info-icon`)}</button>
1703
1703
  </div>
1704
1704
  </pi-message-actions-menu>
1705
1705
  </div>
1706
- ${o?null:FN(e,t,n)}
1707
- `}function FN(e,t,n){return D`<div id=${`message-meta-${n}`} class="msg-meta-details chat-message-meta" ?hidden=${e.metadata.expandedKey!==n}>${e.metadata.label(t)}</div>`}function IN(e,t,n,r,i){let a=JSON.stringify([e.machineId,e.sessionId,n.entryId??r,i]);if(t.type===`customMessage`){let i=t.parts.map((t,i)=>IN(e,t,n,r,i)),o=e.transcriptRenderers.find(e=>e.target===`custom-message`&&e.customType===t.customType);return o?.target===`custom-message`?D`<pi-web-transcript-renderer class="part" .itemKey=${a} .scope=${e.rendererScope}
1708
- .entryId=${n.entryId} .request=${{kind:`custom-message`,renderer:o,entry:t}}>${i}</pi-web-transcript-renderer>`:D`${i}`}if(t.type===`text`||t.type===`thinking`){let r=t.type===`text`&&t.presentation!==void 0?fN(t.presentation):t.displayText??t.text;if(r===``)return null;if(t.type===`thinking`){let t=`thinking:${a}`,n=e.disclosure.isOpen(t,!0);return D`
1706
+ ${o?null:IN(e,t,n)}
1707
+ `}function IN(e,t,n){return D`<div id=${`message-meta-${n}`} class="msg-meta-details chat-message-meta" ?hidden=${e.metadata.expandedKey!==n}>${e.metadata.label(t)}</div>`}function LN(e,t,n,r,i){let a=JSON.stringify([e.machineId,e.sessionId,n.entryId??r,i]);if(t.type===`customMessage`){let i=t.parts.map((t,i)=>LN(e,t,n,r,i)),o=e.transcriptRenderers.find(e=>e.target===`custom-message`&&e.customType===t.customType);return o?.target===`custom-message`?D`<pi-web-transcript-renderer class="part" .itemKey=${a} .scope=${e.rendererScope}
1708
+ .entryId=${n.entryId} .request=${{kind:`custom-message`,renderer:o,entry:t}}>${i}</pi-web-transcript-renderer>`:D`${i}`}if(t.type===`text`||t.type===`thinking`){let r=t.type===`text`&&t.presentation!==void 0?pN(t.presentation):t.displayText??t.text;if(r===``)return null;if(t.type===`thinking`){let t=`thinking:${a}`,n=e.disclosure.isOpen(t,!0);return D`
1709
1709
  <details class="part thinking ui-transcript-surface ui-transcript-activity" ?open=${Ze(n)}
1710
1710
  @toggle=${n=>{e.disclosure.toggle(t,n,!0)}}>
1711
1711
  <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>${q.t(`thinking`)}</summary>
@@ -1737,18 +1737,18 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1737
1737
  ></ask-user-card>
1738
1738
  `;if(t.type===`image`)return D`<pi-web-transcript-image class="part chat-image" .imagePart=${t} .loadingDisabled=${!e.behaviors.loadImages}
1739
1739
  .session=${e.session} .machineId=${e.machineId}
1740
- ></pi-web-transcript-image>`;if(t.type===`toolCall`)return D`<div class="part tool-line ui-transcript-surface ui-transcript-activity ui-transcript-tool"><div class="ui-transcript-heading"><span aria-hidden="true">▶</span> ${t.toolName}<span class="summary">${t.summaryPresentation===void 0?t.summary:dN(t.summaryPresentation)}</span></div></div>`;if(t.type===`toolExecution`){let n=D`<tool-execution-view class="part" .execution=${t}></tool-execution-view>`;return e.transcriptRenderers.some(e=>e.target===`tool`)?D`<pi-web-transcript-renderer class="part" .itemKey=${a} .scope=${e.rendererScope}
1740
+ ></pi-web-transcript-image>`;if(t.type===`toolCall`)return D`<div class="part tool-line ui-transcript-surface ui-transcript-activity ui-transcript-tool"><div class="ui-transcript-heading"><span aria-hidden="true">▶</span> ${t.toolName}<span class="summary">${t.summaryPresentation===void 0?t.summary:fN(t.summaryPresentation)}</span></div></div>`;if(t.type===`toolExecution`){let n=D`<tool-execution-view class="part" .execution=${t}></tool-execution-view>`;return e.transcriptRenderers.some(e=>e.target===`tool`)?D`<pi-web-transcript-renderer class="part" .itemKey=${a} .scope=${e.rendererScope}
1741
1741
  .request=${{kind:`tool`,renderers:e.transcriptRenderers,entry:t}}>${n}</pi-web-transcript-renderer>`:n}if(t.type===`toolResult`){let n=`tool-result:${a}`,r=e.disclosure.isOpen(n,t.isError);return D`
1742
1742
  <details class=${`part tool-result ui-transcript-surface ui-transcript-activity ui-transcript-tool${t.isError?` error`:``}`} ?open=${Ze(r)} @toggle=${r=>{e.disclosure.toggle(n,r,t.isError)}}>
1743
1743
  <summary class="ui-transcript-disclosure ui-transcript-heading">${t.isError?`✖`:`✓`} ${q.t(`toolResult`,{name:t.toolName,failed:t.isError?`yes`:`no`})}</summary>
1744
1744
  ${r?D`<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>`:E}
1745
1745
  </details>
1746
- `}return null}function LN(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 D`
1746
+ `}return null}function RN(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 D`
1747
1747
  <div class="msg-actions" aria-label=${q.t(`actions`)}>
1748
1748
  ${a.map(({action:i,enabled:a,ariaLabel:o})=>{let s=e.actions.presentation(n,i.id),c=s?.icon??i.icon;return D`<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>`})}
1749
1749
  ${o===void 0?null:D`<span role="alert">${o}</span>`}
1750
1750
  </div>
1751
- `}var RN=`pi-web:chat-groups:`,zN={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(VN(e));return t===null||t===``?void 0:HN(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(VN(e),JSON.stringify(t))}catch{}}},BN=class{constructor(e=zN){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&&WN(i,this.openGroupKeys)&&WN(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 VN(e){return`${RN}${e}`}function HN(e){if(Array.isArray(e))return{open:UN(e),closedDefaultOpen:[]};if(GN(e))return{open:Array.isArray(e.open)?UN(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?UN(e.closedDefaultOpen):[]}}function UN(e){return e.filter(e=>typeof e==`string`)}function WN(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function GN(e){return typeof e==`object`&&!!e}function KN(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 qN(e){let t=new Map;for(let n of e)for(let e of Hn(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 JN=`pi-web:chat-scroll:`,YN=180,XN=48,ZN=2,QN={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)}},$N={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},eP=class{constructor(e=QN,t=$N){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=YN){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=ZN){if(e===``||t===void 0||!rP(t))return`skipped`;try{if(aP(t,r))return this.storage.setItem(tP(e),JSON.stringify({mode:`bottom`})),`saved`;let i=sP(t,n);if(i===void 0)return`skipped`;let a=oP(t,i);return this.storage.setItem(tP(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||!rP(t))return{status:`skipped`};let i=cP(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(tP(e));if(t===null||t===``)return;let n=JSON.parse(t);return nP(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!rP(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function tP(e){return`${JN}${e}`}function nP(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 rP(e){return e.clientHeight>0&&e.scrollHeight>0}function iP(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function aP(e,t=XN){return iP(e)<t}function oP(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:lP(t)??``,offset:t.getBoundingClientRect().top-n}}function sP(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0,s,c=1/0;for(let e of t){if(lP(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 cP(e,t){return e.find(e=>{if(lP(e)!==t)return!1;let n=e.getBoundingClientRect();return n.bottom>n.top})}function lP(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}var uP={request:e=>requestAnimationFrame(e),cancel:e=>{cancelAnimationFrame(e)}};function dP(e){return e.hasMore()&&!e.isLoadingMore()&&e.canRequestEarlier()}var fP=2,pP=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<fP))}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<fP,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)}},mP=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&&dP(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}},hP=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&&dP(this.host)&&(this.frame=this.frames.request(()=>{if(this.frame=void 0,!this.host.getBehaviors().automaticHistory||!dP(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}},gP=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=sP(e,this.host.getAnchors());t!==void 0&&(this.snapshot=oP(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}},_P=class{constructor(e,t=uP,n={}){this.host=e,this.started=!1,this.disposed=!1;let r=new eP(n.storage,n.saveScheduler);this.tail=new pP(e,t),this.position=new mP(e,t,r,()=>{this.tail.syncFollowingAfterNavigation()},()=>{this.tail.pause(),this.tail.recordScrollBaseline()}),this.history=new hP(e,t),this.prepend=new gP(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())}},vP=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)}},yP=T`
1751
+ `}var zN=`pi-web:chat-groups:`,BN={read(e){try{if(typeof localStorage>`u`)return;let t=localStorage.getItem(HN(e));return t===null||t===``?void 0:UN(JSON.parse(t))}catch{return}},write(e,t){try{if(typeof localStorage>`u`)return;localStorage.setItem(HN(e),JSON.stringify(t))}catch{}}},VN=class{constructor(e=BN){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&&GN(i,this.openGroupKeys)&&GN(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 HN(e){return`${zN}${e}`}function UN(e){if(Array.isArray(e))return{open:WN(e),closedDefaultOpen:[]};if(KN(e))return{open:Array.isArray(e.open)?WN(e.open):[],closedDefaultOpen:Array.isArray(e.closedDefaultOpen)?WN(e.closedDefaultOpen):[]}}function WN(e){return e.filter(e=>typeof e==`string`)}function GN(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function KN(e){return typeof e==`object`&&!!e}function qN(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 JN(e){let t=new Map;for(let n of e)for(let e of Hn(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 YN=`pi-web:chat-scroll:`,XN=180,ZN=48,QN=2,$N={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)}},eP={setTimeout(e,t){return window.setTimeout(e,t)},clearTimeout(e){window.clearTimeout(e)}},tP=class{constructor(e=$N,t=eP){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=XN){this.clearScheduledSave(),this.saveTimer=this.scheduler.setTimeout(()=>{this.saveTimer=void 0,t(e)},n)}savePosition(e,t,n,r=QN){if(e===``||t===void 0||!iP(t))return`skipped`;try{if(oP(t,r))return this.storage.setItem(nP(e),JSON.stringify({mode:`bottom`})),`saved`;let i=cP(t,n);if(i===void 0)return`skipped`;let a=sP(t,i);return this.storage.setItem(nP(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||!iP(t))return{status:`skipped`};let i=lP(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(nP(e));if(t===null||t===``)return;let n=JSON.parse(t);return rP(n)?n:void 0}catch{return}}scrollToBottom(e){return e===void 0||!iP(e)?{status:`skipped`}:(e.scrollTop=e.scrollHeight,{status:`bottom`})}};function nP(e){return`${YN}${e}`}function rP(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 iP(e){return e.clientHeight>0&&e.scrollHeight>0}function aP(e){return e.scrollHeight-e.scrollTop-e.clientHeight}function oP(e,t=ZN){return aP(e)<t}function sP(e,t){let n=e.getBoundingClientRect().top;return{mode:`anchor`,anchorId:uP(t)??``,offset:t.getBoundingClientRect().top-n}}function cP(e,t){let n=e.getBoundingClientRect(),r,i=-1/0,a,o=1/0,s,c=1/0;for(let e of t){if(uP(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 lP(e,t){return e.find(e=>{if(uP(e)!==t)return!1;let n=e.getBoundingClientRect();return n.bottom>n.top})}function uP(e){return e.dataset.scrollAnchorId!==void 0&&e.dataset.scrollAnchorId!==``?e.dataset.scrollAnchorId:void 0}var dP={request:e=>requestAnimationFrame(e),cancel:e=>{cancelAnimationFrame(e)}};function fP(e){return e.hasMore()&&!e.isLoadingMore()&&e.canRequestEarlier()}var pP=2,mP=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<pP))}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<pP,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)}},hP=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&&fP(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}},gP=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&&fP(this.host)&&(this.frame=this.frames.request(()=>{if(this.frame=void 0,!this.host.getBehaviors().automaticHistory||!fP(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}},_P=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=cP(e,this.host.getAnchors());t!==void 0&&(this.snapshot=sP(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}},vP=class{constructor(e,t=dP,n={}){this.host=e,this.started=!1,this.disposed=!1;let r=new tP(n.storage,n.saveScheduler);this.tail=new mP(e,t),this.position=new hP(e,t,r,()=>{this.tail.syncFollowingAfterNavigation()},()=>{this.tail.pause(),this.tail.recordScrollBaseline()}),this.history=new gP(e,t),this.prepend=new _P(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())}},yP=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)}},bP=T`
1752
1752
  ${e}
1753
1753
  ${t}
1754
1754
  ${Gd}
@@ -1907,7 +1907,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1907
1907
  pre { margin: 6px 0 0; white-space: pre-wrap; overflow-wrap: anywhere; font: inherit; direction: ltr; text-align: left; unicode-bidi: isolate; }
1908
1908
  .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; }
1909
1909
  }
1910
- `,bP=r(`.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)}`),xP={questions:x(`Questions`,`Heading for an agent question set`),answers:x(`Answers`,`Heading for a compact recorded response`),progress:x(`{answered, number} of {total, number} answered`,`Live question-set completion status`),questionNumber:x(`{number, number}.`,`Number preceding a question in the form or record`),skip:x(`Skip questions`,`Send an explicit empty response, ignoring retained drafts`),send:x(`Send answers`,`Submit answers to the agent's question set`),sending:x(`Sending…`,`Answer submission in progress`),custom:x(`Custom`,`Alternative to the agent-provided answer choices`),customAnswer:x(`Custom answer`,`Label for a free-text answer`),addComment:x(`Add a comment`,`Add optional context beside selected choices`),comment:x(`Comment (optional)`,`Label for context attached to selected choices`),closeComment:x(`Close comment`,`Hide optional comment without deleting its draft`),closeCommentHint:x(`Close comment (kept as draft)`,`Tooltip explaining that closing retains the comment`),confirmPartial:x(`Confirm partial answers`,`Accessible name of partial-submission confirmation`),partialPrompt:x(`Send without answering these questions?`,`Confirmation prompt followed by links to unanswered questions`),keepEditing:x(`Keep editing`,`Return to the first unanswered question`),sendAnyway:x(`Send anyway`,`Submit a partially answered question set`),closed:x(`Closed · {total, plural, one {# question} other {# questions}}`,`Closed question-set disclosure status`),multiple:x(`Multiple choices allowed`,`Historical question allowed several choices`),skipped:x(`Questions skipped`,`Recorded submitted response contains no answers`),sent:x(`Answers sent`,`Recorded submitted response contains answers`),superseded:x(`Superseded`,`Legacy question set replaced by a newer one`),cancelled:x(`Cancelled`,`Question set was cancelled`),supersededSummary:x(`A newer question set replaced this one. Draft answers shown below were not sent to the model.`,`Legacy superseded question-set explanation`),completeSummary:x(`Answered {answered, number} of {total, number}; none left unanswered`,`Recorded answer counts when all questions were answered`),partialSummary:x(`Answered {answered, number} of {total, number}; unanswered: {ids}`,`Recorded counts and native-locale list of raw unanswered question identifiers`),unanswered:x(`Unanswered`,`Historical question has no answer`),customRecord:x(`Custom: {answer}`,`Recorded custom answer; preserve the user's answer verbatim`),commentRecord:x(`Comment: {comment}`,`Recorded optional context; preserve the user's comment verbatim`),draft:x(`Draft answer · not sent`,`Retained local draft shown in a closed question set`)},SP=e=>e??E,J=w.registerMessages(`core.askUser`,xP);function CP(e){let t={answered:e.answeredCount,total:e.questions.length};return e.unansweredIds.length===0?J.t(`completeSummary`,t):J.t(`partialSummary`,{...t,ids:w.list(e.unansweredIds)})}var wP=class extends O{constructor(){super(),this.open=!1,this.outcomes=[],this.compact=!1,this.draftSessionId=``,this.answers={},this.confirmingPartialSubmit=!1,this.submitting=!1,o.createController(this),new S(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=Zo(e.questions,this.answers),n=Qo(e.questions,this.answers);return D`
1910
+ `,xP=r(`.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)}`),SP={questions:x(`Questions`,`Heading for an agent question set`),answers:x(`Answers`,`Heading for a compact recorded response`),progress:x(`{answered, number} of {total, number} answered`,`Live question-set completion status`),questionNumber:x(`{number, number}.`,`Number preceding a question in the form or record`),skip:x(`Skip questions`,`Send an explicit empty response, ignoring retained drafts`),send:x(`Send answers`,`Submit answers to the agent's question set`),sending:x(`Sending…`,`Answer submission in progress`),custom:x(`Custom`,`Alternative to the agent-provided answer choices`),customAnswer:x(`Custom answer`,`Label for a free-text answer`),addComment:x(`Add a comment`,`Add optional context beside selected choices`),comment:x(`Comment (optional)`,`Label for context attached to selected choices`),closeComment:x(`Close comment`,`Hide optional comment without deleting its draft`),closeCommentHint:x(`Close comment (kept as draft)`,`Tooltip explaining that closing retains the comment`),confirmPartial:x(`Confirm partial answers`,`Accessible name of partial-submission confirmation`),partialPrompt:x(`Send without answering these questions?`,`Confirmation prompt followed by links to unanswered questions`),keepEditing:x(`Keep editing`,`Return to the first unanswered question`),sendAnyway:x(`Send anyway`,`Submit a partially answered question set`),closed:x(`Closed · {total, plural, one {# question} other {# questions}}`,`Closed question-set disclosure status`),multiple:x(`Multiple choices allowed`,`Historical question allowed several choices`),skipped:x(`Questions skipped`,`Recorded submitted response contains no answers`),sent:x(`Answers sent`,`Recorded submitted response contains answers`),superseded:x(`Superseded`,`Legacy question set replaced by a newer one`),cancelled:x(`Cancelled`,`Question set was cancelled`),supersededSummary:x(`A newer question set replaced this one. Draft answers shown below were not sent to the model.`,`Legacy superseded question-set explanation`),completeSummary:x(`Answered {answered, number} of {total, number}; none left unanswered`,`Recorded answer counts when all questions were answered`),partialSummary:x(`Answered {answered, number} of {total, number}; unanswered: {ids}`,`Recorded counts and native-locale list of raw unanswered question identifiers`),unanswered:x(`Unanswered`,`Historical question has no answer`),customRecord:x(`Custom: {answer}`,`Recorded custom answer; preserve the user's answer verbatim`),commentRecord:x(`Comment: {comment}`,`Recorded optional context; preserve the user's comment verbatim`),draft:x(`Draft answer · not sent`,`Retained local draft shown in a closed question set`)},CP=e=>e??E,J=w.registerMessages(`core.askUser`,SP);function wP(e){let t={answered:e.answeredCount,total:e.questions.length};return e.unansweredIds.length===0?J.t(`completeSummary`,t):J.t(`partialSummary`,{...t,ids:w.list(e.unansweredIds)})}var TP=class extends O{constructor(){super(),this.open=!1,this.outcomes=[],this.compact=!1,this.draftSessionId=``,this.answers={},this.confirmingPartialSubmit=!1,this.submitting=!1,o.createController(this),new S(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=Zo(e.questions,this.answers),n=Qo(e.questions,this.answers);return D`
1911
1911
  <article class="ui-transcript-surface card open-card" aria-labelledby="ask-user-heading">
1912
1912
  <header class="ui-transcript-card-header card-header">
1913
1913
  <h2 id="ask-user-heading">${J.t(`questions`)}</h2>
@@ -1934,7 +1934,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
1934
1934
  <fieldset
1935
1935
  id=${this.questionFieldsetId(n)}
1936
1936
  class=${`question${i?` answered`:``}`}
1937
- aria-describedby=${SP(a)}
1937
+ aria-describedby=${CP(a)}
1938
1938
  tabindex="-1"
1939
1939
  >
1940
1940
  <legend>
@@ -2016,7 +2016,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2016
2016
  `}renderClosedAsk(e){return D`
2017
2017
  <details class="ui-transcript-surface card closed-card">
2018
2018
  <summary class="ui-transcript-disclosure ui-transcript-card-header card-header"><h2>${J.t(`questions`)}</h2><span class="ui-transcript-card-status header-status">${J.t(`closed`,{total:e.questions.length})}</span></summary>
2019
- ${this.outcomes.map(e=>D`<p class="record-summary">${CP(e)}</p>`)}
2019
+ ${this.outcomes.map(e=>D`<p class="record-summary">${wP(e)}</p>`)}
2020
2020
  <div class="record-questions">
2021
2021
  ${e.questions.map((e,t)=>D`
2022
2022
  <section class="record-question" aria-labelledby=${this.recordQuestionHeadingId(t)}>
@@ -2038,7 +2038,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2038
2038
  <span class=${`ui-transcript-card-status header-status ${e.reason} ${e.reason===`submitted`?`ui-transcript-card-status--success`:e.reason===`superseded`?`ui-transcript-card-status--warning`:``}`}>${t}</span>
2039
2039
  </header>
2040
2040
  <p class="record-summary">
2041
- ${e.reason===`superseded`?J.t(`supersededSummary`):CP(e)}
2041
+ ${e.reason===`superseded`?J.t(`supersededSummary`):wP(e)}
2042
2042
  </p>
2043
2043
  <div class="record-questions">
2044
2044
  ${e.questions.map((t,n)=>this.renderQuestionRecord(e,t,n))}
@@ -2063,7 +2063,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2063
2063
  </ul>
2064
2064
  ${n.fromDraft?D`<p class="draft-note">${J.t(`draft`)}</p>`:null}
2065
2065
  `}
2066
- `}changeOption(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;if(e.multiple!==!0){r.checked&&this.setAnswer(e,{values:[t],customSelected:!1});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})}changeOther(e,t,n){let r=n.currentTarget;r instanceof HTMLInputElement&&(e.multiple===!0?this.setAnswer(e,{customSelected:r.checked}):r.checked&&this.setAnswer(e,{values:[],customSelected:!0}),r.checked&&this.focusOtherInput(t))}changeOtherText(e,t){let n=t.currentTarget;n instanceof HTMLTextAreaElement&&this.setAnswer(e,{otherText:n.value.slice(0,Ct),customSelected:!0})}async addComment(e,t){this.setAnswer(e,{commentOpen:!0}),await this.updateComplete,this.renderRoot.querySelector(`#${this.commentInputId(t)}`)?.focus()}async closeComment(e,t){this.setAnswer(e,{commentOpen:!1}),await this.updateComplete,this.renderRoot.querySelector(`#${this.questionFieldsetId(t)} .add-comment`)?.focus()}changeComment(e,t){let n=t.currentTarget;n instanceof HTMLTextAreaElement&&this.setAnswer(e,{comment:n.value.slice(0,At),commentOpen:!0})}setAnswer(e,t){let n={values:[],...this.answers[e.id],...t},r={...this.answers,[e.id]:n};this.answers=r,this.confirmingPartialSubmit=!1,this.ask!==void 0&&this.draftSessionId!==``&&qo(this.draftSessionId,this.ask.askId,r)}handleSubmit(e,t){e.preventDefault(),!this.submitting&&(Qo(t.questions,this.answers).length>0?this.showPartialSubmitConfirmation():this.submitAnswers(t))}submitAnswers(e,t=$o(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()}displayedRecordAnswer(e,t){if(t.answered)return{values:[...t.values],...t.otherText===void 0?{}:{otherText:t.otherText},...t.comment===void 0?{}:{comment:t.comment},fromDraft:!1};if(e!==void 0&&e.reason!==`superseded`)return;let n=$o([t.question],this.answers).answers[0];if(n!==void 0)return{values:[...n.values],...n.otherText===void 0?{}:{otherText:n.otherText},...n.comment===void 0?{}:{comment:n.comment},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===``?{}:Ko(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)}`}commentInputId(e){return`ask-user-comment-${String(e)}`}recordQuestionHeadingId(e){return`ask-user-record-question-${String(e)}`}static{this.styles=[e,Qe,Gd,bP,T`
2066
+ `}changeOption(e,t,n){let r=n.currentTarget;if(!(r instanceof HTMLInputElement))return;if(e.multiple!==!0){r.checked&&this.setAnswer(e,{values:[t],customSelected:!1});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})}changeOther(e,t,n){let r=n.currentTarget;r instanceof HTMLInputElement&&(e.multiple===!0?this.setAnswer(e,{customSelected:r.checked}):r.checked&&this.setAnswer(e,{values:[],customSelected:!0}),r.checked&&this.focusOtherInput(t))}changeOtherText(e,t){let n=t.currentTarget;n instanceof HTMLTextAreaElement&&this.setAnswer(e,{otherText:n.value.slice(0,Ct),customSelected:!0})}async addComment(e,t){this.setAnswer(e,{commentOpen:!0}),await this.updateComplete,this.renderRoot.querySelector(`#${this.commentInputId(t)}`)?.focus()}async closeComment(e,t){this.setAnswer(e,{commentOpen:!1}),await this.updateComplete,this.renderRoot.querySelector(`#${this.questionFieldsetId(t)} .add-comment`)?.focus()}changeComment(e,t){let n=t.currentTarget;n instanceof HTMLTextAreaElement&&this.setAnswer(e,{comment:n.value.slice(0,At),commentOpen:!0})}setAnswer(e,t){let n={values:[],...this.answers[e.id],...t},r={...this.answers,[e.id]:n};this.answers=r,this.confirmingPartialSubmit=!1,this.ask!==void 0&&this.draftSessionId!==``&&qo(this.draftSessionId,this.ask.askId,r)}handleSubmit(e,t){e.preventDefault(),!this.submitting&&(Qo(t.questions,this.answers).length>0?this.showPartialSubmitConfirmation():this.submitAnswers(t))}submitAnswers(e,t=$o(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()}displayedRecordAnswer(e,t){if(t.answered)return{values:[...t.values],...t.otherText===void 0?{}:{otherText:t.otherText},...t.comment===void 0?{}:{comment:t.comment},fromDraft:!1};if(e!==void 0&&e.reason!==`superseded`)return;let n=$o([t.question],this.answers).answers[0];if(n!==void 0)return{values:[...n.values],...n.otherText===void 0?{}:{otherText:n.otherText},...n.comment===void 0?{}:{comment:n.comment},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===``?{}:Ko(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)}`}commentInputId(e){return`ask-user-comment-${String(e)}`}recordQuestionHeadingId(e){return`ask-user-record-question-${String(e)}`}static{this.styles=[e,Qe,Gd,xP,T`
2067
2067
  :host {
2068
2068
  display: block;
2069
2069
  box-sizing: border-box;
@@ -2198,7 +2198,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2198
2198
  .partial-confirmation { align-items: stretch; flex-direction: column; }
2199
2199
  .confirmation-actions { justify-content: flex-end; }
2200
2200
  }
2201
- `]}};g([y({attribute:!1})],wP.prototype,`ask`,void 0),g([y({type:Boolean})],wP.prototype,`open`,void 0),g([y({attribute:!1})],wP.prototype,`outcomes`,void 0),g([y({attribute:!1})],wP.prototype,`outcome`,void 0),g([y({type:Boolean})],wP.prototype,`compact`,void 0),g([y({attribute:!1})],wP.prototype,`draftSessionId`,void 0),g([y({attribute:!1})],wP.prototype,`onSubmit`,void 0),g([v()],wP.prototype,`answers`,void 0),g([v()],wP.prototype,`confirmingPartialSubmit`,void 0),g([v()],wP.prototype,`submitting`,void 0),wP=g([_(`ask-user-card`)],wP);var TP={cancel:x(`Cancel`,`Close an extension dialog without answering`),yes:x(`Yes`,`Affirmative answer to an extension confirmation`),no:x(`No`,`Negative answer to an extension confirmation`),choices:x(`Choices`,`Accessible name of extension-provided answer choices`),yourAnswer:x(`Your answer`,`Accessible name of extension dialog free-text answer`),send:x(`Send`,`Submit an extension dialog answer, including an empty answer`),sending:x(`Sending…`,`Extension dialog answer submission in progress`),dismiss:x(`Dismiss`,`Remove a settled extension dialog outcome from the transcript`),seeAnswer:x(`See answer`,`Accessible label and tooltip of the eye icon that reveals an input answer`),hideAnswer:x(`Hide answer`,`Accessible label and tooltip of the crossed-out eye icon that hides an input answer`),hiddenAnswer:x(`Answer hidden.`,`Settled input-dialog summary before the user chooses to reveal the answer`),answered:x(`Answered`,`Header status of an answered extension dialog`),cancelled:x(`Cancelled`,`Header status of a cancelled extension dialog`),timeout:x(`Timed out`,`Header status of an expired extension dialog`),aborted:x(`Aborted`,`Header status of an extension dialog aborted with its run`),"session-ended":x(`Session ended`,`Header status of an extension dialog closed with its session`),missingAnswer:x(`Closed without an answer.`,`Fallback when an answered outcome contains no answer value`),booleanAnswer:x(`{answer, select, yes {Answered: Yes} other {Answered: No}}`,`Settled confirmation outcome; answer is yes or no`),textAnswer:x(`Answered: {answer}`,`Settled text or choice answer; preserve the extension/user-provided answer verbatim`),emptyAnswer:x(`Answered with an empty response.`,`Settled outcome for a deliberately empty text answer`),cancelledSummary:x(`Dismissed without an answer.`,`Settled cancelled-dialog outcome`),timeoutSummary:x(`No answer was given before the dialog timed out.`,`Settled auto-cancelled-dialog outcome`),abortedSummary:x(`The run ended before this dialog was answered.`,`Settled run-aborted-dialog outcome`),sessionEndedSummary:x(`The session ended before this dialog was answered.`,`Settled session-ended-dialog outcome`),imminent:x(`Auto-cancel imminent`,`Display-only countdown after deadline; server owns cancellation`),hours:x(`Auto-cancels in {hours, number}h {minutes, number}m`,`Display-only countdown, whole hours and remaining whole minutes; h and m are localized unit abbreviations`),minutes:x(`Auto-cancels in {minutes, number}m {seconds, number}s`,`Display-only countdown, whole minutes and remaining seconds; m and s are localized unit abbreviations`),seconds:x(`Auto-cancels in {seconds, number}s`,`Display-only countdown in seconds; s is a localized unit abbreviation`)},EP=w.registerMessages(`core.extensionDialogs`,TP),DP=1e3;function OP(e){return EP.t(e)}function kP(e,t=!1){switch(e.reason){case`answered`:{let n=e.answer;return n===void 0?EP.t(`missingAnswer`):e.dialog.kind===`input`&&!t?EP.t(`hiddenAnswer`):typeof n==`boolean`?EP.t(`booleanAnswer`,{answer:n?`yes`:`no`}):n===``?EP.t(`emptyAnswer`):EP.t(`textAnswer`,{answer:n})}case`cancelled`:return EP.t(`cancelledSummary`);case`timeout`:return EP.t(`timeoutSummary`);case`aborted`:return EP.t(`abortedSummary`);case`session-ended`:return EP.t(`sessionEndedSummary`)}}function AP(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 EP.t(`imminent`);let i=Math.ceil(r/1e3);if(i>=3600){let e=Math.floor(i/3600),t=Math.floor(i%3600/60);return EP.t(`hours`,{hours:e,minutes:t})}if(i>=60){let e=Math.floor(i/60);return EP.t(`minutes`,{minutes:e,seconds:i%60})}return EP.t(`seconds`,{seconds:i})}var jP=class extends O{constructor(){super(),this.inputValue=``,this.closing=!1,this.answerVisible=!1,this.countdownNow=0,o.createController(this),new S(this)}connectedCallback(){super.connectedCallback(),this.syncCountdownTimer()}disconnectedCallback(){this.answerVisible=!1,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.answerVisible=!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=AP(e.timeoutAt,this.countdownNow===0?Date.now():this.countdownNow);return D`
2201
+ `]}};g([y({attribute:!1})],TP.prototype,`ask`,void 0),g([y({type:Boolean})],TP.prototype,`open`,void 0),g([y({attribute:!1})],TP.prototype,`outcomes`,void 0),g([y({attribute:!1})],TP.prototype,`outcome`,void 0),g([y({type:Boolean})],TP.prototype,`compact`,void 0),g([y({attribute:!1})],TP.prototype,`draftSessionId`,void 0),g([y({attribute:!1})],TP.prototype,`onSubmit`,void 0),g([v()],TP.prototype,`answers`,void 0),g([v()],TP.prototype,`confirmingPartialSubmit`,void 0),g([v()],TP.prototype,`submitting`,void 0),TP=g([_(`ask-user-card`)],TP);var EP={cancel:x(`Cancel`,`Close an extension dialog without answering`),yes:x(`Yes`,`Affirmative answer to an extension confirmation`),no:x(`No`,`Negative answer to an extension confirmation`),choices:x(`Choices`,`Accessible name of extension-provided answer choices`),yourAnswer:x(`Your answer`,`Accessible name of extension dialog free-text answer`),send:x(`Send`,`Submit an extension dialog answer, including an empty answer`),sending:x(`Sending…`,`Extension dialog answer submission in progress`),dismiss:x(`Dismiss`,`Remove a settled extension dialog outcome from the transcript`),seeAnswer:x(`See answer`,`Accessible label and tooltip of the eye icon that reveals an input answer`),hideAnswer:x(`Hide answer`,`Accessible label and tooltip of the crossed-out eye icon that hides an input answer`),hiddenAnswer:x(`Answer hidden.`,`Settled input-dialog summary before the user chooses to reveal the answer`),answered:x(`Answered`,`Header status of an answered extension dialog`),cancelled:x(`Cancelled`,`Header status of a cancelled extension dialog`),timeout:x(`Timed out`,`Header status of an expired extension dialog`),aborted:x(`Aborted`,`Header status of an extension dialog aborted with its run`),"session-ended":x(`Session ended`,`Header status of an extension dialog closed with its session`),missingAnswer:x(`Closed without an answer.`,`Fallback when an answered outcome contains no answer value`),booleanAnswer:x(`{answer, select, yes {Answered: Yes} other {Answered: No}}`,`Settled confirmation outcome; answer is yes or no`),textAnswer:x(`Answered: {answer}`,`Settled text or choice answer; preserve the extension/user-provided answer verbatim`),emptyAnswer:x(`Answered with an empty response.`,`Settled outcome for a deliberately empty text answer`),cancelledSummary:x(`Dismissed without an answer.`,`Settled cancelled-dialog outcome`),timeoutSummary:x(`No answer was given before the dialog timed out.`,`Settled auto-cancelled-dialog outcome`),abortedSummary:x(`The run ended before this dialog was answered.`,`Settled run-aborted-dialog outcome`),sessionEndedSummary:x(`The session ended before this dialog was answered.`,`Settled session-ended-dialog outcome`),imminent:x(`Auto-cancel imminent`,`Display-only countdown after deadline; server owns cancellation`),hours:x(`Auto-cancels in {hours, number}h {minutes, number}m`,`Display-only countdown, whole hours and remaining whole minutes; h and m are localized unit abbreviations`),minutes:x(`Auto-cancels in {minutes, number}m {seconds, number}s`,`Display-only countdown, whole minutes and remaining seconds; m and s are localized unit abbreviations`),seconds:x(`Auto-cancels in {seconds, number}s`,`Display-only countdown in seconds; s is a localized unit abbreviation`)},DP=w.registerMessages(`core.extensionDialogs`,EP),OP=1e3;function kP(e){return DP.t(e)}function AP(e,t=!1){switch(e.reason){case`answered`:{let n=e.answer;return n===void 0?DP.t(`missingAnswer`):e.dialog.kind===`input`&&!t?DP.t(`hiddenAnswer`):typeof n==`boolean`?DP.t(`booleanAnswer`,{answer:n?`yes`:`no`}):n===``?DP.t(`emptyAnswer`):DP.t(`textAnswer`,{answer:n})}case`cancelled`:return DP.t(`cancelledSummary`);case`timeout`:return DP.t(`timeoutSummary`);case`aborted`:return DP.t(`abortedSummary`);case`session-ended`:return DP.t(`sessionEndedSummary`)}}function jP(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 DP.t(`imminent`);let i=Math.ceil(r/1e3);if(i>=3600){let e=Math.floor(i/3600),t=Math.floor(i%3600/60);return DP.t(`hours`,{hours:e,minutes:t})}if(i>=60){let e=Math.floor(i/60);return DP.t(`minutes`,{minutes:e,seconds:i%60})}return DP.t(`seconds`,{seconds:i})}var MP=class extends O{constructor(){super(),this.inputValue=``,this.closing=!1,this.answerVisible=!1,this.countdownNow=0,o.createController(this),new S(this)}connectedCallback(){super.connectedCallback(),this.syncCountdownTimer()}disconnectedCallback(){this.answerVisible=!1,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.answerVisible=!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=jP(e.timeoutAt,this.countdownNow===0?Date.now():this.countdownNow);return D`
2202
2202
  <article class="ui-transcript-surface card open-card" aria-labelledby="extension-dialog-heading">
2203
2203
  <header class="ui-transcript-card-header card-header">
2204
2204
  <h2 id="extension-dialog-heading" dir="auto">${e.title}</h2>
@@ -2209,18 +2209,18 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2209
2209
  `}renderOpenBody(e){return e.kind===`select`?this.renderSelectBody(e):e.kind===`input`?this.renderInputBody(e):this.renderConfirmBody(e)}renderConfirmBody(e){return D`
2210
2210
  ${e.message===void 0?null:D`<p class="dialog-message" dir="auto">${e.message}</p>`}
2211
2211
  <footer class="dialog-footer">
2212
- <button class="ui-button ui-button--compact secondary-action" type="button" ?disabled=${this.closing} @click=${()=>{this.cancelDialog(e)}}>${EP.t(`cancel`)}</button>
2213
- <button class="ui-button ui-button--compact secondary-action" type="button" ?disabled=${this.closing} @click=${()=>{this.answerDialog(e,!1)}}>${EP.t(`no`)}</button>
2214
- <button class="ui-button ui-button--primary primary-action" type="button" ?disabled=${this.closing} @click=${()=>{this.answerDialog(e,!0)}}>${EP.t(`yes`)}</button>
2212
+ <button class="ui-button ui-button--compact secondary-action" type="button" ?disabled=${this.closing} @click=${()=>{this.cancelDialog(e)}}>${DP.t(`cancel`)}</button>
2213
+ <button class="ui-button ui-button--compact secondary-action" type="button" ?disabled=${this.closing} @click=${()=>{this.answerDialog(e,!1)}}>${DP.t(`no`)}</button>
2214
+ <button class="ui-button ui-button--primary primary-action" type="button" ?disabled=${this.closing} @click=${()=>{this.answerDialog(e,!0)}}>${DP.t(`yes`)}</button>
2215
2215
  </footer>
2216
2216
  `}renderSelectBody(e){return D`
2217
- <div class="dialog-options" role="group" aria-label=${EP.t(`choices`)}>
2217
+ <div class="dialog-options" role="group" aria-label=${DP.t(`choices`)}>
2218
2218
  ${(e.options??[]).map(t=>D`
2219
2219
  <button class="ui-button ui-transcript-option-row option-button" dir="auto" type="button" ?disabled=${this.closing} @click=${()=>{this.answerDialog(e,t)}}>${t}</button>
2220
2220
  `)}
2221
2221
  </div>
2222
2222
  <footer class="dialog-footer">
2223
- <button class="ui-button ui-button--compact secondary-action" type="button" ?disabled=${this.closing} @click=${()=>{this.cancelDialog(e)}}>${EP.t(`cancel`)}</button>
2223
+ <button class="ui-button ui-button--compact secondary-action" type="button" ?disabled=${this.closing} @click=${()=>{this.cancelDialog(e)}}>${DP.t(`cancel`)}</button>
2224
2224
  </footer>
2225
2225
  `}renderInputBody(e){return D`
2226
2226
  <form class="dialog-input-form" @submit=${t=>{this.submitInput(t,e)}}>
@@ -2229,23 +2229,23 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2229
2229
  type="text"
2230
2230
  name="dialog-answer"
2231
2231
  dir="auto"
2232
- aria-label=${EP.t(`yourAnswer`)}
2233
- placeholder=${SP(e.placeholder)}
2232
+ aria-label=${DP.t(`yourAnswer`)}
2233
+ placeholder=${CP(e.placeholder)}
2234
2234
  maxlength=${String(st)}
2235
2235
  .value=${this.inputValue}
2236
2236
  ?disabled=${this.closing}
2237
2237
  @input=${e=>{this.changeInput(e)}}
2238
2238
  />
2239
2239
  <footer class="dialog-footer">
2240
- <button class="ui-button ui-button--compact secondary-action" type="button" ?disabled=${this.closing} @click=${()=>{this.cancelDialog(e)}}>${EP.t(`cancel`)}</button>
2241
- <button class="ui-button ui-button--primary primary-action" type="submit" ?disabled=${this.closing}>${EP.t(this.closing?`sending`:`send`)}</button>
2240
+ <button class="ui-button ui-button--compact secondary-action" type="button" ?disabled=${this.closing} @click=${()=>{this.cancelDialog(e)}}>${DP.t(`cancel`)}</button>
2241
+ <button class="ui-button ui-button--primary primary-action" type="submit" ?disabled=${this.closing}>${DP.t(this.closing?`sending`:`send`)}</button>
2242
2242
  </footer>
2243
2243
  </form>
2244
- `}renderClosed(e){let t=e.reason===`answered`&&e.dialog.kind===`input`&&e.answer!==void 0,n=EP.t(this.answerVisible?`hideAnswer`:`seeAnswer`);return D`
2244
+ `}renderClosed(e){let t=e.reason===`answered`&&e.dialog.kind===`input`&&e.answer!==void 0,n=DP.t(this.answerVisible?`hideAnswer`:`seeAnswer`);return D`
2245
2245
  <article class="ui-transcript-surface card closed-card" aria-labelledby="extension-dialog-closed-heading">
2246
2246
  <header class="ui-transcript-card-header card-header">
2247
2247
  <h2 id="extension-dialog-closed-heading" dir="auto">${e.dialog.title}</h2>
2248
- <span class=${`ui-transcript-card-status header-status ${e.reason} ${e.reason===`answered`?`ui-transcript-card-status--success`:e.reason===`cancelled`?``:`ui-transcript-card-status--warning`}`}>${OP(e.reason)}</span>
2248
+ <span class=${`ui-transcript-card-status header-status ${e.reason} ${e.reason===`answered`?`ui-transcript-card-status--success`:e.reason===`cancelled`?``:`ui-transcript-card-status--warning`}`}>${kP(e.reason)}</span>
2249
2249
  <div class="closed-actions">
2250
2250
  ${t?D`
2251
2251
  <button
@@ -2262,12 +2262,12 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2262
2262
  </svg>
2263
2263
  </button>
2264
2264
  `:null}
2265
- <button class="ui-button ui-button--compact secondary-action" type="button" @click=${()=>{this.dismissClosed(e)}}>${EP.t(`dismiss`)}</button>
2265
+ <button class="ui-button ui-button--compact secondary-action" type="button" @click=${()=>{this.dismissClosed(e)}}>${DP.t(`dismiss`)}</button>
2266
2266
  </div>
2267
2267
  </header>
2268
- <p id="extension-dialog-answer" class="closed-summary" dir="auto">${kP(e,this.answerVisible)}</p>
2268
+ <p id="extension-dialog-answer" class="closed-summary" dir="auto">${AP(e,this.answerVisible)}</p>
2269
2269
  </article>
2270
- `}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()},DP)):e||this.stopCountdownTimer()}stopCountdownTimer(){this.countdownTimer!==void 0&&(window.clearInterval(this.countdownTimer),this.countdownTimer=void 0)}static{this.styles=[e,Qe,Gd,bP,T`
2270
+ `}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()},OP)):e||this.stopCountdownTimer()}stopCountdownTimer(){this.countdownTimer!==void 0&&(window.clearInterval(this.countdownTimer),this.countdownTimer=void 0)}static{this.styles=[e,Qe,Gd,xP,T`
2271
2271
  :host {
2272
2272
  display: block;
2273
2273
  box-sizing: border-box;
@@ -2331,21 +2331,21 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2331
2331
  white-space: pre-wrap;
2332
2332
  overflow-wrap: anywhere;
2333
2333
  }
2334
- `]}};g([y({attribute:!1})],jP.prototype,`dialog`,void 0),g([y({attribute:!1})],jP.prototype,`outcome`,void 0),g([y({attribute:!1})],jP.prototype,`onAnswer`,void 0),g([y({attribute:!1})],jP.prototype,`onCancel`,void 0),g([y({attribute:!1})],jP.prototype,`onDismiss`,void 0),g([v()],jP.prototype,`inputValue`,void 0),g([v()],jP.prototype,`closing`,void 0),g([v()],jP.prototype,`answerVisible`,void 0),g([v()],jP.prototype,`countdownNow`,void 0),jP=g([_(`extension-dialog-card`)],jP);var MP={show:x(`Show image`,`Load an outside-workspace image after explicit user approval`),loadingDisabled:x(`Image loading disabled`,`Image placeholder when image loading is disabled in chat preferences`),attachedImage:x(`attached image`,`Default alternative text for a transcript attachment with no caller-provided description`),unavailable:x(`Image unavailable`,`Attached image placeholder when no authorized source is available`),enlarge:x(`Enlarge {description}`,`Accessible name for enlarging an image; description is unchanged caller-supplied alt text`),enlargeImage:x(`Enlarge image`,`Accessible name for enlarging an image without a description`),enlargeHint:x(`Click to enlarge`,`Tooltip on an image enlargement button`),preview:x(`Image preview`,`Accessible name of the image gallery dialog`),position:x(`Image {index, number} of {count, number}`,`Live gallery position, with one-based index and total image count`),close:x(`Close image`,`Close the image gallery`),previous:x(`Previous`,`Gallery button to show the previous image`),previousImage:x(`Previous image`,`Accessible name for the previous-image gallery button`),next:x(`Next`,`Gallery button to show the next image`),nextImage:x(`Next image`,`Accessible name for the next-image gallery button`)},NP=w.registerMessages(`core.images`,MP),PP=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===ze(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`==(w.direction===`rtl`)?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==(w.direction===`rtl`)?1:-1)},this.onDialogClick=e=>{e.target===this.dialog&&this.close()},o.createController(this),new S(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=Ne({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-navigation="${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=ze(this.ownerDocument);n===0&&r===this.dialog?.querySelector(`[data-navigation="previous"]`)?this.navigationFocus=`next`:n===t.images.length-1&&r===this.dialog?.querySelector(`[data-navigation="next"]`)&&(this.navigationFocus=`previous`),this.gallery={...t,index:n}}render(){let e=this.gallery,t=e?.images[e.index];return D`
2335
- <dialog class="image-zoom" aria-label=${NP.t(`preview`)} aria-describedby="image-gallery-position"
2334
+ `]}};g([y({attribute:!1})],MP.prototype,`dialog`,void 0),g([y({attribute:!1})],MP.prototype,`outcome`,void 0),g([y({attribute:!1})],MP.prototype,`onAnswer`,void 0),g([y({attribute:!1})],MP.prototype,`onCancel`,void 0),g([y({attribute:!1})],MP.prototype,`onDismiss`,void 0),g([v()],MP.prototype,`inputValue`,void 0),g([v()],MP.prototype,`closing`,void 0),g([v()],MP.prototype,`answerVisible`,void 0),g([v()],MP.prototype,`countdownNow`,void 0),MP=g([_(`extension-dialog-card`)],MP);var NP={show:x(`Show image`,`Load an outside-workspace image after explicit user approval`),loadingDisabled:x(`Image loading disabled`,`Image placeholder when image loading is disabled in chat preferences`),attachedImage:x(`attached image`,`Default alternative text for a transcript attachment with no caller-provided description`),unavailable:x(`Image unavailable`,`Attached image placeholder when no authorized source is available`),enlarge:x(`Enlarge {description}`,`Accessible name for enlarging an image; description is unchanged caller-supplied alt text`),enlargeImage:x(`Enlarge image`,`Accessible name for enlarging an image without a description`),enlargeHint:x(`Click to enlarge`,`Tooltip on an image enlargement button`),preview:x(`Image preview`,`Accessible name of the image gallery dialog`),position:x(`Image {index, number} of {count, number}`,`Live gallery position, with one-based index and total image count`),close:x(`Close image`,`Close the image gallery`),previous:x(`Previous`,`Gallery button to show the previous image`),previousImage:x(`Previous image`,`Accessible name for the previous-image gallery button`),next:x(`Next`,`Gallery button to show the next image`),nextImage:x(`Next image`,`Accessible name for the next-image gallery button`)},PP=w.registerMessages(`core.images`,NP),FP=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===ze(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`==(w.direction===`rtl`)?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==(w.direction===`rtl`)?1:-1)},this.onDialogClick=e=>{e.target===this.dialog&&this.close()},o.createController(this),new S(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=Ne({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-navigation="${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=ze(this.ownerDocument);n===0&&r===this.dialog?.querySelector(`[data-navigation="previous"]`)?this.navigationFocus=`next`:n===t.images.length-1&&r===this.dialog?.querySelector(`[data-navigation="next"]`)&&(this.navigationFocus=`previous`),this.gallery={...t,index:n}}render(){let e=this.gallery,t=e?.images[e.index];return D`
2335
+ <dialog class="image-zoom" aria-label=${PP.t(`preview`)} aria-describedby="image-gallery-position"
2336
2336
  @keydown=${this.onKeyDown} @click=${this.onDialogClick} @close=${this.close} @cancel=${this.close}>
2337
2337
  ${e===void 0||t===void 0?null:D`
2338
2338
  <div class="image-gallery-header ui-toolbar ui-toolbar--primary">
2339
- <span id="image-gallery-position" class="image-gallery-position ui-toolbar-title" role="status" aria-live="polite" aria-atomic="true">${NP.t(`position`,{index:e.index+1,count:e.images.length})}</span>
2340
- <div class="ui-toolbar-group"><button type="button" class="image-zoom-close ui-button ui-button--icon" aria-label=${NP.t(`close`)} title=${NP.t(`close`)} @click=${this.close}>×</button></div>
2339
+ <span id="image-gallery-position" class="image-gallery-position ui-toolbar-title" role="status" aria-live="polite" aria-atomic="true">${PP.t(`position`,{index:e.index+1,count:e.images.length})}</span>
2340
+ <div class="ui-toolbar-group"><button type="button" class="image-zoom-close ui-button ui-button--icon" aria-label=${PP.t(`close`)} title=${PP.t(`close`)} @click=${this.close}>×</button></div>
2341
2341
  </div>
2342
2342
  <div class="image-gallery-stage" @pointerdown=${this.onPointerDown} @pointerup=${this.onPointerUp} @pointercancel=${()=>{this.swipe=void 0}}>
2343
2343
  <img class="image-zoom-full" src=${t.src} alt=${t.alt} decoding="async" draggable="false" />
2344
2344
  </div>
2345
2345
  ${e.images.length<2?null:D`
2346
2346
  <div class="image-gallery-navigation ui-toolbar ui-toolbar--primary ui-toolbar--borderless">
2347
- <button type="button" class="ui-button" data-navigation="previous" aria-label=${NP.t(`previousImage`)} ?disabled=${e.index===0} @click=${()=>{this.move(-1)}}>${NP.t(`previous`)}</button>
2348
- <button type="button" class="ui-button" data-navigation="next" aria-label=${NP.t(`nextImage`)} ?disabled=${e.index===e.images.length-1} @click=${()=>{this.move(1)}}>${NP.t(`next`)}</button>
2347
+ <button type="button" class="ui-button" data-navigation="previous" aria-label=${PP.t(`previousImage`)} ?disabled=${e.index===0} @click=${()=>{this.move(-1)}}>${PP.t(`previous`)}</button>
2348
+ <button type="button" class="ui-button" data-navigation="next" aria-label=${PP.t(`nextImage`)} ?disabled=${e.index===e.images.length-1} @click=${()=>{this.move(1)}}>${PP.t(`next`)}</button>
2349
2349
  </div>
2350
2350
  `}
2351
2351
  `}
@@ -2360,20 +2360,20 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2360
2360
  .image-zoom-full { display: block; width: 100%; height: 100%; min-width: 0; min-height: 0; object-fit: contain; }
2361
2361
  .image-gallery-navigation { border-top: 1px solid var(--pi-border); }
2362
2362
  .image-gallery-navigation .ui-button { flex: 1 1 0; min-width: 0; white-space: normal; overflow-wrap: anywhere; }
2363
- `]}};g([Te(`dialog`)],PP.prototype,`dialog`,void 0),g([v()],PP.prototype,`gallery`,void 0),PP=g([_(`pi-web-image-gallery-dialog`)],PP);var FP={copy:x(`Copy code block`,`Accessible name and tooltip of a Markdown code block copy button`),copied:x(`Copied code block`,`Accessible confirmation after copying a Markdown code block`),failed:x(`Failed to copy code block`,`Accessible feedback when copying a Markdown code block fails`),controls:x(`Code block controls`,`Accessible name of the Markdown code block toolbar`),table:x(`Table`,`Accessible name of a keyboard-scrollable Markdown table region`)},IP=w.registerMessages(`core.formattedText`,FP),LP=`pi-web:markdown-image-dimensions:v1`;function RP(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function zP(e,t=RP()){if(HP(e))return;let n=VP(t).find(t=>t.source===e);return n===void 0?void 0:{width:n.width,height:n.height}}function BP(e,t,n=RP()){if(HP(e))return;let r=ct(t.width,t.height);if(e===``||r===void 0)return;let i=VP(n).filter(t=>t.source!==e);i.push({source:e,...r});try{n?.setItem(LP,JSON.stringify(i.slice(-128)))}catch{}}function VP(e){try{let t=e?.getItem(LP);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=UP(e);t===void 0||HP(t.source)||(r.delete(t.source),r.set(t.source,t))}return[...r.values()].slice(-128)}catch{return[]}}function HP(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 UP(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=ct(e.width,e.height);return t===void 0?void 0:{source:e.source,...t}}var WP=`important`,GP=` !`+WP,KP=ot(class extends Ce{constructor(e){if(super(e),e.type!==Le.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(GP);e.includes(`-`)||t?n.setProperty(e,t?r.slice(0,-11):r,t?WP:``):n[e]=r}}return fn}}),qP=class extends O{constructor(){super(),this.thumbnail=!1,this.description=``,this.label=``,this.requestDisabled=!1,o.createController(this),new S(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=ct(t.naturalWidth,t.naturalHeight);r!==void 0&&this.onIntrinsicDimensions(n,r)}open(e){if(e.preventDefault(),e.stopPropagation(),this.source===void 0||this.source===``)return;let t=this.description;this.dispatchEvent(new CustomEvent(`image-open`,{detail:{src:this.source,get alt(){return typeof t==`function`?t():t}},bubbles:!0,composed:!0}))}render(){let e=this.source===void 0||this.source===``,t=this.dimensions,n=typeof this.description==`function`?this.description():this.description;return D`
2363
+ `]}};g([Te(`dialog`)],FP.prototype,`dialog`,void 0),g([v()],FP.prototype,`gallery`,void 0),FP=g([_(`pi-web-image-gallery-dialog`)],FP);var IP={copy:x(`Copy code block`,`Accessible name and tooltip of a Markdown code block copy button`),copied:x(`Copied code block`,`Accessible confirmation after copying a Markdown code block`),failed:x(`Failed to copy code block`,`Accessible feedback when copying a Markdown code block fails`),controls:x(`Code block controls`,`Accessible name of the Markdown code block toolbar`),table:x(`Table`,`Accessible name of a keyboard-scrollable Markdown table region`)},LP=w.registerMessages(`core.formattedText`,IP),RP=`pi-web:markdown-image-dimensions:v1`;function zP(){try{return typeof localStorage>`u`?void 0:localStorage}catch{return}}function BP(e,t=zP()){if(UP(e))return;let n=HP(t).find(t=>t.source===e);return n===void 0?void 0:{width:n.width,height:n.height}}function VP(e,t,n=zP()){if(UP(e))return;let r=ct(t.width,t.height);if(e===``||r===void 0)return;let i=HP(n).filter(t=>t.source!==e);i.push({source:e,...r});try{n?.setItem(RP,JSON.stringify(i.slice(-128)))}catch{}}function HP(e){try{let t=e?.getItem(RP);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=WP(e);t===void 0||UP(t.source)||(r.delete(t.source),r.set(t.source,t))}return[...r.values()].slice(-128)}catch{return[]}}function UP(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 WP(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=ct(e.width,e.height);return t===void 0?void 0:{source:e.source,...t}}var GP=`important`,KP=` !`+GP,qP=ot(class extends Ce{constructor(e){if(super(e),e.type!==Le.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(KP);e.includes(`-`)||t?n.setProperty(e,t?r.slice(0,-11):r,t?GP:``):n[e]=r}}return fn}}),JP=class extends O{constructor(){super(),this.thumbnail=!1,this.description=``,this.label=``,this.requestDisabled=!1,o.createController(this),new S(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=ct(t.naturalWidth,t.naturalHeight);r!==void 0&&this.onIntrinsicDimensions(n,r)}open(e){if(e.preventDefault(),e.stopPropagation(),this.source===void 0||this.source===``)return;let t=this.description;this.dispatchEvent(new CustomEvent(`image-open`,{detail:{src:this.source,get alt(){return typeof t==`function`?t():t}},bubbles:!0,composed:!0}))}render(){let e=this.source===void 0||this.source===``,t=this.dimensions,n=typeof this.description==`function`?this.description():this.description;return D`
2364
2364
  <div class="frame">
2365
2365
  <button class="placeholder ui-button" type="button" ?hidden=${!e} ?disabled=${this.requestDisabled}
2366
2366
  @click=${e=>{this.requestImage(e)}}>
2367
- <span>${this.pendingLabel??NP.t(`show`)}</span>${this.label===``?null:D`<code dir="auto">${this.label}</code>`}
2367
+ <span>${this.pendingLabel??PP.t(`show`)}</span>${this.label===``?null:D`<code dir="auto">${this.label}</code>`}
2368
2368
  </button>
2369
2369
  <button class="image-button ui-button" type="button" ?hidden=${e} ?disabled=${e}
2370
- aria-label=${n===``?NP.t(`enlargeImage`):NP.t(`enlarge`,{description:n})} title=${NP.t(`enlargeHint`)}
2370
+ aria-label=${n===``?PP.t(`enlargeImage`):PP.t(`enlarge`,{description:n})} title=${PP.t(`enlargeHint`)}
2371
2371
  @click=${e=>{this.open(e)}}
2372
2372
  @keydown=${e=>{(e.key===`Enter`||e.key===` `)&&this.open(e)}}>
2373
2373
  <img loading="lazy" decoding="async" src=${e?E:this.source} alt=${n}
2374
2374
  @load=${e=>{this.reportIntrinsicDimensions(e)}}
2375
2375
  width=${t?.width??E} height=${t?.height??E}
2376
- style=${KP(t===void 0?{}:{"--image-width":`${String(t.width)}px`,"--image-height":`${String(t.height)}px`,"--image-ratio":String(t.width/t.height)})} />
2376
+ style=${qP(t===void 0?{}:{"--image-width":`${String(t.width)}px`,"--image-height":`${String(t.height)}px`,"--image-ratio":String(t.width/t.height)})} />
2377
2377
  </button>
2378
2378
  </div>
2379
2379
  `}static{this.styles=[e,T`
@@ -2396,51 +2396,51 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2396
2396
  :host([thumbnail]) .placeholder code { display: none; }
2397
2397
  :host([thumbnail]) img { width: 100%; height: 100%; max-height: none; border-radius: 0; }
2398
2398
  }
2399
- `]}};g([y({attribute:!1})],qP.prototype,`source`,void 0),g([y({type:Boolean,reflect:!0})],qP.prototype,`thumbnail`,void 0),g([y({attribute:!1})],qP.prototype,`dimensions`,void 0),g([y({attribute:!1})],qP.prototype,`onIntrinsicDimensions`,void 0),g([y()],qP.prototype,`description`,void 0),g([y()],qP.prototype,`label`,void 0),g([y({type:Boolean})],qP.prototype,`requestDisabled`,void 0),g([y()],qP.prototype,`pendingLabel`,void 0),qP=g([_(`pi-web-image-presentation`)],qP);var JP=new gD,YP=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||(BP(e,t),(this.dimensions?.width!==t.width||this.dimensions.height!==t.height)&&(this.dimensions=t))},o.createController(this),new S(this)}willUpdate(e){e.has(`previewUrl`)&&(this.dimensions=zP(this.previewUrl)),(e.has(`previewUrl`)||e.has(`intentKey`)||e.has(`outside`))&&(this.approved=this.outside&&this.intentKey!==void 0&&JP.read(this.intentKey,this.previewUrl)===!0)}showImage(){!this.loadingDisabled&&this.outside&&this.previewUrl!==``&&(this.approved=!0,this.intentKey!==void 0&&JP.choose(this.intentKey,this.previewUrl,!0))}render(){return D`<pi-web-image-presentation
2399
+ `]}};g([y({attribute:!1})],JP.prototype,`source`,void 0),g([y({type:Boolean,reflect:!0})],JP.prototype,`thumbnail`,void 0),g([y({attribute:!1})],JP.prototype,`dimensions`,void 0),g([y({attribute:!1})],JP.prototype,`onIntrinsicDimensions`,void 0),g([y()],JP.prototype,`description`,void 0),g([y()],JP.prototype,`label`,void 0),g([y({type:Boolean})],JP.prototype,`requestDisabled`,void 0),g([y()],JP.prototype,`pendingLabel`,void 0),JP=g([_(`pi-web-image-presentation`)],JP);var YP=new gD,XP=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||(VP(e,t),(this.dimensions?.width!==t.width||this.dimensions.height!==t.height)&&(this.dimensions=t))},o.createController(this),new S(this)}willUpdate(e){e.has(`previewUrl`)&&(this.dimensions=BP(this.previewUrl)),(e.has(`previewUrl`)||e.has(`intentKey`)||e.has(`outside`))&&(this.approved=this.outside&&this.intentKey!==void 0&&YP.read(this.intentKey,this.previewUrl)===!0)}showImage(){!this.loadingDisabled&&this.outside&&this.previewUrl!==``&&(this.approved=!0,this.intentKey!==void 0&&YP.choose(this.intentKey,this.previewUrl,!0))}render(){return D`<pi-web-image-presentation
2400
2400
  .source=${!this.loadingDisabled&&this.previewUrl!==``&&(!this.outside||this.approved)?this.previewUrl:void 0}
2401
2401
  .dimensions=${this.dimensions} .onIntrinsicDimensions=${this.rememberDimensions}
2402
2402
  .requestDisabled=${this.loadingDisabled||!this.outside||this.previewUrl===``}
2403
- .pendingLabel=${this.loadingDisabled?NP.t(`loadingDisabled`):NP.t(`show`)}
2403
+ .pendingLabel=${this.loadingDisabled?PP.t(`loadingDisabled`):PP.t(`show`)}
2404
2404
  .description=${this.description} .label=${this.path}
2405
2405
  @image-request=${()=>{this.showImage()}}
2406
2406
  ></pi-web-image-presentation>`}static{this.styles=T`
2407
2407
  :host { display: inline-block; max-width: 100%; vertical-align: middle; }
2408
- `}};g([y({attribute:`preview-url`})],YP.prototype,`previewUrl`,void 0),g([y()],YP.prototype,`path`,void 0),g([y()],YP.prototype,`description`,void 0),g([y({attribute:`intent-key`})],YP.prototype,`intentKey`,void 0),g([y({type:Boolean})],YP.prototype,`outside`,void 0),g([y({type:Boolean,attribute:`loading-disabled`})],YP.prototype,`loadingDisabled`,void 0),g([v()],YP.prototype,`approved`,void 0),g([v()],YP.prototype,`dimensions`,void 0),YP=g([_(`pi-web-markdown-image`)],YP);function XP(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 ZP(e,t,n){e.querySelectorAll(`img[src]`).forEach((e,r)=>{let i=XP(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`,xt(t.projectId,t.workspaceId,i.path,{machineId:t.machineId})),i.outside&&a.setAttribute(`outside`,``),e.replaceWith(a)})}var QP=new V.Renderer;function $P(e){let t=new V.Renderer;return t.html=({text:e})=>rF(e),t.code=t=>{let n=e.presentation===`code`?QP.code(t):`<div class="plain-code-block">${rF(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">${rF(r)}</span>`,a=e.copy?`<button type="button" class="code-copy-button code-block-copy ui-button ui-button--icon ui-button--compact" title="${FP.copy.message}" aria-label="${FP.copy.message}"><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="${FP.controls.message}">${i}${a}</div>`}${n}</div>\n`},t}var eF=300,tF=new Map;function nF(e,t,n,r=!0,i=er){let a=JSON.stringify([e,r,i.presentation,i.copy,t===void 0?null:[t.machineId,t.projectId,t.workspaceId,t.root,u(te(``)),n]]),o=tF.get(a);if(o!==void 0)return o;let s=aF(V.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:$P(i)}),t,n,r);if(tF.set(a,s),tF.size>eF){let e=tF.keys().next().value;e!==void 0&&tF.delete(e)}return s}function rF(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`)}var iF=`table-scroll`;function aF(e,t,n,r){let i=document.createElement(`template`);return i.innerHTML=e,t!==void 0&&ZP(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=Ju(n,t);r!==void 0&&(e.setAttribute(`href`,xt(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`||sF(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`,``)}),oF(i.content),i.innerHTML}function oF(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(iF)===!0)return;let t=document.createElement(`div`);t.className=iF,t.setAttribute(`role`,`region`),t.setAttribute(`aria-label`,FP.table.message),t.setAttribute(`tabindex`,`0`),e.before(t),t.append(e)})}function sF(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}function cF(e){if((e.getAttribute(`src`)??``).trim()===``)return;let t=e.src;return/^https?:\/\//u.test(t)?t:void 0}function lF(e,t){return e.complete&&e.currentSrc===t?ct(e.naturalWidth,e.naturalHeight):void 0}function uF(e,t){e.setAttribute(`width`,String(t.width)),e.setAttribute(`height`,String(t.height))}function dF(e){e.querySelectorAll(`img[src]`).forEach(e=>{if(!(e instanceof HTMLImageElement))return;let t=cF(e);if(t===void 0)return;let n=lF(e,t)??zP(t);n!==void 0&&uF(e,n)})}function fF(e){let t=cF(e);if(t===void 0)return;let n=lF(e,t);n!==void 0&&(BP(t,n),uF(e,n))}var pF=r(`: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))}`),mF=class extends O{constructor(){super(),this.text=``,this.highlight=``,this.imagesEnabled=!0,this.codeBlocks=er,this.contentRendererVersion=0,this.machineId=`local`,this.enhancement=new wD(this),this.phase=`markdown`,this.scheduled=!1,this.displayedText=``,this.replacing=!1,this.layoutChanged=!1,this.labelsDirty=!0,this.copyStates=new WeakMap,this.onImageLoad={capture:!0,handleEvent:e=>{e.target instanceof HTMLImageElement&&fF(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)},o.createController(this),new S(this,void 0,()=>{this.labelsDirty=!0})}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 D`<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()})),dF(this.renderRoot),this.applyHighlight(),this.labelsDirty&&(this.labelsDirty=!1,this.renderRoot.querySelectorAll(`.code-copy-button`).forEach(e=>{this.setCopyButtonState(e,this.copyStates.get(e)??`idle`)}),this.renderRoot.querySelectorAll(`.code-block-header`).forEach(e=>{e.setAttribute(`aria-label`,IP.t(`controls`))}),this.renderRoot.querySelectorAll(`.table-scroll`).forEach(e=>{e.setAttribute(`aria-label`,IP.t(`table`))})),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)hF(e,t)}formatMarkdown(){try{this.markup=nF(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.labelsDirty=!0,this.layoutChanged=!0,this.content=D`${ST(this.markup)}`,this.displayedText=this.text,this.replacing=!1}enhanceMarkdown(){this.labelsDirty=!0;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:nF(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 Hf(e);this.setCopyButtonState(t,n?`copied`:`failed`),window.setTimeout(()=>{this.setCopyButtonState(t,`idle`)},1200)}setCopyButtonState(e,t){this.copyStates.set(e,t);let n=e.querySelector(`span`);n!==null&&(n.textContent=t===`copied`?`✓`:`⧉`);let r=IP.t(t===`idle`?`copy`:t);e.title=r,e.setAttribute(`aria-label`,r)}static{this.styles=[pF,vD,T`
2408
+ `}};g([y({attribute:`preview-url`})],XP.prototype,`previewUrl`,void 0),g([y()],XP.prototype,`path`,void 0),g([y()],XP.prototype,`description`,void 0),g([y({attribute:`intent-key`})],XP.prototype,`intentKey`,void 0),g([y({type:Boolean})],XP.prototype,`outside`,void 0),g([y({type:Boolean,attribute:`loading-disabled`})],XP.prototype,`loadingDisabled`,void 0),g([v()],XP.prototype,`approved`,void 0),g([v()],XP.prototype,`dimensions`,void 0),XP=g([_(`pi-web-markdown-image`)],XP);function ZP(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 QP(e,t,n){e.querySelectorAll(`img[src]`).forEach((e,r)=>{let i=ZP(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`,xt(t.projectId,t.workspaceId,i.path,{machineId:t.machineId})),i.outside&&a.setAttribute(`outside`,``),e.replaceWith(a)})}var $P=new V.Renderer;function eF(e){let t=new V.Renderer;return t.html=({text:e})=>iF(e),t.code=t=>{let n=e.presentation===`code`?$P.code(t):`<div class="plain-code-block">${iF(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">${iF(r)}</span>`,a=e.copy?`<button type="button" class="code-copy-button code-block-copy ui-button ui-button--icon ui-button--compact" title="${IP.copy.message}" aria-label="${IP.copy.message}"><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="${IP.controls.message}">${i}${a}</div>`}${n}</div>\n`},t}var tF=300,nF=new Map;function rF(e,t,n,r=!0,i=er){let a=JSON.stringify([e,r,i.presentation,i.copy,t===void 0?null:[t.machineId,t.projectId,t.workspaceId,t.root,u(te(``)),n]]),o=nF.get(a);if(o!==void 0)return o;let s=oF(V.parse(e,{async:!1,breaks:!0,gfm:!0,renderer:eF(i)}),t,n,r);if(nF.set(a,s),nF.size>tF){let e=nF.keys().next().value;e!==void 0&&nF.delete(e)}return s}function iF(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`).replaceAll(`"`,`&quot;`)}var aF=`table-scroll`;function oF(e,t,n,r){let i=document.createElement(`template`);return i.innerHTML=e,t!==void 0&&QP(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=Ju(n,t);r!==void 0&&(e.setAttribute(`href`,xt(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`||cF(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`,``)}),sF(i.content),i.innerHTML}function sF(e){e.querySelectorAll(`table`).forEach(e=>{if(e.parentElement?.classList.contains(aF)===!0)return;let t=document.createElement(`div`);t.className=aF,t.setAttribute(`role`,`region`),t.setAttribute(`aria-label`,IP.table.message),t.setAttribute(`tabindex`,`0`),e.before(t),t.append(e)})}function cF(e){if(e.startsWith(`#`)||e.startsWith(`/`))return!0;try{return[`http:`,`https:`,`mailto:`].includes(new URL(e).protocol)}catch{return!1}}function lF(e){if((e.getAttribute(`src`)??``).trim()===``)return;let t=e.src;return/^https?:\/\//u.test(t)?t:void 0}function uF(e,t){return e.complete&&e.currentSrc===t?ct(e.naturalWidth,e.naturalHeight):void 0}function dF(e,t){e.setAttribute(`width`,String(t.width)),e.setAttribute(`height`,String(t.height))}function fF(e){e.querySelectorAll(`img[src]`).forEach(e=>{if(!(e instanceof HTMLImageElement))return;let t=lF(e);if(t===void 0)return;let n=uF(e,t)??BP(t);n!==void 0&&dF(e,n)})}function pF(e){let t=lF(e);if(t===void 0)return;let n=uF(e,t);n!==void 0&&(VP(t,n),dF(e,n))}var mF=r(`: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))}`),hF=class extends O{constructor(){super(),this.text=``,this.highlight=``,this.imagesEnabled=!0,this.codeBlocks=er,this.contentRendererVersion=0,this.machineId=`local`,this.enhancement=new wD(this),this.phase=`markdown`,this.scheduled=!1,this.displayedText=``,this.replacing=!1,this.layoutChanged=!1,this.labelsDirty=!0,this.copyStates=new WeakMap,this.onImageLoad={capture:!0,handleEvent:e=>{e.target instanceof HTMLImageElement&&pF(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)},o.createController(this),new S(this,void 0,()=>{this.labelsDirty=!0})}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 D`<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()})),fF(this.renderRoot),this.applyHighlight(),this.labelsDirty&&(this.labelsDirty=!1,this.renderRoot.querySelectorAll(`.code-copy-button`).forEach(e=>{this.setCopyButtonState(e,this.copyStates.get(e)??`idle`)}),this.renderRoot.querySelectorAll(`.code-block-header`).forEach(e=>{e.setAttribute(`aria-label`,LP.t(`controls`))}),this.renderRoot.querySelectorAll(`.table-scroll`).forEach(e=>{e.setAttribute(`aria-label`,LP.t(`table`))})),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)gF(e,t)}formatMarkdown(){try{this.markup=rF(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.labelsDirty=!0,this.layoutChanged=!0,this.content=D`${ST(this.markup)}`,this.displayedText=this.text,this.replacing=!1}enhanceMarkdown(){this.labelsDirty=!0;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:rF(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 Hf(e);this.setCopyButtonState(t,n?`copied`:`failed`),window.setTimeout(()=>{this.setCopyButtonState(t,`idle`)},1200)}setCopyButtonState(e,t){this.copyStates.set(e,t);let n=e.querySelector(`span`);n!==null&&(n.textContent=t===`copied`?`✓`:`⧉`);let r=LP.t(t===`idle`?`copy`:t);e.title=r,e.setAttribute(`aria-label`,r)}static{this.styles=[mF,vD,T`
2409
2409
  .pending-source { white-space: pre-wrap; overflow-wrap: anywhere; }
2410
2410
  .enhanced-content { display: contents; }
2411
2411
  .enhanced-content[hidden] { display: none; }
2412
2412
  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); }
2413
- `]}};g([y()],mF.prototype,`text`,void 0),g([y()],mF.prototype,`highlight`,void 0),g([y()],mF.prototype,`intentKey`,void 0),g([y({type:Boolean})],mF.prototype,`imagesEnabled`,void 0),g([y({attribute:!1})],mF.prototype,`codeBlocks`,void 0),g([y({attribute:!1})],mF.prototype,`contentRendering`,void 0),g([y({type:Number})],mF.prototype,`contentRendererVersion`,void 0),g([y()],mF.prototype,`machineId`,void 0),g([y({attribute:!1})],mF.prototype,`workspaceContext`,void 0),mF=g([_(`formatted-text`)],mF);function hF(e,t){let n=e.data,r=[...n.matchAll(new RegExp(gF(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 gF(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}var _F={status:x(`{status, select, success {done} error {failed} running {running} other {pending}}`,`Tool execution status; status is success, error, running or pending`),targetLabel:x(`{kind, select, file {File} command {Command} other {Input}}`,`Expanded tool target field label; kind is file, command or input`),targetDescription:x(`{kind, select, file {File: {text}} command {Command: {text}} other {Input: {text}}}`,`Accessible tool target description; preserve raw path, command or input text`),edits:x(`{count, plural, one {# edit} other {# edits}}`,`Number of edit operations in a tool call`),mismatch:x(`Applied diff differs from the preview.`,`Notice when the applied tool diff differs from its proposed preview`),details:x(`Details`,`Expand tool command/input and result text`),result:x(`Result`,`Label of raw tool result text`),previewComputed:x(`Edit preview computed.`,`Transient PI WEB edit-tool progress notice when no diff preview is available; raw tool diagnostics are separate`),previewDiff:x(`Preview diff`,`Proposed diff disclosure and accessible name`),appliedDiff:x(`Applied diff`,`Applied diff disclosure and accessible name`),lines:x(`{count, plural, one {# line} other {# lines}}`,`Total number of lines in a tool diff`),showing:x(`Showing {visible, number} of {total, number} lines`,`Truncated tool diff preview line count`),fullDiff:x(`Full diff`,`Diff toolbar status when every line is shown`),copied:x(`Copied`,`Confirmation that the full raw tool diff was copied`),copyDiff:x(`Copy diff`,`Copy the full raw tool diff including collapsed lines`),showAll:x(`Show all {count, number} diff lines`,`Expand the truncated tool diff`)},vF=w.registerMessages(`core.toolExecution`,_F),yF=180,bF=class extends O{constructor(){super(),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0,o.createController(this),new S(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=CF(e.args),n=TF(e.details),r=e.preview,i=n??r?.diff;i!==this.countedDiff&&(this.countedDiff=i,this.diffStats=i===void 0?void 0:EF(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?xF(e):void 0,l=SF(e,t),u=wF(e);return D`
2413
+ `]}};g([y()],hF.prototype,`text`,void 0),g([y()],hF.prototype,`highlight`,void 0),g([y()],hF.prototype,`intentKey`,void 0),g([y({type:Boolean})],hF.prototype,`imagesEnabled`,void 0),g([y({attribute:!1})],hF.prototype,`codeBlocks`,void 0),g([y({attribute:!1})],hF.prototype,`contentRendering`,void 0),g([y({type:Number})],hF.prototype,`contentRendererVersion`,void 0),g([y()],hF.prototype,`machineId`,void 0),g([y({attribute:!1})],hF.prototype,`workspaceContext`,void 0),hF=g([_(`formatted-text`)],hF);function gF(e,t){let n=e.data,r=[...n.matchAll(new RegExp(_F(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 _F(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}var vF={status:x(`{status, select, success {done} error {failed} running {running} other {pending}}`,`Tool execution status; status is success, error, running or pending`),targetLabel:x(`{kind, select, file {File} command {Command} other {Input}}`,`Expanded tool target field label; kind is file, command or input`),targetDescription:x(`{kind, select, file {File: {text}} command {Command: {text}} other {Input: {text}}}`,`Accessible tool target description; preserve raw path, command or input text`),edits:x(`{count, plural, one {# edit} other {# edits}}`,`Number of edit operations in a tool call`),mismatch:x(`Applied diff differs from the preview.`,`Notice when the applied tool diff differs from its proposed preview`),details:x(`Details`,`Expand tool command/input and result text`),result:x(`Result`,`Label of raw tool result text`),previewComputed:x(`Edit preview computed.`,`Transient PI WEB edit-tool progress notice when no diff preview is available; raw tool diagnostics are separate`),previewDiff:x(`Preview diff`,`Proposed diff disclosure and accessible name`),appliedDiff:x(`Applied diff`,`Applied diff disclosure and accessible name`),lines:x(`{count, plural, one {# line} other {# lines}}`,`Total number of lines in a tool diff`),showing:x(`Showing {visible, number} of {total, number} lines`,`Truncated tool diff preview line count`),fullDiff:x(`Full diff`,`Diff toolbar status when every line is shown`),copied:x(`Copied`,`Confirmation that the full raw tool diff was copied`),copyDiff:x(`Copy diff`,`Copy the full raw tool diff including collapsed lines`),showAll:x(`Show all {count, number} diff lines`,`Expand the truncated tool diff`)},yF=w.registerMessages(`core.toolExecution`,vF),bF=180,xF=class extends O{constructor(){super(),this.showFullDiff=!1,this.copied=!1,this.diffOpen=!0,o.createController(this),new S(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=wF(e.args),n=EF(e.details),r=e.preview,i=n??r?.diff;i!==this.countedDiff&&(this.countedDiff=i,this.diffStats=i===void 0?void 0:DF(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?SF(e):void 0,l=CF(e,t),u=TF(e);return D`
2414
2414
  <section class=${`tool-card ui-transcript-surface ui-transcript-activity ui-transcript-tool ${e.status}`}>
2415
2415
  <div class="tool-header ui-transcript-heading">
2416
2416
  <div class="tool-title">
2417
- <span class="status-icon" aria-hidden="true">${AF(e.status)}</span>
2417
+ <span class="status-icon" aria-hidden="true">${jF(e.status)}</span>
2418
2418
  <strong>${e.toolName}</strong>
2419
2419
  ${this.renderHeaderTarget(l)}
2420
2420
  </div>
2421
2421
  <div class="tool-meta">
2422
- ${u===void 0?null:D`<span>${vF.t(`edits`,{count:u})}</span>`}
2422
+ ${u===void 0?null:D`<span>${yF.t(`edits`,{count:u})}</span>`}
2423
2423
  ${a===void 0?null:D`<span class="diff-stats"><b class="added">${w.number(a.added,{signDisplay:`always`})}</b><span>/</span><b class="removed">${w.number(-a.removed,{signDisplay:`always`})}</b></span>`}
2424
- <span class="status-label">${vF.t(`status`,{status:e.status})}</span>
2424
+ <span class="status-label">${yF.t(`status`,{status:e.status})}</span>
2425
2425
  </div>
2426
2426
  </div>
2427
2427
 
2428
- ${o?D`<p class="notice">${vF.t(`mismatch`)}</p>`:null}
2428
+ ${o?D`<p class="notice">${yF.t(`mismatch`)}</p>`:null}
2429
2429
  ${s===void 0||s===``?null:D`<pre class="error-text">${s}</pre>`}
2430
- ${i===void 0?this.renderTextBody(c,e.status===`error`,l):this.renderDiffBody(i,vF.t(n===void 0?`previewDiff`:`appliedDiff`),l)}
2430
+ ${i===void 0?this.renderTextBody(c,e.status===`error`,l):this.renderDiffBody(i,yF.t(n===void 0?`previewDiff`:`appliedDiff`),l)}
2431
2431
  </section>
2432
- `}renderHeaderTarget(e){if(e===void 0)return null;let t=e.kind===`file`?`path`:e.generated===!0?`summary generated-summary`:`summary`;return D`<span class=${t} title=${e.text} aria-label=${vF.t(`targetDescription`,{kind:e.kind,text:e.text})}>${e.text}</span>`}renderExpandedTarget(e){return e===void 0?null:D`
2432
+ `}renderHeaderTarget(e){if(e===void 0)return null;let t=e.kind===`file`?`path`:e.generated===!0?`summary generated-summary`:`summary`;return D`<span class=${t} title=${e.text} aria-label=${yF.t(`targetDescription`,{kind:e.kind,text:e.text})}>${e.text}</span>`}renderExpandedTarget(e){return e===void 0?null:D`
2433
2433
  <div class="detail-target">
2434
- <span class="detail-label">${vF.t(`targetLabel`,{kind:e.kind})}</span>
2434
+ <span class="detail-label">${yF.t(`targetLabel`,{kind:e.kind})}</span>
2435
2435
  <pre class=${e.generated===!0?`detail-target-value generated-summary`:`detail-target-value`}>${e.text}</pre>
2436
2436
  </div>
2437
2437
  `}renderTextBody(e,t,n){if((e===void 0||e===``)&&n===void 0)return null;let r=this.textOpen??t;return D`
2438
2438
  <details class="text-body" ?open=${r} @toggle=${e=>{e.currentTarget instanceof HTMLDetailsElement&&(this.textOpen=e.currentTarget.open)}}>
2439
- <summary class="ui-transcript-disclosure">${vF.t(`details`)}</summary>
2439
+ <summary class="ui-transcript-disclosure">${yF.t(`details`)}</summary>
2440
2440
  ${r?D`${this.renderExpandedTarget(n)}
2441
2441
  ${e===void 0||e===``?null:D`
2442
2442
  <div class="detail-result">
2443
- <span class="detail-label">${vF.t(`result`)}</span>
2443
+ <span class="detail-label">${yF.t(`result`)}</span>
2444
2444
  <pre>${e}</pre>
2445
2445
  </div>
2446
2446
  `}`:null}
@@ -2449,21 +2449,21 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2449
2449
  <details class="diff-details" ?open=${this.diffOpen} @toggle=${e=>{this.onDiffToggle(e)}}>
2450
2450
  <summary class="ui-transcript-disclosure">
2451
2451
  <span>${t}</span>
2452
- <small>${vF.t(`lines`,{count:r})}</small>
2452
+ <small>${yF.t(`lines`,{count:r})}</small>
2453
2453
  </summary>
2454
2454
  ${this.diffOpen?this.renderDiffContent(e,t,n):null}
2455
2455
  </details>
2456
2456
  `}renderDiffContent(e,t,n){let r=e.split(`
2457
- `),i=!this.showFullDiff&&r.length>yF,a=i?r.slice(0,yF):r;return D`
2457
+ `),i=!this.showFullDiff&&r.length>bF,a=i?r.slice(0,bF):r;return D`
2458
2458
  ${this.renderExpandedTarget(n)}
2459
2459
  <div class="diff-toolbar">
2460
- <span>${i?vF.t(`showing`,{visible:a.length,total:r.length}):vF.t(`fullDiff`)}</span>
2461
- <button class="ui-button ui-button--compact" type="button" @click=${()=>{this.copyDiff(e)}}>${vF.t(this.copied?`copied`:`copyDiff`)}</button>
2460
+ <span>${i?yF.t(`showing`,{visible:a.length,total:r.length}):yF.t(`fullDiff`)}</span>
2461
+ <button class="ui-button ui-button--compact" type="button" @click=${()=>{this.copyDiff(e)}}>${yF.t(this.copied?`copied`:`copyDiff`)}</button>
2462
2462
  </div>
2463
- <pre class="diff" dir="ltr" aria-label=${t}><code class="diff-content">${a.map(e=>D`<span class=${DF(e)}>${e}</span>`)}</code></pre>
2463
+ <pre class="diff" dir="ltr" aria-label=${t}><code class="diff-content">${a.map(e=>D`<span class=${OF(e)}>${e}</span>`)}</code></pre>
2464
2464
  ${i?D`
2465
2465
  <button class="show-more ui-button ui-button--compact" type="button" @click=${()=>{this.showFullDiff=!0}}>
2466
- ${vF.t(`showAll`,{count:r.length})}
2466
+ ${yF.t(`showAll`,{count:r.length})}
2467
2467
  </button>
2468
2468
  `:null}
2469
2469
  `}onDiffToggle(e){let t=e.currentTarget;t instanceof HTMLDetailsElement&&(this.diffOpen=t.open)}async copyDiff(e){await Hf(e)?(this.copied=!0,window.setTimeout(()=>{this.copied=!1},1200)):this.copied=!1}static{this.styles=[e,Gd,T`
@@ -2513,21 +2513,21 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2513
2513
  .diff .added { background: color-mix(in srgb, var(--pi-success) 12%, transparent); }
2514
2514
  .diff .removed { background: color-mix(in srgb, var(--pi-danger) 12%, transparent); }
2515
2515
  .show-more { justify-self: start; margin-inline: 12px; }
2516
- `]}};g([y({attribute:!1})],bF.prototype,`execution`,void 0),g([v()],bF.prototype,`showFullDiff`,void 0),g([v()],bF.prototype,`copied`,void 0),g([v()],bF.prototype,`diffOpen`,void 0),g([v()],bF.prototype,`textOpen`,void 0),bF=g([_(`tool-execution-view`)],bF);function xF(e){let t=MF(e.details,`presentation`);return e.toolName===`edit`&&e.status===`running`&&NF(t,`kind`)===`editPreviewComputed`?vF.t(`previewComputed`):e.resultText}function SF(e,t){if(t!==void 0&&t!==``)return{kind:`file`,text:t};let n=NF(e.args,`command`);if(n!==void 0&&n!==``)return{kind:`command`,text:n};let r=e.summaryPresentation===void 0?e.summary:dN(e.summaryPresentation);if(r!==``)return{kind:`input`,text:r,...e.summaryPresentation===void 0?{}:{generated:!0}}}function CF(e){return NF(e,`path`)??NF(e,`file_path`)}function wF(e){if(e.toolName!==`edit`)return;let t=MF(e.args,`edits`);if(Array.isArray(t))return t.length;if(typeof MF(e.args,`oldText`)==`string`&&typeof MF(e.args,`newText`)==`string`)return 1}function TF(e){return NF(e,`diff`)}function EF(e){let t=0,n=0,r=e.split(`
2517
- `);for(let e of r)OF(e)?t++:kF(e)&&n++;return{added:t,removed:n,lines:r.length}}function DF(e){return OF(e)?`added`:kF(e)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`+++`)||e.startsWith(`---`)?`file`:e.startsWith(`diff `)||e.startsWith(`index `)?`meta`:`context`}function OF(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)}function kF(e){return e.startsWith(`-`)&&!e.startsWith(`---`)}function AF(e){return e===`success`?`✓`:e===`error`?`✖`:e===`running`?`●`:`○`}function jF(e){return typeof e==`object`&&!!e}function MF(e,t){return jF(e)?e[t]:void 0}function NF(e,t){let n=MF(e,t);return typeof n==`string`?n:void 0}var PF={defaultView:x(`Default view`,`Show the host's original transcript presentation instead of the plugin's custom view`),customView:x(`Custom view`,`Restore the plugin's custom transcript presentation`)},FF=w.registerMessages(`core.transcript-renderer`,PF),IF=class extends O{constructor(){super(),this.itemKey=``,this.defaultView=!1,this.attempted=!1,this.hasCustomView=!1,new S(this),o.createController(this,{sharedUi:!0})}connectedCallback(){super.connectedCallback(),this.requestUpdate()}disconnectedCallback(){this.cancel(),super.disconnectedCallback()}willUpdate(e){e.has(`itemKey`)&&(this.defaultView=!1);let t=e.get(`request`),n=LF(t)!==LF(this.request);(e.has(`request`)&&(n||t?.entry!==this.request?.entry||t?.kind!==this.request?.kind)||e.has(`scope`)||e.has(`itemKey`)||e.has(`entryId`))&&(this.cancel(),(n||e.has(`itemKey`))&&(this.defaultView=!1),this.defaultView||(this.hasCustomView=!1))}cancel(){this.controller?.abort(),this.controller=void 0,this.preview=void 0,this.attempted=!1}renderPreview(){let e=this.request;if(!this.isConnected||this.defaultView||this.attempted||e===void 0||this.scope===void 0)return;this.attempted=!0;let t=new AbortController;this.controller=t;let n=n=>{t.signal.aborted||this.controller!==t||(console.warn(`Transcript renderer for ${e.kind===`tool`?e.entry.toolName:e.entry.customType} failed`,n),t.abort(),this.preview=void 0,this.hasCustomView=!1,this.requestUpdate())};try{let r={scope:Object.freeze({...this.scope}),signal:t.signal,fail:n},i;if(e.kind===`tool`){let{toolCallId:t,toolName:n,args:a,status:o,content:s,details:c,resultText:l}=e.entry,u=Object.freeze({render:()=>D`<slot></slot>`}),d=Jw(n,e.renderers,()=>u);i=d===u?void 0:d?.render({...r,entry:Object.freeze({toolName:n,args:a,status:o,content:s,details:c,...t===void 0?{}:{toolCallId:t},...l===void 0?{}:{resultText:l}})})}else{let{customType:t,content:n,details:a}=e.entry;i=e.renderer.render({...r,entry:Object.freeze({customType:t,content:n,details:a,...this.entryId===void 0?{}:{entryId:this.entryId}})})}if(zF(i)&&Promise.resolve(i).catch(n),i!==void 0&&!RF(i))throw Error(`Transcript renderer must return a Lit template or undefined synchronously`);t.signal.aborted||(this.preview=i,this.hasCustomView=i!==void 0,i===void 0&&t.abort())}catch(e){n(e)}}toggleView(){this.defaultView=!this.defaultView,this.cancel()}render(){return this.renderPreview(),D`
2518
- ${this.hasCustomView?D`<div class="controls"><button type="button" class="ui-button ui-button--compact" @click=${()=>{this.toggleView()}}>${FF.t(this.defaultView?`customView`:`defaultView`)}</button></div>`:null}
2516
+ `]}};g([y({attribute:!1})],xF.prototype,`execution`,void 0),g([v()],xF.prototype,`showFullDiff`,void 0),g([v()],xF.prototype,`copied`,void 0),g([v()],xF.prototype,`diffOpen`,void 0),g([v()],xF.prototype,`textOpen`,void 0),xF=g([_(`tool-execution-view`)],xF);function SF(e){let t=NF(e.details,`presentation`);return e.toolName===`edit`&&e.status===`running`&&PF(t,`kind`)===`editPreviewComputed`?yF.t(`previewComputed`):e.resultText}function CF(e,t){if(t!==void 0&&t!==``)return{kind:`file`,text:t};let n=PF(e.args,`command`);if(n!==void 0&&n!==``)return{kind:`command`,text:n};let r=e.summaryPresentation===void 0?e.summary:fN(e.summaryPresentation);if(r!==``)return{kind:`input`,text:r,...e.summaryPresentation===void 0?{}:{generated:!0}}}function wF(e){return PF(e,`path`)??PF(e,`file_path`)}function TF(e){if(e.toolName!==`edit`)return;let t=NF(e.args,`edits`);if(Array.isArray(t))return t.length;if(typeof NF(e.args,`oldText`)==`string`&&typeof NF(e.args,`newText`)==`string`)return 1}function EF(e){return PF(e,`diff`)}function DF(e){let t=0,n=0,r=e.split(`
2517
+ `);for(let e of r)kF(e)?t++:AF(e)&&n++;return{added:t,removed:n,lines:r.length}}function OF(e){return kF(e)?`added`:AF(e)?`removed`:e.startsWith(`@@`)?`hunk`:e.startsWith(`+++`)||e.startsWith(`---`)?`file`:e.startsWith(`diff `)||e.startsWith(`index `)?`meta`:`context`}function kF(e){return e.startsWith(`+`)&&!e.startsWith(`+++`)}function AF(e){return e.startsWith(`-`)&&!e.startsWith(`---`)}function jF(e){return e===`success`?`✓`:e===`error`?`✖`:e===`running`?`●`:`○`}function MF(e){return typeof e==`object`&&!!e}function NF(e,t){return MF(e)?e[t]:void 0}function PF(e,t){let n=NF(e,t);return typeof n==`string`?n:void 0}var FF={defaultView:x(`Default view`,`Show the host's original transcript presentation instead of the plugin's custom view`),customView:x(`Custom view`,`Restore the plugin's custom transcript presentation`)},IF=w.registerMessages(`core.transcript-renderer`,FF),LF=class extends O{constructor(){super(),this.itemKey=``,this.defaultView=!1,this.attempted=!1,this.hasCustomView=!1,new S(this),o.createController(this,{sharedUi:!0})}connectedCallback(){super.connectedCallback(),this.requestUpdate()}disconnectedCallback(){this.cancel(),super.disconnectedCallback()}willUpdate(e){e.has(`itemKey`)&&(this.defaultView=!1);let t=e.get(`request`),n=RF(t)!==RF(this.request);(e.has(`request`)&&(n||t?.entry!==this.request?.entry||t?.kind!==this.request?.kind)||e.has(`scope`)||e.has(`itemKey`)||e.has(`entryId`))&&(this.cancel(),(n||e.has(`itemKey`))&&(this.defaultView=!1),this.defaultView||(this.hasCustomView=!1))}cancel(){this.controller?.abort(),this.controller=void 0,this.preview=void 0,this.attempted=!1}renderPreview(){let e=this.request;if(!this.isConnected||this.defaultView||this.attempted||e===void 0||this.scope===void 0)return;this.attempted=!0;let t=new AbortController;this.controller=t;let n=n=>{t.signal.aborted||this.controller!==t||(console.warn(`Transcript renderer for ${e.kind===`tool`?e.entry.toolName:e.entry.customType} failed`,n),t.abort(),this.preview=void 0,this.hasCustomView=!1,this.requestUpdate())};try{let r={scope:Object.freeze({...this.scope}),signal:t.signal,fail:n},i;if(e.kind===`tool`){let{toolCallId:t,toolName:n,args:a,status:o,content:s,details:c,resultText:l}=e.entry,u=Object.freeze({render:()=>D`<slot></slot>`}),d=Jw(n,e.renderers,()=>u);i=d===u?void 0:d?.render({...r,entry:Object.freeze({toolName:n,args:a,status:o,content:s,details:c,...t===void 0?{}:{toolCallId:t},...l===void 0?{}:{resultText:l}})})}else{let{customType:t,content:n,details:a}=e.entry;i=e.renderer.render({...r,entry:Object.freeze({customType:t,content:n,details:a,...this.entryId===void 0?{}:{entryId:this.entryId}})})}if(BF(i)&&Promise.resolve(i).catch(n),i!==void 0&&!zF(i))throw Error(`Transcript renderer must return a Lit template or undefined synchronously`);t.signal.aborted||(this.preview=i,this.hasCustomView=i!==void 0,i===void 0&&t.abort())}catch(e){n(e)}}toggleView(){this.defaultView=!this.defaultView,this.cancel()}render(){return this.renderPreview(),D`
2518
+ ${this.hasCustomView?D`<div class="controls"><button type="button" class="ui-button ui-button--compact" @click=${()=>{this.toggleView()}}>${IF.t(this.defaultView?`customView`:`defaultView`)}</button></div>`:null}
2519
2519
  ${this.defaultView||this.preview===void 0?D`<slot></slot>`:this.preview}
2520
2520
  `}updated(){this.dispatchEvent(new CustomEvent(`content-layout-changed`,{bubbles:!0,composed:!0}))}static{this.styles=T`
2521
2521
  @layer pi-web-base {
2522
2522
  :host { display: block; min-width: 0; max-width: 100%; color: var(--pi-text); }
2523
2523
  .controls { display: flex; justify-content: flex-end; margin-block-end: 4px; }
2524
2524
  }
2525
- `}};g([y({attribute:!1})],IF.prototype,`request`,void 0),g([y({attribute:!1})],IF.prototype,`scope`,void 0),g([y()],IF.prototype,`itemKey`,void 0),g([y({attribute:!1})],IF.prototype,`entryId`,void 0),g([v()],IF.prototype,`defaultView`,void 0),IF=g([_(`pi-web-transcript-renderer`)],IF);function LF(e){return e?.kind===`tool`?e.renderers:e?.renderer}function RF(e){return typeof e==`object`&&!!e&&`_$litType$`in e}function zF(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function BF(e,t,n=`local`){return e.mediaId===void 0?{src:`data:${e.mimeType};base64,${e.data}`,get alt(){return NP.t(`attachedImage`)}}:t===void 0||!Wt(e.mediaId)?void 0:{src:dt(t,e.mediaId,n),get alt(){return NP.t(`attachedImage`)}}}var VF=class extends O{constructor(){super(),this.machineId=`local`,this.loadingDisabled=!1,this.thumbnail=!1,this.description=()=>NP.t(`attachedImage`),o.createController(this),new S(this)}render(){let e=this.loadingDisabled||this.imagePart===void 0?void 0:BF(this.imagePart,this.session,this.machineId)?.src;return D`<pi-web-image-presentation
2525
+ `}};g([y({attribute:!1})],LF.prototype,`request`,void 0),g([y({attribute:!1})],LF.prototype,`scope`,void 0),g([y()],LF.prototype,`itemKey`,void 0),g([y({attribute:!1})],LF.prototype,`entryId`,void 0),g([v()],LF.prototype,`defaultView`,void 0),LF=g([_(`pi-web-transcript-renderer`)],LF);function RF(e){return e?.kind===`tool`?e.renderers:e?.renderer}function zF(e){return typeof e==`object`&&!!e&&`_$litType$`in e}function BF(e){return typeof e==`object`&&!!e&&`then`in e&&typeof e.then==`function`}function VF(e,t,n=`local`){return e.mediaId===void 0?{src:`data:${e.mimeType};base64,${e.data}`,get alt(){return PP.t(`attachedImage`)}}:t===void 0||!Wt(e.mediaId)?void 0:{src:dt(t,e.mediaId,n),get alt(){return PP.t(`attachedImage`)}}}var HF=class extends O{constructor(){super(),this.machineId=`local`,this.loadingDisabled=!1,this.thumbnail=!1,this.description=()=>PP.t(`attachedImage`),o.createController(this),new S(this)}render(){let e=this.loadingDisabled||this.imagePart===void 0?void 0:VF(this.imagePart,this.session,this.machineId)?.src;return D`<pi-web-image-presentation
2526
2526
  .source=${e} .requestDisabled=${!0} .thumbnail=${this.thumbnail}
2527
2527
  .dimensions=${ct(this.imagePart?.width,this.imagePart?.height)}
2528
- .pendingLabel=${this.loadingDisabled?NP.t(`loadingDisabled`):NP.t(`unavailable`)}
2528
+ .pendingLabel=${this.loadingDisabled?PP.t(`loadingDisabled`):PP.t(`unavailable`)}
2529
2529
  .description=${this.description} .label=${typeof this.description==`function`?this.description():this.description}
2530
- ></pi-web-image-presentation>`}static{this.styles=T`:host { display: block; max-width: 100%; min-width: 0; }`}};g([y({attribute:!1})],VF.prototype,`imagePart`,void 0),g([y({attribute:!1})],VF.prototype,`session`,void 0),g([y()],VF.prototype,`machineId`,void 0),g([y({type:Boolean})],VF.prototype,`loadingDisabled`,void 0),g([y({type:Boolean,reflect:!0})],VF.prototype,`thumbnail`,void 0),g([y()],VF.prototype,`description`,void 0),VF=g([_(`pi-web-transcript-image`)],VF);function HF(e){let t=e.meta?.timestamp,n=t===void 0?void 0:UF(t),r=WF(e),i=e.meta?.thinkingLevel,a=[n,r,i===void 0||i===``?void 0:on(i,C)].filter(e=>e!==void 0&&e!==``);return a.length===0?q.t(`noMetadata`):w.list(a)}function UF(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return w.date(t,{dateStyle:`medium`,timeStyle:`medium`})}function WF(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 GF(e,t){return KF(t)??String(e)}function KF(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 qF(e,t){let n=KF(t);return n===void 0?void 0:`m:${n}`}function JF(e,t){let n=KF(t);return n===void 0?void 0:`e:${n}`}var Y=class extends O{constructor(){super(),this.messages=[],this.sessionId=``,this.sessionCwd=``,this.machineId=`local`,this.messageActions=[],this.messageActionController=new uN(()=>({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.transcriptRenderers=[],this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.searchNavigationVersion=0,this.searchHighlightsActive=!1,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.queuedCopyFailed=!1,this.queuedCopyGeneration=0,this.behaviors=nr,this.quietMode=!1,this.followingLive=!1,this.disclosures=new BN,this.transientDisclosures=new Map,this.scrollFlows=new _P({getScroller:()=>this.chat??void 0,onFollowingChange:e=>{this.followingLive=e},getAnchors:()=>this.scrollAnchorElements(),getSessionId:()=>M(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=qN([]),this.questionIds=new Set,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageGrouper=new vN,this.messageMetaCache=new WeakMap,this.navigationLocalizationChanged=!1,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=>{this.behaviors.loadImages&&this.imageGalleryDialog?.show([e])},this.onPageHide=()=>{this.saveScrollPosition()},this.handleClearServerQueue=()=>{this.onClearServerQueue?.()},this.renderKeys=new vP,this.canClearServerQueue=!1,this.contentRendererVersion=0,o.createController(this),new S(this,w,()=>{this.messageMetaCache=new WeakMap,this.messageActionController.localizationChanged(),this.navigationLocalizationChanged=!0})}openToolImageGallery(e,t){if(!this.behaviors.loadImages)return;let n=e.flatMap((e,t)=>{let n=BF(e.part,this.transcriptSession(),this.machineId);return n===void 0?[]:[{src:n.src,get alt(){return 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.searchNavigationVersion+=1,this.scrollFlows.dispose(),this.messageActionController.reset(),this.queuedCopyGeneration+=1,this.queuedCopyFailed=!1,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(M(this.machineId,this.sessionId)),this.loadMoreRequested=!1}willUpdate(e){e.has(`searchTarget`)&&(this.searchTargetMachineId=this.machineId),e.has(`messages`)&&(this.questionOutcomes=qN(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,this.navigatedSearchTarget=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.queuedCopyFailed=!1,this.messageActionIdentity=t,this.messageActionController.reset()),(e.has(`sessionId`)||e.has(`machineId`))&&this.prepareSessionUiState(),e.has(`behaviors`)&&(this.scrollFlows.configure(),this.behaviors.rememberDisclosures&&this.disclosures.syncSession(M(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:M(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(`searchTarget`)||e.has(`messages`)||e.has(`messageStart`)||e.has(`historyReady`)||e.has(`sessionId`)||e.has(`machineId`))&&this.navigateToSearchTarget(),this.onTranscriptRendered!==void 0&&this.reportRenderedTranscript(),this.lastOpenQuestionId=t,(this.navigationLocalizationChanged||e.has(`followingLive`)||e.has(`behaviors`)||e.has(`onNavigationChange`))&&(this.navigationLocalizationChanged=!1,this.onNavigationChange?.(this.renderNavigation()))}async navigateToSearchTarget(){let e=++this.searchNavigationVersion,t=this.searchTarget;t===void 0&&(this.navigatedSearchTarget=void 0);let n=t?.sessionId===this.sessionId&&this.searchTargetMachineId===this.machineId?this.messages.findIndex((e,n)=>(e.transcriptIndex??this.messageStart+n)===t.messageIndex&&e.parts.some(e=>e.type===`text`&&(e.displayText??e.text)!==``)):-1;if(n<0&&!this.searchHighlightsActive)return;let r=n<0?null:this.renderRoot.querySelector(`article.msg[data-index="${String(this.messageStart+n)}"]`),i=Array.from(this.renderRoot.querySelectorAll(`formatted-text`));for(let e of i)e.highlight=r?.contains(e)===!0&&e.closest(`details`)===null?t?.query??``:``;this.searchHighlightsActive=r!==null&&(t?.query.trim()??``)!==``,r!==null&&t!==void 0&&this.historyReady&&this.navigatedSearchTarget!==t&&(this.scrollFlows.onUpIntent(),await Promise.all(i.filter(e=>r.contains(e)).map(e=>e.updateComplete)),this.isConnected&&e===this.searchNavigationVersion&&this.searchTarget===t&&this.chat!==void 0&&(this.chat.scrollTop+=r.getBoundingClientRect().top-this.chat.getBoundingClientRect().top,this.navigatedSearchTarget=t,this.scrollFlows.savePosition()))}render(){let e=this.groupedMessages(),t=CN(e),n=yN(e),r=this.transcriptRenderContext(),i=M(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=KF(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 D`
2530
+ ></pi-web-image-presentation>`}static{this.styles=T`:host { display: block; max-width: 100%; min-width: 0; }`}};g([y({attribute:!1})],HF.prototype,`imagePart`,void 0),g([y({attribute:!1})],HF.prototype,`session`,void 0),g([y()],HF.prototype,`machineId`,void 0),g([y({type:Boolean})],HF.prototype,`loadingDisabled`,void 0),g([y({type:Boolean,reflect:!0})],HF.prototype,`thumbnail`,void 0),g([y()],HF.prototype,`description`,void 0),HF=g([_(`pi-web-transcript-image`)],HF);function UF(e){let t=e.meta?.timestamp,n=t===void 0?void 0:WF(t),r=GF(e),i=e.meta?.thinkingLevel,a=[n,r,i===void 0||i===``?void 0:on(i,C)].filter(e=>e!==void 0&&e!==``);return a.length===0?q.t(`noMetadata`):w.list(a)}function WF(e){let t=new Date(e);if(Number.isFinite(t.getTime()))return w.date(t,{dateStyle:`medium`,timeStyle:`medium`})}function GF(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 KF(e,t){return qF(t)??String(e)}function qF(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 JF(e,t){let n=qF(t);return n===void 0?void 0:`m:${n}`}function YF(e,t){let n=qF(t);return n===void 0?void 0:`e:${n}`}var Y=class extends O{constructor(){super(),this.messages=[],this.sessionId=``,this.sessionCwd=``,this.machineId=`local`,this.messageActions=[],this.messageActionController=new dN(()=>({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.transcriptRenderers=[],this.messageStart=0,this.messageEnd=0,this.messageTotal=0,this.searchNavigationVersion=0,this.searchHighlightsActive=!1,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.queuedCopyFailed=!1,this.queuedCopyGeneration=0,this.behaviors=nr,this.quietMode=!1,this.followingLive=!1,this.disclosures=new VN,this.transientDisclosures=new Map,this.scrollFlows=new vP({getScroller:()=>this.chat??void 0,onFollowingChange:e=>{this.followingLive=e},getAnchors:()=>this.scrollAnchorElements(),getSessionId:()=>M(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=JN([]),this.questionIds=new Set,this.groupedMessagesStart=0,this.groupedMessagesCache=[],this.messageGrouper=new yN,this.messageMetaCache=new WeakMap,this.navigationLocalizationChanged=!1,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=>{this.behaviors.loadImages&&this.imageGalleryDialog?.show([e])},this.onPageHide=()=>{this.saveScrollPosition()},this.handleClearServerQueue=()=>{this.onClearServerQueue?.()},this.renderKeys=new yP,this.canClearServerQueue=!1,this.contentRendererVersion=0,o.createController(this),new S(this,w,()=>{this.messageMetaCache=new WeakMap,this.messageActionController.localizationChanged(),this.navigationLocalizationChanged=!0})}openToolImageGallery(e,t){if(!this.behaviors.loadImages)return;let n=e.flatMap((e,t)=>{let n=VF(e.part,this.transcriptSession(),this.machineId);return n===void 0?[]:[{src:n.src,get alt(){return 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.searchNavigationVersion+=1,this.scrollFlows.dispose(),this.messageActionController.reset(),this.queuedCopyGeneration+=1,this.queuedCopyFailed=!1,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(M(this.machineId,this.sessionId)),this.loadMoreRequested=!1}willUpdate(e){e.has(`searchTarget`)&&(this.searchTargetMachineId=this.machineId),e.has(`messages`)&&(this.questionOutcomes=JN(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,this.navigatedSearchTarget=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.queuedCopyFailed=!1,this.messageActionIdentity=t,this.messageActionController.reset()),(e.has(`sessionId`)||e.has(`machineId`))&&this.prepareSessionUiState(),e.has(`behaviors`)&&(this.scrollFlows.configure(),this.behaviors.rememberDisclosures&&this.disclosures.syncSession(M(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:M(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(`searchTarget`)||e.has(`messages`)||e.has(`messageStart`)||e.has(`historyReady`)||e.has(`sessionId`)||e.has(`machineId`))&&this.navigateToSearchTarget(),this.onTranscriptRendered!==void 0&&this.reportRenderedTranscript(),this.lastOpenQuestionId=t,(this.navigationLocalizationChanged||e.has(`followingLive`)||e.has(`behaviors`)||e.has(`onNavigationChange`))&&(this.navigationLocalizationChanged=!1,this.onNavigationChange?.(this.renderNavigation()))}async navigateToSearchTarget(){let e=++this.searchNavigationVersion,t=this.searchTarget;t===void 0&&(this.navigatedSearchTarget=void 0);let n=t?.sessionId===this.sessionId&&this.searchTargetMachineId===this.machineId?this.messages.findIndex((e,n)=>(e.transcriptIndex??this.messageStart+n)===t.messageIndex&&e.parts.some(e=>e.type===`text`&&(e.displayText??e.text)!==``)):-1;if(n<0&&!this.searchHighlightsActive)return;let r=n<0?null:this.renderRoot.querySelector(`article.msg[data-index="${String(this.messageStart+n)}"]`),i=Array.from(this.renderRoot.querySelectorAll(`formatted-text`));for(let e of i)e.highlight=r?.contains(e)===!0&&e.closest(`details`)===null?t?.query??``:``;this.searchHighlightsActive=r!==null&&(t?.query.trim()??``)!==``,r!==null&&t!==void 0&&this.historyReady&&this.navigatedSearchTarget!==t&&(this.scrollFlows.onUpIntent(),await Promise.all(i.filter(e=>r.contains(e)).map(e=>e.updateComplete)),this.isConnected&&e===this.searchNavigationVersion&&this.searchTarget===t&&this.chat!==void 0&&(this.chat.scrollTop+=r.getBoundingClientRect().top-this.chat.getBoundingClientRect().top,this.navigatedSearchTarget=t,this.scrollFlows.savePosition()))}render(){let e=this.groupedMessages(),t=wN(e),n=bN(e),r=this.transcriptRenderContext(),i=M(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=qF(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 D`
2531
2531
  ${this.renderTopNotices()}
2532
2532
  <div class=${this.behaviors.visualEffects?`chat-wrap`:`chat-wrap plain`}>
2533
2533
  <div class="chat" @image-open=${e=>{this.openImageZoom(e.detail)}}
@@ -2540,7 +2540,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2540
2540
  @touchend=${this.handlesScrollIntent?this.handleTouchEnd:void 0}
2541
2541
  @touchcancel=${this.handlesScrollIntent?this.handleTouchEnd:void 0}>
2542
2542
  ${this.renderHistoryBoundary()}
2543
- ${lN(i,qe(n,(e,t)=>a[t],(e,i)=>e.kind===`group`?this.renderMessageGroup(r,e,this.isLiveTailGroup(n,i),t):e.kind===`tool-images`?kN(r,e,t):ON(r,e.message,e.index,t)))}
2543
+ ${uN(i,qe(n,(e,t)=>a[t],(e,i)=>e.kind===`group`?this.renderMessageGroup(r,e,this.isLiveTailGroup(n,i),t):e.kind===`tool-images`?AN(r,e,t):kN(r,e.message,e.index,t)))}
2544
2544
  ${this.renderQueuedMessages()}
2545
2545
  ${this.renderSessionActivity()}
2546
2546
  ${this.renderSuggestedInput()}
@@ -2562,8 +2562,8 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2562
2562
  .onDismissNotification=${this.onDismissNotification}
2563
2563
  .onDismissAllNotifications=${this.onDismissAllNotifications}
2564
2564
  ></session-notification-tray>
2565
- </div>`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart&&this.groupedRenderers===this.transcriptRenderers||(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedRenderers=this.transcriptRenderers,this.groupedMessagesCache=this.messageGrouper.group(this.messages,this.messageStart,e=>this.transcriptRenderers.some(t=>t.target===`custom-message`&&t.customType===e))),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 D`${aN(this.clientQueuedMessages,e,(e,t)=>({heading:R.t(e===`client`?`clientHeading`:`serverHeading`),detail:e===`client`?R.t(`clientDetail`):R.t(`pending`,{count:t})})).map(e=>this.renderQueuedMessageList(e))}
2566
- ${this.queuedCopyFailed?D`<small role="status">${R.t(`copyFailed`)}</small>`:E}`}renderQueuedMessageList(e){let t={machineId:this.machineId,sessionId:this.sessionId,cwd:this.sessionCwd};return cN(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 Hf(e);this.isConnected&&t===this.queuedCopyGeneration&&(this.queuedCopyFailed=!n)}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 D`
2565
+ </div>`}groupedMessages(){return this.groupedMessagesInput===this.messages&&this.groupedMessagesStart===this.messageStart&&this.groupedRenderers===this.transcriptRenderers||(this.groupedMessagesInput=this.messages,this.groupedMessagesStart=this.messageStart,this.groupedRenderers=this.transcriptRenderers,this.groupedMessagesCache=this.messageGrouper.group(this.messages,this.messageStart,e=>this.transcriptRenderers.some(t=>t.target===`custom-message`&&t.customType===e))),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 D`${oN(this.clientQueuedMessages,e,(e,t)=>({heading:R.t(e===`client`?`clientHeading`:`serverHeading`),detail:e===`client`?R.t(`clientDetail`):R.t(`pending`,{count:t})})).map(e=>this.renderQueuedMessageList(e))}
2566
+ ${this.queuedCopyFailed?D`<small role="status">${R.t(`copyFailed`)}</small>`:E}`}renderQueuedMessageList(e){let t={machineId:this.machineId,sessionId:this.sessionId,cwd:this.sessionCwd};return lN(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 Hf(e);this.isConnected&&t===this.queuedCopyGeneration&&(this.queuedCopyFailed=!n)}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 D`
2567
2567
  ${qe(this.closedDialogs,e=>e.dialog.dialogId,e=>D`
2568
2568
  <extension-dialog-card
2569
2569
  class="closed-dialog-card"
@@ -2592,24 +2592,24 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2592
2592
  ${this.behaviors.automaticHistory?D`<span>${R.t(`scrollHistory`)}</span>`:null}
2593
2593
  ${e}
2594
2594
  </div>
2595
- `:this.messages.length?D`<div class="history-boundary"><span>${R.t(`beginning`)}</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 D`<small>${R.t(`range`,{from:e,to:t,total:n})}</small>`}loadedRawMessageEnd(){return Math.max(this.messageEnd,this.messageStart+this.messages.length)}transcriptRenderContext(){let e=this.workspaceContext?.machineId===this.machineId?this.workspaceContext:void 0;return(this.rendererScope?.machineId!==this.machineId||this.rendererScope.sessionId!==this.sessionId||this.rendererScope.projectId!==e?.projectId||this.rendererScope.workspaceId!==e?.workspaceId)&&(this.rendererScope=Object.freeze({machineId:this.machineId,sessionId:this.sessionId,...e===void 0?{}:{projectId:e.projectId,workspaceId:e.workspaceId}})),{machineId:this.machineId,sessionId:this.sessionId,session:this.transcriptSession(),messages:this.messages,messageStart:this.messageStart,behaviors:this.behaviors,contentRendering:this.contentRendering,contentRendererVersion:this.contentRendererVersion,transcriptRenderers:this.transcriptRenderers,rendererScope:this.rendererScope,workspaceContext:this.workspaceContext,anchors:{message:qF,event:JF},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=n&&!this.quietMode,a=this.groupDisclosureKey(t,n);return jN(e,t,n,r,{open:this.isDisclosureOpen(a,i),anchor:this.groupAnchorKey(t,n),toggle:e=>{this.onDisclosureToggle(a,e,i)}})}messageMetaLabel(e){let t=this.messageMetaCache.get(e);if(t!==void 0)return t;let n=HF(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(`transcriptRenderers`)||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 KN(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(M(this.machineId,e))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll(`[data-scroll-anchor-id]`))}groupDisclosureKey(e,t){return t?`${M(this.machineId,this.sessionId)}:live:${GF(e.startIndex,e.messages[0]?.message)}`:`${M(this.machineId,this.sessionId)}:${GF(e.endIndex,e.messages.at(-1)?.message)}`}groupAnchorKey(e,t){let n=e.messages.map(({message:e})=>KF(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=yP}renderSuggestedInput(){let e=this.status?.sessionId===this.sessionId?this.status.suggestedInput:void 0;return e===void 0||this.onUseSuggestedInput===void 0?null:D`
2595
+ `:this.messages.length?D`<div class="history-boundary"><span>${R.t(`beginning`)}</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 D`<small>${R.t(`range`,{from:e,to:t,total:n})}</small>`}loadedRawMessageEnd(){return Math.max(this.messageEnd,this.messageStart+this.messages.length)}transcriptRenderContext(){let e=this.workspaceContext?.machineId===this.machineId?this.workspaceContext:void 0;return(this.rendererScope?.machineId!==this.machineId||this.rendererScope.sessionId!==this.sessionId||this.rendererScope.projectId!==e?.projectId||this.rendererScope.workspaceId!==e?.workspaceId)&&(this.rendererScope=Object.freeze({machineId:this.machineId,sessionId:this.sessionId,...e===void 0?{}:{projectId:e.projectId,workspaceId:e.workspaceId}})),{machineId:this.machineId,sessionId:this.sessionId,session:this.transcriptSession(),messages:this.messages,messageStart:this.messageStart,behaviors:this.behaviors,contentRendering:this.contentRendering,contentRendererVersion:this.contentRendererVersion,transcriptRenderers:this.transcriptRenderers,rendererScope:this.rendererScope,workspaceContext:this.workspaceContext,anchors:{message:JF,event:YF},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=n&&!this.quietMode,a=this.groupDisclosureKey(t,n);return MN(e,t,n,r,{open:this.isDisclosureOpen(a,i),anchor:this.groupAnchorKey(t,n),toggle:e=>{this.onDisclosureToggle(a,e,i)}})}messageMetaLabel(e){let t=this.messageMetaCache.get(e);if(t!==void 0)return t;let n=UF(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(`transcriptRenderers`)||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 qN(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(M(this.machineId,e))}scrollAnchorElements(){return Array.from(this.renderRoot.querySelectorAll(`[data-scroll-anchor-id]`))}groupDisclosureKey(e,t){return t?`${M(this.machineId,this.sessionId)}:live:${KF(e.startIndex,e.messages[0]?.message)}`:`${M(this.machineId,this.sessionId)}:${KF(e.endIndex,e.messages.at(-1)?.message)}`}groupAnchorKey(e,t){let n=e.messages.map(({message:e})=>qF(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=bP}renderSuggestedInput(){let e=this.status?.sessionId===this.sessionId?this.status.suggestedInput:void 0;return e===void 0||this.onUseSuggestedInput===void 0?null:D`
2596
2596
  <aside class="suggested-input">
2597
2597
  <strong>${C(`ui.chatView.suggestedInput`,`Suggested input`)}</strong>
2598
2598
  <p class="suggested-input-text" dir="auto">${e===``?C(`ui.chatView.emptyInput`,`Empty input`):e}</p>
2599
2599
  <small>${C(`ui.chatView.suggestedInputHint`,`Replaces your current draft. Nothing is sent.`)}</small>
2600
2600
  <button type="button" class="ui-button" @click=${()=>{this.onUseSuggestedInput?.(this.machineId,this.sessionId)}}>${C(`ui.chatView.useSuggestedInput`,`Use suggested input`)}</button>
2601
2601
  </aside>
2602
- `}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)}};g([y({attribute:!1})],Y.prototype,`messages`,void 0),g([y()],Y.prototype,`sessionId`,void 0),g([y({attribute:!1})],Y.prototype,`onNavigationChange`,void 0),g([y()],Y.prototype,`sessionCwd`,void 0),g([y({attribute:!1})],Y.prototype,`workspaceContext`,void 0),g([y({attribute:!1})],Y.prototype,`contentRendering`,void 0),g([y()],Y.prototype,`machineId`,void 0),g([y({attribute:!1})],Y.prototype,`messageActions`,void 0),g([y({attribute:!1})],Y.prototype,`messageActionContext`,void 0),g([y({attribute:!1})],Y.prototype,`onMessageAction`,void 0),g([y({attribute:!1})],Y.prototype,`onDisplayedMessageAction`,void 0),g([y({attribute:!1})],Y.prototype,`transcriptRenderers`,void 0),g([y({type:Number})],Y.prototype,`messageStart`,void 0),g([y({type:Number})],Y.prototype,`messageEnd`,void 0),g([y({type:Number})],Y.prototype,`messageTotal`,void 0),g([y({attribute:!1})],Y.prototype,`searchTarget`,void 0),g([y({type:Boolean})],Y.prototype,`hasMore`,void 0),g([y({type:Boolean})],Y.prototype,`historyReady`,void 0),g([y({type:Boolean})],Y.prototype,`loadingMore`,void 0),g([y({type:Boolean})],Y.prototype,`isSendingPrompt`,void 0),g([y({type:Boolean})],Y.prototype,`isCompacting`,void 0),g([y({type:Number})],Y.prototype,`pendingMessageCount`,void 0),g([y({attribute:!1})],Y.prototype,`clientQueuedMessages`,void 0),g([y({attribute:!1})],Y.prototype,`status`,void 0),g([y({attribute:!1})],Y.prototype,`activity`,void 0),g([y({attribute:!1})],Y.prototype,`askDraftSessionId`,void 0),g([y({attribute:!1})],Y.prototype,`onSubmitAsk`,void 0),g([y({attribute:!1})],Y.prototype,`pendingDialogs`,void 0),g([y({attribute:!1})],Y.prototype,`closedDialogs`,void 0),g([y({attribute:!1})],Y.prototype,`onAnswerDialog`,void 0),g([y({attribute:!1})],Y.prototype,`onCancelDialog`,void 0),g([y({attribute:!1})],Y.prototype,`onDismissClosedDialog`,void 0),g([y({attribute:!1})],Y.prototype,`notificationInbox`,void 0),g([y({attribute:!1})],Y.prototype,`onClearServerQueue`,void 0),g([y({attribute:!1})],Y.prototype,`onQueuedMessageAction`,void 0),g([y({type:Boolean})],Y.prototype,`canMutateQueuedMessages`,void 0),g([y({type:Boolean})],Y.prototype,`queuedMessageActionPending`,void 0),g([v()],Y.prototype,`queuedCopyFailed`,void 0),g([y({attribute:!1})],Y.prototype,`onDismissNotification`,void 0),g([y({attribute:!1})],Y.prototype,`onDismissAllNotifications`,void 0),g([y({attribute:!1})],Y.prototype,`onLoadMore`,void 0),g([y({attribute:!1})],Y.prototype,`behaviors`,void 0),g([y({type:Boolean})],Y.prototype,`quietMode`,void 0),g([Te(`.chat`)],Y.prototype,`chat`,void 0),g([Te(`pi-web-image-gallery-dialog`)],Y.prototype,`imageGalleryDialog`,void 0),g([v()],Y.prototype,`followingLive`,void 0),g([v()],Y.prototype,`expandedMetaKey`,void 0),g([y({attribute:!1})],Y.prototype,`onTranscriptRendered`,void 0),g([y({type:Boolean})],Y.prototype,`canClearServerQueue`,void 0),g([y({attribute:!1})],Y.prototype,`onUseSuggestedInput`,void 0),g([y({type:Number})],Y.prototype,`contentRendererVersion`,void 0),Y=g([_(`chat-view`)],Y);var YF={placeholder:x(`Message pi... Use / for commands, @ for tracked files, @ space for all files, # for models`,`Empty composer hint; /, @, @ space and # are literal completion triggers`),message:x(`Message pi`,`Accessible name of the message editor`),attach:x(`Attach files`,`Open attachment chooser`),source:x(`Attachment source`,`Attachment source group name`),photosTitle:x(`Choose from your photo library`,`Photo library chooser tooltip`),photos:x(`Photos`,`Photo library source button`),cameraTitle:x(`Take a new photo`,`Camera chooser tooltip`),camera:x(`Camera`,`Camera source button`),filesTitle:x(`Browse documents and other files`,`File chooser tooltip`),files:x(`Files`,`File source button`),shell:x(`{excluded, select, yes {Shell command · excluded from context} other {Shell command}}`,`Shell input mode; excluded commands are not added to model context`),compacting:x(`Compacting history · message will be queued`,`Composer hint while context is compacting`),queueTitle:x(`Queue until the current activity finishes`,`Queue message tooltip`),queue:x(`Queue message`,`Queue message accessible name`),send:x(`Send message`,`Send message accessible name and tooltip`),steerTitle:x(`Steer the current response before the next model call`,`Steering tooltip`),steer:x(`Steer current response`,`Steering button accessible name`),stopTitle:x(`Stop current work and clear queued messages`,`Stop button tooltip`),idle:x(`Nothing running`,`Disabled stop button tooltip`),stop:x(`Stop current work`,`Stop button accessible name`),noModel:x(`no model`,`Fallback when no model is selected`),status:x(`Session status`,`Model and thinking controls group name`),selectModel:x(`Select model`,`Model selector tooltip`),thinking:x(`Thinking level: {level}`,`Thinking selector accessible name and tooltip; level is a runtime identifier`),context:x(`Pending plugin context`,`Staged plugin context group name`),remove:x(`Remove {name}`,`Remove a named context chip or attachment; name is unmodified user/plugin content`),attachments:x(`Pending attachments`,`Staged attachments group name`),removeAttachment:x(`Remove attachment`,`Remove attachment tooltip`),deliveryTitle:x(`How attachments are delivered to the agent`,`Attachment delivery selector tooltip`),filesDeliveryTitle:x(`General files are saved and mentioned from the workspace`,`Delivery tooltip when non-image files require saving`),delivery:x(`Attachment delivery`,`Delivery selector accessible name`),inline:x(`{available, select, yes {Attach to message} other {Attach to message (images only)}}`,`Inline attachment delivery option; disabled for general files`),folder:x(`Save to {folder}`,`Folder delivery option; path remains unmodified`),file:x(`FILE`,`Generic file preview badge when no extension exists`),readFailed:x(`Failed to read an attachment.`,`Attachment capture failure; successfully read files are retained`),retry:x(`Message not submitted. Context kept for retry.`,`Submission was not confirmed; draft and context retained`),submitFailed:x(`Message not submitted: {error}`,`Submission failure with unmodified diagnostic`),fileKind:x(`{kind, select, tracked {Tracked} untracked {Untracked} other {Other}}`,`File completion tracking annotation, not part of the inserted path`)},X=w.registerMessages(`core.promptEditor`,YF),XF=Nn.define(),ZF=In.define({create:()=>null,update(e,t){for(let e of t.effects)if(e.is(XF))return e.value;return t.docChanged||t.selection!==void 0?null:e}}),QF=class extends xn{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}},$F=[ZF,Fn.decorations.compute([ZF],e=>{let t=e.field(ZF);return t===null?Sn.none:Sn.set([Sn.widget({widget:new QF(t.text),side:1}).range(t.pos)])})],eI=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function tI(e){return typeof e==`string`&&eI.has(e)}function nI(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 rI=`application/octet-stream`,iI=C(`client.promptAttachmentCapture.failed.to.read.an.attachment.aa0fe0`,`Failed to read an attachment.`);async function aI(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(lI(i,e))}catch{r=iI}return{attachments:n,...r===void 0?{}:{error:r}}}function oI(e){return e.kind===`image`&&tI(e.mimeType)}function sI(e){return e.every(e=>oI(e))}function cI(e,t){return sI(t)?e:`folder`}function lI(e,t){return tI(e.type)?{kind:`image`,name:dI(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:dI(e),mimeType:uI(e),data:t,size:e.size}}function uI(e){let t=e.type.trim();return t===``?rI:t}function dI(e){return e.name===``?tI(e.type)?`pasted-image.${nI(e.type)}`:`pasted-file.bin`:e.name}var fI=`pi-web:attachment-delivery`;function pI(e=Oi()){try{return e?.getItem(fI)===`folder`?`folder`:`inline`}catch{return`inline`}}function mI(e,t=Oi()){try{t?.setItem(fI,e)}catch{}}var hI=ot(class extends Ce{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===Le.ELEMENT}update(e,[t,n]){if(!this.isElementPart)throw Error(`scrollWhenSelected must be used on an element`);if(t&&(!this.wasSelected||n!==this.previousKey)){let t=`element`in e?e.element:void 0;requestAnimationFrame(()=>{t instanceof HTMLElement&&t.scrollIntoView({block:`nearest`})})}this.wasSelected=t,this.previousKey=n}render(e,t){}}),gI=class extends O{constructor(){super(),this.popup=new VA(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,o.createController(this),new S(this)}render(){return this.items.length?D`
2602
+ `}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)}};g([y({attribute:!1})],Y.prototype,`messages`,void 0),g([y()],Y.prototype,`sessionId`,void 0),g([y({attribute:!1})],Y.prototype,`onNavigationChange`,void 0),g([y()],Y.prototype,`sessionCwd`,void 0),g([y({attribute:!1})],Y.prototype,`workspaceContext`,void 0),g([y({attribute:!1})],Y.prototype,`contentRendering`,void 0),g([y()],Y.prototype,`machineId`,void 0),g([y({attribute:!1})],Y.prototype,`messageActions`,void 0),g([y({attribute:!1})],Y.prototype,`messageActionContext`,void 0),g([y({attribute:!1})],Y.prototype,`onMessageAction`,void 0),g([y({attribute:!1})],Y.prototype,`onDisplayedMessageAction`,void 0),g([y({attribute:!1})],Y.prototype,`transcriptRenderers`,void 0),g([y({type:Number})],Y.prototype,`messageStart`,void 0),g([y({type:Number})],Y.prototype,`messageEnd`,void 0),g([y({type:Number})],Y.prototype,`messageTotal`,void 0),g([y({attribute:!1})],Y.prototype,`searchTarget`,void 0),g([y({type:Boolean})],Y.prototype,`hasMore`,void 0),g([y({type:Boolean})],Y.prototype,`historyReady`,void 0),g([y({type:Boolean})],Y.prototype,`loadingMore`,void 0),g([y({type:Boolean})],Y.prototype,`isSendingPrompt`,void 0),g([y({type:Boolean})],Y.prototype,`isCompacting`,void 0),g([y({type:Number})],Y.prototype,`pendingMessageCount`,void 0),g([y({attribute:!1})],Y.prototype,`clientQueuedMessages`,void 0),g([y({attribute:!1})],Y.prototype,`status`,void 0),g([y({attribute:!1})],Y.prototype,`activity`,void 0),g([y({attribute:!1})],Y.prototype,`askDraftSessionId`,void 0),g([y({attribute:!1})],Y.prototype,`onSubmitAsk`,void 0),g([y({attribute:!1})],Y.prototype,`pendingDialogs`,void 0),g([y({attribute:!1})],Y.prototype,`closedDialogs`,void 0),g([y({attribute:!1})],Y.prototype,`onAnswerDialog`,void 0),g([y({attribute:!1})],Y.prototype,`onCancelDialog`,void 0),g([y({attribute:!1})],Y.prototype,`onDismissClosedDialog`,void 0),g([y({attribute:!1})],Y.prototype,`notificationInbox`,void 0),g([y({attribute:!1})],Y.prototype,`onClearServerQueue`,void 0),g([y({attribute:!1})],Y.prototype,`onQueuedMessageAction`,void 0),g([y({type:Boolean})],Y.prototype,`canMutateQueuedMessages`,void 0),g([y({type:Boolean})],Y.prototype,`queuedMessageActionPending`,void 0),g([v()],Y.prototype,`queuedCopyFailed`,void 0),g([y({attribute:!1})],Y.prototype,`onDismissNotification`,void 0),g([y({attribute:!1})],Y.prototype,`onDismissAllNotifications`,void 0),g([y({attribute:!1})],Y.prototype,`onLoadMore`,void 0),g([y({attribute:!1})],Y.prototype,`behaviors`,void 0),g([y({type:Boolean})],Y.prototype,`quietMode`,void 0),g([Te(`.chat`)],Y.prototype,`chat`,void 0),g([Te(`pi-web-image-gallery-dialog`)],Y.prototype,`imageGalleryDialog`,void 0),g([v()],Y.prototype,`followingLive`,void 0),g([v()],Y.prototype,`expandedMetaKey`,void 0),g([y({attribute:!1})],Y.prototype,`onTranscriptRendered`,void 0),g([y({type:Boolean})],Y.prototype,`canClearServerQueue`,void 0),g([y({attribute:!1})],Y.prototype,`onUseSuggestedInput`,void 0),g([y({type:Number})],Y.prototype,`contentRendererVersion`,void 0),Y=g([_(`chat-view`)],Y);var XF={placeholder:x(`Message pi... Use / for commands, @ for tracked files, @ space for all files, # for models`,`Empty composer hint; /, @, @ space and # are literal completion triggers`),message:x(`Message pi`,`Accessible name of the message editor`),attach:x(`Attach files`,`Open attachment chooser`),source:x(`Attachment source`,`Attachment source group name`),photosTitle:x(`Choose from your photo library`,`Photo library chooser tooltip`),photos:x(`Photos`,`Photo library source button`),cameraTitle:x(`Take a new photo`,`Camera chooser tooltip`),camera:x(`Camera`,`Camera source button`),filesTitle:x(`Browse documents and other files`,`File chooser tooltip`),files:x(`Files`,`File source button`),shell:x(`{excluded, select, yes {Shell command · excluded from context} other {Shell command}}`,`Shell input mode; excluded commands are not added to model context`),compacting:x(`Compacting history · message will be queued`,`Composer hint while context is compacting`),queueTitle:x(`Queue until the current activity finishes`,`Queue message tooltip`),queue:x(`Queue message`,`Queue message accessible name`),send:x(`Send message`,`Send message accessible name and tooltip`),steerTitle:x(`Steer the current response before the next model call`,`Steering tooltip`),steer:x(`Steer current response`,`Steering button accessible name`),stopTitle:x(`Stop current work and clear queued messages`,`Stop button tooltip`),idle:x(`Nothing running`,`Disabled stop button tooltip`),stop:x(`Stop current work`,`Stop button accessible name`),noModel:x(`no model`,`Fallback when no model is selected`),status:x(`Session status`,`Model and thinking controls group name`),selectModel:x(`Select model`,`Model selector tooltip`),thinking:x(`Thinking level: {level}`,`Thinking selector accessible name and tooltip; level is a runtime identifier`),context:x(`Pending plugin context`,`Staged plugin context group name`),remove:x(`Remove {name}`,`Remove a named context chip or attachment; name is unmodified user/plugin content`),attachments:x(`Pending attachments`,`Staged attachments group name`),removeAttachment:x(`Remove attachment`,`Remove attachment tooltip`),deliveryTitle:x(`How attachments are delivered to the agent`,`Attachment delivery selector tooltip`),filesDeliveryTitle:x(`General files are saved and mentioned from the workspace`,`Delivery tooltip when non-image files require saving`),delivery:x(`Attachment delivery`,`Delivery selector accessible name`),inline:x(`{available, select, yes {Attach to message} other {Attach to message (images only)}}`,`Inline attachment delivery option; disabled for general files`),folder:x(`Save to {folder}`,`Folder delivery option; path remains unmodified`),file:x(`FILE`,`Generic file preview badge when no extension exists`),readFailed:x(`Failed to read an attachment.`,`Attachment capture failure; successfully read files are retained`),retry:x(`Message not submitted. Context kept for retry.`,`Submission was not confirmed; draft and context retained`),submitFailed:x(`Message not submitted: {error}`,`Submission failure with unmodified diagnostic`),fileKind:x(`{kind, select, tracked {Tracked} untracked {Untracked} other {Other}}`,`File completion tracking annotation, not part of the inserted path`)},X=w.registerMessages(`core.promptEditor`,XF),ZF=Nn.define(),QF=In.define({create:()=>null,update(e,t){for(let e of t.effects)if(e.is(ZF))return e.value;return t.docChanged||t.selection!==void 0?null:e}}),$F=class extends xn{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}},eI=[QF,Fn.decorations.compute([QF],e=>{let t=e.field(QF);return t===null?Sn.none:Sn.set([Sn.widget({widget:new $F(t.text),side:1}).range(t.pos)])})],tI=new Set([`image/jpeg`,`image/png`,`image/gif`,`image/webp`]);function nI(e){return typeof e==`string`&&tI.has(e)}function rI(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 iI=`application/octet-stream`,aI=C(`client.promptAttachmentCapture.failed.to.read.an.attachment.aa0fe0`,`Failed to read an attachment.`);async function oI(e,t){let n=[],r;for(let i of e)try{let e=await t(i);n.push(uI(i,e))}catch{r=aI}return{attachments:n,...r===void 0?{}:{error:r}}}function sI(e){return e.kind===`image`&&nI(e.mimeType)}function cI(e){return e.every(e=>sI(e))}function lI(e,t){return cI(t)?e:`folder`}function uI(e,t){return nI(e.type)?{kind:`image`,name:fI(e),mimeType:e.type,data:t,size:e.size}:{kind:`file`,name:fI(e),mimeType:dI(e),data:t,size:e.size}}function dI(e){let t=e.type.trim();return t===``?iI:t}function fI(e){return e.name===``?nI(e.type)?`pasted-image.${rI(e.type)}`:`pasted-file.bin`:e.name}var pI=`pi-web:attachment-delivery`;function mI(e=Oi()){try{return e?.getItem(pI)===`folder`?`folder`:`inline`}catch{return`inline`}}function hI(e,t=Oi()){try{t?.setItem(pI,e)}catch{}}var gI=ot(class extends Ce{constructor(e){super(e),this.wasSelected=!1,this.isElementPart=e.type===Le.ELEMENT}update(e,[t,n]){if(!this.isElementPart)throw Error(`scrollWhenSelected must be used on an element`);if(t&&(!this.wasSelected||n!==this.previousKey)){let t=`element`in e?e.element:void 0;requestAnimationFrame(()=>{t instanceof HTMLElement&&t.scrollIntoView({block:`nearest`})})}this.wasSelected=t,this.previousKey=n}render(e,t){}}),_I=class extends O{constructor(){super(),this.popup=new VA(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,o.createController(this),new S(this)}render(){return this.items.length?D`
2603
2603
  <div class="menu ui-popup-panel" data-ui-context="completions" popover="auto">
2604
2604
  ${this.items.map((e,t)=>D`
2605
- <button class=${t===this.selectedIndex?`ui-choice selected`:`ui-choice`} data-selected=${t===this.selectedIndex} ${hI(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
2605
+ <button class=${t===this.selectedIndex?`ui-choice selected`:`ui-choice`} data-selected=${t===this.selectedIndex} ${gI(t===this.selectedIndex,e)} @mousedown=${t=>{t.preventDefault(),this.onPick?.(e)}}>
2606
2606
  <span class="label" dir="auto"><strong>${e.insertText}</strong>${e.argumentHint===void 0||e.argumentHint===``?null:D` <span class="argument-hint">${e.argumentHint}</span>`}</span>
2607
2607
  <span class="detail">${e.kind===`file`?X.t(`fileKind`,{kind:e.detail}):e.detail}</span>
2608
2608
  ${e.description!==void 0&&e.description!==``?D`<small>${e.description}</small>`:null}
2609
2609
  </button>
2610
2610
  `)}
2611
2611
  </div>
2612
- `:null}static{this.styles=nf}};g([y({attribute:!1})],gI.prototype,`anchor`,void 0),g([y({attribute:!1})],gI.prototype,`onClose`,void 0),g([y({attribute:!1})],gI.prototype,`items`,void 0),g([y({type:Number})],gI.prototype,`selectedIndex`,void 0),g([y({attribute:!1})],gI.prototype,`onPick`,void 0),gI=g([_(`autocomplete-menu`)],gI);function _I(){return typeof navigator<`u`&&/Android/i.test(navigator.userAgent)}function vI(){let e=document.createElement(`span`);return e.className=`prompt-placeholder`,e.dataset.placeholder=X.t(`placeholder`),e}var Z=class extends O{constructor(){super(),this.defaultStreamingBehavior=`steer`,this.disabled=!1,this.machineId=`local`,this.attachmentsFolder=Ee,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=pI(),this.attachmentError=void 0,this.chipSendingKey=void 0,this.chipError=void 0,this.attachSourceOpen=!1,this.attachPopup=new VA(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.editorLabelsDirty=!0,this.editorLabelsCompartment=new wn,this.editableCompartment=new wn,this.readOnlyCompartment=new wn,this.mobilePromptEnterMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(He):void 0,this.handleShortcutMediaChange=()=>{this.requestUpdate()},this.explicitShiftKeyActive=!1,o.createController(this),new S(this,void 0,()=>{this.editorLabelsDirty=!0})}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=bI(e.has(`machineId`)?e.get(`machineId`):this.machineId,t);n!==void 0&&No(n,this.draft);let r=bI(this.machineId,this.sessionId);this.draft=r===void 0?``:Mo(r),this.attachments=r===void 0?[]:Ro(r),this.attachmentError=void 0,this.chipError=void 0,this.currentInputMode=bc(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return!this.editorLabelsDirty&&e.has(`status`)&&e.size===1?!yI(e.get(`status`),this.status):!0}firstUpdated(){this.createEditor()}get submitting(){return this.sending||this.chipSendingKey===this.composerKey()}get busy(){return this.disabled||this.submitting}connectedCallback(){super.connectedCallback(),this.mobilePromptEnterMedia?.addEventListener(`change`,this.handleShortcutMediaChange),this.requestUpdate()}updated(e){this.editorLabelsDirty&&(this.editorLabelsDirty=!1,this.editor?.dispatch({effects:this.editorLabelsCompartment.reconfigure(this.editorLabels())})),e.has(`disabled`)&&this.updateEditorDisabledState(),(e.has(`sessionId`)||e.has(`machineId`))&&this.syncEditorDoc()}disconnectedCallback(){this.mobilePromptEnterMedia?.removeEventListener(`change`,this.handleShortcutMediaChange),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=n?`queue`:`send`,o=tt(this.shortcuts??this.shortcutConfig,this.mobilePromptEnterMedia),s=o!==null&&Se(o).length===1,c=i||!s?`none`:r?`steer`:a,l=_I();return D`
2612
+ `:null}static{this.styles=nf}};g([y({attribute:!1})],_I.prototype,`anchor`,void 0),g([y({attribute:!1})],_I.prototype,`onClose`,void 0),g([y({attribute:!1})],_I.prototype,`items`,void 0),g([y({type:Number})],_I.prototype,`selectedIndex`,void 0),g([y({attribute:!1})],_I.prototype,`onPick`,void 0),_I=g([_(`autocomplete-menu`)],_I);function vI(){return typeof navigator<`u`&&/Android/i.test(navigator.userAgent)}function yI(){let e=document.createElement(`span`);return e.className=`prompt-placeholder`,e.dataset.placeholder=X.t(`placeholder`),e}var Z=class extends O{constructor(){super(),this.defaultStreamingBehavior=`steer`,this.disabled=!1,this.machineId=`local`,this.attachmentsFolder=Ee,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=mI(),this.attachmentError=void 0,this.chipSendingKey=void 0,this.chipError=void 0,this.attachSourceOpen=!1,this.attachPopup=new VA(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.editorLabelsDirty=!0,this.editorLabelsCompartment=new wn,this.editableCompartment=new wn,this.readOnlyCompartment=new wn,this.mobilePromptEnterMedia=typeof window<`u`&&`matchMedia`in window?window.matchMedia(He):void 0,this.handleShortcutMediaChange=()=>{this.requestUpdate()},this.explicitShiftKeyActive=!1,o.createController(this),new S(this,void 0,()=>{this.editorLabelsDirty=!0})}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=xI(e.has(`machineId`)?e.get(`machineId`):this.machineId,t);n!==void 0&&No(n,this.draft);let r=xI(this.machineId,this.sessionId);this.draft=r===void 0?``:Mo(r),this.attachments=r===void 0?[]:Ro(r),this.attachmentError=void 0,this.chipError=void 0,this.currentInputMode=bc(this.draft),this.completions=[],this.selectedIndex=0}shouldUpdate(e){return!this.editorLabelsDirty&&e.has(`status`)&&e.size===1?!bI(e.get(`status`),this.status):!0}firstUpdated(){this.createEditor()}get submitting(){return this.sending||this.chipSendingKey===this.composerKey()}get busy(){return this.disabled||this.submitting}connectedCallback(){super.connectedCallback(),this.mobilePromptEnterMedia?.addEventListener(`change`,this.handleShortcutMediaChange),this.requestUpdate()}updated(e){this.editorLabelsDirty&&(this.editorLabelsDirty=!1,this.editor?.dispatch({effects:this.editorLabelsCompartment.reconfigure(this.editorLabels())})),e.has(`disabled`)&&this.updateEditorDisabledState(),(e.has(`sessionId`)||e.has(`machineId`))&&this.syncEditorDoc()}disconnectedCallback(){this.mobilePromptEnterMedia?.removeEventListener(`change`,this.handleShortcutMediaChange),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=n?`queue`:`send`,o=tt(this.shortcuts??this.shortcutConfig,this.mobilePromptEnterMedia),s=o!==null&&Se(o).length===1,c=i||!s?`none`:r?`steer`:a,l=vI();return D`
2613
2613
  <footer ?data-active-work=${this.canStop} data-ui-context="composer" data-mode=${t?`shell`:`text`} data-busy=${this.submitting} data-disabled=${this.disabled} data-compacting=${this.isCompacting} data-default-action=${c} class=${t?`shell-mode`:``} @paste=${e=>{this.handlePaste(e)}} @dragover=${e=>{this.handleDragOver(e)}} @drop=${e=>{this.handleDrop(e)}}>
2614
2614
  <div class="editor-wrap">
2615
2615
  <div class="editor-input">
@@ -2618,11 +2618,11 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2618
2618
  <input class="attachment-input" type="file" multiple hidden @change=${e=>{this.handleFileInput(e)}} />
2619
2619
  <input class="attachment-image-input" type="file" multiple accept="image/*" hidden @change=${e=>{this.handleFileInput(e)}} />
2620
2620
  <input class="attachment-camera-input" type="file" accept="image/*" capture="environment" hidden @change=${e=>{this.handleFileInput(e)}} />
2621
- <button type="button" class=${`editor-attach icon-button ui-button ui-button--icon${l?` ui-popup-trigger`:``}`} data-composer-action="attach" ?disabled=${i} title=${X.t(`attach`)} aria-label=${X.t(`attach`)} aria-controls=${l?`attach-source-panel`:E} aria-expanded=${l?String(this.attachSourceOpen):E} @click=${()=>{this.handleAttachClick()}}>${$M()}</button>
2621
+ <button type="button" class=${`editor-attach icon-button ui-button ui-button--icon${l?` ui-popup-trigger`:``}`} data-composer-action="attach" ?disabled=${i} title=${X.t(`attach`)} aria-label=${X.t(`attach`)} aria-controls=${l?`attach-source-panel`:E} aria-expanded=${l?String(this.attachSourceOpen):E} @click=${()=>{this.handleAttachClick()}}>${eN()}</button>
2622
2622
  <div id="attach-source-panel" class="attach-source-panel ui-menu ui-popup-panel" data-ui-context="composer-attachment-sources" popover="auto" role="group" aria-label=${X.t(`source`)}>
2623
- <button type="button" class="ui-button ui-menu-item" data-composer-action="attach-photos" ?disabled=${i} title=${X.t(`photosTitle`)} @click=${()=>{this.openAttachmentPicker(this.attachmentImageInput)}}><span class="attach-source-icon" aria-hidden="true">${ZM()}</span><span class="attach-source-label">${X.t(`photos`)}</span></button>
2624
- <button type="button" class="ui-button ui-menu-item" data-composer-action="attach-camera" ?disabled=${i} title=${X.t(`cameraTitle`)} @click=${()=>{this.openAttachmentPicker(this.attachmentCameraInput)}}><span class="attach-source-icon" aria-hidden="true">${QM()}</span><span class="attach-source-label">${X.t(`camera`)}</span></button>
2625
- <button type="button" class="ui-button ui-menu-item" data-composer-action="attach-files" ?disabled=${i} title=${X.t(`filesTitle`)} @click=${()=>{this.openAttachmentPicker(this.attachmentInput)}}><span class="attach-source-icon" aria-hidden="true">${$M()}</span><span class="attach-source-label">${X.t(`files`)}</span></button>
2623
+ <button type="button" class="ui-button ui-menu-item" data-composer-action="attach-photos" ?disabled=${i} title=${X.t(`photosTitle`)} @click=${()=>{this.openAttachmentPicker(this.attachmentImageInput)}}><span class="attach-source-icon" aria-hidden="true">${QM()}</span><span class="attach-source-label">${X.t(`photos`)}</span></button>
2624
+ <button type="button" class="ui-button ui-menu-item" data-composer-action="attach-camera" ?disabled=${i} title=${X.t(`cameraTitle`)} @click=${()=>{this.openAttachmentPicker(this.attachmentCameraInput)}}><span class="attach-source-icon" aria-hidden="true">${$M()}</span><span class="attach-source-label">${X.t(`camera`)}</span></button>
2625
+ <button type="button" class="ui-button ui-menu-item" data-composer-action="attach-files" ?disabled=${i} title=${X.t(`filesTitle`)} @click=${()=>{this.openAttachmentPicker(this.attachmentInput)}}><span class="attach-source-icon" aria-hidden="true">${eN()}</span><span class="attach-source-label">${X.t(`files`)}</span></button>
2626
2626
  </div>
2627
2627
  ${t?D`<div class="mode-hint">${X.t(`shell`,{excluded:e.excludeFromContext?`yes`:`no`})}</div>`:null}
2628
2628
  ${this.isCompacting&&!t?D`<div class="mode-hint">${X.t(`compacting`)}</div>`:null}
@@ -2634,17 +2634,17 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2634
2634
  <div class="actions ui-toolbar ui-toolbar--primary ui-toolbar--borderless ui-composer-toolbar">
2635
2635
  ${this.renderCompactStatus()}
2636
2636
  <div class="ui-toolbar-group ui-composer-actions">
2637
- <button class="ui-button ui-button--icon icon-button send-button ${c===a?`default-send-action`:``}" data-composer-action=${a} data-default=${c===a} ?disabled=${i} title=${X.t(n?`queueTitle`:`send`)} aria-label=${X.t(n?`queue`:`send`)} @click=${()=>{this.send(`followUp`)}}>${n?tN():eN()}</button>
2638
- ${this.canSteer&&!this.isCompacting?D`<button class="ui-button ui-button--icon icon-button steer-button ${c===`steer`?`default-send-action`:``}" data-composer-action="steer" data-default=${c===`steer`} ?disabled=${i} title=${X.t(`steerTitle`)} aria-label=${X.t(`steer`)} @click=${()=>{this.send(`steer`)}}>${nN()}</button>`:null}
2639
- <button class="ui-button ui-button--icon icon-button stop-button" data-composer-action="stop" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?C(`ui.promptEditor.stopCurrentWorkAndClearQueuedMessages`,`Stop current work and clear queued messages`):X.t(`idle`)} aria-label=${X.t(`stop`)} @click=${()=>this.onStop?.()}>${rN()}</button>
2637
+ <button class="ui-button ui-button--icon icon-button send-button ${c===a?`default-send-action`:``}" data-composer-action=${a} data-default=${c===a} ?disabled=${i} title=${X.t(n?`queueTitle`:`send`)} aria-label=${X.t(n?`queue`:`send`)} @click=${()=>{this.send(`followUp`)}}>${n?nN():tN()}</button>
2638
+ ${this.canSteer&&!this.isCompacting?D`<button class="ui-button ui-button--icon icon-button steer-button ${c===`steer`?`default-send-action`:``}" data-composer-action="steer" data-default=${c===`steer`} ?disabled=${i} title=${X.t(`steerTitle`)} aria-label=${X.t(`steer`)} @click=${()=>{this.send(`steer`)}}>${rN()}</button>`:null}
2639
+ <button class="ui-button ui-button--icon icon-button stop-button" data-composer-action="stop" ?disabled=${this.disabled||!this.canStop} title=${this.canStop?C(`ui.promptEditor.stopCurrentWorkAndClearQueuedMessages`,`Stop current work and clear queued messages`):X.t(`idle`)} aria-label=${X.t(`stop`)} @click=${()=>this.onStop?.()}>${iN()}</button>
2640
2640
  </div>
2641
2641
  </div>
2642
2642
  </footer>
2643
- `}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=bI(this.machineId,this.sessionId);t!==void 0&&No(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:yn.cursor(e.length)})}this.cancelFileCompletion(),this.currentInputMode=bc(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??X.t(`noModel`),n=e.model?.provider!==void 0&&e.model.provider!==``?`${e.model.provider}/`:``;return D`
2643
+ `}focusInput(){this.editor?.focus()}replaceText(e){this.draft=e;let t=xI(this.machineId,this.sessionId);t!==void 0&&No(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:yn.cursor(e.length)})}this.cancelFileCompletion(),this.currentInputMode=bc(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??X.t(`noModel`),n=e.model?.provider!==void 0&&e.model.provider!==``?`${e.model.provider}/`:``;return D`
2644
2644
  <div class="compact-status" aria-label=${X.t(`status`)}>
2645
2645
  <div class="ui-toolbar-group ui-toolbar-group--bounded ui-composer-settings">
2646
2646
  <button class="ui-button select-model" data-composer-action="model" title=${X.t(`selectModel`)} @click=${()=>this.onSelectModel?.()}>${n}${t}</button>
2647
- <button class="ui-button ui-button--icon select-thinking icon-button" data-composer-action="thinking" title=${X.t(`thinking`,{level:on(e.thinkingLevel,C)})} aria-label=${X.t(`thinking`,{level:on(e.thinkingLevel,C)})} @click=${()=>this.onSelectThinking?.()}>${iN(Ft(e.thinkingLevel,this.availableThinkingLevels))}</button>
2647
+ <button class="ui-button ui-button--icon select-thinking icon-button" data-composer-action="thinking" title=${X.t(`thinking`,{level:on(e.thinkingLevel,C)})} aria-label=${X.t(`thinking`,{level:on(e.thinkingLevel,C)})} @click=${()=>this.onSelectThinking?.()}>${aN(Ft(e.thinkingLevel,this.availableThinkingLevels))}</button>
2648
2648
  </div>
2649
2649
  </div>
2650
2650
  `}renderPromptChips(){return this.promptChips.length===0&&this.chipError===void 0?null:D`
@@ -2657,10 +2657,10 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2657
2657
  `)}
2658
2658
  ${this.chipError===void 0?null:D`<div class="chip-error" role="alert">${this.chipError.kind===`retry`?X.t(`retry`):X.t(`submitFailed`,{error:this.chipError.error})}</div>`}
2659
2659
  </div>
2660
- `}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=sI(this.attachments),t=this.effectiveAttachmentDelivery();return D`
2660
+ `}renderAttachments(){if(this.attachments.length===0&&this.attachmentError===void 0)return null;let e=cI(this.attachments),t=this.effectiveAttachmentDelivery();return D`
2661
2661
  <div class="attachments" aria-label=${X.t(`attachments`)}>
2662
2662
  ${this.attachments.map(e=>D`
2663
- <div class=${`attachment-chip ${oI(e)?`attachment-chip-image`:`attachment-chip-file`}`} title=${e.name}>
2663
+ <div class=${`attachment-chip ${sI(e)?`attachment-chip-image`:`attachment-chip-file`}`} title=${e.name}>
2664
2664
  ${this.renderAttachmentPreview(e)}
2665
2665
  <button type="button" class="ui-button ui-button--compact ui-button--icon attachment-remove" title=${X.t(`removeAttachment`)} aria-label=${X.t(`remove`,{name:e.name})} @click=${()=>{this.removeAttachment(e.id)}}>×</button>
2666
2666
  </div>
@@ -2669,54 +2669,54 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2669
2669
  <label class="attachment-delivery" title=${X.t(e?`deliveryTitle`:`filesDeliveryTitle`)}>
2670
2670
  <select class="ui-select" aria-label=${X.t(`delivery`)} .value=${t} @change=${e=>{this.changeDelivery(e)}}>
2671
2671
  <option value="inline" ?disabled=${!e}>${X.t(`inline`,{available:e?`yes`:`no`})}</option>
2672
- <option value="folder">${DI(this.attachmentsFolder)}</option>
2672
+ <option value="folder">${OI(this.attachmentsFolder)}</option>
2673
2673
  </select>
2674
2674
  </label>
2675
2675
  `:null}
2676
2676
  ${this.attachmentError===void 0?null:D`<div class="attachment-error">${X.t(`readFailed`)}</div>`}
2677
2677
  </div>
2678
- `}renderAttachmentPreview(e){return oI(e)?D`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:D`
2679
- <div class="attachment-file-preview" aria-hidden="true">${OI(e.name)}</div>
2678
+ `}renderAttachmentPreview(e){return sI(e)?D`<img src=${`data:${e.mimeType};base64,${e.data}`} alt=${e.name} />`:D`
2679
+ <div class="attachment-file-preview" aria-hidden="true">${kI(e.name)}</div>
2680
2680
  <span class="attachment-file-name" dir="auto">${e.name}</span>
2681
- `}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;t===`inline`&&!sI(this.attachments)?e.target.value=`folder`:(this.attachmentDelivery=t,mI(this.attachmentDelivery))}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e);let t=bI(this.machineId,this.sessionId);t!==void 0&&zo(t,this.attachments)}async handlePaste(e){let t=wI(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&TI(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=wI(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleAttachClick(){this.busy||(_I()?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 aI(e,kI);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=bI(this.machineId,this.sessionId);e!==void 0&&zo(e,this.attachments)}i!==void 0&&(this.attachmentError=!0)}}currentAttachments(){return this.attachments.map(e=>EI(e))}effectiveAttachmentDelivery(){return cI(this.attachmentDelivery,this.attachments)}createEditor(){this.editorHost&&this.editor===void 0&&(this.editor=new Fn({parent:this.editorHost,state:kn.create({doc:this.draft,extensions:[Ln(),$F,Bn(),jn(),bn.of(` `),Cn(Rn,{fallback:!0}),Fn.lineWrapping,En(),Fn.contentAttributes.of(e=>MI(e.state.sliceDoc(0,e.state.selection.main.head))),Fn.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),this.editorLabelsCompartment.of(this.editorLabels()),$F,this.editableCompartment.of(Fn.editable.of(!this.disabled)),this.readOnlyCompartment.of(kn.readOnly.of(this.disabled)),Fn.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),Tn.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=>An.shift?.(e)??!1},{key:`Backspace`,run:e=>Vn(e)},...On,...Mn])]})}))}editorLabels(){return[Dn(vI),Fn.contentAttributes.of({"aria-placeholder":X.t(`placeholder`),"aria-label":X.t(`message`)})]}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:yn.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(Fn.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(kn.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;let t=bI(this.machineId,this.sessionId);t!==void 0&&No(t,this.draft);let n=bc(this.draft);Sc(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.length>0&&(this.completions=[]);else if(e.kind===`command`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await Xt.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(xI);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:lc(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 Xt.files(e.query,{signal:this.fileCompletionAbort.signal,scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId}).catch(SI);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=hc(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 Xt.models({id:this.sessionId,cwd:this.cwd},this.machineId).then(e=>e.models).catch(CI);if(t!==this.requestVersion)return;this.completions=fc(n,e.query).map(t=>({kind:`model`,replaceFrom:e.from,replaceTo:e.to,...t}))}}currentTrigger(){return uc(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`?et(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia):e.shiftKey;return Je({key:e.key,ctrlKey:e.ctrlKey,metaKey:e.metaKey,altKey:e.altKey,shiftKey:t,isComposing:e.isComposing,target:e.target},tt(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&&!et(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?zn(t)||Pn(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):An.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:yn.cursor(r),effects:e.argumentHint===void 0||e.argumentHint===``?[]:XF.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={kind:`retry`}}catch(e){o===this.composerKey()&&(this.chipError={kind:`failed`,error:String(e)})}finally{this.chipSendingKey===o&&(this.chipSendingKey=void 0)}}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=bI(this.machineId,this.sessionId);e!==void 0&&(Po(e),Bo(e)),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=af}};g([y()],Z.prototype,`defaultStreamingBehavior`,void 0),g([y({attribute:!1})],Z.prototype,`chatNavigation`,void 0),g([y({type:Boolean})],Z.prototype,`disabled`,void 0),g([y()],Z.prototype,`sessionId`,void 0),g([y()],Z.prototype,`cwd`,void 0),g([y()],Z.prototype,`machineId`,void 0),g([y()],Z.prototype,`projectId`,void 0),g([y()],Z.prototype,`workspaceId`,void 0),g([y()],Z.prototype,`attachmentsFolder`,void 0),g([y({type:Boolean})],Z.prototype,`workspaceScopedFileSuggestions`,void 0),g([y({type:Boolean})],Z.prototype,`canSteer`,void 0),g([y({type:Boolean})],Z.prototype,`isCompacting`,void 0),g([y({type:Boolean})],Z.prototype,`canStop`,void 0),g([y({attribute:!1})],Z.prototype,`status`,void 0),g([y({type:Boolean})],Z.prototype,`sending`,void 0),g([y({attribute:!1})],Z.prototype,`shortcutConfig`,void 0),g([y({attribute:!1})],Z.prototype,`shortcuts`,void 0),g([y({attribute:!1})],Z.prototype,`promptChips`,void 0),g([y({attribute:!1})],Z.prototype,`onRemoveChip`,void 0),g([y({attribute:!1})],Z.prototype,`onSend`,void 0),g([y({attribute:!1})],Z.prototype,`onStop`,void 0),g([y({attribute:!1})],Z.prototype,`onSelectModel`,void 0),g([y({attribute:!1})],Z.prototype,`onSelectThinking`,void 0),g([y({attribute:!1})],Z.prototype,`availableThinkingLevels`,void 0),g([Te(`.markdown-editor`)],Z.prototype,`editorHost`,void 0),g([Te(`.attachment-input`)],Z.prototype,`attachmentInput`,void 0),g([Te(`.attachment-image-input`)],Z.prototype,`attachmentImageInput`,void 0),g([Te(`.attachment-camera-input`)],Z.prototype,`attachmentCameraInput`,void 0),g([Te(`.attach-source-panel`)],Z.prototype,`attachSourcePanel`,void 0),g([Te(`.editor-attach`)],Z.prototype,`attachButton`,void 0),g([v()],Z.prototype,`currentInputMode`,void 0),g([v()],Z.prototype,`completions`,void 0),g([v()],Z.prototype,`selectedIndex`,void 0),g([v()],Z.prototype,`attachments`,void 0),g([v()],Z.prototype,`attachmentDelivery`,void 0),g([v()],Z.prototype,`attachmentError`,void 0),g([v()],Z.prototype,`chipSendingKey`,void 0),g([v()],Z.prototype,`chipError`,void 0),g([v()],Z.prototype,`attachSourceOpen`,void 0),Z=g([_(`prompt-editor`)],Z);function yI(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 bI(e,t){if(typeof e==`string`&&e!==``&&typeof t==`string`&&t!==``)return M(e,t)}function xI(){return[]}function SI(){return[]}function CI(){return[]}function wI(e){return e===null?[]:Array.from(e.files)}function TI(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function EI(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 DI(e){return X.t(`folder`,{folder:e})}function OI(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():X.t(`file`)}function kI(e){return new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>{n(r.error??Error(C(`ui.promptEditor.failedToReadFile`,`Failed to read file`)))},r.onload=()=>{let e=r.result;if(typeof e!=`string`){n(Error(C(`ui.promptEditor.unexpectedFileReadResult`,`Unexpected file read result`)));return}let i=e.indexOf(`,`);t(i===-1?e:e.slice(i+1))},r.readAsDataURL(e)})}var AI={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},jI={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function MI(e){return bc(e).kind===`normal`?AI:jI}function NI(e){return w.number(Number.isFinite(e)?e:0,{notation:`compact`,maximumFractionDigits:+(e>=1e3&&e<1e4||e>=1e6&&e<1e7)})}function PI(e){let t=Number.isFinite(e)?e:0,n=t===0?0:t<.01?4:2;return w.number(t,{style:`currency`,currency:`USD`,minimumFractionDigits:n,maximumFractionDigits:n})}var FI={empty:x(`No session status yet`,`Status bar before session statistics arrive`),contextSize:x(`context {size}`,`Status bar context window size when usage is unavailable; size is a regionally formatted token count`),contextUsage:x(`{percent}/{size}`,`Compact context usage and window size; percent includes its localized percent sign, size is a formatted token count`),contextUnknown:x(`context unknown`,`Status bar when the context window size is unavailable`),queued:x(`{count, plural, one {# queued} other {# queued}}`,`Pending session message count in the compact status bar`),minimizeWarnings:x(`{count, plural, one {Minimise # warning} other {Minimise # warnings}}`,`Warning toggle accessible label and tooltip when expanded`),showWarnings:x(`{count, plural, one {Show # warning in the warning area} other {Show # warnings in the warning area}}`,`Warning toggle accessible label and tooltip when collapsed`)},II=w.registerMessages(`core.statusBar`,FI),LI=class extends O{constructor(){super(),o.createController(this),new S(this)}render(){let e=this.status;if(e===void 0)return D`<div class="bar muted">${II.t(`empty`)}</div>`;let t=e.contextUsage,n=t?t.percent==null?II.t(`contextSize`,{size:NI(t.contextWindow)}):II.t(`contextUsage`,{percent:w.number(t.percent/100,{style:`percent`,minimumFractionDigits:1,maximumFractionDigits:1}),size:NI(t.contextWindow)}):II.t(`contextUnknown`),r=e.tokens;return D`
2681
+ `}changeDelivery(e){if(!(e.target instanceof HTMLSelectElement))return;let t=e.target.value===`folder`?`folder`:`inline`;t===`inline`&&!cI(this.attachments)?e.target.value=`folder`:(this.attachmentDelivery=t,hI(this.attachmentDelivery))}removeAttachment(e){this.attachments=this.attachments.filter(t=>t.id!==e);let t=xI(this.machineId,this.sessionId);t!==void 0&&zo(t,this.attachments)}async handlePaste(e){let t=TI(e.clipboardData);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleDragOver(e){e.dataTransfer!==null&&EI(e.dataTransfer)&&e.preventDefault()}async handleDrop(e){let t=TI(e.dataTransfer);t.length!==0&&(e.preventDefault(),await this.addAttachmentFiles(t))}handleAttachClick(){this.busy||(vI()?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 oI(e,AI);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=xI(this.machineId,this.sessionId);e!==void 0&&zo(e,this.attachments)}i!==void 0&&(this.attachmentError=!0)}}currentAttachments(){return this.attachments.map(e=>DI(e))}effectiveAttachmentDelivery(){return lI(this.attachmentDelivery,this.attachments)}createEditor(){this.editorHost&&this.editor===void 0&&(this.editor=new Fn({parent:this.editorHost,state:kn.create({doc:this.draft,extensions:[Ln(),eI,Bn(),jn(),bn.of(` `),Cn(Rn,{fallback:!0}),Fn.lineWrapping,En(),Fn.contentAttributes.of(e=>NI(e.state.sliceDoc(0,e.state.selection.main.head))),Fn.domEventHandlers({keyup:e=>this.handleEditorKeyUp(e),blur:()=>this.resetEditorModifierState()}),this.editorLabelsCompartment.of(this.editorLabels()),eI,this.editableCompartment.of(Fn.editable.of(!this.disabled)),this.readOnlyCompartment.of(kn.readOnly.of(this.disabled)),Fn.updateListener.of(e=>{e.docChanged&&this.updateDraft(e.state.doc.toString())}),Tn.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=>An.shift?.(e)??!1},{key:`Backspace`,run:e=>Vn(e)},...On,...Mn])]})}))}editorLabels(){return[Dn(yI),Fn.contentAttributes.of({"aria-placeholder":X.t(`placeholder`),"aria-label":X.t(`message`)})]}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:yn.cursor(this.draft.length)})}updateEditorDisabledState(){this.editor?.dispatch({effects:[this.editableCompartment.reconfigure(Fn.editable.of(!this.disabled)),this.readOnlyCompartment.reconfigure(kn.readOnly.of(this.disabled))]})}updateDraft(e){this.draft=e;let t=xI(this.machineId,this.sessionId);t!==void 0&&No(t,this.draft);let n=bc(this.draft);Sc(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.length>0&&(this.completions=[]);else if(e.kind===`command`&&this.sessionId!==void 0&&this.sessionId!==``&&this.cwd!==void 0&&this.cwd!==``){let n=await Xt.commands({id:this.sessionId,cwd:this.cwd},this.machineId).catch(SI);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:lc(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 Xt.files(e.query,{signal:this.fileCompletionAbort.signal,scope:e.fileScope,machineId:this.machineId,projectId:this.projectId,workspaceId:this.workspaceId}).catch(CI);if(t!==this.requestVersion)return;this.completions=n.slice(0,12).map(t=>{let n=hc(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 Xt.models({id:this.sessionId,cwd:this.cwd},this.machineId).then(e=>e.models).catch(wI);if(t!==this.requestVersion)return;this.completions=fc(n,e.query).map(t=>({kind:`model`,replaceFrom:e.from,replaceTo:e.to,...t}))}}currentTrigger(){return uc(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`?et(e.shiftKey,this.explicitShiftKeyActive,this.mobilePromptEnterMedia):e.shiftKey;return Je({key:e.key,ctrlKey:e.ctrlKey,metaKey:e.metaKey,altKey:e.altKey,shiftKey:t,isComposing:e.isComposing,target:e.target},tt(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&&!et(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?zn(t)||Pn(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):An.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:yn.cursor(r),effects:e.argumentHint===void 0||e.argumentHint===``?[]:ZF.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={kind:`retry`}}catch(e){o===this.composerKey()&&(this.chipError={kind:`failed`,error:String(e)})}finally{this.chipSendingKey===o&&(this.chipSendingKey=void 0)}}resetComposer(){this.draft=``,this.currentInputMode={kind:`normal`};let e=xI(this.machineId,this.sessionId);e!==void 0&&(Po(e),Bo(e)),this.completions=[],this.attachments=[],this.attachmentError=void 0,this.syncEditorDoc()}static{this.styles=af}};g([y()],Z.prototype,`defaultStreamingBehavior`,void 0),g([y({attribute:!1})],Z.prototype,`chatNavigation`,void 0),g([y({type:Boolean})],Z.prototype,`disabled`,void 0),g([y()],Z.prototype,`sessionId`,void 0),g([y()],Z.prototype,`cwd`,void 0),g([y()],Z.prototype,`machineId`,void 0),g([y()],Z.prototype,`projectId`,void 0),g([y()],Z.prototype,`workspaceId`,void 0),g([y()],Z.prototype,`attachmentsFolder`,void 0),g([y({type:Boolean})],Z.prototype,`workspaceScopedFileSuggestions`,void 0),g([y({type:Boolean})],Z.prototype,`canSteer`,void 0),g([y({type:Boolean})],Z.prototype,`isCompacting`,void 0),g([y({type:Boolean})],Z.prototype,`canStop`,void 0),g([y({attribute:!1})],Z.prototype,`status`,void 0),g([y({type:Boolean})],Z.prototype,`sending`,void 0),g([y({attribute:!1})],Z.prototype,`shortcutConfig`,void 0),g([y({attribute:!1})],Z.prototype,`shortcuts`,void 0),g([y({attribute:!1})],Z.prototype,`promptChips`,void 0),g([y({attribute:!1})],Z.prototype,`onRemoveChip`,void 0),g([y({attribute:!1})],Z.prototype,`onSend`,void 0),g([y({attribute:!1})],Z.prototype,`onStop`,void 0),g([y({attribute:!1})],Z.prototype,`onSelectModel`,void 0),g([y({attribute:!1})],Z.prototype,`onSelectThinking`,void 0),g([y({attribute:!1})],Z.prototype,`availableThinkingLevels`,void 0),g([Te(`.markdown-editor`)],Z.prototype,`editorHost`,void 0),g([Te(`.attachment-input`)],Z.prototype,`attachmentInput`,void 0),g([Te(`.attachment-image-input`)],Z.prototype,`attachmentImageInput`,void 0),g([Te(`.attachment-camera-input`)],Z.prototype,`attachmentCameraInput`,void 0),g([Te(`.attach-source-panel`)],Z.prototype,`attachSourcePanel`,void 0),g([Te(`.editor-attach`)],Z.prototype,`attachButton`,void 0),g([v()],Z.prototype,`currentInputMode`,void 0),g([v()],Z.prototype,`completions`,void 0),g([v()],Z.prototype,`selectedIndex`,void 0),g([v()],Z.prototype,`attachments`,void 0),g([v()],Z.prototype,`attachmentDelivery`,void 0),g([v()],Z.prototype,`attachmentError`,void 0),g([v()],Z.prototype,`chipSendingKey`,void 0),g([v()],Z.prototype,`chipError`,void 0),g([v()],Z.prototype,`attachSourceOpen`,void 0),Z=g([_(`prompt-editor`)],Z);function bI(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 xI(e,t){if(typeof e==`string`&&e!==``&&typeof t==`string`&&t!==``)return M(e,t)}function SI(){return[]}function CI(){return[]}function wI(){return[]}function TI(e){return e===null?[]:Array.from(e.files)}function EI(e){let t=Array.from(e.items);return t.length>0?t.some(e=>e.kind===`file`):Array.from(e.types).includes(`Files`)}function DI(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 OI(e){return X.t(`folder`,{folder:e})}function kI(e){let t=e.trim(),n=t.lastIndexOf(`.`);return n>=0&&n<t.length-1?t.slice(n+1,n+5).toUpperCase():X.t(`file`)}function AI(e){return new Promise((t,n)=>{let r=new FileReader;r.onerror=()=>{n(r.error??Error(C(`ui.promptEditor.failedToReadFile`,`Failed to read file`)))},r.onload=()=>{let e=r.result;if(typeof e!=`string`){n(Error(C(`ui.promptEditor.unexpectedFileReadResult`,`Unexpected file read result`)));return}let i=e.indexOf(`,`);t(i===-1?e:e.slice(i+1))},r.readAsDataURL(e)})}var jI={spellcheck:`true`,autocorrect:`on`,autocapitalize:`sentences`,writingsuggestions:`true`,dir:`auto`},MI={spellcheck:`false`,autocorrect:`off`,autocapitalize:`off`,writingsuggestions:`false`,dir:`auto`};function NI(e){return bc(e).kind===`normal`?jI:MI}function PI(e){return w.number(Number.isFinite(e)?e:0,{notation:`compact`,maximumFractionDigits:+(e>=1e3&&e<1e4||e>=1e6&&e<1e7)})}function FI(e){let t=Number.isFinite(e)?e:0,n=t===0?0:t<.01?4:2;return w.number(t,{style:`currency`,currency:`USD`,minimumFractionDigits:n,maximumFractionDigits:n})}var II={empty:x(`No session status yet`,`Status bar before session statistics arrive`),contextSize:x(`context {size}`,`Status bar context window size when usage is unavailable; size is a regionally formatted token count`),contextUsage:x(`{percent}/{size}`,`Compact context usage and window size; percent includes its localized percent sign, size is a formatted token count`),contextUnknown:x(`context unknown`,`Status bar when the context window size is unavailable`),queued:x(`{count, plural, one {# queued} other {# queued}}`,`Pending session message count in the compact status bar`),minimizeWarnings:x(`{count, plural, one {Minimise # warning} other {Minimise # warnings}}`,`Warning toggle accessible label and tooltip when expanded`),showWarnings:x(`{count, plural, one {Show # warning in the warning area} other {Show # warnings in the warning area}}`,`Warning toggle accessible label and tooltip when collapsed`)},LI=w.registerMessages(`core.statusBar`,II),RI=class extends O{constructor(){super(),o.createController(this),new S(this)}render(){let e=this.status;if(e===void 0)return D`<div class="bar muted">${LI.t(`empty`)}</div>`;let t=e.contextUsage,n=t?t.percent==null?LI.t(`contextSize`,{size:PI(t.contextWindow)}):LI.t(`contextUsage`,{percent:w.number(t.percent/100,{style:`percent`,minimumFractionDigits:1,maximumFractionDigits:1}),size:PI(t.contextWindow)}):LI.t(`contextUnknown`),r=e.tokens;return D`
2682
2682
  <div class="bar">
2683
- <span class="token-input">↑${NI(r.input)}</span>
2684
- <span class="token-output">↓${NI(r.output)}</span>
2683
+ <span class="token-input">↑${PI(r.input)}</span>
2684
+ <span class="token-output">↓${PI(r.output)}</span>
2685
2685
  <span class="context" title=${C(`ui.statusBar.contextUsage`,`Context usage`)}>${n}</span>
2686
- <span class="cost" title=${C(`ui.statusBar.sessionCost`,`Session cost`)}>${PI(e.cost)}</span>
2687
- ${e.pendingMessageCount>0?D`<span>${II.t(`queued`,{count:e.pendingMessageCount})}</span>`:null}
2686
+ <span class="cost" title=${C(`ui.statusBar.sessionCost`,`Session cost`)}>${FI(e.cost)}</span>
2687
+ ${e.pendingMessageCount>0?D`<span>${LI.t(`queued`,{count:e.pendingMessageCount})}</span>`:null}
2688
2688
  </div>
2689
- `}static{this.styles=tf}};g([y({attribute:!1})],LI.prototype,`status`,void 0),LI=g([_(`status-bar`)],LI);function RI(e){return e.composedPath().some(e=>e instanceof HTMLButtonElement||e instanceof HTMLAnchorElement&&e.hasAttribute(`href`))}function zI(e,t,n,r){let i=t?C(`ui.main.963044ce5371`,`{arg0} is already the default for new sessions`,{arg0:e}):A.t(`useDefault`,{label:e});return D`<button type="button" class="default-pin ui-button ui-button--icon" aria-label=${i} title=${i}
2689
+ `}static{this.styles=tf}};g([y({attribute:!1})],RI.prototype,`status`,void 0),RI=g([_(`status-bar`)],RI);function zI(e){return e.composedPath().some(e=>e instanceof HTMLButtonElement||e instanceof HTMLAnchorElement&&e.hasAttribute(`href`))}function BI(e,t,n,r){let i=t?C(`ui.main.963044ce5371`,`{arg0} is already the default for new sessions`,{arg0:e}):A.t(`useDefault`,{label:e});return D`<button type="button" class="default-pin ui-button ui-button--icon" aria-label=${i} title=${i}
2690
2690
  aria-pressed=${String(t)} ?disabled=${n} @click=${r}>
2691
2691
  <svg aria-hidden="true" viewBox="0 0 24 24" width="18" height="18" fill=${t?`currentColor`:`none`} stroke="currentColor" stroke-width="1.8">
2692
2692
  <path d="M12 3.2 14.7 8.7l6 .9-4.4 4.2 1 6-5.3-2.8L6.7 19.8l1-6L3.3 9.6l6-.9z" />
2693
2693
  </svg>
2694
- </button>`}function BI(){return D`<div class="default-help"><strong>${A.t(`defaultHelp`)}</strong></div>`}var VI=T`
2694
+ </button>`}function VI(){return D`<div class="default-help"><strong>${A.t(`defaultHelp`)}</strong></div>`}var HI=T`
2695
2695
  @layer pi-web-base {
2696
2696
  .default-help { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 4px 12px; padding: 8px 12px; color: var(--pi-muted); }
2697
2697
  .default-pin { align-self: stretch; }
2698
2698
  .default-pin[aria-pressed="true"] svg { color: var(--pi-accent); }
2699
2699
 
2700
2700
  }
2701
- `,HI=class extends O{constructor(){super(),this.title=``,this.searchable=!1,this.options=[],this.defaultsLoading=!1,this.selectedIndex=0,this.query=``,this.defaultPending=!1,o.createController(this),new S(this)}render(){let e=this.filteredOptions();return D`
2701
+ `,UI=class extends O{constructor(){super(),this.title=``,this.searchable=!1,this.options=[],this.defaultsLoading=!1,this.selectedIndex=0,this.query=``,this.defaultPending=!1,o.createController(this),new S(this)}render(){let e=this.filteredOptions();return D`
2702
2702
  <modal-surface .onClose=${()=>this.onCancel?.()} .initialFocus=${this.searchable?`input`:`.options`} .label=${this.title||A.t(`select`)} @keydown=${e=>{this.handleKeyDown(e)}}>
2703
2703
  <header class="ui-dialog-header">
2704
2704
  <strong class="ui-dialog-title">${this.title||A.t(`select`)}</strong>
2705
2705
  <button class="ui-button ui-button--icon" aria-label="${A.t(`close`)}" @click=${()=>this.onCancel?.()}>×</button>
2706
2706
  </header>
2707
2707
  ${this.searchable?D`<div class="ui-dialog-search-row"><input class="ui-dialog-search" placeholder="${A.t(`search`)}" .value=${this.query} @input=${e=>{this.handleSearchInput(e)}}></div>`:null}
2708
- ${this.onSetDefault===void 0?E:BI()}
2708
+ ${this.onSetDefault===void 0?E:VI()}
2709
2709
  <div class="options ui-selection-list" tabindex="0">
2710
2710
  ${e.map((e,t)=>this.renderOption(e,t))}
2711
2711
  ${e.length===0?D`<div class="empty ui-dialog-empty">${A.t(`noOptions`)}</div>`:null}
2712
2712
  </div>
2713
2713
  </modal-surface>
2714
2714
  `}firstUpdated(){this.selectInitialValue()}renderOption(e,t){let n=D`
2715
- <button class=${`ui-button ui-selection-option ${t===this.selectedIndex?`selected`:``}`} aria-current=${t===this.selectedIndex?`true`:E} ${hI(t===this.selectedIndex,e.value)} @focus=${()=>{this.selectedIndex=t}} @click=${()=>this.onPick?.(e.value)}>
2715
+ <button class=${`ui-button ui-selection-option ${t===this.selectedIndex?`selected`:``}`} aria-current=${t===this.selectedIndex?`true`:E} ${gI(t===this.selectedIndex,e.value)} @focus=${()=>{this.selectedIndex=t}} @click=${()=>this.onPick?.(e.value)}>
2716
2716
  <span>${e.label}</span>
2717
2717
  ${e.description!==void 0&&e.description!==``?D`<small class="ui-selection-detail">${e.description}</small>`:null}
2718
2718
  </button>
2719
- `;return this.onSetDefault===void 0?n:D`<div class="default-row ui-selection-row">${n}${zI(e.label,e.value===this.defaultValue,this.defaultsLoading||this.defaultPending,()=>{this.setDefault(e.value)})}</div>`}async setDefault(e){if(!(this.onSetDefault===void 0||this.defaultsLoading||this.defaultPending)){this.defaultPending=!0;try{await this.onSetDefault(e)}catch(e){console.warn(`Failed to set default option`,e)}finally{this.defaultPending=!1}}}selectInitialValue(){if(this.selectedValue===void 0)return;let e=this.filteredOptions().findIndex(e=>e.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){let e=this.query.trim().toLowerCase();return e===``?this.options:this.options.filter(t=>`${t.label} ${t.description??``} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){if(RI(e))return;let t=this.filteredOptions();if(e.key===`ArrowDown`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key===`ArrowUp`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key===`Enter`){e.preventDefault();let n=t[this.selectedIndex];n&&this.onPick?.(n.value)}}static{this.styles=[We,Ge,VI]}};g([y()],HI.prototype,`title`,void 0),g([y({type:Boolean})],HI.prototype,`searchable`,void 0),g([y({attribute:!1})],HI.prototype,`options`,void 0),g([y({attribute:!1})],HI.prototype,`selectedValue`,void 0),g([y({attribute:!1})],HI.prototype,`defaultValue`,void 0),g([y({type:Boolean})],HI.prototype,`defaultsLoading`,void 0),g([y({attribute:!1})],HI.prototype,`onPick`,void 0),g([y({attribute:!1})],HI.prototype,`onSetDefault`,void 0),g([y({attribute:!1})],HI.prototype,`onCancel`,void 0),g([v()],HI.prototype,`selectedIndex`,void 0),g([v()],HI.prototype,`query`,void 0),g([v()],HI.prototype,`defaultPending`,void 0),HI=g([_(`command-picker`)],HI);function UI(e){return`${e.provider}/${e.id}`}function WI(e,t){let n=t.trim().toLowerCase();return n===``?[...e]:e.filter(e=>`${e.label} ${e.description??``} ${e.value}`.toLowerCase().includes(n))}function GI(e){return e.every(e=>e.catalogIndex!==void 0)?[...e].sort((e,t)=>(e.catalogIndex??0)-(t.catalogIndex??0)):[...e]}function KI(e,t,n){let r=GI(e),i=new Map(r.map(e=>[UI(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(UI(e)))],s=t.trim().toLowerCase();return{rows:s===``?o:o.filter(e=>`${e.provider} ${e.id} ${e.name??``}`.toLowerCase().includes(s))}}function qI(e,t){let n=e.filter(e=>e.enabled),r=t===void 0?void 0:e.find(e=>UI(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 JI=class extends O{constructor(){super(),this.title=``,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=[],o.createController(this),new S(this)}render(){let e=this.visibleRows();return D`
2719
+ `;return this.onSetDefault===void 0?n:D`<div class="default-row ui-selection-row">${n}${BI(e.label,e.value===this.defaultValue,this.defaultsLoading||this.defaultPending,()=>{this.setDefault(e.value)})}</div>`}async setDefault(e){if(!(this.onSetDefault===void 0||this.defaultsLoading||this.defaultPending)){this.defaultPending=!0;try{await this.onSetDefault(e)}catch(e){console.warn(`Failed to set default option`,e)}finally{this.defaultPending=!1}}}selectInitialValue(){if(this.selectedValue===void 0)return;let e=this.filteredOptions().findIndex(e=>e.value===this.selectedValue);e>=0&&(this.selectedIndex=e)}handleSearchInput(e){e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}filteredOptions(){let e=this.query.trim().toLowerCase();return e===``?this.options:this.options.filter(t=>`${t.label} ${t.description??``} ${t.value}`.toLowerCase().includes(e))}handleKeyDown(e){if(zI(e))return;let t=this.filteredOptions();if(e.key===`ArrowDown`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex+1)%t.length);else if(e.key===`ArrowUp`)e.preventDefault(),t.length>0&&(this.selectedIndex=(this.selectedIndex-1+t.length)%t.length);else if(e.key===`Enter`){e.preventDefault();let n=t[this.selectedIndex];n&&this.onPick?.(n.value)}}static{this.styles=[We,Ge,HI]}};g([y()],UI.prototype,`title`,void 0),g([y({type:Boolean})],UI.prototype,`searchable`,void 0),g([y({attribute:!1})],UI.prototype,`options`,void 0),g([y({attribute:!1})],UI.prototype,`selectedValue`,void 0),g([y({attribute:!1})],UI.prototype,`defaultValue`,void 0),g([y({type:Boolean})],UI.prototype,`defaultsLoading`,void 0),g([y({attribute:!1})],UI.prototype,`onPick`,void 0),g([y({attribute:!1})],UI.prototype,`onSetDefault`,void 0),g([y({attribute:!1})],UI.prototype,`onCancel`,void 0),g([v()],UI.prototype,`selectedIndex`,void 0),g([v()],UI.prototype,`query`,void 0),g([v()],UI.prototype,`defaultPending`,void 0),UI=g([_(`command-picker`)],UI);function WI(e){return`${e.provider}/${e.id}`}function GI(e,t){let n=t.trim().toLowerCase();return n===``?[...e]:e.filter(e=>`${e.label} ${e.description??``} ${e.value}`.toLowerCase().includes(n))}function KI(e){return e.every(e=>e.catalogIndex!==void 0)?[...e].sort((e,t)=>(e.catalogIndex??0)-(t.catalogIndex??0)):[...e]}function qI(e,t,n){let r=KI(e),i=new Map(r.map(e=>[WI(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(WI(e)))],s=t.trim().toLowerCase();return{rows:s===``?o:o.filter(e=>`${e.provider} ${e.id} ${e.name??``}`.toLowerCase().includes(s))}}function JI(e,t){let n=e.filter(e=>e.enabled),r=t===void 0?void 0:e.find(e=>WI(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 YI=class extends O{constructor(){super(),this.title=``,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=[],o.createController(this),new S(this)}render(){let e=this.visibleRows();return D`
2720
2720
  <modal-surface
2721
2721
  .onClose=${()=>this.onCancel?.()}
2722
2722
  .initialFocus=${`input.search`}
@@ -2737,7 +2737,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2737
2737
  <span>${A.rich(`overrideNotice`,{path:`.pi/settings.json`,code:e=>D`<code dir="ltr">${e}</code>`})}</span>
2738
2738
  </div>
2739
2739
  `}
2740
- ${this.onSetDefault===void 0?E:BI()}
2740
+ ${this.onSetDefault===void 0?E:VI()}
2741
2741
  <div class="search-row ui-dialog-search-row">
2742
2742
  <input class="search ui-dialog-search" aria-label=${A.t(`searchModels`)} placeholder=${A.t(`search`)} .value=${this.query} @input=${e=>{this.handleSearchInput(e)}}>
2743
2743
  ${this.mode===`all`?this.renderToggleAllButton():E}
@@ -2753,7 +2753,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2753
2753
  ${e.length===0?D`<div class="empty ui-dialog-empty">${A.t(`noOptions`)}</div>`:null}
2754
2754
  </div>
2755
2755
  </modal-surface>
2756
- `}willUpdate(e){if(this.hasUpdated||this.anchorSelectionToSelectedValue(),!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=KI(t,this.query,this.catalogOrder).rows[this.selectedIndex],r=KI(this.catalog,this.query,this.catalogOrder).rows,i=n===void 0?void 0:UI(n),a=i===void 0?-1:r.findIndex(e=>UI(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 D`<button class="ui-button" ?disabled=${this.membershipChangePending} aria-pressed=${this.mode===e?`true`:`false`} @click=${()=>{this.selectMode(e)}}>${t}</button>`}renderToggleAllButton(){let e=qI(this.catalog,this.selectedValue),t=e.mode===`all`?A.t(`selectAll`):A.t(`deselectAll`);return D`
2756
+ `}willUpdate(e){if(this.hasUpdated||this.anchorSelectionToSelectedValue(),!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=qI(t,this.query,this.catalogOrder).rows[this.selectedIndex],r=qI(this.catalog,this.query,this.catalogOrder).rows,i=n===void 0?void 0:WI(n),a=i===void 0?-1:r.findIndex(e=>WI(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 D`<button class="ui-button" ?disabled=${this.membershipChangePending} aria-pressed=${this.mode===e?`true`:`false`} @click=${()=>{this.selectMode(e)}}>${t}</button>`}renderToggleAllButton(){let e=JI(this.catalog,this.selectedValue),t=e.mode===`all`?A.t(`selectAll`):A.t(`deselectAll`);return D`
2757
2757
  <button
2758
2758
  class="toggle-all ui-button"
2759
2759
  ?disabled=${!this.modelScopeEditable||!e.canApply||!e.hasChanges||this.toggleAllPending||this.pendingToggles.size>0}
@@ -2762,13 +2762,13 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2762
2762
  @click=${()=>{this.requestToggleAll()}}
2763
2763
  >${t}</button>
2764
2764
  <span id="model-scope-status" class="scope-status" aria-live="polite">${this.membershipChangePending?A.t(`updating`):this.modelScopeEditable?e.canApply?E:A.t(`unavailableCurrent`):A.t(`workspaceControl`)}</span>
2765
- `}rememberCatalogOrder(){let e=new Set(this.catalogOrder);for(let t of KI(this.catalog,``).rows){let n=UI(t);e.has(n)||(e.add(n),this.catalogOrder.push(n))}}renderEnabledList(){return WI(this.options,this.query).map((e,t)=>{let n=D`
2766
- <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`:E} ${hI(t===this.selectedIndex,e.value)} @focus=${()=>{this.selectedIndex=t}} @click=${()=>this.onPick?.(e.value)}>
2765
+ `}rememberCatalogOrder(){let e=new Set(this.catalogOrder);for(let t of qI(this.catalog,``).rows){let n=WI(t);e.has(n)||(e.add(n),this.catalogOrder.push(n))}}renderEnabledList(){return GI(this.options,this.query).map((e,t)=>{let n=D`
2766
+ <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`:E} ${gI(t===this.selectedIndex,e.value)} @focus=${()=>{this.selectedIndex=t}} @click=${()=>this.onPick?.(e.value)}>
2767
2767
  <span>${e.label}</span>
2768
2768
  ${e.description!==void 0&&e.description!==``?D`<small class="ui-selection-detail">${e.description}</small>`:null}
2769
2769
  </button>
2770
- `;return this.onSetDefault===void 0?n:D`<div class="default-row ui-selection-row">${n}${zI(e.label,e.value===this.defaultValue,this.defaultsLoading||this.defaultPending||this.membershipChangePending||this.catalog.find(t=>UI(t)===e.value)?.enabled===!1,()=>{this.setDefault(e.value)})}</div>`})}renderCatalogList(){let e=KI(this.catalog,this.query,this.catalogOrder).rows;return D`${qe(e,UI,(e,t)=>this.renderCatalogRow(e,t))}`}renderDefaultPin(e,t,n){return this.onSetDefault?zI(t,e===this.defaultValue,!n||this.defaultsLoading||this.defaultPending||this.membershipChangePending,()=>{this.setDefault(e)}):E}async setDefault(e){if(!(this.onSetDefault===void 0||this.defaultsLoading||this.defaultPending||this.membershipChangePending)&&this.catalog.find(t=>UI(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=UI(e),r=t===this.selectedIndex,i=n===this.selectedValue&&e.enabled,a=!this.modelScopeEditable||this.membershipChangePending||i,o=this.modelScopeEditable?i?A.t(`protectedModel`,{model:n}):A.t(e.enabled?`disableModel`:`enableModel`,{model:n}):A.t(`controlledModel`,{model:n});return D`
2771
- <div class="catalog-row ui-selection-row ${r?`selected`:``}" data-model-value=${n} ${hI(r,n)}>
2770
+ `;return this.onSetDefault===void 0?n:D`<div class="default-row ui-selection-row">${n}${BI(e.label,e.value===this.defaultValue,this.defaultsLoading||this.defaultPending||this.membershipChangePending||this.catalog.find(t=>WI(t)===e.value)?.enabled===!1,()=>{this.setDefault(e.value)})}</div>`})}renderCatalogList(){let e=qI(this.catalog,this.query,this.catalogOrder).rows;return D`${qe(e,WI,(e,t)=>this.renderCatalogRow(e,t))}`}renderDefaultPin(e,t,n){return this.onSetDefault?BI(t,e===this.defaultValue,!n||this.defaultsLoading||this.defaultPending||this.membershipChangePending,()=>{this.setDefault(e)}):E}async setDefault(e){if(!(this.onSetDefault===void 0||this.defaultsLoading||this.defaultPending||this.membershipChangePending)&&this.catalog.find(t=>WI(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=WI(e),r=t===this.selectedIndex,i=n===this.selectedValue&&e.enabled,a=!this.modelScopeEditable||this.membershipChangePending||i,o=this.modelScopeEditable?i?A.t(`protectedModel`,{model:n}):A.t(e.enabled?`disableModel`:`enableModel`,{model:n}):A.t(`controlledModel`,{model:n});return D`
2771
+ <div class="catalog-row ui-selection-row ${r?`selected`:``}" data-model-value=${n} ${gI(r,n)}>
2772
2772
  <label class="membership-checkbox">
2773
2773
  <input
2774
2774
  type="checkbox"
@@ -2793,7 +2793,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2793
2793
  </button>
2794
2794
  ${this.renderDefaultPin(n,e.name??e.id,e.enabled)}
2795
2795
  </div>
2796
- `}visibleRows(){return this.mode===`all`?KI(this.catalog,this.query,this.catalogOrder).rows.map(e=>({value:UI(e),entry:e})):WI(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(RI(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=UI(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=qI(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=[We,Ge,t,VI,T`
2796
+ `}visibleRows(){return this.mode===`all`?qI(this.catalog,this.query,this.catalogOrder).rows.map(e=>({value:WI(e),entry:e})):GI(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(zI(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=WI(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=JI(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=[We,Ge,t,HI,T`
2797
2797
  @layer pi-web-base {
2798
2798
  .scope-toggle { border-bottom: 1px solid var(--pi-border-muted); }
2799
2799
  .scope-toggle button { flex: 1; }
@@ -2806,7 +2806,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2806
2806
  .membership-checkbox input { margin: 0; accent-color: var(--pi-accent); }
2807
2807
 
2808
2808
  }
2809
- `]}};g([y()],JI.prototype,`title`,void 0),g([y({attribute:!1})],JI.prototype,`options`,void 0),g([y({attribute:!1})],JI.prototype,`catalog`,void 0),g([y({attribute:!1})],JI.prototype,`selectedValue`,void 0),g([y({attribute:!1})],JI.prototype,`defaultValue`,void 0),g([y({type:Boolean})],JI.prototype,`defaultsLoading`,void 0),g([y({attribute:!1})],JI.prototype,`onPick`,void 0),g([y({attribute:!1})],JI.prototype,`onSetDefault`,void 0),g([y({attribute:!1})],JI.prototype,`onCancel`,void 0),g([y({attribute:!1})],JI.prototype,`onToggleEnabled`,void 0),g([y({attribute:!1})],JI.prototype,`onSetScope`,void 0),g([v()],JI.prototype,`mode`,void 0),g([v()],JI.prototype,`defaultPending`,void 0),g([v()],JI.prototype,`selectedIndex`,void 0),g([v()],JI.prototype,`query`,void 0),g([v()],JI.prototype,`pendingToggles`,void 0),g([v()],JI.prototype,`toggleAllPending`,void 0),JI=g([_(`model-picker`)],JI);var YI=class extends O{constructor(){super(),this.actions=[],this.queryText=``,this.selectedIndex=0,o.createController(this),new S(this)}render(){let e=this.filteredActions();return D`
2809
+ `]}};g([y()],YI.prototype,`title`,void 0),g([y({attribute:!1})],YI.prototype,`options`,void 0),g([y({attribute:!1})],YI.prototype,`catalog`,void 0),g([y({attribute:!1})],YI.prototype,`selectedValue`,void 0),g([y({attribute:!1})],YI.prototype,`defaultValue`,void 0),g([y({type:Boolean})],YI.prototype,`defaultsLoading`,void 0),g([y({attribute:!1})],YI.prototype,`onPick`,void 0),g([y({attribute:!1})],YI.prototype,`onSetDefault`,void 0),g([y({attribute:!1})],YI.prototype,`onCancel`,void 0),g([y({attribute:!1})],YI.prototype,`onToggleEnabled`,void 0),g([y({attribute:!1})],YI.prototype,`onSetScope`,void 0),g([v()],YI.prototype,`mode`,void 0),g([v()],YI.prototype,`defaultPending`,void 0),g([v()],YI.prototype,`selectedIndex`,void 0),g([v()],YI.prototype,`query`,void 0),g([v()],YI.prototype,`pendingToggles`,void 0),g([v()],YI.prototype,`toggleAllPending`,void 0),YI=g([_(`model-picker`)],YI);var XI=class extends O{constructor(){super(),this.actions=[],this.queryText=``,this.selectedIndex=0,o.createController(this),new S(this)}render(){let e=this.filteredActions();return D`
2810
2810
  <modal-surface
2811
2811
  .onClose=${()=>this.onCancel?.()}
2812
2812
  .initialFocus=${`input`}
@@ -2828,7 +2828,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2828
2828
  ?disabled=${e.enabled===!1}
2829
2829
  title=${e.disabledReason??e.title}
2830
2830
  aria-current=${t===this.selectedIndex?`true`:E}
2831
- ${hI(t===this.selectedIndex,e.id)}
2831
+ ${gI(t===this.selectedIndex,e.id)}
2832
2832
  @focus=${()=>{this.selectedIndex=t}}
2833
2833
  @click=${()=>{this.run(e)}}
2834
2834
  >
@@ -2843,14 +2843,14 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2843
2843
  `})}
2844
2844
  </div>
2845
2845
  </modal-surface>
2846
- `}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 XI(this.actions,this.queryText)}handleKeyDown(e){if(RI(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=[We,Ge,T`
2846
+ `}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 ZI(this.actions,this.queryText)}handleKeyDown(e){if(zI(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=[We,Ge,T`
2847
2847
  .heading, .details { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 12px; min-width: 0; }
2848
2848
  strong { flex: 1 1 12ch; min-width: 0; }
2849
2849
  .description { flex: 1 1 24ch; min-width: 0; font: inherit; }
2850
2850
  .disabled-reason { color: var(--pi-warning); }
2851
2851
  .group { flex: 0 1 auto; min-width: 0; max-width: 100%; margin-inline-start: auto; text-align: end; font-size: 12px; }
2852
2852
  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; }
2853
- `]}};g([y({attribute:!1})],YI.prototype,`actions`,void 0),g([y({attribute:!1})],YI.prototype,`onRun`,void 0),g([y({attribute:!1})],YI.prototype,`onCancel`,void 0),g([v()],YI.prototype,`queryText`,void 0),g([v()],YI.prototype,`selectedIndex`,void 0),YI=g([_(`action-palette`)],YI);function XI(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 ZI=class extends O{constructor(){super(),this.selectedIndex=0,this.query=``,new S(this),o.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 D`
2853
+ `]}};g([y({attribute:!1})],XI.prototype,`actions`,void 0),g([y({attribute:!1})],XI.prototype,`onRun`,void 0),g([y({attribute:!1})],XI.prototype,`onCancel`,void 0),g([v()],XI.prototype,`queryText`,void 0),g([v()],XI.prototype,`selectedIndex`,void 0),XI=g([_(`action-palette`)],XI);function ZI(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 QI=class extends O{constructor(){super(),this.selectedIndex=0,this.query=``,new S(this),o.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 D`
2854
2854
  <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)}}>
2855
2855
  <header class="ui-dialog-header">
2856
2856
  <strong class="ui-dialog-title">${this.dialogTitle(e)}</strong>
@@ -2858,7 +2858,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2858
2858
  </header>
2859
2859
  ${this.renderBody(e)}
2860
2860
  </modal-surface>
2861
- `}willUpdate(e){if(e.has(`state`)&&aL(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=aL(e.get(`state`));if(t===void 0)return;let n=this.state?.step,r=t!==n,i=t===`oauth`&&n===`oauth`&&rL(e.get(`state`))!==rL(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 P.t(`methodTitle`)+t;case`starting`:return e.mode===void 0?e.title:P.t(e.mode===`login`?`startMcpLogin`:`startMcpLogout`);case`providers`:return P.t(e.authType===void 0?`selectProvider`:e.authType===`oauth`?`selectSubscription`:`selectCredentials`)+t;case`apiKey`:return C(`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?P.t(`mcpAuthentication`):e.flow.select===void 0?P.t(e.flow.mcpMode===`login`?`mcpLoginProvider`:`mcpLogoutProvider`,{provider:e.flow.providerName}):P.t(e.flow.mcpMode===`login`?`mcpLogin`:`mcpLogout`):P.t(`loginProvider`,{provider:e.flow.providerName})+t;case`logout`:return P.t(`removeTitle`)+t}}renderBody(e){let t=e.target.projectName===void 0?C(`ui.authDialog.currentMode`,`current mode`):C(`ui.authDialog.currentProject`,`current project`);switch(e.step){case`starting`:return D`<div class="form ui-dialog-body ui-form-body">
2861
+ `}willUpdate(e){if(e.has(`state`)&&oL(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=oL(e.get(`state`));if(t===void 0)return;let n=this.state?.step,r=t!==n,i=t===`oauth`&&n===`oauth`&&iL(e.get(`state`))!==iL(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 P.t(`methodTitle`)+t;case`starting`:return e.mode===void 0?e.title:P.t(e.mode===`login`?`startMcpLogin`:`startMcpLogout`);case`providers`:return P.t(e.authType===void 0?`selectProvider`:e.authType===`oauth`?`selectSubscription`:`selectCredentials`)+t;case`apiKey`:return C(`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?P.t(`mcpAuthentication`):e.flow.select===void 0?P.t(e.flow.mcpMode===`login`?`mcpLoginProvider`:`mcpLogoutProvider`,{provider:e.flow.providerName}):P.t(e.flow.mcpMode===`login`?`mcpLogin`:`mcpLogout`):P.t(`loginProvider`,{provider:e.flow.providerName})+t;case`logout`:return P.t(`removeTitle`)+t}}renderBody(e){let t=e.target.projectName===void 0?C(`ui.authDialog.currentMode`,`current mode`):C(`ui.authDialog.currentProject`,`current project`);switch(e.step){case`starting`:return D`<div class="form ui-dialog-body ui-form-body">
2862
2862
  ${e.error===void 0?D`<p role="status">${P.t(`startingMcp`)}</p>`:D`<p class="ui-form-error" role="alert">${e.error}</p>`}
2863
2863
  <div class="ui-form-actions"><button class="ui-button" @click=${()=>{this.onCancel?.()}}>${e.error===void 0?P.t(`cancel`):P.t(`close`)}</button></div>
2864
2864
  </div>`;case`method`:case`providers`:case`logout`:return this.renderOptionList(e,t);case`apiKey`:return D`
@@ -2876,13 +2876,13 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2876
2876
  `:null}
2877
2877
  <div class="options ui-selection-list">
2878
2878
  ${n.length===0?D`<div class="empty ui-dialog-empty">${i}</div>`:r.length===0?D`<div class="empty ui-dialog-empty">${P.t(`noMatches`)}</div>`:r.map((e,t)=>D`
2879
- <button class=${t===this.selectedIndex?`ui-button ui-selection-option selected`:`ui-button ui-selection-option`} aria-current=${t===this.selectedIndex?`true`:E} ${hI(t===this.selectedIndex,e.key)} @focus=${()=>{this.selectedIndex=t}} @click=${()=>{e.run()}}>
2879
+ <button class=${t===this.selectedIndex?`ui-button ui-selection-option selected`:`ui-button ui-selection-option`} aria-current=${t===this.selectedIndex?`true`:E} ${gI(t===this.selectedIndex,e.key)} @focus=${()=>{this.selectedIndex=t}} @click=${()=>{e.run()}}>
2880
2880
  <span>${e.title}</span>
2881
2881
  <small class="ui-selection-detail"><bdi>${e.detail}</bdi></small>
2882
2882
  </button>
2883
2883
  `)}
2884
2884
  </div>
2885
- `}optionsFor(e,t=e.target.projectName===void 0?C(`ui.authDialog.currentMode`,`current mode`):C(`ui.authDialog.currentProject`,`current project`)){switch(e.step){case`method`:return[{key:`oauth`,title:P.t(`subscription`),detail:C(`ui.authDialog.chatgptPlusProClaudeProMaxOrGithub`,`ChatGPT Plus/Pro, Claude Pro/Max, or GitHub Copilot`),searchText:P.t(`subscription`),run:()=>{this.onChooseMethod?.(`oauth`)}},{key:`api_key`,title:C(`ui.authDialog.useApiKey`,`Use API key`),detail:C(`ui.authDialog.credentialDestination`,`Save the API key in auth.json for the {scope}`,{scope:t}),searchText:C(`ui.authDialog.useApiKey`,`Use API key`),run:()=>{this.onChooseMethod?.(`api_key`)}}];case`providers`:return e.providers.map(e=>({key:`${e.id}:${e.authType}`,title:D`<bdi>${e.name}</bdi>${e.status.source===void 0?null:D` <em>${oL(e)}</em>`}`,detail:P.t(`providerDetail`,{provider:e.id,type:nL(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:P.t(`providerDetail`,{provider:e.id,type:nL(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=QI(i?.promptType),c=(n||tL(e.target.machineId,window.location.hostname))&&t.status===`running`&&(n?i!==void 0&&t.auth!==void 0:i?.promptType===`manual_code`);return D`
2885
+ `}optionsFor(e,t=e.target.projectName===void 0?C(`ui.authDialog.currentMode`,`current mode`):C(`ui.authDialog.currentProject`,`current project`)){switch(e.step){case`method`:return[{key:`oauth`,title:P.t(`subscription`),detail:C(`ui.authDialog.chatgptPlusProClaudeProMaxOrGithub`,`ChatGPT Plus/Pro, Claude Pro/Max, or GitHub Copilot`),searchText:P.t(`subscription`),run:()=>{this.onChooseMethod?.(`oauth`)}},{key:`api_key`,title:C(`ui.authDialog.useApiKey`,`Use API key`),detail:C(`ui.authDialog.credentialDestination`,`Save the API key in auth.json for the {scope}`,{scope:t}),searchText:C(`ui.authDialog.useApiKey`,`Use API key`),run:()=>{this.onChooseMethod?.(`api_key`)}}];case`providers`:return e.providers.map(e=>({key:`${e.id}:${e.authType}`,title:D`<bdi>${e.name}</bdi>${e.status.source===void 0?null:D` <em>${sL(e)}</em>`}`,detail:P.t(`providerDetail`,{provider:e.id,type:rL(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:P.t(`providerDetail`,{provider:e.id,type:rL(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=$I(i?.promptType),c=(n||nL(e.target.machineId,window.location.hostname))&&t.status===`running`&&(n?i!==void 0&&t.auth!==void 0:i?.promptType===`manual_code`);return D`
2886
2886
  <div class="form ui-dialog-body ui-form-body">
2887
2887
  ${o&&t.auth!==void 0?D`
2888
2888
  <p>${n?P.t(`approveBrowser`):P.t(`authorizationLink`)}</p>
@@ -2922,7 +2922,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2922
2922
  ${r?null:D`<div class="actions ui-form-actions"><button class="ui-button" @click=${()=>{this.cancel()}}>${P.t(`close`)}</button></div>`}
2923
2923
  ${i===void 0&&(a===void 0||n)&&r?D`<div class="actions ui-form-actions"><button class="ui-button" @click=${()=>{t.cancelRequested===!0?this.onCancel?.():this.onOAuthCancel?.()}}>${P.t(t.cancelRequested===!0?`close`:`cancel`)}</button></div>`:null}
2924
2924
  </div>
2925
- `}handleKeyDown(e){let t=this.state;if(!(t===void 0||RI(e))){if(e.key===`ArrowDown`||e.key===`ArrowUp`){let n=this.visibleOptions(t);if(n.length===0)return;e.preventDefault();let r=e.key===`ArrowDown`?1:-1;this.selectedIndex=(this.selectedIndex+r+n.length)%n.length}else if(e.key===`Enter`){if(t.step===`apiKey`)e.preventDefault(),this.onSaveApiKey?.();else if(t.step===`oauth`&&t.flow.status===`running`&&t.flow.cancelRequested!==!0&&t.flow.prompt!==void 0)e.preventDefault(),this.onOAuthRespond?.();else{let n=this.visibleOptions(t)[this.selectedIndex];if(n===void 0)return;e.preventDefault(),n.run()}}}}cancel(){let e=this.state;e?.step===`oauth`&&e.flow.cancelRequested!==!0?this.onOAuthCancel?.():this.onCancel?.()}initialFocus(e){return e.step===`apiKey`||e.step===`oauth`&&e.flow.status===`running`&&e.flow.cancelRequested!==!0&&e.flow.prompt!==void 0||(e.step===`providers`||e.step===`logout`)&&e.providers.length>0?`input`:void 0}static{this.styles=[We,Qe,Ge,T`
2925
+ `}handleKeyDown(e){let t=this.state;if(!(t===void 0||zI(e))){if(e.key===`ArrowDown`||e.key===`ArrowUp`){let n=this.visibleOptions(t);if(n.length===0)return;e.preventDefault();let r=e.key===`ArrowDown`?1:-1;this.selectedIndex=(this.selectedIndex+r+n.length)%n.length}else if(e.key===`Enter`){if(t.step===`apiKey`)e.preventDefault(),this.onSaveApiKey?.();else if(t.step===`oauth`&&t.flow.status===`running`&&t.flow.cancelRequested!==!0&&t.flow.prompt!==void 0)e.preventDefault(),this.onOAuthRespond?.();else{let n=this.visibleOptions(t)[this.selectedIndex];if(n===void 0)return;e.preventDefault(),n.run()}}}}cancel(){let e=this.state;e?.step===`oauth`&&e.flow.cancelRequested!==!0?this.onOAuthCancel?.():this.onCancel?.()}initialFocus(e){return e.step===`apiKey`||e.step===`oauth`&&e.flow.status===`running`&&e.flow.cancelRequested!==!0&&e.flow.prompt!==void 0||(e.step===`providers`||e.step===`logout`)&&e.providers.length>0?`input`:void 0}static{this.styles=[We,Qe,Ge,T`
2926
2926
  @layer pi-web-base {
2927
2927
  .form p { margin: 0; color: var(--pi-text-secondary); overflow-wrap: anywhere; }
2928
2928
  .form a { color: var(--pi-accent); overflow-wrap: anywhere; }
@@ -2933,12 +2933,12 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2933
2933
  em { color: var(--pi-success); font-style: normal; font-size: 12px; }
2934
2934
 
2935
2935
  }
2936
- `]}};g([y({attribute:!1})],ZI.prototype,`state`,void 0),g([y({attribute:!1})],ZI.prototype,`onChooseMethod`,void 0),g([y({attribute:!1})],ZI.prototype,`onSelectProvider`,void 0),g([y({attribute:!1})],ZI.prototype,`onApiKeyInput`,void 0),g([y({attribute:!1})],ZI.prototype,`onSaveApiKey`,void 0),g([y({attribute:!1})],ZI.prototype,`onLogoutProvider`,void 0),g([y({attribute:!1})],ZI.prototype,`onOAuthInput`,void 0),g([y({attribute:!1})],ZI.prototype,`onOAuthRespond`,void 0),g([y({attribute:!1})],ZI.prototype,`onOAuthCancel`,void 0),g([y({attribute:!1})],ZI.prototype,`onCancel`,void 0),g([Te(`modal-surface`)],ZI.prototype,`modalSurface`,void 0),g([v()],ZI.prototype,`selectedIndex`,void 0),g([v()],ZI.prototype,`query`,void 0),ZI=g([_(`auth-dialog`)],ZI);function QI(e){return e===`secret`?`password`:`text`}var $I=new Set([`localhost`,`127.0.0.1`,`::1`]);function eL(e){return $I.has(e.trim().replace(/^\[|\]$/gu,``).toLowerCase())}function tL(e,t){return e!==`local`||!eL(t)}function nL(e){return P.t(e===`oauth`?`typeSubscription`:`typeCredentials`)}function rL(e){if(aL(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?iL(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?iL(t.select):void 0;return i===void 0?`${n}:waiting:${`status`in t&&typeof t.status==`string`?t.status:`unknown`}`:`${n}:select:${i}`}function iL(e){if(typeof e==`object`&&e&&`requestId`in e)return typeof e.requestId==`string`?e.requestId:void 0}function aL(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 oL(e){if(e.status.source===void 0)return``;switch(e.status.source){case`stored`:return P.t(`configured`);case`environment`:return e.status.label===void 0?P.t(`environment`):P.t(`environmentLabel`,{label:e.status.label});case`runtime`:return P.t(`runtime`);case`fallback`:return P.t(`customKey`);case`models_json_key`:return P.t(`modelsKey`);case`models_json_command`:return P.t(`modelsCommand`);default:return``}}var sL=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 D`
2937
- <modal-surface .onClose=${this.mode===`change`?()=>this.onCancel?.():void 0} .busy=${this.loading} .initialFocus=${`input`} .label=${cL(this.mode)}>
2936
+ `]}};g([y({attribute:!1})],QI.prototype,`state`,void 0),g([y({attribute:!1})],QI.prototype,`onChooseMethod`,void 0),g([y({attribute:!1})],QI.prototype,`onSelectProvider`,void 0),g([y({attribute:!1})],QI.prototype,`onApiKeyInput`,void 0),g([y({attribute:!1})],QI.prototype,`onSaveApiKey`,void 0),g([y({attribute:!1})],QI.prototype,`onLogoutProvider`,void 0),g([y({attribute:!1})],QI.prototype,`onOAuthInput`,void 0),g([y({attribute:!1})],QI.prototype,`onOAuthRespond`,void 0),g([y({attribute:!1})],QI.prototype,`onOAuthCancel`,void 0),g([y({attribute:!1})],QI.prototype,`onCancel`,void 0),g([Te(`modal-surface`)],QI.prototype,`modalSurface`,void 0),g([v()],QI.prototype,`selectedIndex`,void 0),g([v()],QI.prototype,`query`,void 0),QI=g([_(`auth-dialog`)],QI);function $I(e){return e===`secret`?`password`:`text`}var eL=new Set([`localhost`,`127.0.0.1`,`::1`]);function tL(e){return eL.has(e.trim().replace(/^\[|\]$/gu,``).toLowerCase())}function nL(e,t){return e!==`local`||!tL(t)}function rL(e){return P.t(e===`oauth`?`typeSubscription`:`typeCredentials`)}function iL(e){if(oL(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?aL(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?aL(t.select):void 0;return i===void 0?`${n}:waiting:${`status`in t&&typeof t.status==`string`?t.status:`unknown`}`:`${n}:select:${i}`}function aL(e){if(typeof e==`object`&&e&&`requestId`in e)return typeof e.requestId==`string`?e.requestId:void 0}function oL(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 sL(e){if(e.status.source===void 0)return``;switch(e.status.source){case`stored`:return P.t(`configured`);case`environment`:return e.status.label===void 0?P.t(`environment`):P.t(`environmentLabel`,{label:e.status.label});case`runtime`:return P.t(`runtime`);case`fallback`:return P.t(`customKey`);case`models_json_key`:return P.t(`modelsKey`);case`models_json_command`:return P.t(`modelsCommand`);default:return``}}var cL=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 D`
2937
+ <modal-surface .onClose=${this.mode===`change`?()=>this.onCancel?.():void 0} .busy=${this.loading} .initialFocus=${`input`} .label=${lL(this.mode)}>
2938
2938
  <header>
2939
2939
  <div>
2940
2940
  <span class="eyebrow">${C(`ui.normalAuthDialog.normalMode`,`Normal mode`)}</span>
2941
- <h1>${cL(this.mode)}</h1>
2941
+ <h1>${lL(this.mode)}</h1>
2942
2942
  </div>
2943
2943
  ${this.mode===`change`?D`<button class="close-button" title=${C(`ui.normalAuthDialog.close`,`Close`)} aria-label=${C(`ui.normalAuthDialog.close`,`Close`)} @click=${()=>this.onCancel?.()}>×</button>`:null}
2944
2944
  </header>
@@ -2946,17 +2946,17 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2946
2946
  ${this.mode===`change`?D`
2947
2947
  <label>
2948
2948
  <span>${C(`ui.normalAuthDialog.currentPassword`,`Current password`)}</span>
2949
- <input type="password" .value=${this.currentPassword} autocomplete="current-password" @input=${e=>{this.currentPassword=uL(e),this.localError=``}}>
2949
+ <input type="password" .value=${this.currentPassword} autocomplete="current-password" @input=${e=>{this.currentPassword=dL(e),this.localError=``}}>
2950
2950
  </label>
2951
2951
  `:null}
2952
2952
  <label>
2953
2953
  <span>${this.mode===`login`?C(`ui.normalAuthDialog.password`,`Password`):C(`ui.normalAuthDialog.newPassword`,`New password`)}</span>
2954
- <input type="password" .value=${this.password} autocomplete=${this.mode===`login`?`current-password`:`new-password`} @input=${e=>{this.password=uL(e),this.localError=``}}>
2954
+ <input type="password" .value=${this.password} autocomplete=${this.mode===`login`?`current-password`:`new-password`} @input=${e=>{this.password=dL(e),this.localError=``}}>
2955
2955
  </label>
2956
2956
  ${this.mode===`login`?null:D`
2957
2957
  <label>
2958
2958
  <span>${C(`ui.normalAuthDialog.confirmPassword`,`Confirm password`)}</span>
2959
- <input type="password" .value=${this.confirmPassword} autocomplete="new-password" @input=${e=>{this.confirmPassword=uL(e),this.localError=``}}>
2959
+ <input type="password" .value=${this.confirmPassword} autocomplete="new-password" @input=${e=>{this.confirmPassword=dL(e),this.localError=``}}>
2960
2960
  </label>
2961
2961
  `}
2962
2962
  ${this.message()===``?null:D`<p class="message">${this.message()}</p>`}
@@ -2966,7 +2966,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2966
2966
  </footer>
2967
2967
  </form>
2968
2968
  </modal-surface>
2969
- `}submitLabel(){return this.mode===`setup`?C(`ui.normalAuthDialog.setPasswordAndEnter`,`Set password and enter`):this.mode===`change`?C(`ui.normalAuthDialog.savePassword`,`Save password`):C(`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=lL(this.mode,t);n===void 0?(this.localError=``,await this.onSubmit?.(t)):this.localError=n}static{this.styles=T`
2969
+ `}submitLabel(){return this.mode===`setup`?C(`ui.normalAuthDialog.setPasswordAndEnter`,`Set password and enter`):this.mode===`change`?C(`ui.normalAuthDialog.savePassword`,`Save password`):C(`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=uL(this.mode,t);n===void 0?(this.localError=``,await this.onSubmit?.(t)):this.localError=n}static{this.styles=T`
2970
2970
  :host { position: fixed; inset: 0; z-index: 40; color: var(--pi-text); font: 14px system-ui, sans-serif; }
2971
2971
  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%); }
2972
2972
  header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 16px; border-bottom: 1px solid var(--pi-border); }
@@ -2983,7 +2983,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
2983
2983
  .close-button { width: 34px; height: 34px; display: grid; place-items: center; border: 0; background: transparent; color: var(--pi-muted); padding: 0; font-size: 24px; }
2984
2984
  .message { margin: 0; border: 1px solid var(--pi-danger-border); border-radius: 8px; background: var(--pi-danger-surface); color: var(--pi-danger); padding: 10px; }
2985
2985
  footer { display: flex; justify-content: flex-end; gap: 8px; }
2986
- `}};g([y()],sL.prototype,`mode`,void 0),g([y({type:Boolean})],sL.prototype,`loading`,void 0),g([y()],sL.prototype,`error`,void 0),g([y({attribute:!1})],sL.prototype,`onSubmit`,void 0),g([y({attribute:!1})],sL.prototype,`onCancel`,void 0),g([v()],sL.prototype,`currentPassword`,void 0),g([v()],sL.prototype,`password`,void 0),g([v()],sL.prototype,`confirmPassword`,void 0),g([v()],sL.prototype,`localError`,void 0),sL=g([_(`normal-auth-dialog`)],sL);function cL(e){return e===`setup`?C(`ui.normalAuthDialog.setAccessPassword`,`Set access password`):e===`change`?C(`ui.normalAuthDialog.changeAccessPassword`,`Change access password`):C(`ui.normalAuthDialog.enterPassword`,`Enter password`)}function lL(e,t){if(e===`change`&&(t.currentPassword??``)===``)return C(`ui.normalAuthDialog.enterYourCurrentPassword`,`Enter your current password.`);if(t.password===``)return C(`ui.normalAuthDialog.enterAPassword`,`Enter a password.`);if(e!==`login`&&t.password!==(t.confirmPassword??``))return C(`ui.normalAuthDialog.passwordsDoNotMatch`,`Passwords do not match.`)}function uL(e){return e.target instanceof HTMLInputElement?e.target.value:``}var dL=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,o.createController(this),new S(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 Xt.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 sn.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 D`
2986
+ `}};g([y()],cL.prototype,`mode`,void 0),g([y({type:Boolean})],cL.prototype,`loading`,void 0),g([y()],cL.prototype,`error`,void 0),g([y({attribute:!1})],cL.prototype,`onSubmit`,void 0),g([y({attribute:!1})],cL.prototype,`onCancel`,void 0),g([v()],cL.prototype,`currentPassword`,void 0),g([v()],cL.prototype,`password`,void 0),g([v()],cL.prototype,`confirmPassword`,void 0),g([v()],cL.prototype,`localError`,void 0),cL=g([_(`normal-auth-dialog`)],cL);function lL(e){return e===`setup`?C(`ui.normalAuthDialog.setAccessPassword`,`Set access password`):e===`change`?C(`ui.normalAuthDialog.changeAccessPassword`,`Change access password`):C(`ui.normalAuthDialog.enterPassword`,`Enter password`)}function uL(e,t){if(e===`change`&&(t.currentPassword??``)===``)return C(`ui.normalAuthDialog.enterYourCurrentPassword`,`Enter your current password.`);if(t.password===``)return C(`ui.normalAuthDialog.enterAPassword`,`Enter a password.`);if(e!==`login`&&t.password!==(t.confirmPassword??``))return C(`ui.normalAuthDialog.passwordsDoNotMatch`,`Passwords do not match.`)}function dL(e){return e.target instanceof HTMLInputElement?e.target.value:``}var fL=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,o.createController(this),new S(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 Xt.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 sn.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 D`
2987
2987
  <label class="check ui-checkbox-field">
2988
2988
  <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)}} />
2989
2989
  <span>${U.t(`trustProject`)}</span>
@@ -3051,7 +3051,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3051
3051
  .trust-hint a { color: var(--pi-accent); }
3052
3052
 
3053
3053
  }
3054
- `]}};g([y({attribute:!1})],dL.prototype,`onSubmit`,void 0),g([y({attribute:!1})],dL.prototype,`onCancel`,void 0),g([y()],dL.prototype,`machineId`,void 0),g([y({type:Boolean})],dL.prototype,`managementMode`,void 0),g([v()],dL.prototype,`path`,void 0),g([v()],dL.prototype,`createMissing`,void 0),g([v()],dL.prototype,`suggestions`,void 0),g([v()],dL.prototype,`selected`,void 0),g([v()],dL.prototype,`loading`,void 0),g([v()],dL.prototype,`suggestionError`,void 0),g([v()],dL.prototype,`trust`,void 0),g([v()],dL.prototype,`trustTouched`,void 0),g([Te(`input`)],dL.prototype,`pathInput`,void 0),dL=g([_(`project-dialog`)],dL);var fL=class extends O{constructor(){super(),this.error=``,this.url=``,this.name=``,this.token=``,this.submitting=!1,o.createController(this),new S(this)}willUpdate(e){e.has(`machine`)&&(this.name=this.machine?.nameOverride??``,this.url=this.machine?.baseUrl??``)}handleUrlInput(e){e.target instanceof HTMLInputElement&&(this.url=e.target.value)}handleNameInput(e){e.target instanceof HTMLInputElement&&(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`&&pL(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===``||pL(e)!==void 0)return;let n=this.token.trim();return{name:t,baseUrl:e,...n===``?{}:{token:n}}}render(){let e=this.machine!==void 0,t=e?F.t(`editTitle`):F.t(`addTitle`),n=this.url.trim()!==``,r=n?pL(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return D`
3054
+ `]}};g([y({attribute:!1})],fL.prototype,`onSubmit`,void 0),g([y({attribute:!1})],fL.prototype,`onCancel`,void 0),g([y()],fL.prototype,`machineId`,void 0),g([y({type:Boolean})],fL.prototype,`managementMode`,void 0),g([v()],fL.prototype,`path`,void 0),g([v()],fL.prototype,`createMissing`,void 0),g([v()],fL.prototype,`suggestions`,void 0),g([v()],fL.prototype,`selected`,void 0),g([v()],fL.prototype,`loading`,void 0),g([v()],fL.prototype,`suggestionError`,void 0),g([v()],fL.prototype,`trust`,void 0),g([v()],fL.prototype,`trustTouched`,void 0),g([Te(`input`)],fL.prototype,`pathInput`,void 0),fL=g([_(`project-dialog`)],fL);var pL=class extends O{constructor(){super(),this.error=``,this.url=``,this.name=``,this.token=``,this.submitting=!1,o.createController(this),new S(this)}willUpdate(e){e.has(`machine`)&&(this.name=this.machine?.nameOverride??``,this.url=this.machine?.baseUrl??``)}handleUrlInput(e){e.target instanceof HTMLInputElement&&(this.url=e.target.value)}handleNameInput(e){e.target instanceof HTMLInputElement&&(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`&&mL(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===``||mL(e)!==void 0)return;let n=this.token.trim();return{name:t,baseUrl:e,...n===``?{}:{token:n}}}render(){let e=this.machine!==void 0,t=e?F.t(`editTitle`):F.t(`addTitle`),n=this.url.trim()!==``,r=n?mL(this.url):void 0,i=this.validInput()!==void 0&&!this.submitting;return D`
3055
3055
  <modal-surface
3056
3056
  .onClose=${()=>this.onCancel?.()}
3057
3057
  .busy=${this.submitting}
@@ -3098,7 +3098,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3098
3098
  .field-error { color: var(--pi-danger); }
3099
3099
 
3100
3100
  }
3101
- `]}};g([y({attribute:!1})],fL.prototype,`onSubmit`,void 0),g([y({attribute:!1})],fL.prototype,`onCancel`,void 0),g([y()],fL.prototype,`error`,void 0),g([y({attribute:!1})],fL.prototype,`machine`,void 0),g([v()],fL.prototype,`url`,void 0),g([v()],fL.prototype,`name`,void 0),g([v()],fL.prototype,`token`,void 0),g([v()],fL.prototype,`submitting`,void 0),g([Te(`input[name='name']`)],fL.prototype,`nameInput`,void 0),fL=g([_(`machine-dialog`)],fL);function pL(e){let t=e.trim();if(t===``)return F.t(`urlRequired`);let n;try{n=new URL(t)}catch{return F.t(`urlInvalid`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)return F.t(`urlProtocol`);if(n.username!==``||n.password!==``)return F.t(`urlCredentials`);if(n.search!==``||n.hash!==``)return F.t(`urlQuery`)}var mL=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 hL(e,t,n){return n===`rtl`?{left:t+e>1,right:-e>1}:{left:e>1,right:t-e>1}}function gL(){return dn`<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 _L(e){return typeof e==`string`?vL(e):D`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`}function vL(e){switch(e){case`navigation`:return dn`
3101
+ `]}};g([y({attribute:!1})],pL.prototype,`onSubmit`,void 0),g([y({attribute:!1})],pL.prototype,`onCancel`,void 0),g([y()],pL.prototype,`error`,void 0),g([y({attribute:!1})],pL.prototype,`machine`,void 0),g([v()],pL.prototype,`url`,void 0),g([v()],pL.prototype,`name`,void 0),g([v()],pL.prototype,`token`,void 0),g([v()],pL.prototype,`submitting`,void 0),g([Te(`input[name='name']`)],pL.prototype,`nameInput`,void 0),pL=g([_(`machine-dialog`)],pL);function mL(e){let t=e.trim();if(t===``)return F.t(`urlRequired`);let n;try{n=new URL(t)}catch{return F.t(`urlInvalid`)}if(n.protocol!==`http:`&&n.protocol!==`https:`)return F.t(`urlProtocol`);if(n.username!==``||n.password!==``)return F.t(`urlCredentials`);if(n.search!==``||n.hash!==``)return F.t(`urlQuery`)}var hL=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 gL(e,t,n){return n===`rtl`?{left:t+e>1,right:-e>1}:{left:e>1,right:t-e>1}}function _L(){return dn`<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 vL(e){return typeof e==`string`?yL(e):D`<span class="tab-custom-icon" aria-hidden="true">${e}</span>`}function yL(e){switch(e){case`navigation`:return dn`
3102
3102
  <svg class="tab-icon" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
3103
3103
  <circle cx="6" cy="7" r="1.5"></circle>
3104
3104
  <path d="M10 7h8"></path>
@@ -3113,7 +3113,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3113
3113
  <path d="M8 9h8"></path>
3114
3114
  <path d="M8 13h5"></path>
3115
3115
  </svg>
3116
- `}}var yL=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()},new S(this),o.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:k.t(`selectWorkspace`),body:k.t(`chooseWorkspace`)}:{title:C(`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=gA(e,this.pinnedIds);return D`
3116
+ `}}var bL=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()},new S(this),o.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:k.t(`selectWorkspace`),body:k.t(`chooseWorkspace`)}:{title:C(`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=gA(e,this.pinnedIds);return D`
3117
3117
  ${this.hideToolTabs?null:D`
3118
3118
  <header>
3119
3119
  <div class=${this.workspaceHeaderFrameClass()}>
@@ -3140,52 +3140,52 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3140
3140
  ${e.icon===void 0?null:D`<span class="tab-custom-icon" aria-hidden="true">${e.icon}</span>`}
3141
3141
  <span class="tab-label">${e.title}</span>
3142
3142
  ${this.isEmptyBadge(t)?null:D`<span class="tab-badge">${typeof t==`number`?w.number(t):t}</span>`}
3143
- `}isEmptyBadge(e){return e===void 0||e===``}renderNavigationButton(e=!1){return this.onShowNavigation===void 0?null:D`<button type="button" class=${`ui-button ui-button--icon navigation-menu-button${e?` selected`:``}`} data-navigation-trigger title=${k.t(`navigation`)} aria-label=${k.t(`navigation`)} aria-haspopup="dialog" @click=${this.onShowNavigation}>${gL()}</button>`}renderEmptyState(e,t=!1){return D`
3143
+ `}isEmptyBadge(e){return e===void 0||e===``}renderNavigationButton(e=!1){return this.onShowNavigation===void 0?null:D`<button type="button" class=${`ui-button ui-button--icon navigation-menu-button${e?` selected`:``}`} data-navigation-trigger title=${k.t(`navigation`)} aria-label=${k.t(`navigation`)} aria-haspopup="dialog" @click=${this.onShowNavigation}>${_L()}</button>`}renderEmptyState(e,t=!1){return D`
3144
3144
  ${t&&!this.hideToolTabs?D`<header>${this.renderNavigationButton()}</header>`:null}
3145
3145
  <section class="empty-state" role=${this.error===``?`status`:`alert`}>
3146
3146
  <h2>${e.title}</h2>
3147
3147
  ${e.body===void 0?null:D`<p>${e.body}</p>`}
3148
3148
  </section>
3149
- `}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=hL(e?.scrollLeft??0,t,w.direction),r=e!==void 0&&n.left,i=e!==void 0&&n.right;this.workspaceHeaderCanScrollLeft!==r&&(this.workspaceHeaderCanScrollLeft=r),this.workspaceHeaderCanScrollRight!==i&&(this.workspaceHeaderCanScrollRight=i)}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=$d}};g([y({attribute:!1})],yL.prototype,`workspace`,void 0),g([y({attribute:!1})],yL.prototype,`emptyState`,void 0),g([y()],yL.prototype,`error`,void 0),g([y()],yL.prototype,`tool`,void 0),g([y({attribute:!1})],yL.prototype,`panels`,void 0),g([y({type:Boolean})],yL.prototype,`hideToolTabs`,void 0),g([y({attribute:!1})],yL.prototype,`pinnedIds`,void 0),g([y({attribute:!1})],yL.prototype,`onShowNavigation`,void 0),g([y({attribute:!1})],yL.prototype,`onTogglePanel`,void 0),g([y({type:Boolean})],yL.prototype,`hiddenActiveDestination`,void 0),g([y({attribute:!1})],yL.prototype,`onSelectTool`,void 0),g([Te(`.workspace-header-strip`)],yL.prototype,`workspaceHeaderStrip`,void 0),g([v()],yL.prototype,`workspaceHeaderCanScrollLeft`,void 0),g([v()],yL.prototype,`workspaceHeaderCanScrollRight`,void 0),yL=g([_(`workspace-panel`)],yL);function bL(e){return e.kind===`local`||e.baseUrl===void 0?te(`favicon.svg`):new URL(`favicon.svg`,e.baseUrl.endsWith(`/`)?e.baseUrl:`${e.baseUrl}/`).toString()}function xL(e){let t=new URL(e);return`${t.host}${t.pathname.replace(/\/+$/,``)}`}function SL(){return xL(te(``))}var CL=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()},new S(this),o.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=wL(this.machine,this.machines),t=this.machines.length>1,n=e===void 0?`context-chip machine-chip empty`:`context-chip machine-chip`,r=OL(this.project),i=AL(this.workspace),a=ML(this.session);return D`
3149
+ `}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=gL(e?.scrollLeft??0,t,w.direction),r=e!==void 0&&n.left,i=e!==void 0&&n.right;this.workspaceHeaderCanScrollLeft!==r&&(this.workspaceHeaderCanScrollLeft=r),this.workspaceHeaderCanScrollRight!==i&&(this.workspaceHeaderCanScrollRight=i)}workspaceHeaderStripElement(){let e=this.workspaceHeaderStrip;return e instanceof HTMLElement?e:void 0}static{this.styles=$d}};g([y({attribute:!1})],bL.prototype,`workspace`,void 0),g([y({attribute:!1})],bL.prototype,`emptyState`,void 0),g([y()],bL.prototype,`error`,void 0),g([y()],bL.prototype,`tool`,void 0),g([y({attribute:!1})],bL.prototype,`panels`,void 0),g([y({type:Boolean})],bL.prototype,`hideToolTabs`,void 0),g([y({attribute:!1})],bL.prototype,`pinnedIds`,void 0),g([y({attribute:!1})],bL.prototype,`onShowNavigation`,void 0),g([y({attribute:!1})],bL.prototype,`onTogglePanel`,void 0),g([y({type:Boolean})],bL.prototype,`hiddenActiveDestination`,void 0),g([y({attribute:!1})],bL.prototype,`onSelectTool`,void 0),g([Te(`.workspace-header-strip`)],bL.prototype,`workspaceHeaderStrip`,void 0),g([v()],bL.prototype,`workspaceHeaderCanScrollLeft`,void 0),g([v()],bL.prototype,`workspaceHeaderCanScrollRight`,void 0),bL=g([_(`workspace-panel`)],bL);function xL(e){return e.kind===`local`||e.baseUrl===void 0?te(`favicon.svg`):new URL(`favicon.svg`,e.baseUrl.endsWith(`/`)?e.baseUrl:`${e.baseUrl}/`).toString()}function SL(e){let t=new URL(e);return`${t.host}${t.pathname.replace(/\/+$/,``)}`}function CL(){return SL(te(``))}var wL=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()},new S(this),o.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=TL(this.machine,this.machines),t=this.machines.length>1,n=e===void 0?`context-chip machine-chip empty`:`context-chip machine-chip`,r=kL(this.project),i=jL(this.workspace),a=NL(this.session);return D`
3150
3150
  <pi-web-ui-presentation region="context-bar" .runtime=${this.presentationRuntime} .context=${this.presentationContext}>
3151
3151
  <nav slot="content" class=${this.contextBarClass()} aria-label=${k.t(`currentLocation`)}>
3152
3152
  <span class="context-bar-label">${k.t(`location`)}</span>
3153
3153
  <ol class="context-items" @scroll=${this.onContextScroll}>
3154
3154
  <li class="context-item">
3155
3155
  ${t?D`
3156
- <button type="button" class=${n} title=${DL(e)} aria-label=${k.t(`machineSelection`,{label:TL(e)})} @click=${()=>{this.onOpenSection?.(`machines`)}}>
3156
+ <button type="button" class=${n} title=${OL(e)} aria-label=${k.t(`machineSelection`,{label:EL(e)})} @click=${()=>{this.onOpenSection?.(`machines`)}}>
3157
3157
  ${this.renderMachineChipContent(e)}
3158
3158
  </button>
3159
3159
  `:D`
3160
3160
  <!-- No machine choice: the chip is the instance identity, not a control. -->
3161
- <span class="${n} static" title=${DL(e)}>
3161
+ <span class="${n} static" title=${OL(e)}>
3162
3162
  ${this.renderMachineChipContent(e)}
3163
3163
  </span>
3164
3164
  `}
3165
3165
  </li>
3166
3166
  <li class="context-item">
3167
- <button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${kL(this.project)} aria-label=${k.t(`projectSelection`,{label:r})} @click=${()=>{this.onOpenSection?.(`projects`)}}>
3167
+ <button type="button" class=${this.project===void 0?`context-chip empty`:`context-chip`} title=${AL(this.project)} aria-label=${k.t(`projectSelection`,{label:r})} @click=${()=>{this.onOpenSection?.(`projects`)}}>
3168
3168
  <span class="context-kind">${k.t(`project`)}</span>
3169
3169
  <span class="context-value">${r}</span>
3170
3170
  </button>
3171
3171
  </li>
3172
3172
  ${this.workspaceSelectionVisible?D`<li class="context-item">
3173
- <button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${jL(this.workspace)} aria-label=${k.t(`workspaceSelection`,{label:i})} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
3173
+ <button type="button" class=${this.workspace===void 0?`context-chip empty`:`context-chip`} title=${ML(this.workspace)} aria-label=${k.t(`workspaceSelection`,{label:i})} @click=${()=>{this.onOpenSection?.(`workspaces`)}}>
3174
3174
  <span class="context-kind">${k.t(`workspace`)}</span>
3175
3175
  <span class="context-value">${i}</span>
3176
3176
  </button>
3177
3177
  </li>`:null}
3178
3178
  <li class="context-item">
3179
- <button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${NL(this.session)} aria-label=${k.t(`sessionSelection`,{label:a})} @click=${()=>{this.onOpenSection?.(`sessions`)}}>
3179
+ <button type="button" class=${this.session===void 0?`context-chip empty`:`context-chip`} title=${PL(this.session)} aria-label=${k.t(`sessionSelection`,{label:a})} @click=${()=>{this.onOpenSection?.(`sessions`)}}>
3180
3180
  <span class="context-kind">${k.t(`session`)}</span>
3181
3181
  <span class="context-value">${a}</span>
3182
3182
  </button>
3183
3183
  </li>
3184
3184
  </ol>
3185
- ${this.hasContextActions()?D`<div class="context-actions">${this.onShowNavigation===void 0?null:D`<button type="button" class=${`context-action-button${this.hiddenActiveDestination?` selected`:``}`} aria-pressed=${String(this.hiddenActiveDestination)} data-navigation-trigger title=${k.t(`navigation`)} aria-label=${k.t(`navigation`)} aria-haspopup="dialog" @click=${this.onShowNavigation}>${gL()}</button>`}${this.refreshControl}${this.renderActionsButton()}</div>`:null}
3185
+ ${this.hasContextActions()?D`<div class="context-actions">${this.onShowNavigation===void 0?null:D`<button type="button" class=${`context-action-button${this.hiddenActiveDestination?` selected`:``}`} aria-pressed=${String(this.hiddenActiveDestination)} data-navigation-trigger title=${k.t(`navigation`)} aria-label=${k.t(`navigation`)} aria-haspopup="dialog" @click=${this.onShowNavigation}>${_L()}</button>`}${this.refreshControl}${this.renderActionsButton()}</div>`:null}
3186
3186
  </nav></pi-web-ui-presentation>
3187
- `}renderMachineChipContent(e){let t=e??{id:`local`,name:`PI-WEB`,kind:`local`,createdAt:``,updatedAt:``},n=this.machines.length>1?EL(t):TL(t);return D`
3188
- <img class="context-chip-icon" src=${bL(t)} alt="" @error=${this.hideBrokenIcon} />
3187
+ `}renderMachineChipContent(e){let t=e??{id:`local`,name:`PI-WEB`,kind:`local`,createdAt:``,updatedAt:``},n=this.machines.length>1?DL(t):EL(t);return D`
3188
+ <img class="context-chip-icon" src=${xL(t)} alt="" @error=${this.hideBrokenIcon} />
3189
3189
  <span class="context-value">${n}</span>
3190
3190
  `}renderActionsButton(){return this.onShowActions===void 0?null:D`
3191
3191
  <button type="button" class="context-action-button" title=${k.t(`showActions`)} aria-label=${k.t(`showActions`)} @click=${e=>{e.stopPropagation(),this.onShowActions?.()}}>
@@ -3193,7 +3193,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3193
3193
  <path d="M13 2 4 14h7l-1 8 10-13h-7V2Z"></path>
3194
3194
  </svg>
3195
3195
  </button>
3196
- `}contextBarClass(){let e=[`context-bar`];return this.canScrollLeft&&e.push(`can-scroll-left`),this.canScrollRight&&e.push(`can-scroll-right`),e.join(` `)}hasContextActions(){return this.refreshControl!==void 0||this.onShowActions!==void 0||this.onShowNavigation!==void 0}observeContextItems(){let e=this.contextItemsElement();this.observedContextItems!==e&&(this.contextItemsResizeObserver?.disconnect(),this.observedContextItems=e,this.contextItemsResizeObserver=void 0,e!==void 0&&typeof ResizeObserver<`u`&&(this.contextItemsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.contextItemsResizeObserver.observe(e)))}updateScrollState(){let e=this.contextItemsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=hL(e?.scrollLeft??0,t,w.direction),r=e!==void 0&&n.left,i=e!==void 0&&n.right;this.canScrollLeft!==r&&(this.canScrollLeft=r),this.canScrollRight!==i&&(this.canScrollRight=i)}contextItemsElement(){let e=this.contextItems;return e instanceof HTMLElement?e:void 0}static{this.styles=T`
3196
+ `}contextBarClass(){let e=[`context-bar`];return this.canScrollLeft&&e.push(`can-scroll-left`),this.canScrollRight&&e.push(`can-scroll-right`),e.join(` `)}hasContextActions(){return this.refreshControl!==void 0||this.onShowActions!==void 0||this.onShowNavigation!==void 0}observeContextItems(){let e=this.contextItemsElement();this.observedContextItems!==e&&(this.contextItemsResizeObserver?.disconnect(),this.observedContextItems=e,this.contextItemsResizeObserver=void 0,e!==void 0&&typeof ResizeObserver<`u`&&(this.contextItemsResizeObserver=new ResizeObserver(()=>{this.updateScrollState()}),this.contextItemsResizeObserver.observe(e)))}updateScrollState(){let e=this.contextItemsElement(),t=e===void 0?0:Math.max(0,e.scrollWidth-e.clientWidth),n=gL(e?.scrollLeft??0,t,w.direction),r=e!==void 0&&n.left,i=e!==void 0&&n.right;this.canScrollLeft!==r&&(this.canScrollLeft=r),this.canScrollRight!==i&&(this.canScrollRight=i)}contextItemsElement(){let e=this.contextItems;return e instanceof HTMLElement?e:void 0}static{this.styles=T`
3197
3197
  @layer pi-web-base {
3198
3198
  /* Keep the refresh menu in this shadow tree above the following mobile tab strip. */
3199
3199
  :host { position: relative; z-index: 20; flex: 0 0 auto; min-width: 0; }
@@ -3222,7 +3222,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3222
3222
  button { cursor: pointer; }
3223
3223
 
3224
3224
  }
3225
- `}};g([y({attribute:!1})],CL.prototype,`machines`,void 0),g([y({attribute:!1})],CL.prototype,`presentationRuntime`,void 0),g([y({attribute:!1})],CL.prototype,`presentationContext`,void 0),g([y({attribute:!1})],CL.prototype,`machine`,void 0),g([y({type:Boolean})],CL.prototype,`locationIndicator`,void 0),g([y({attribute:!1})],CL.prototype,`project`,void 0),g([y({type:Boolean})],CL.prototype,`workspaceSelectionVisible`,void 0),g([y({attribute:!1})],CL.prototype,`workspace`,void 0),g([y({attribute:!1})],CL.prototype,`session`,void 0),g([y({attribute:!1})],CL.prototype,`refreshControl`,void 0),g([y({attribute:!1})],CL.prototype,`onOpenSection`,void 0),g([y({attribute:!1})],CL.prototype,`onShowActions`,void 0),g([y({attribute:!1})],CL.prototype,`onShowNavigation`,void 0),g([y({type:Boolean})],CL.prototype,`hiddenActiveDestination`,void 0),g([Te(`.context-items`)],CL.prototype,`contextItems`,void 0),g([v()],CL.prototype,`canScrollLeft`,void 0),g([v()],CL.prototype,`canScrollRight`,void 0),CL=g([_(`app-context-bar`)],CL);function wL(e,t){return e??t.find(e=>e.id===`local`)??t[0]}function TL(e){return e?.name??`PI-WEB`}function EL(e){return e.kind===`remote`?k.t(`remoteMachine`,{name:e.name}):e.name}function DL(e){return e===void 0?`PI-WEB`:e.baseUrl??e.name}function OL(e){return e?.name??k.t(`noProject`)}function kL(e){return e===void 0?k.t(`noProjectSelected`):k.t(`projectDetail`,{name:e.name,path:e.path})}function AL(e){return e===void 0?k.t(`noWorkspace`):k.t(`workspaceLabel`,{label:e.label,main:e.isMain?`yes`:`no`,path:e.path})}function jL(e){return e===void 0?k.t(`noWorkspaceSelected`):k.t(`workspaceDetail`,{label:e.label,main:e.isMain?`yes`:`no`,path:e.path})}function ML(e){let t=e?.name?.trim(),n=e?.firstMessage.trim();return t!==void 0&&t!==``?t:n!==void 0&&n!==``?n:e===void 0?k.t(`noSession`):_j(e.id)}function NL(e){return e===void 0?k.t(`noSessionSelected`):e.path}var PL=class extends O{constructor(){super(),this.tabs=[],this.leadingControl=null,this.trailingControl=null,this.controlsOnly=!1,this.hiddenActiveDestination=!1,this.selectedTab=`chat`,this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()},new S(this),o.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 D`
3225
+ `}};g([y({attribute:!1})],wL.prototype,`machines`,void 0),g([y({attribute:!1})],wL.prototype,`presentationRuntime`,void 0),g([y({attribute:!1})],wL.prototype,`presentationContext`,void 0),g([y({attribute:!1})],wL.prototype,`machine`,void 0),g([y({type:Boolean})],wL.prototype,`locationIndicator`,void 0),g([y({attribute:!1})],wL.prototype,`project`,void 0),g([y({type:Boolean})],wL.prototype,`workspaceSelectionVisible`,void 0),g([y({attribute:!1})],wL.prototype,`workspace`,void 0),g([y({attribute:!1})],wL.prototype,`session`,void 0),g([y({attribute:!1})],wL.prototype,`refreshControl`,void 0),g([y({attribute:!1})],wL.prototype,`onOpenSection`,void 0),g([y({attribute:!1})],wL.prototype,`onShowActions`,void 0),g([y({attribute:!1})],wL.prototype,`onShowNavigation`,void 0),g([y({type:Boolean})],wL.prototype,`hiddenActiveDestination`,void 0),g([Te(`.context-items`)],wL.prototype,`contextItems`,void 0),g([v()],wL.prototype,`canScrollLeft`,void 0),g([v()],wL.prototype,`canScrollRight`,void 0),wL=g([_(`app-context-bar`)],wL);function TL(e,t){return e??t.find(e=>e.id===`local`)??t[0]}function EL(e){return e?.name??`PI-WEB`}function DL(e){return e.kind===`remote`?k.t(`remoteMachine`,{name:e.name}):e.name}function OL(e){return e===void 0?`PI-WEB`:e.baseUrl??e.name}function kL(e){return e?.name??k.t(`noProject`)}function AL(e){return e===void 0?k.t(`noProjectSelected`):k.t(`projectDetail`,{name:e.name,path:e.path})}function jL(e){return e===void 0?k.t(`noWorkspace`):k.t(`workspaceLabel`,{label:e.label,main:e.isMain?`yes`:`no`,path:e.path})}function ML(e){return e===void 0?k.t(`noWorkspaceSelected`):k.t(`workspaceDetail`,{label:e.label,main:e.isMain?`yes`:`no`,path:e.path})}function NL(e){let t=e?.name?.trim(),n=e?.firstMessage.trim();return t!==void 0&&t!==``?t:n!==void 0&&n!==``?n:e===void 0?k.t(`noSession`):_j(e.id)}function PL(e){return e===void 0?k.t(`noSessionSelected`):e.path}var FL=class extends O{constructor(){super(),this.tabs=[],this.leadingControl=null,this.trailingControl=null,this.controlsOnly=!1,this.hiddenActiveDestination=!1,this.selectedTab=`chat`,this.canScrollLeft=!1,this.canScrollRight=!1,this.onMobileTabsScroll=()=>{this.updateScrollState()},new S(this),o.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 D`
3226
3226
  <div class=${this.frameClass()}>
3227
3227
  ${this.leadingControl}
3228
3228
  <div class="mobile-tabs" @scroll=${this.onMobileTabsScroll}>
@@ -3233,11 +3233,11 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3233
3233
  ${this.renderBadge(t.badge,t.badgeTone)}
3234
3234
  </button>
3235
3235
  `})}
3236
- ${this.onShowNavigation===void 0?null:D`<button type="button" class=${`ui-button ui-button--icon ui-tab navigation-menu-button${this.hiddenActiveDestination?` selected`:``}`} aria-pressed=${String(this.hiddenActiveDestination)} data-navigation-trigger title=${k.t(`navigation`)} aria-label=${k.t(`navigation`)} aria-haspopup="dialog" @click=${this.onShowNavigation}>${gL()}</button>`}
3236
+ ${this.onShowNavigation===void 0?null:D`<button type="button" class=${`ui-button ui-button--icon ui-tab navigation-menu-button${this.hiddenActiveDestination?` selected`:``}`} aria-pressed=${String(this.hiddenActiveDestination)} data-navigation-trigger title=${k.t(`navigation`)} aria-label=${k.t(`navigation`)} aria-haspopup="dialog" @click=${this.onShowNavigation}>${_L()}</button>`}
3237
3237
  </div>
3238
3238
  ${this.trailingControl}
3239
3239
  </div>
3240
- `}frameClass(){return`mobile-tabs-frame${this.controlsOnly?` controls-only`:``}${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`?(typeof e.badge==`number`?w.number(e.badge):e.badge).trim():``);return t===``?e.label:k.t(`badge`,{label:e.label,badge:t})}renderBadge(e,t){return e===void 0||e===``?null:D`<span class=${`tab-badge${t===void 0?``:` ${t}`}`}>${typeof e==`number`?w.number(e):e}</span>`}renderTabMark(e,t){return e.icon===void 0?D`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:_L(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(w.language);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=hL(e?.scrollLeft??0,t,w.direction),r=e!==void 0&&n.left,i=e!==void 0&&n.right;this.canScrollLeft!==r&&(this.canScrollLeft=r),this.canScrollRight!==i&&(this.canScrollRight=i)}mobileTabsElement(){let e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}static{this.styles=T`
3240
+ `}frameClass(){return`mobile-tabs-frame${this.controlsOnly?` controls-only`:``}${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`?(typeof e.badge==`number`?w.number(e.badge):e.badge).trim():``);return t===``?e.label:k.t(`badge`,{label:e.label,badge:t})}renderBadge(e,t){return e===void 0||e===``?null:D`<span class=${`tab-badge${t===void 0?``:` ${t}`}`}>${typeof e==`number`?w.number(e):e}</span>`}renderTabMark(e,t){return e.icon===void 0?D`<span class="tab-fallback" aria-hidden="true">${t.get(e.id)??this.initialsLabel(e.label)}</span>`:vL(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(w.language);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=gL(e?.scrollLeft??0,t,w.direction),r=e!==void 0&&n.left,i=e!==void 0&&n.right;this.canScrollLeft!==r&&(this.canScrollLeft=r),this.canScrollRight!==i&&(this.canScrollRight=i)}mobileTabsElement(){let e=this.mobileTabs;return e instanceof HTMLElement?e:void 0}static{this.styles=T`
3241
3241
  @layer pi-web-base {
3242
3242
  :host { flex: 0 0 auto; min-width: 0; }
3243
3243
  .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); }
@@ -3272,7 +3272,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3272
3272
  }
3273
3273
 
3274
3274
  }
3275
- `}};g([y({attribute:!1})],PL.prototype,`tabs`,void 0),g([y({attribute:!1})],PL.prototype,`leadingControl`,void 0),g([y({attribute:!1})],PL.prototype,`trailingControl`,void 0),g([y({type:Boolean})],PL.prototype,`controlsOnly`,void 0),g([y({attribute:!1})],PL.prototype,`onShowNavigation`,void 0),g([y({type:Boolean})],PL.prototype,`hiddenActiveDestination`,void 0),g([y({attribute:!1})],PL.prototype,`selectedTab`,void 0),g([y({attribute:!1})],PL.prototype,`onSelect`,void 0),g([Te(`.mobile-tabs`)],PL.prototype,`mobileTabs`,void 0),g([v()],PL.prototype,`canScrollLeft`,void 0),g([v()],PL.prototype,`canScrollRight`,void 0),PL=g([_(`app-mobile-main-tabs`)],PL);var FL=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`})},new S(this),o.createController(this)}filteredTabs(){let e=this.query.trim().toLocaleLowerCase(w.language);return this.tabs.filter(t=>t.label.toLocaleLowerCase(w.language).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 D`
3275
+ `}};g([y({attribute:!1})],FL.prototype,`tabs`,void 0),g([y({attribute:!1})],FL.prototype,`leadingControl`,void 0),g([y({attribute:!1})],FL.prototype,`trailingControl`,void 0),g([y({type:Boolean})],FL.prototype,`controlsOnly`,void 0),g([y({attribute:!1})],FL.prototype,`onShowNavigation`,void 0),g([y({type:Boolean})],FL.prototype,`hiddenActiveDestination`,void 0),g([y({attribute:!1})],FL.prototype,`selectedTab`,void 0),g([y({attribute:!1})],FL.prototype,`onSelect`,void 0),g([Te(`.mobile-tabs`)],FL.prototype,`mobileTabs`,void 0),g([v()],FL.prototype,`canScrollLeft`,void 0),g([v()],FL.prototype,`canScrollRight`,void 0),FL=g([_(`app-mobile-main-tabs`)],FL);var IL=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`})},new S(this),o.createController(this)}filteredTabs(){let e=this.query.trim().toLocaleLowerCase(w.language);return this.tabs.filter(t=>t.label.toLocaleLowerCase(w.language).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 D`
3276
3276
  <modal-surface .label=${k.t(`navigation`)} .initialFocus=${`input`} .onClose=${this.onClose} @keydown=${this.navigateDestinations}>
3277
3277
  <header class="ui-dialog-header">
3278
3278
  <input class="ui-dialog-search" aria-label=${k.t(`search`)} aria-describedby="navigation-selection" placeholder=${k.t(`searchPlaceholder`)} .value=${this.query} @input=${e=>{e.target instanceof HTMLInputElement&&(this.query=e.target.value,this.selectedIndex=0)}}>
@@ -3284,7 +3284,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3284
3284
  ${e.length===0?D`<div class="empty ui-dialog-empty">${k.t(`noDestinations`)}</div>`:E}
3285
3285
  ${e.map((e,t)=>D`
3286
3286
  <div class="destination ui-selection-row">
3287
- <button class=${`destination-button ui-button ui-selection-option ${t===this.selectedIndex?`selected`:``}`} aria-current=${e.id===this.selectedTab?`page`:E} aria-pressed=${String(e.id===this.selectedTab)} ${hI(t===this.selectedIndex,e.id)} @focus=${()=>{this.selectedIndex=t}} @click=${()=>{this.select(e)}}>${e.label}</button>
3287
+ <button class=${`destination-button ui-button ui-selection-option ${t===this.selectedIndex?`selected`:``}`} aria-current=${e.id===this.selectedTab?`page`:E} aria-pressed=${String(e.id===this.selectedTab)} ${gI(t===this.selectedIndex,e.id)} @focus=${()=>{this.selectedIndex=t}} @click=${()=>{this.select(e)}}>${e.label}</button>
3288
3288
  <button type="button" class="pin-button ui-button ui-button--icon" aria-label=${k.t(hA(e.id,this.preferences.pinnedIds)?`unpin`:`pin`,{label:e.label})} title=${k.t(hA(e.id,this.preferences.pinnedIds)?`unpin`:`pin`,{label:e.label})} aria-pressed=${String(hA(e.id,this.preferences.pinnedIds))} @click=${()=>{this.onPreferencesChange?.({...this.preferences,pinnedIds:vA(e.id,this.preferences.pinnedIds,this.pinUniverse??this.tabs.map(e=>e.id))})}}>
3289
3289
  <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true" focusable="false" fill=${hA(e.id,this.preferences.pinnedIds)?`currentColor`:`none`} stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
3290
3290
  <path d="M8 3h8l-1 7 4 4v2H5v-2l4-4-1-7Z"></path><path d="M12 16v6"></path>
@@ -3316,7 +3316,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3316
3316
  .mobile-navigation { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; font-size: 12px; }
3317
3317
 
3318
3318
  }
3319
- `]}};g([y({attribute:!1})],FL.prototype,`tabs`,void 0),g([y({attribute:!1})],FL.prototype,`pinUniverse`,void 0),g([y({attribute:!1})],FL.prototype,`preferences`,void 0),g([y({attribute:!1})],FL.prototype,`selectedTab`,void 0),g([y({attribute:!1})],FL.prototype,`onSelect`,void 0),g([y({attribute:!1})],FL.prototype,`onPreferencesChange`,void 0),g([y({attribute:!1})],FL.prototype,`onClose`,void 0),g([v()],FL.prototype,`query`,void 0),g([v()],FL.prototype,`selectedIndex`,void 0),FL=g([_(`navigation-dialog`)],FL);var IL=`pi-web:navigation-section-sizes:v1`,LL=class{constructor(e,t={}){this.host=e,this.storage=t.storage??UL(),this.heights=VL(this.storage),e.addController(this)}hostConnected(){}height(e){return this.heights[e]}resize(e,t){if(!Number.isFinite(t))return;let n=BL(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(IL):this.storage?.setItem(IL,JSON.stringify({version:1,...this.heights}))}catch{}}};function RL(e,t,n){return BL(e+n-t)}function zL(e,t,n={}){if(t===`Home`)return 44;let r=n.largeStep===!0?72:24;if(t===`ArrowUp`)return BL(e-r);if(t===`ArrowDown`)return BL(e+r)}function BL(e){return Number.isFinite(e)?Math.max(44,Math.round(e)):44}function VL(e){try{let t=e?.getItem(IL);if(t==null||t===``)return{};let n=JSON.parse(t);if(!HL(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]=BL(t))}return r}catch{return{}}}function HL(e){return typeof e==`object`&&!!e}function UL(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}var WL=class extends O{constructor(){super(),this.sectionLabel=``,this.controls=``,this.measurement={height:44,maxHeight:44},this.lastTapAt=0,new S(this),o.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(RL(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:zL(t,e.key,{largeStep:e.shiftKey});r!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commit(r))}render(){return D`<div
3319
+ `]}};g([y({attribute:!1})],IL.prototype,`tabs`,void 0),g([y({attribute:!1})],IL.prototype,`pinUniverse`,void 0),g([y({attribute:!1})],IL.prototype,`preferences`,void 0),g([y({attribute:!1})],IL.prototype,`selectedTab`,void 0),g([y({attribute:!1})],IL.prototype,`onSelect`,void 0),g([y({attribute:!1})],IL.prototype,`onPreferencesChange`,void 0),g([y({attribute:!1})],IL.prototype,`onClose`,void 0),g([v()],IL.prototype,`query`,void 0),g([v()],IL.prototype,`selectedIndex`,void 0),IL=g([_(`navigation-dialog`)],IL);var LL=`pi-web:navigation-section-sizes:v1`,RL=class{constructor(e,t={}){this.host=e,this.storage=t.storage??WL(),this.heights=HL(this.storage),e.addController(this)}hostConnected(){}height(e){return this.heights[e]}resize(e,t){if(!Number.isFinite(t))return;let n=VL(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(LL):this.storage?.setItem(LL,JSON.stringify({version:1,...this.heights}))}catch{}}};function zL(e,t,n){return VL(e+n-t)}function BL(e,t,n={}){if(t===`Home`)return 44;let r=n.largeStep===!0?72:24;if(t===`ArrowUp`)return VL(e-r);if(t===`ArrowDown`)return VL(e+r)}function VL(e){return Number.isFinite(e)?Math.max(44,Math.round(e)):44}function HL(e){try{let t=e?.getItem(LL);if(t==null||t===``)return{};let n=JSON.parse(t);if(!UL(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]=VL(t))}return r}catch{return{}}}function UL(e){return typeof e==`object`&&!!e}function WL(){try{return typeof window>`u`?void 0:window.localStorage}catch{return}}var GL=class extends O{constructor(){super(),this.sectionLabel=``,this.controls=``,this.measurement={height:44,maxHeight:44},this.lastTapAt=0,new S(this),o.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(zL(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:BL(t,e.key,{largeStep:e.shiftKey});r!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commit(r))}render(){return D`<div
3320
3320
  role="separator" tabindex="0" aria-orientation="horizontal"
3321
3321
  aria-label=${k.t(`resizeSection`,{section:this.sectionLabel})}
3322
3322
  title=${k.t(`resizeHint`,{label:k.t(`resizeSection`,{section:this.sectionLabel})})}
@@ -3337,12 +3337,12 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3337
3337
  [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; }
3338
3338
  [role="separator"]:hover::after, [role="separator"]:focus-visible::after,
3339
3339
  :host([resizing]) [role="separator"]::after { height: 3px; background: var(--pi-accent); opacity: .72; }
3340
- `}};g([y()],WL.prototype,`sectionLabel`,void 0),g([y()],WL.prototype,`controls`,void 0),g([y({attribute:!1})],WL.prototype,`measurement`,void 0),g([y({attribute:!1})],WL.prototype,`onResize`,void 0),g([y({attribute:!1})],WL.prototype,`onReset`,void 0),WL=g([_(`navigation-section-resize-handle`)],WL);var GL=class extends O{constructor(){super(),this.actionsPopup=new VA(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 VA(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.statuses={},this.activities={},this.unreadMachineIds=new Set,this.statusSnapshots={},this.open=!1,this.hideBrokenIcon=e=>{e.currentTarget instanceof HTMLImageElement&&(e.currentTarget.style.display=`none`)},o.createController(this),new S(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=KL(e,this.statuses),n=e.name;return D`
3340
+ `}};g([y()],GL.prototype,`sectionLabel`,void 0),g([y()],GL.prototype,`controls`,void 0),g([y({attribute:!1})],GL.prototype,`measurement`,void 0),g([y({attribute:!1})],GL.prototype,`onResize`,void 0),g([y({attribute:!1})],GL.prototype,`onReset`,void 0),GL=g([_(`navigation-section-resize-handle`)],GL);var KL=class extends O{constructor(){super(),this.actionsPopup=new VA(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 VA(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.statuses={},this.activities={},this.unreadMachineIds=new Set,this.statusSnapshots={},this.open=!1,this.hideBrokenIcon=e=>{e.currentTarget instanceof HTMLImageElement&&(e.currentTarget.style.display=`none`)},o.createController(this),new S(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=qL(e,this.statuses),n=e.name;return D`
3341
3341
  <div class="machine-switcher">
3342
3342
  <button
3343
3343
  type="button"
3344
3344
  class=${`machine-switcher-button ui-popup-trigger ${t===`offline`||t===`error`?`disconnected`:``}`}
3345
- title=${F.t(`identity`,{name:e.name,location:YL(e),status:qL(t)})}
3345
+ title=${F.t(`identity`,{name:e.name,location:XL(e),status:JL(t)})}
3346
3346
  aria-label=${this.machineSwitcherAriaLabel(e)}
3347
3347
  aria-expanded=${String(this.open)}
3348
3348
  aria-controls="machine-switcher-menu"
@@ -3364,12 +3364,12 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3364
3364
  </div>
3365
3365
  `:null}
3366
3366
  </div>
3367
- `}renderMachineOption(e){let t=this.selectedMachine()?.id===e.id,n=KL(e,this.statuses),r=oj(e)&&(this.onRemove!==void 0||this.onEdit!==void 0),i=this.openActionsMachineId===e.id,a=`machine-option-actions-${encodeURIComponent(e.id)}`;return D`
3367
+ `}renderMachineOption(e){let t=this.selectedMachine()?.id===e.id,n=qL(e,this.statuses),r=oj(e)&&(this.onRemove!==void 0||this.onEdit!==void 0),i=this.openActionsMachineId===e.id,a=`machine-option-actions-${encodeURIComponent(e.id)}`;return D`
3368
3368
  <div class=${`machine-option ${t?`selected`:``} ${r?``:`no-actions`}`}>
3369
3369
  <button
3370
3370
  type="button"
3371
3371
  class="ui-button ui-menu-item machine-option-main"
3372
- title=${JL(e)}
3372
+ title=${YL(e)}
3373
3373
  data-machine-id=${e.id}
3374
3374
  data-current=${String(t)}
3375
3375
  aria-current=${t?`true`:E}
@@ -3377,7 +3377,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3377
3377
  @keydown=${e=>{this.handleMachineOptionKeydown(e)}}
3378
3378
  >
3379
3379
  <span class="machine-option-name">${this.renderMachineIcon(e)}${this.renderActivity(e)}<span><bdi>${e.name}</bdi></span></span>
3380
- <small>${F.t(`subtitle`,{location:YL(e),status:qL(n)})}</small>
3380
+ <small>${F.t(`subtitle`,{location:XL(e),status:JL(n)})}</small>
3381
3381
  </button>
3382
3382
  ${r?D`
3383
3383
  <div class="machine-option-actions">
@@ -3399,15 +3399,15 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3399
3399
  </div>
3400
3400
  `:null}
3401
3401
  </div>
3402
- `}renderMachineInfo(e){let t=KL(e,this.statuses);return D`
3403
- <div class=${`machine-info ${t===`offline`||t===`error`?`disconnected`:``}`} title=${F.t(`identity`,{name:e.name,location:YL(e),status:qL(t)})}>
3402
+ `}renderMachineInfo(e){let t=qL(e,this.statuses);return D`
3403
+ <div class=${`machine-info ${t===`offline`||t===`error`?`disconnected`:``}`} title=${F.t(`identity`,{name:e.name,location:XL(e),status:JL(t)})}>
3404
3404
  ${this.renderMachineIcon(e)}
3405
3405
  ${this.renderActivity(e)}
3406
3406
  <span class="machine-switcher-text">
3407
3407
  <span class="machine-switcher-label"><bdi>${e.name}</bdi></span>
3408
3408
  </span>
3409
3409
  </div>
3410
- `}renderMachineIcon(e){let t=KL(e,this.statuses);return D`<img class=${t===`offline`||t===`error`?`machine-icon dimmed`:`machine-icon`} src=${bL(e)} alt="" @error=${this.hideBrokenIcon} />`}renderActivity(e){let t=KL(e,this.statuses),n=this.statusSnapshots[e.id],r=n?.machine,i=t===`offline`||t===`error`?void 0:n===void 0?Br(this.activities[e.id]):LA(r),a=n===void 0?this.unreadMachineIds.has(e.id)?C(`ui.machineSwitcher.unreadSessionsOnThisMachine`,`Unread sessions on this machine`):void 0:RA(r)?C(`ui.machineSwitcher.unreadSessionsOnThisMachine`,`Unread sessions on this machine`):void 0;return IA(i,i===`terminal`?C(`ui.machineSwitcher.machineTerminalActive`,`Machine terminal active`):C(`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(KL(e,this.statuses))).map(e=>this.statusSnapshots[e.id]===void 0?Br(this.activities[e.id]):LA(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):RA(this.statusSnapshots[e.id]?.machine)),a=IA(r,r===`terminal`?F.t(`otherTerminal`):F.t(`otherActive`),i?F.t(`otherUnread`):void 0);return a===void 0?void 0:D`<span class="other-machines-activity">${a}</span>`}selectedMachine(){return this.selected??this.machines.find(e=>e.id===`local`)??this.machines[0]}machineSwitcherAriaLabel(e){return F.t(`switch`,{name:e.name,status:qL(KL(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=[e,a,Xd,T`
3410
+ `}renderMachineIcon(e){let t=qL(e,this.statuses);return D`<img class=${t===`offline`||t===`error`?`machine-icon dimmed`:`machine-icon`} src=${xL(e)} alt="" @error=${this.hideBrokenIcon} />`}renderActivity(e){let t=qL(e,this.statuses),n=this.statusSnapshots[e.id],r=n?.machine,i=t===`offline`||t===`error`?void 0:n===void 0?Br(this.activities[e.id]):LA(r),a=n===void 0?this.unreadMachineIds.has(e.id)?C(`ui.machineSwitcher.unreadSessionsOnThisMachine`,`Unread sessions on this machine`):void 0:RA(r)?C(`ui.machineSwitcher.unreadSessionsOnThisMachine`,`Unread sessions on this machine`):void 0;return IA(i,i===`terminal`?C(`ui.machineSwitcher.machineTerminalActive`,`Machine terminal active`):C(`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(qL(e,this.statuses))).map(e=>this.statusSnapshots[e.id]===void 0?Br(this.activities[e.id]):LA(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):RA(this.statusSnapshots[e.id]?.machine)),a=IA(r,r===`terminal`?F.t(`otherTerminal`):F.t(`otherActive`),i?F.t(`otherUnread`):void 0);return a===void 0?void 0:D`<span class="other-machines-activity">${a}</span>`}selectedMachine(){return this.selected??this.machines.find(e=>e.id===`local`)??this.machines[0]}machineSwitcherAriaLabel(e){return F.t(`switch`,{name:e.name,status:JL(qL(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=[e,a,Xd,T`
3411
3411
  @layer pi-web-base {
3412
3412
  :host { min-width: 0; display: flex; container: machine-selector / inline-size; }
3413
3413
  .machine-switcher { flex: 1 1 auto; min-width: 0; display: flex; }
@@ -3445,14 +3445,14 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3445
3445
  .machine-option.selected .machine-option-main { background: var(--pi-selection-bg); }
3446
3446
  @keyframes machine-activity-pulse { 0%, 100% { opacity: .55; } 50% { opacity: 1; } }
3447
3447
  }
3448
- `]}};g([y({attribute:!1})],GL.prototype,`machines`,void 0),g([y({attribute:!1})],GL.prototype,`selected`,void 0),g([y({attribute:!1})],GL.prototype,`statuses`,void 0),g([y({attribute:!1})],GL.prototype,`activities`,void 0),g([y({attribute:!1})],GL.prototype,`unreadMachineIds`,void 0),g([y({attribute:!1})],GL.prototype,`statusSnapshots`,void 0),g([y({attribute:!1})],GL.prototype,`onSelect`,void 0),g([y({attribute:!1})],GL.prototype,`onEdit`,void 0),g([y({attribute:!1})],GL.prototype,`onRemove`,void 0),g([y({attribute:!1})],GL.prototype,`onFocusNextSection`,void 0),g([y({attribute:!1})],GL.prototype,`onCancelKeyboardNavigation`,void 0),g([v()],GL.prototype,`open`,void 0),g([v()],GL.prototype,`openActionsMachineId`,void 0),GL=g([_(`machine-switcher`)],GL);function KL(e,t){return t[e.id]?.status??e.status??`unknown`}function qL(e){return F.t(e)}function JL(e){return e.baseUrl??e.name}function YL(e){return e.kind===`local`?SL():e.baseUrl??F.t(`remote`)}var Q=class extends O{constructor(){super(),this.machines=[],this.presentationContext={mode:`normal`},this.machineStatuses={},this.machineActivities={},this.machineStatusSnapshots={},this.projects=[],this.workspaces=[],this.sessions=[],this.pinnedSessionIds=[],this.projectSelectionLoading=!1,this.sessionsLoading=!1,this.pinnedRootIds=[],this.workspaceSelectionVisible=!0,this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.unreadSessionIds=new Set,this.unreadPresence=vd,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=C(`ui.appNavigationPanel.updateAndRestartPiWebOnThisMachine2`,`Update and restart Pi-Web on this machine before deleting archived sessions.`),this.cleanupUnavailableMessage=C(`ui.appNavigationPanel.updateAndRestartPiWebOnThisMachine`,`Update and restart Pi-Web on this machine before cleaning up sessions.`),this.sectionSizes=new LL(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),markSessionUnread:e=>this.onMarkSessionUnread?.(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=[],new S(this),o.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:C(`client.sessionController.new.session.c57c30`,`New session`),disabled:!this.canStartSession,run:()=>this.onStartSession?.()}),this.onSearchSessions!==void 0&&t.push({id:`search`,label:C(`ui.sessionSearchDialog.searchSessions`,`Search sessions`),run:()=>{this.onSearchSessions?.()}}),!this.managementMode&&this.onAddProject!==void 0&&t.push({id:`add-project`,label:C(`client.actions.add.project.8964f5`,`Add project`),run:()=>{this.onAddProject?.()}}),this.onShowSettings!==void 0&&t.push({id:`settings`,label:C(`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:D`<navigation-section-resize-handle
3448
+ `]}};g([y({attribute:!1})],KL.prototype,`machines`,void 0),g([y({attribute:!1})],KL.prototype,`selected`,void 0),g([y({attribute:!1})],KL.prototype,`statuses`,void 0),g([y({attribute:!1})],KL.prototype,`activities`,void 0),g([y({attribute:!1})],KL.prototype,`unreadMachineIds`,void 0),g([y({attribute:!1})],KL.prototype,`statusSnapshots`,void 0),g([y({attribute:!1})],KL.prototype,`onSelect`,void 0),g([y({attribute:!1})],KL.prototype,`onEdit`,void 0),g([y({attribute:!1})],KL.prototype,`onRemove`,void 0),g([y({attribute:!1})],KL.prototype,`onFocusNextSection`,void 0),g([y({attribute:!1})],KL.prototype,`onCancelKeyboardNavigation`,void 0),g([v()],KL.prototype,`open`,void 0),g([v()],KL.prototype,`openActionsMachineId`,void 0),KL=g([_(`machine-switcher`)],KL);function qL(e,t){return t[e.id]?.status??e.status??`unknown`}function JL(e){return F.t(e)}function YL(e){return e.baseUrl??e.name}function XL(e){return e.kind===`local`?CL():e.baseUrl??F.t(`remote`)}var Q=class extends O{constructor(){super(),this.machines=[],this.presentationContext={mode:`normal`},this.machineStatuses={},this.machineActivities={},this.machineStatusSnapshots={},this.projects=[],this.workspaces=[],this.sessions=[],this.pinnedSessionIds=[],this.projectSelectionLoading=!1,this.sessionsLoading=!1,this.pinnedRootIds=[],this.workspaceSelectionVisible=!0,this.workspaceActivities={},this.sessionActivities={},this.sessionStatuses={},this.sendingPrompts={},this.unreadSessionIds=new Set,this.unreadPresence=vd,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=C(`ui.appNavigationPanel.updateAndRestartPiWebOnThisMachine2`,`Update and restart Pi-Web on this machine before deleting archived sessions.`),this.cleanupUnavailableMessage=C(`ui.appNavigationPanel.updateAndRestartPiWebOnThisMachine`,`Update and restart Pi-Web on this machine before cleaning up sessions.`),this.sectionSizes=new RL(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),markSessionUnread:e=>this.onMarkSessionUnread?.(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=[],new S(this),o.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:C(`client.sessionController.new.session.c57c30`,`New session`),disabled:!this.canStartSession,run:()=>this.onStartSession?.()}),this.onSearchSessions!==void 0&&t.push({id:`search`,label:C(`ui.sessionSearchDialog.searchSessions`,`Search sessions`),run:()=>{this.onSearchSessions?.()}}),!this.managementMode&&this.onAddProject!==void 0&&t.push({id:`add-project`,label:C(`client.actions.add.project.8964f5`,`Add project`),run:()=>{this.onAddProject?.()}}),this.onShowSettings!==void 0&&t.push({id:`settings`,label:C(`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:D`<navigation-section-resize-handle
3449
3449
  slot=${e===`projects`?`project-resize`:`workspace-resize`}
3450
3450
  .sectionLabel=${e===`projects`?k.t(`projects`):k.t(`workspaces`)}
3451
3451
  .controls=${`navigation-${e}`}
3452
3452
  .measurement=${this.sectionMeasurements[e]}
3453
3453
  .onResize=${t=>{this.sectionSizes.resize(e,t)}}
3454
3454
  .onReset=${()=>{this.sectionSizes.reset(e)}}
3455
- ></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=ZL(this.machines),n=!this.managementMode||t,r=this.refreshControl!==void 0||this.onShowActions!==void 0,i=this.showBrand||n||r||this.onTogglePanel!==void 0;return D`
3455
+ ></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=QL(this.machines),n=!this.managementMode||t,r=this.refreshControl!==void 0||this.onShowActions!==void 0,i=this.showBrand||n||r||this.onTogglePanel!==void 0;return D`
3456
3456
  <pi-web-ui-presentation region="navigation" .runtime=${this.presentationRuntime} .context=${this.navigationPresentationContext()}>
3457
3457
  ${i?D`<header slot="header">
3458
3458
  ${or(`navigation`,!1,this.onTogglePanel)}
@@ -3511,7 +3511,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3511
3511
  slot="projects"
3512
3512
  .machineId=${this.selectedMachine?.id??`local`}
3513
3513
  id="navigation-projects"
3514
- style=${KP(this.sectionSizeStyle(`projects`))}
3514
+ style=${qP(this.sectionSizeStyle(`projects`))}
3515
3515
  ?data-manual-size=${!this.compact&&this.sectionSizes.height(`projects`)!==void 0}
3516
3516
  .projects=${this.projects}
3517
3517
  .selected=${this.selectedProject}
@@ -3535,7 +3535,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3535
3535
  ></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?D``:this.workspaceSelectionVisible?this.renderWorkspaceList(!0):this.selectedWorkspace?.projectId===this.selectedProject.id?this.renderSessionList(!0):D``),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 D`<workspace-list
3536
3536
  slot="workspaces"
3537
3537
  id="navigation-workspaces"
3538
- style=${KP(this.sectionSizeStyle(`workspaces`))}
3538
+ style=${qP(this.sectionSizeStyle(`workspaces`))}
3539
3539
  ?data-manual-size=${!this.compact&&this.sectionSizes.height(`workspaces`)!==void 0}
3540
3540
  .machineId=${this.selectedMachine?.id??`local`}
3541
3541
  .managementMode=${this.managementMode}
@@ -3560,12 +3560,12 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3560
3560
  ></workspace-list>`}renderSessionList(e){return D`<session-list
3561
3561
  slot="sessions"
3562
3562
  .externalScroll=${e}
3563
- .scopeKey=${XL(this.selectedMachine?.id,this.selectedWorkspace?.id)}
3563
+ .scopeKey=${ZL(this.selectedMachine?.id,this.selectedWorkspace?.id)}
3564
3564
  .sessions=${e?this.treeSessions():this.sessions}
3565
3565
  .pinnedSessionIds=${this.pinnedSessionIds}
3566
3566
  .loading=${this.sessionsLoading}
3567
3567
  .pinnedRootIds=${this.pinnedRootIds}
3568
- .onMovePin=${this.managementMode||this.onMoveSessionPin===void 0?void 0:this.childCallbacks.moveSessionPin}
3568
+ .onMovePin=${this.onMoveSessionPin===void 0?void 0:this.childCallbacks.moveSessionPin}
3569
3569
  .statuses=${this.sessionStatuses}
3570
3570
  .activities=${this.sessionActivities}
3571
3571
  .sessionFlags=${this.selectedMachineStatusSnapshot()?.sessions}
@@ -3606,7 +3606,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3606
3606
  .onFocusPreviousSection=${this.childCallbacks.previousFromSessions}
3607
3607
  .onFocusNextSection=${this.childCallbacks.nextFromSessions}
3608
3608
  .onCancelKeyboardNavigation=${this.childCallbacks.cancelKeyboardNavigation}
3609
- ></session-list>`}selectedMachineStatusSnapshot(){return this.machineStatusSnapshots[N({selectedMachine:this.selectedMachine})]}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=QL(e,this.machines,this.workspaceSelectionVisible);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.($L(e,this.machines,this.workspaceSelectionVisible))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=[e,T`
3609
+ ></session-list>`}selectedMachineStatusSnapshot(){return this.machineStatusSnapshots[N({selectedMachine:this.selectedMachine})]}async focusNavigableSection(e){return e!==void 0&&await e.focusSelectedOrFirst()}focusPreviousFrom(e){let t=$L(e,this.machines,this.workspaceSelectionVisible);t!==void 0&&this.onFocusNavigationTarget?.(t)}focusNextFrom(e){this.onFocusNavigationTarget?.(eR(e,this.machines,this.workspaceSelectionVisible))}cancelKeyboardNavigation(){this.onCancelKeyboardNavigation?.()}static{this.styles=[e,T`
3610
3610
  :host { display: flex; flex-direction: column; min-height: 0; overflow: hidden; container: navigation-panel / inline-size; }
3611
3611
  :host([compact]) { flex: 1 1 auto; }
3612
3612
  header { flex: 0 0 auto; display: flex; align-items: stretch; min-height: 44px; gap: 0; padding: 0; border-bottom: 1px solid var(--pi-border); }
@@ -3635,7 +3635,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3635
3635
  project-list[collapsed],
3636
3636
  workspace-list[collapsed],
3637
3637
  session-list[collapsed] { flex: 0 0 auto; min-height: auto; overflow: hidden; border-bottom: 0; }
3638
- `]}};g([y({attribute:!1})],Q.prototype,`machines`,void 0),g([y({attribute:!1})],Q.prototype,`presentationRuntime`,void 0),g([y({attribute:!1})],Q.prototype,`presentationContext`,void 0),g([y({attribute:!1})],Q.prototype,`selectedMachine`,void 0),g([y({attribute:!1})],Q.prototype,`machineStatuses`,void 0),g([y({attribute:!1})],Q.prototype,`machineActivities`,void 0),g([y({attribute:!1})],Q.prototype,`machineStatusSnapshots`,void 0),g([y({attribute:!1})],Q.prototype,`projects`,void 0),g([y({attribute:!1})],Q.prototype,`selectedProject`,void 0),g([y({attribute:!1})],Q.prototype,`workspaces`,void 0),g([y({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),g([y({attribute:!1})],Q.prototype,`sessions`,void 0),g([y({attribute:!1})],Q.prototype,`pinnedSessionIds`,void 0),g([y({type:Boolean})],Q.prototype,`projectSelectionLoading`,void 0),g([y({type:Boolean})],Q.prototype,`sessionsLoading`,void 0),g([y({attribute:!1})],Q.prototype,`selectedSession`,void 0),g([y({attribute:!1})],Q.prototype,`pinnedRootIds`,void 0),g([y({type:Boolean})],Q.prototype,`workspaceSelectionVisible`,void 0),g([y({attribute:!1})],Q.prototype,`onMoveProject`,void 0),g([y({attribute:!1})],Q.prototype,`onMoveWorkspace`,void 0),g([y({attribute:!1})],Q.prototype,`onMoveSessionPin`,void 0),g([y({attribute:!1})],Q.prototype,`onTogglePanel`,void 0),g([y({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),g([y({attribute:!1})],Q.prototype,`sessionActivities`,void 0),g([y({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),g([y({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),g([y({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),g([y({attribute:!1})],Q.prototype,`unreadPresence`,void 0),g([y({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),g([y({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),g([y({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),g([y({attribute:!1})],Q.prototype,`sessionLabelItems`,void 0),g([y({attribute:!1})],Q.prototype,`refreshControl`,void 0),g([y({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),g([y({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),g([y({type:Boolean})],Q.prototype,`showBrand`,void 0),g([y({type:Boolean})],Q.prototype,`managementMode`,void 0),g([y({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),g([y({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),g([y({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),g([y({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),g([y({type:Number})],Q.prototype,`startingSessionCount`,void 0),g([y({type:Boolean})],Q.prototype,`canStartSession`,void 0),g([y({type:Boolean})],Q.prototype,`canDeleteArchivedSessions`,void 0),g([y({type:Boolean})],Q.prototype,`canReloadSessions`,void 0),g([y({type:Boolean})],Q.prototype,`canCleanupSessions`,void 0),g([y({type:Boolean})],Q.prototype,`authoritativeSessionPersistence`,void 0),g([y({type:String})],Q.prototype,`archivedDeleteUnavailableMessage`,void 0),g([y({type:String})],Q.prototype,`cleanupUnavailableMessage`,void 0),g([y({attribute:!1})],Q.prototype,`onShowActions`,void 0),g([y({attribute:!1})],Q.prototype,`onAddProject`,void 0),g([y({attribute:!1})],Q.prototype,`onShowSettings`,void 0),g([y({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),g([y({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),g([y({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),g([y({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),g([y({attribute:!1})],Q.prototype,`onSelectProject`,void 0),g([y({attribute:!1})],Q.prototype,`onCloseProject`,void 0),g([y({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),g([y({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),g([y({attribute:!1})],Q.prototype,`onStartSession`,void 0),g([y({attribute:!1})],Q.prototype,`onSelectSession`,void 0),g([y({attribute:!1})],Q.prototype,`onSearchSessions`,void 0),g([y({attribute:!1})],Q.prototype,`onToggleSessionPin`,void 0),g([y({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),g([y({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),g([y({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),g([y({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),g([y({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),g([y({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),g([y({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),g([y({attribute:!1})],Q.prototype,`onRenameSession`,void 0),g([y({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),g([y({attribute:!1})],Q.prototype,`onMarkSessionRead`,void 0),g([y({attribute:!1})],Q.prototype,`onMarkSessionUnread`,void 0),g([y({attribute:!1})],Q.prototype,`onMarkSessionsRead`,void 0),g([y({attribute:!1})],Q.prototype,`onReloadSession`,void 0),g([y({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),g([y({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),g([y({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),g([y({attribute:!1})],Q.prototype,`onEditMachine`,void 0),g([y({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),g([y({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),g([y({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),g([v()],Q.prototype,`sectionMeasurements`,void 0),g([Te(`machine-list`)],Q.prototype,`machineList`,void 0),g([Te(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),g([Te(`project-list`)],Q.prototype,`projectList`,void 0),Q=g([_(`app-navigation-panel`)],Q);function XL(e,t){return JSON.stringify([e??``,t??``])}function ZL(e){return e.length>1}function QL(e,t,n=!0){let r=eR(t,n);return r[r.indexOf(e)-1]}function $L(e,t,n=!0){let r=eR(t,n);return r[r.indexOf(e)+1]??`chat`}function eR(e,t=!0){return Mk.filter(n=>(n!==`machines`||ZL(e))&&(n!==`workspaces`||t))}var tR=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),nR=420,rR=4,iR=class extends O{constructor(){super(),this.side=`navigation`,this.collapsed=!1,this.resizable=!1,this.controls=``,this.expandLabel=C(`ui.appPanelEdgeControl.expandPanel`,`Expand panel`),this.collapseLabel=C(`ui.appPanelEdgeControl.collapsePanel`,`Collapse panel`),this.lastTapAt=0,new S(this),o.createController(this)}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){return this.renderResizeHandle()}renderResizeHandle(){if(!this.resizable)return E;let e=this.resizeConstraints();return D`
3638
+ `]}};g([y({attribute:!1})],Q.prototype,`machines`,void 0),g([y({attribute:!1})],Q.prototype,`presentationRuntime`,void 0),g([y({attribute:!1})],Q.prototype,`presentationContext`,void 0),g([y({attribute:!1})],Q.prototype,`selectedMachine`,void 0),g([y({attribute:!1})],Q.prototype,`machineStatuses`,void 0),g([y({attribute:!1})],Q.prototype,`machineActivities`,void 0),g([y({attribute:!1})],Q.prototype,`machineStatusSnapshots`,void 0),g([y({attribute:!1})],Q.prototype,`projects`,void 0),g([y({attribute:!1})],Q.prototype,`selectedProject`,void 0),g([y({attribute:!1})],Q.prototype,`workspaces`,void 0),g([y({attribute:!1})],Q.prototype,`selectedWorkspace`,void 0),g([y({attribute:!1})],Q.prototype,`sessions`,void 0),g([y({attribute:!1})],Q.prototype,`pinnedSessionIds`,void 0),g([y({type:Boolean})],Q.prototype,`projectSelectionLoading`,void 0),g([y({type:Boolean})],Q.prototype,`sessionsLoading`,void 0),g([y({attribute:!1})],Q.prototype,`selectedSession`,void 0),g([y({attribute:!1})],Q.prototype,`pinnedRootIds`,void 0),g([y({type:Boolean})],Q.prototype,`workspaceSelectionVisible`,void 0),g([y({attribute:!1})],Q.prototype,`onMoveProject`,void 0),g([y({attribute:!1})],Q.prototype,`onMoveWorkspace`,void 0),g([y({attribute:!1})],Q.prototype,`onMoveSessionPin`,void 0),g([y({attribute:!1})],Q.prototype,`onTogglePanel`,void 0),g([y({attribute:!1})],Q.prototype,`workspaceActivities`,void 0),g([y({attribute:!1})],Q.prototype,`sessionActivities`,void 0),g([y({attribute:!1})],Q.prototype,`sessionStatuses`,void 0),g([y({attribute:!1})],Q.prototype,`sendingPrompts`,void 0),g([y({attribute:!1})],Q.prototype,`unreadSessionIds`,void 0),g([y({attribute:!1})],Q.prototype,`unreadPresence`,void 0),g([y({attribute:!1})],Q.prototype,`workspacesByProjectId`,void 0),g([y({attribute:!1})],Q.prototype,`deletingWorkspaceIds`,void 0),g([y({attribute:!1})],Q.prototype,`workspaceLabelItems`,void 0),g([y({attribute:!1})],Q.prototype,`sessionLabelItems`,void 0),g([y({attribute:!1})],Q.prototype,`refreshControl`,void 0),g([y({type:Boolean,reflect:!0})],Q.prototype,`collapsible`,void 0),g([y({type:Boolean,reflect:!0})],Q.prototype,`compact`,void 0),g([y({type:Boolean})],Q.prototype,`showBrand`,void 0),g([y({type:Boolean})],Q.prototype,`managementMode`,void 0),g([y({type:Boolean})],Q.prototype,`machinesCollapsed`,void 0),g([y({type:Boolean})],Q.prototype,`projectsCollapsed`,void 0),g([y({type:Boolean})],Q.prototype,`workspacesCollapsed`,void 0),g([y({type:Boolean})],Q.prototype,`sessionsCollapsed`,void 0),g([y({type:Number})],Q.prototype,`startingSessionCount`,void 0),g([y({type:Boolean})],Q.prototype,`canStartSession`,void 0),g([y({type:Boolean})],Q.prototype,`canDeleteArchivedSessions`,void 0),g([y({type:Boolean})],Q.prototype,`canReloadSessions`,void 0),g([y({type:Boolean})],Q.prototype,`canCleanupSessions`,void 0),g([y({type:Boolean})],Q.prototype,`authoritativeSessionPersistence`,void 0),g([y({type:String})],Q.prototype,`archivedDeleteUnavailableMessage`,void 0),g([y({type:String})],Q.prototype,`cleanupUnavailableMessage`,void 0),g([y({attribute:!1})],Q.prototype,`onShowActions`,void 0),g([y({attribute:!1})],Q.prototype,`onAddProject`,void 0),g([y({attribute:!1})],Q.prototype,`onShowSettings`,void 0),g([y({attribute:!1})],Q.prototype,`onToggleMachines`,void 0),g([y({attribute:!1})],Q.prototype,`onToggleProjects`,void 0),g([y({attribute:!1})],Q.prototype,`onToggleWorkspaces`,void 0),g([y({attribute:!1})],Q.prototype,`onToggleSessions`,void 0),g([y({attribute:!1})],Q.prototype,`onSelectProject`,void 0),g([y({attribute:!1})],Q.prototype,`onCloseProject`,void 0),g([y({attribute:!1})],Q.prototype,`onSelectWorkspace`,void 0),g([y({attribute:!1})],Q.prototype,`onDeleteWorkspace`,void 0),g([y({attribute:!1})],Q.prototype,`onStartSession`,void 0),g([y({attribute:!1})],Q.prototype,`onSelectSession`,void 0),g([y({attribute:!1})],Q.prototype,`onSearchSessions`,void 0),g([y({attribute:!1})],Q.prototype,`onToggleSessionPin`,void 0),g([y({attribute:!1})],Q.prototype,`onArchiveSession`,void 0),g([y({attribute:!1})],Q.prototype,`onArchiveSessionWithDescendants`,void 0),g([y({attribute:!1})],Q.prototype,`onArchiveSessions`,void 0),g([y({attribute:!1})],Q.prototype,`onRestoreSession`,void 0),g([y({attribute:!1})],Q.prototype,`onDeleteCachedNewSession`,void 0),g([y({attribute:!1})],Q.prototype,`onDeleteArchivedSession`,void 0),g([y({attribute:!1})],Q.prototype,`onDeleteArchivedSessions`,void 0),g([y({attribute:!1})],Q.prototype,`onRenameSession`,void 0),g([y({attribute:!1})],Q.prototype,`onDetachParentSession`,void 0),g([y({attribute:!1})],Q.prototype,`onMarkSessionRead`,void 0),g([y({attribute:!1})],Q.prototype,`onMarkSessionUnread`,void 0),g([y({attribute:!1})],Q.prototype,`onMarkSessionsRead`,void 0),g([y({attribute:!1})],Q.prototype,`onReloadSession`,void 0),g([y({attribute:!1})],Q.prototype,`onCleanupSessions`,void 0),g([y({attribute:!1})],Q.prototype,`onArchivedCollapsed`,void 0),g([y({attribute:!1})],Q.prototype,`onSelectMachine`,void 0),g([y({attribute:!1})],Q.prototype,`onEditMachine`,void 0),g([y({attribute:!1})],Q.prototype,`onRemoveMachine`,void 0),g([y({attribute:!1})],Q.prototype,`onFocusNavigationTarget`,void 0),g([y({attribute:!1})],Q.prototype,`onCancelKeyboardNavigation`,void 0),g([v()],Q.prototype,`sectionMeasurements`,void 0),g([Te(`machine-list`)],Q.prototype,`machineList`,void 0),g([Te(`machine-switcher`)],Q.prototype,`machineSwitcher`,void 0),g([Te(`project-list`)],Q.prototype,`projectList`,void 0),Q=g([_(`app-navigation-panel`)],Q);function ZL(e,t){return JSON.stringify([e??``,t??``])}function QL(e){return e.length>1}function $L(e,t,n=!0){let r=tR(t,n);return r[r.indexOf(e)-1]}function eR(e,t,n=!0){let r=tR(t,n);return r[r.indexOf(e)+1]??`chat`}function tR(e,t=!0){return Mk.filter(n=>(n!==`machines`||QL(e))&&(n!==`workspaces`||t))}var nR=new Set([`ArrowLeft`,`ArrowRight`,`Home`,`End`]),rR=420,iR=4,aR=class extends O{constructor(){super(),this.side=`navigation`,this.collapsed=!1,this.resizable=!1,this.controls=``,this.expandLabel=C(`ui.appPanelEdgeControl.expandPanel`,`Expand panel`),this.collapseLabel=C(`ui.appPanelEdgeControl.collapsePanel`,`Collapse panel`),this.lastTapAt=0,new S(this),o.createController(this)}disconnectedCallback(){this.finishActiveResize(),super.disconnectedCallback()}render(){return this.renderResizeHandle()}renderResizeHandle(){if(!this.resizable)return E;let e=this.resizeConstraints();return D`
3639
3639
  <div
3640
3640
  class="resize-handle"
3641
3641
  role="separator"
@@ -3654,7 +3654,7 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3654
3654
  @dblclick=${e=>{this.onResizeDoubleClick(e)}}
3655
3655
  @keydown=${e=>{this.onResizeKeyDown(e)}}
3656
3656
  ></div>
3657
- `}resizeAriaValueNow(){return this.panelWidth===void 0?E:String(Math.round(this.panelWidth))}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)<=rR)&&(t.moved=!0,this.commitPanelWidth(Qk(this.side,t.startWidth,t.startClientX,w.direction===`rtl`?2*t.startClientX-e.clientX: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||!tR.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=w.direction===`rtl`?e.key===`ArrowLeft`?`ArrowRight`:e.key===`ArrowRight`?`ArrowLeft`:e.key:e.key,r=$k(this.side,t,n,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});r!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(r),this.onResizeEnd?.())}registerTapForReset(){let e=Date.now();e-this.lastTapAt<=nR?(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 eA(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(eA(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=Xk(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=T`
3657
+ `}resizeAriaValueNow(){return this.panelWidth===void 0?E:String(Math.round(this.panelWidth))}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)<=iR)&&(t.moved=!0,this.commitPanelWidth(Qk(this.side,t.startWidth,t.startClientX,w.direction===`rtl`?2*t.startClientX-e.clientX: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||!nR.has(e.key))return;let t=this.resizeStartWidth();if(t===void 0)return;let n=w.direction===`rtl`?e.key===`ArrowLeft`?`ArrowRight`:e.key===`ArrowRight`?`ArrowLeft`:e.key:e.key,r=$k(this.side,t,n,{largeStep:e.shiftKey,constraints:this.resizeConstraints()});r!==void 0&&(e.preventDefault(),e.stopPropagation(),this.commitPanelWidth(r),this.onResizeEnd?.())}registerTapForReset(){let e=Date.now();e-this.lastTapAt<=rR?(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 eA(this.side,e,this.resizeConstraints())}commitPanelWidth(e){this.onResize?.(eA(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=Xk(this.side);return{...e,minWidth:this.minWidth??e.minWidth,maxWidth:this.maxWidth??e.maxWidth}}static{this.styles=T`
3658
3658
  @layer pi-web-base {
3659
3659
  :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; }
3660
3660
  :host([side="navigation"]) { grid-column: 2; }
@@ -3676,9 +3676,9 @@ This only removes it from PI WEB; it will not change the project folder.`,`Proje
3676
3676
  }
3677
3677
 
3678
3678
  }
3679
- `}};g([y({reflect:!0})],iR.prototype,`side`,void 0),g([y({type:Boolean,reflect:!0})],iR.prototype,`collapsed`,void 0),g([y({type:Boolean})],iR.prototype,`resizable`,void 0),g([y({type:Number})],iR.prototype,`panelWidth`,void 0),g([y({type:Number})],iR.prototype,`minWidth`,void 0),g([y({type:Number})],iR.prototype,`maxWidth`,void 0),g([y()],iR.prototype,`controls`,void 0),g([y()],iR.prototype,`resizeLabel`,void 0),g([y()],iR.prototype,`expandLabel`,void 0),g([y()],iR.prototype,`collapseLabel`,void 0),g([y({attribute:!1})],iR.prototype,`onToggle`,void 0),g([y({attribute:!1})],iR.prototype,`onResizeStart`,void 0),g([y({attribute:!1})],iR.prototype,`onResize`,void 0),g([y({attribute:!1})],iR.prototype,`onResizeEnd`,void 0),g([y({attribute:!1})],iR.prototype,`onReset`,void 0),iR=g([_(`app-panel-edge-control`)],iR);var aR={navigationOrderFailed:x(`Failed to load or save navigation order: {detail}`,`Navigation ordering failure; diagnostic stays unchanged`),workspaceRemovalUnavailable:x(`Workspace removal is not available`,`Requested workspace has no supported removal action`),workspaceRemovalFailed:x(`Failed to start workspace removal: {detail}`,`Workspace removal could not start; diagnostic stays unchanged`),workspaceRemovalRefreshFailed:x(`Workspace removal succeeded, but refreshing the workspace list failed: {detail}. Retrying…`,`Removal completed but the list refresh will be retried; diagnostic stays unchanged`),removeMachine:x(`Remove {name}?
3679
+ `}};g([y({reflect:!0})],aR.prototype,`side`,void 0),g([y({type:Boolean,reflect:!0})],aR.prototype,`collapsed`,void 0),g([y({type:Boolean})],aR.prototype,`resizable`,void 0),g([y({type:Number})],aR.prototype,`panelWidth`,void 0),g([y({type:Number})],aR.prototype,`minWidth`,void 0),g([y({type:Number})],aR.prototype,`maxWidth`,void 0),g([y()],aR.prototype,`controls`,void 0),g([y()],aR.prototype,`resizeLabel`,void 0),g([y()],aR.prototype,`expandLabel`,void 0),g([y()],aR.prototype,`collapseLabel`,void 0),g([y({attribute:!1})],aR.prototype,`onToggle`,void 0),g([y({attribute:!1})],aR.prototype,`onResizeStart`,void 0),g([y({attribute:!1})],aR.prototype,`onResize`,void 0),g([y({attribute:!1})],aR.prototype,`onResizeEnd`,void 0),g([y({attribute:!1})],aR.prototype,`onReset`,void 0),aR=g([_(`app-panel-edge-control`)],aR);var oR={navigationOrderFailed:x(`Failed to load or save navigation order: {detail}`,`Navigation ordering failure; diagnostic stays unchanged`),workspaceRemovalUnavailable:x(`Workspace removal is not available`,`Requested workspace has no supported removal action`),workspaceRemovalFailed:x(`Failed to start workspace removal: {detail}`,`Workspace removal could not start; diagnostic stays unchanged`),workspaceRemovalRefreshFailed:x(`Workspace removal succeeded, but refreshing the workspace list failed: {detail}. Retrying…`,`Removal completed but the list refresh will be retried; diagnostic stays unchanged`),removeMachine:x(`Remove {name}?
3680
3680
 
3681
- This only removes it from this PI WEB gateway.`,`Confirmation for forgetting a remote machine, not deleting its data; machine name stays unchanged`),actionFailed:x(`Action failed: {detail}`,`Unexpected action failure; raw diagnostics stay unchanged and browser-owned nested guidance retains live localization`),activityLabel:x(`Recent activity in another instance`,`Accessible name of the cross-instance session activity alert`),activityNotice:x(`Recently active in another PI-WEB instance. Avoid working on this session in both instances at once.`,`Session activity warning above the composer`),dismissActivity:x(`Dismiss and continue`,`Acknowledge cross-instance activity and resume composing`),loadingConversation:x(`Loading conversation…`,`Selected conversation is being loaded before the transcript mounts`)},oR=w.registerMessages(`core.appFeedback`,aR),sR=class extends O{constructor(){super(),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()},new S(this),o.createController(this)}render(){let e=k.t(`reload`);return D`
3681
+ This only removes it from this PI WEB gateway.`,`Confirmation for forgetting a remote machine, not deleting its data; machine name stays unchanged`),actionFailed:x(`Action failed: {detail}`,`Unexpected action failure; raw diagnostics stay unchanged and browser-owned nested guidance retains live localization`),activityLabel:x(`Recent activity in another instance`,`Accessible name of the cross-instance session activity alert`),activityNotice:x(`Recently active in another PI-WEB instance. Avoid working on this session in both instances at once.`,`Session activity warning above the composer`),dismissActivity:x(`Dismiss and continue`,`Acknowledge cross-instance activity and resume composing`),loadingConversation:x(`Loading conversation…`,`Selected conversation is being loaded before the transcript mounts`)},sR=w.registerMessages(`core.appFeedback`,oR),cR=class extends O{constructor(){super(),this.onReloadClick=e=>{e.stopPropagation(),this.onReload?.()},new S(this),o.createController(this)}render(){let e=k.t(`reload`);return D`
3682
3682
  <button
3683
3683
  class="app-refresh-button"
3684
3684
  title=${e}
@@ -3702,18 +3702,18 @@ This only removes it from this PI WEB gateway.`,`Confirmation for forgetting a r
3702
3702
  .app-refresh-icon { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; pointer-events: none; }
3703
3703
 
3704
3704
  }
3705
- `}};g([y({attribute:!1})],sR.prototype,`onReload`,void 0),sR=g([_(`app-refresh-control`)],sR);var cR={dismissError:x(`Dismiss error`,`Accessible name and tooltip for dismissing an error banner`),dismissWarning:x(`Dismiss warning`,`Accessible name and tooltip for dismissing a warning banner`),dismissInfo:x(`Dismiss info`,`Accessible name and tooltip for dismissing an informational banner`),retry:x(`Retry`,`Retry the failed read operation from a banner`)},lR=w.registerMessages(`core.banners`,cR),uR={error:`dismissError`,warning:`dismissWarning`,info:`dismissInfo`};function dR(e,t,n=`error`,r){if(e===``)return null;let i=lR.t(uR[n]);return D`<div class=${`error ${n}`} role="alert">
3705
+ `}};g([y({attribute:!1})],cR.prototype,`onReload`,void 0),cR=g([_(`app-refresh-control`)],cR);var lR={dismissError:x(`Dismiss error`,`Accessible name and tooltip for dismissing an error banner`),dismissWarning:x(`Dismiss warning`,`Accessible name and tooltip for dismissing a warning banner`),dismissInfo:x(`Dismiss info`,`Accessible name and tooltip for dismissing an informational banner`),retry:x(`Retry`,`Retry the failed read operation from a banner`)},uR=w.registerMessages(`core.banners`,lR),dR={error:`dismissError`,warning:`dismissWarning`,info:`dismissInfo`};function fR(e,t,n=`error`,r){if(e===``)return null;let i=uR.t(dR[n]);return D`<div class=${`error ${n}`} role="alert">
3706
3706
  <span class="error-text">${e}</span>
3707
- ${r===void 0?null:D`<button type="button" class="error-retry ui-button ui-button--compact" @click=${()=>{r()}}>${lR.t(`retry`)}</button>`}
3707
+ ${r===void 0?null:D`<button type="button" class="error-retry ui-button ui-button--compact" @click=${()=>{r()}}>${uR.t(`retry`)}</button>`}
3708
3708
  <button type="button" class="error-dismiss" aria-label=${i} title=${i} @click=${()=>{t()}}>✕</button>
3709
- </div>`}var fR=9e5,pR=3e4,mR=750,hR=[1e3,3e3,8e3,15e3,3e4],gR=[`machine`,`project`,`workspace`,`session`,`tool`,`view`],_R=[`machine`,`project`,`workspace`,`session`],vR=[`tool`,`view`],yR=[1e3,2e3,5e3,1e4],bR={capture:!0},xR=320,SR=2,CR=`workspace.terminal`,wR=gR;function TR(e){let t=vo();return{machineId:N(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 ER(e){return{url:DR(),...e===void 0?{}:{navigation:e}}}function DR(){return window.location.href}function OR(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 kR(e,t){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&AR(e[n],t[n]))}function AR(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 jR(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 MR(e,t){return e.machineId===t.machineId&&e.projectId===t.projectId&&e.workspaceId===t.workspaceId}var $=class extends O{constructor(){super(),this.chatBehaviors=nr,this.state=br(),this.browserErrors=new Ar(()=>this.state,e=>{this.setState(e)}),this.handleChatNavigationChange=e=>{this.chatNavigation=e},this.apiScope=PR(),this.sessionUnread=new ud({onChange:e=>{this.syncUnreadPresence(),N(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(N(this.state),this.state.sessions),this.unreadPresence=vd,this.unreadConnected=!1,this.handleTranscriptRendered=e=>{this.renderedTranscript=e,this.syncSelectedSessionReadState()},this.chatWasVisible=!1,this.unreadRenderGeneration=0,this.modelDialogMutationInFlight=0,this.modelDialogRefreshPending=!1,this.modelDialogScopeInvalidation=0,this.notifications=new fu(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessionWorkTransitions=new Rl,this.sessions=new _l(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Kc,{socket:new wc(this.apiScope),canMutateQueueMessage:(e,t)=>this.canMutateQueueMessage(e,t),notifications:this.notifications,isChatVisible:()=>this.isChatVisible(),automaticSessionCandidates:e=>this.navigationPanel?.automaticSessionCandidates(e)??nM(e,{collapsed:this.navigationSections.isCollapsed(`sessions`)}),observeSessionSnapshot:(e,t)=>{let n=this.sessionWorkTransitions.snapshotObserver(e,t),r=this.state.conversationRefreshedAt===void 0||!Pr(this.state.status),i=this.state.selectedSession,a=this.unreadRenderGeneration,o=i?.id===t?this.sessionUnread.completion(e,i):void 0;return s=>{if(s.sessionId!==t)return;i!==void 0&&o!==void 0&&this.commitUnreadCompletionAfterRender(e,i,o,a);let c=n(s);(r&&Pr(s)||c!==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&&N(this.state)===e&&this.state.selectedSession?.id===t&&(this.promptEditor?.replaceText(n),this.messageRevertTarget?.machineId===e&&this.messageRevertTarget.sessionId===t&&(this.messageRevertTarget=void 0,this.requestUpdate()))}}),this.projectActivityOwnership=new xi(()=>this.state,e=>{this.setState(e)},{api:Et,onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Wr(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.machineStatus=new ai(()=>this.state,e=>{this.setState(e)}),this.auth=new Jr(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)},{scope:this.apiScope}),this.workspaces=new Cu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new yu,{captureNavigation:()=>this.captureNavigation(),beginNavigationOperation:e=>this.beginNavigationOperation(e),navigateToWorkspace:(e,t)=>this.navigateToWorkspaceFromController(e,t)}),this.projects=new yi(()=>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 ei(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects,{captureNavigation:()=>this.captureNavigation(),navigateToMachine:(e,t)=>this.selectMachineWithMemory(e,t)}),this.piWebStatusController=new Ei(()=>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 ci(fi,{onChange:()=>{this.navigationOrderVersion+=1},onError:(e,t)=>{this.browserErrors.reportLocalized(j(e.machineId),()=>oR.t(`navigationOrderFailed`,{detail:ez(t)}))}}),this.keyboard=new Me,this.realtime=new Tc(this.apiScope),this.serverNotices=new jd({onChange:e=>{N(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 Iu,this.appShell=new Tk(this),this.browserResume=new Dk({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:e=>this.refreshAfterBrowserResume(e),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new Wk(this),this.panelResize=new Yk(this),this.navigationSections=new Bk(this,()=>({...this.state,workspaceSelectionVisible:gu(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.modelDialogInstanceId=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 c(i,e=>{this.plugins.failUiPresentationStylesheetError(e),console.error(`Failed to apply plugin stylesheets`,e)},e=>{console.error(`Failed to apply theme stylesheets`,e),this.revealAfterRender()}),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.fileIcons=new iw,this.fileIconPreference=Ie(),this.plugins=new qD({hostCapabilities:[{capability:nw,value:this.fileIcons.capability}],onPromptChipsChanged:()=>{this.requestUpdate()},isContributionEnabled:(e,t)=>this.pluginContributionAvailable(e,t),getSelection:()=>mn(this.state),onUiPresentationError:(e,t)=>{let n=`${e}: ${ez(t)}`;this.pluginLoadErrors.set(`local`,n),this.browserErrors.report(j(N(this.state)),n),this.applyPreferredTheme(!1),this.requestUpdate()}}),this.resetKeyboardSequence=()=>{this.keyboard.reset()},this.builtInPluginsReady=this.plugins.registerBatch([{id:`core`,plugin:Qf},{id:`themes`,plugin:YC}]).then(({failures:e})=>{if(e.length>0)throw e[0]?.error;this.isConnected&&this.applyPreferredTheme(!1),this.invalidateWorkspaceSurface()}),this.pluginLoads=new gk((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.declarativeThemesReady=be.catalog.then(e=>(e!==void 0&&(this.declarativeThemes===void 0&&this.registerThemeCatalog(e),this.requestedThemeId??=me(e,void 0).themeId),e)),this.gatewayPluginLoadAttemptComplete=!1,this.themeConfigReady=!1,this.themePolicyFromApplication=!1,this.activeThemeColorScheme=this.startupColorScheme(),this.localThemePreference=ue(),this.activeThemeId=``,this.navigationPreferences=pA(),this.navigationDialogOpen=!1,this.isRefreshingApp=!1,this.sessionSearchDialogOpen=!1,this.sessionCleanupRequestEpoch=0,this.settingsSection=yA(),this.normalAuthLoading=!0,this.normalAuthError=``,this.shortcutConfig={},this.defaultStreamingBehavior=`steer`,this.quietMode=!1,this.workspaceUploadDefaultFolder=Pt(void 0),this.workspaceAttachmentsDefaultFolder=ke(void 0),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`&&$e(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&&M(N(this.state),t.id)===e&&this.unacknowledgedActivitySessionKey()===void 0&&this.effectiveMainView()===`chat`&&this.promptEditor?.disabled===!1&&!this.isRenderedModalOpen()&&this.promptEditor.focusInput()},this.remoteRouteRestoreDetails=new WeakMap,this.handleWorkspaceFileOpen=e=>{let t=this.state.selectedWorkspace,n=e.detail;if(e.defaultPrevented||t===void 0||n.machineId!==N(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=Xa(this.currentContributionQueryForState(),r.contributionId,r.navigationAliases??[],r.query);e.preventDefault(),this.publishWorkspaceTool(r.contributionId,i)},this.workspaceSurfaceRevision=0,this.navigationActions={toggleMachines:()=>{this.cancelAutomaticProjectNavigation(),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.cancelAutomaticProjectNavigation(),this.navigationSections.toggle(`projects`)},toggleWorkspaces:()=>{this.cancelAutomaticProjectNavigation(),this.navigationSections.toggle(`workspaces`)},toggleSessions:()=>{this.cancelAutomaticProjectNavigation(),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])},markSessionUnread:e=>{this.markSessionUnread(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`,async()=>{let t=await this.sessions.restoreSession(e);return t!==void 0&&this.selectSessionFromNavigation(t)}),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.cancelAutomaticProjectNavigation(),this.focusNavigationTarget(e)},cancelKeyboardNavigation:()=>{this.cancelAutomaticProjectNavigation(),this.openChatAndFocusComposer()},moveProject:(e,t)=>{this.moveNavigationItem({kind:`projects`,machineId:N(this.state)},e.id,t)},moveWorkspace:(e,t)=>{this.moveNavigationItem({kind:`workspaces`,machineId:N(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)||N(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=$n(e.expectedQueue,e.index);if(t!==void 0&&!window.confirm(t)||(n?.view?.state.doc.toString()??``)!==``&&!window.confirm(Xn.t(`recallDraft`)))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||N(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:Un(i,e.message.role);if(a===void 0)return;let o={...r,message:a};return this.plugins.runMessageAction(t,o,e=>{let t=()=>N(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(C(`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(Xn.t(`backDraft`)))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.handleNoticeDismiss=e=>{let{machineId:t,sessionId:n,dismissId:r}=e.detail;t===N(this.state)&&n===this.state.selectedSession?.id&&this.sessions.dismissWarning(r)},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.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=ze(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||Be(this.ownerDocument)||e!==void 0&&Re(e))return;let t=ze(this.ownerDocument);if(!(t instanceof HTMLElement&&t!==this&&t!==this.ownerDocument.body&&t!==this.ownerDocument.documentElement&&Re(t)))for(let e of this.renderRoot.querySelectorAll(`app-context-bar, app-mobile-main-tabs, workspace-panel`)){let t=e.shadowRoot?.querySelector(`button[data-navigation-trigger]`);if(t!=null&&Re(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)]},mA(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)}))},new S(this,w,()=>{this.invalidateWorkspaceSurface()}),o.createController(this),new mL(this,()=>this.settingsSection!==void 0,()=>_e(()=>import(`./SettingsDialog-BvlvoXvD.js`),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url),e=>{this.closeSettings(),this.setState({error:ez(e)})})}get themePreference(){return oe(this.localThemePreference,this.configuredThemePreference)}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionActivityAcknowledgement()}updated(){this.sessions.isChatLoadDeferred&&(this.readyChatIdentity=void 0),this.committedChatIdentity=RR(this.state),this.syncSelectedSessionReadState(),this.plugins.notifySelectionChanged(),this.syncFileIcons(),this.syncPluginStylesheets(),this.isChatVisible()?this.sessions.isChatLoadDeferred?this.scheduleSelectedChatLoad():this.displayedChatIdentity=RR(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()}syncSessionActivityAcknowledgement(){if(this.dismissedActivityNotices.size===0)return;let e=this.state.selectedSession,t=this.state.status,n=N(this.state);for(let t of Object.values(this.state.sessionStatuses))t.sessionId!==e?.id&&t.recentlyActiveElsewhere===!1&&this.dismissedActivityNotices.delete(M(n,t.sessionId));e!==void 0&&t?.sessionId===e.id&&t.recentlyActiveElsewhere===!1&&this.dismissedActivityNotices.delete(M(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=M(N(e),t.id);return this.dismissedActivityNotices.has(n)?void 0:n}renderSessionActivityNotice(){return this.unacknowledgedActivitySessionKey()===void 0?null:D`
3710
- <section class="composer-activity-notice" role="alert" aria-label=${oR.t(`activityLabel`)}>
3709
+ </div>`}var pR=9e5,mR=3e4,hR=750,gR=[1e3,3e3,8e3,15e3,3e4],_R=[`machine`,`project`,`workspace`,`session`,`tool`,`view`],vR=[`machine`,`project`,`workspace`,`session`],yR=[`tool`,`view`],bR=[1e3,2e3,5e3,1e4],xR={capture:!0},SR=320,CR=2,wR=`workspace.terminal`,TR=_R;function ER(e){let t=vo();return{machineId:N(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 DR(e){return{url:OR(),...e===void 0?{}:{navigation:e}}}function OR(){return window.location.href}function kR(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 AR(e,t){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&jR(e[n],t[n]))}function jR(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 MR(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 NR(e,t){return e.machineId===t.machineId&&e.projectId===t.projectId&&e.workspaceId===t.workspaceId}var $=class extends O{constructor(){super(),this.chatBehaviors=nr,this.state=br(),this.browserErrors=new Ar(()=>this.state,e=>{this.setState(e)}),this.handleChatNavigationChange=e=>{this.chatNavigation=e},this.apiScope=FR(),this.sessionUnread=new ud({onChange:e=>{this.syncUnreadPresence(),N(this.state)===e&&(this.syncUnreadSessionIds(),this.syncSelectedSessionReadState())},onBackgroundError:(e,t,n)=>{console.warn(`Failed to ${e} session unread state for ${t}`,n)}}),this.unreadSessionIds=this.sessionUnread.unreadSessionIds(N(this.state),this.state.sessions),this.unreadPresence=vd,this.unreadConnected=!1,this.handleTranscriptRendered=e=>{this.renderedTranscript=e,this.syncSelectedSessionReadState()},this.chatWasVisible=!1,this.unreadRenderGeneration=0,this.modelDialogMutationInFlight=0,this.modelDialogRefreshPending=!1,this.modelDialogScopeInvalidation=0,this.notifications=new fu(()=>this.state,e=>{this.setState(e)},{onBackgroundError:(e,t)=>{console.warn(e,t)}}),this.sessionWorkTransitions=new Rl,this.sessions=new _l(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},new Kc,{socket:new wc(this.apiScope),canMutateQueueMessage:(e,t)=>this.canMutateQueueMessage(e,t),notifications:this.notifications,isChatVisible:()=>this.isChatVisible(),automaticSessionCandidates:e=>this.navigationPanel?.automaticSessionCandidates(e)??rM(e,{collapsed:this.navigationSections.isCollapsed(`sessions`)}),observeSessionSnapshot:(e,t)=>{let n=this.sessionWorkTransitions.snapshotObserver(e,t),r=this.state.conversationRefreshedAt===void 0||!Pr(this.state.status),i=this.state.selectedSession,a=this.unreadRenderGeneration,o=i?.id===t?this.sessionUnread.completion(e,i):void 0;return s=>{if(s.sessionId!==t)return;i!==void 0&&o!==void 0&&this.commitUnreadCompletionAfterRender(e,i,o,a);let c=n(s);(r&&Pr(s)||c!==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&&N(this.state)===e&&this.state.selectedSession?.id===t&&(this.promptEditor?.replaceText(n),this.messageRevertTarget?.machineId===e&&this.messageRevertTarget.sessionId===t&&(this.messageRevertTarget=void 0,this.requestUpdate()))}}),this.projectActivityOwnership=new xi(()=>this.state,e=>{this.setState(e)},{api:Et,onError:({machineId:e,projectId:t,error:n})=>{console.warn(`Failed to discover project activity ownership for ${t} on ${e}`,n)}}),this.activity=new Wr(()=>this.state,e=>{this.setState(e)},{onActivityApplied:e=>{this.projectActivityOwnership.handleActivityApplied(e)}}),this.machineStatus=new ai(()=>this.state,e=>{this.setState(e)}),this.auth=new Jr(()=>this.state,e=>{this.setState(e)},e=>{this.sessions.applySessionStatus(e)},{scope:this.apiScope}),this.workspaces=new Cu(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.sessions,new yu,{captureNavigation:()=>this.captureNavigation(),beginNavigationOperation:e=>this.beginNavigationOperation(e),navigateToWorkspace:(e,t)=>this.navigateToWorkspaceFromController(e,t)}),this.projects=new yi(()=>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 ei(()=>this.state,e=>{this.setState(e)},()=>{this.updateUrl()},this.projects,{captureNavigation:()=>this.captureNavigation(),navigateToMachine:(e,t)=>this.selectMachineWithMemory(e,t)}),this.piWebStatusController=new Ei(()=>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 ci(fi,{onChange:()=>{this.navigationOrderVersion+=1},onError:(e,t)=>{this.browserErrors.reportLocalized(j(e.machineId),()=>sR.t(`navigationOrderFailed`,{detail:tz(t)}))}}),this.keyboard=new Me,this.realtime=new Tc(this.apiScope),this.serverNotices=new jd({onChange:e=>{N(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 Iu,this.appShell=new Tk(this),this.browserResume=new Dk({onResumeSignal:()=>{this.handleBrowserResumeSignal()},refreshAfterResume:e=>this.refreshAfterBrowserResume(e),onRefreshError:e=>{console.warn(`Failed to refresh after browser resume`,e)}}),this.panelCollapse=new Wk(this),this.panelResize=new Yk(this),this.navigationSections=new Bk(this,()=>({...this.state,workspaceSelectionVisible:gu(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.modelDialogInstanceId=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 c(i,e=>{this.plugins.failUiPresentationStylesheetError(e),console.error(`Failed to apply plugin stylesheets`,e)},e=>{console.error(`Failed to apply theme stylesheets`,e),this.revealAfterRender()}),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.fileIcons=new iw,this.fileIconPreference=Ie(),this.plugins=new qD({hostCapabilities:[{capability:nw,value:this.fileIcons.capability}],onPromptChipsChanged:()=>{this.requestUpdate()},isContributionEnabled:(e,t)=>this.pluginContributionAvailable(e,t),getSelection:()=>mn(this.state),onUiPresentationError:(e,t)=>{let n=`${e}: ${tz(t)}`;this.pluginLoadErrors.set(`local`,n),this.browserErrors.report(j(N(this.state)),n),this.applyPreferredTheme(!1),this.requestUpdate()}}),this.resetKeyboardSequence=()=>{this.keyboard.reset()},this.builtInPluginsReady=this.plugins.registerBatch([{id:`core`,plugin:Qf},{id:`themes`,plugin:YC}]).then(({failures:e})=>{if(e.length>0)throw e[0]?.error;this.isConnected&&this.applyPreferredTheme(!1),this.invalidateWorkspaceSurface()}),this.pluginLoads=new gk((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.declarativeThemesReady=be.catalog.then(e=>(e!==void 0&&(this.declarativeThemes===void 0&&this.registerThemeCatalog(e),this.requestedThemeId??=me(e,void 0).themeId),e)),this.gatewayPluginLoadAttemptComplete=!1,this.themeConfigReady=!1,this.themePolicyFromApplication=!1,this.activeThemeColorScheme=this.startupColorScheme(),this.localThemePreference=ue(),this.activeThemeId=``,this.navigationPreferences=pA(),this.navigationDialogOpen=!1,this.isRefreshingApp=!1,this.sessionSearchDialogOpen=!1,this.sessionCleanupRequestEpoch=0,this.settingsSection=yA(),this.normalAuthLoading=!0,this.normalAuthError=``,this.shortcutConfig={},this.defaultStreamingBehavior=`steer`,this.quietMode=!1,this.workspaceUploadDefaultFolder=Pt(void 0),this.workspaceAttachmentsDefaultFolder=ke(void 0),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`&&$e(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&&M(N(this.state),t.id)===e&&this.unacknowledgedActivitySessionKey()===void 0&&this.effectiveMainView()===`chat`&&this.promptEditor?.disabled===!1&&!this.isRenderedModalOpen()&&this.promptEditor.focusInput()},this.remoteRouteRestoreDetails=new WeakMap,this.handleWorkspaceFileOpen=e=>{let t=this.state.selectedWorkspace,n=e.detail;if(e.defaultPrevented||t===void 0||n.machineId!==N(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=Xa(this.currentContributionQueryForState(),r.contributionId,r.navigationAliases??[],r.query);e.preventDefault(),this.publishWorkspaceTool(r.contributionId,i)},this.workspaceSurfaceRevision=0,this.navigationActions={toggleMachines:()=>{this.cancelAutomaticProjectNavigation(),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.cancelAutomaticProjectNavigation(),this.navigationSections.toggle(`projects`)},toggleWorkspaces:()=>{this.cancelAutomaticProjectNavigation(),this.navigationSections.toggle(`workspaces`)},toggleSessions:()=>{this.cancelAutomaticProjectNavigation(),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])},markSessionUnread:e=>{this.markSessionUnread(e)},markSessionsRead:e=>{this.markSessionsRead(e)},searchSessions:()=>{this.openSessionSearchDialog()},toggleSessionPin:e=>{this.toggleSessionPin(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`,async()=>{let t=await this.sessions.restoreSession(e);return t!==void 0&&this.selectSessionFromNavigation(t)}),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.cancelAutomaticProjectNavigation(),this.focusNavigationTarget(e)},cancelKeyboardNavigation:()=>{this.cancelAutomaticProjectNavigation(),this.openChatAndFocusComposer()},moveProject:(e,t)=>{this.moveNavigationItem({kind:`projects`,machineId:N(this.state)},e.id,t)},moveWorkspace:(e,t)=>{this.moveNavigationItem({kind:`workspaces`,machineId:N(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)||N(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=$n(e.expectedQueue,e.index);if(t!==void 0&&!window.confirm(t)||(n?.view?.state.doc.toString()??``)!==``&&!window.confirm(Xn.t(`recallDraft`)))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||N(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:Un(i,e.message.role);if(a===void 0)return;let o={...r,message:a};return this.plugins.runMessageAction(t,o,e=>{let t=()=>N(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(C(`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(Xn.t(`backDraft`)))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.handleNoticeDismiss=e=>{let{machineId:t,sessionId:n,dismissId:r}=e.detail;t===N(this.state)&&n===this.state.selectedSession?.id&&this.sessions.dismissWarning(r)},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.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=ze(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||Be(this.ownerDocument)||e!==void 0&&Re(e))return;let t=ze(this.ownerDocument);if(!(t instanceof HTMLElement&&t!==this&&t!==this.ownerDocument.body&&t!==this.ownerDocument.documentElement&&Re(t)))for(let e of this.renderRoot.querySelectorAll(`app-context-bar, app-mobile-main-tabs, workspace-panel`)){let t=e.shadowRoot?.querySelector(`button[data-navigation-trigger]`);if(t!=null&&Re(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)]},mA(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)}))},new S(this,w,()=>{this.invalidateWorkspaceSurface()}),o.createController(this),new hL(this,()=>this.settingsSection!==void 0,()=>_e(()=>import(`./SettingsDialog-SOljSiee.js`),__vite__mapDeps([0,1,2,3,4,5,6,7]),import.meta.url),e=>{this.closeSettings(),this.setState({error:tz(e)})})}get themePreference(){return oe(this.localThemePreference,this.configuredThemePreference)}get routeRestoreInProgress(){return this.routeRestoreDepth>0}willUpdate(){this.toggleAttribute(`pwa-display-mode`,this.appShell.isPwaDisplayMode),this.syncSessionActivityAcknowledgement()}updated(){this.sessions.isChatLoadDeferred&&(this.readyChatIdentity=void 0),this.committedChatIdentity=zR(this.state),this.syncSelectedSessionReadState(),this.plugins.notifySelectionChanged(),this.syncFileIcons(),this.syncPluginStylesheets(),this.isChatVisible()?this.sessions.isChatLoadDeferred?this.scheduleSelectedChatLoad():this.displayedChatIdentity=zR(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()}syncSessionActivityAcknowledgement(){if(this.dismissedActivityNotices.size===0)return;let e=this.state.selectedSession,t=this.state.status,n=N(this.state);for(let t of Object.values(this.state.sessionStatuses))t.sessionId!==e?.id&&t.recentlyActiveElsewhere===!1&&this.dismissedActivityNotices.delete(M(n,t.sessionId));e!==void 0&&t?.sessionId===e.id&&t.recentlyActiveElsewhere===!1&&this.dismissedActivityNotices.delete(M(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=M(N(e),t.id);return this.dismissedActivityNotices.has(n)?void 0:n}renderSessionActivityNotice(){return this.unacknowledgedActivitySessionKey()===void 0?null:D`
3710
+ <section class="composer-activity-notice" role="alert" aria-label=${sR.t(`activityLabel`)}>
3711
3711
  <div class="composer-activity-notice-text">
3712
- <p>${oR.t(`activityNotice`)}</p>
3712
+ <p>${sR.t(`activityNotice`)}</p>
3713
3713
  </div>
3714
- <button type="button" @click=${this.handleDismissActivityNotice}>${oR.t(`dismissActivity`)}</button>
3714
+ <button type="button" @click=${this.handleDismissActivityNotice}>${sR.t(`dismissActivity`)}</button>
3715
3715
  </section>
3716
- `}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=N(this.state);if(this.manuallyUnreadChatIdentity===LR(t,e)||!this.isSessionSeen(t,e))return;let n=this.renderedTranscript;if(n?.sessionId!==e.id||n.messages!==this.state.messages||n.start!==this.state.messagePageStart||n.end!==this.state.messagePageEnd)return;let r=this.sessionUnread.completion(t,e);if(r===void 0)return;let i=this.renderedUnreadCompletion;if(i!==void 0&&JSON.stringify(i)===JSON.stringify(r)){this.sessionUnread.acknowledgeRendered(t,e,i,{start:n.start,end:n.end,total:this.state.messagePageTotal,leafId:this.state.messagePageLeafId});return}let a=JSON.stringify([t,r]);this.requestedUnreadSnapshot!==a&&(this.requestedUnreadSnapshot=a,this.sessions.refreshSelectedSession(e.id,{silent:!0}))}async commitUnreadCompletionAfterRender(e,t,n,r){let i=this.state.messages;await this.updateComplete,this.unreadConnected&&r===this.unreadRenderGeneration&&RR(this.state)===LR(e,t)&&this.state.messages===i&&(this.renderedUnreadCompletion=n,this.syncSelectedSessionReadState())}markSessionsRead(e){let t=N(this.state);for(let n of e)this.manuallyUnreadChatIdentity===LR(t,n)&&(this.manuallyUnreadChatIdentity=void 0),this.sessionUnread.acknowledge(t,n)}async markSessionUnread(e){let t=N(this.state),n=LR(t,e);RR(this.state)===n&&(this.manuallyUnreadChatIdentity=n);try{await this.sessionUnread.markUnread(t,e)}catch(e){this.manuallyUnreadChatIdentity===n&&(this.manuallyUnreadChatIdentity=void 0),this.browserErrors.reportLocalized(j(t),()=>oR.t(`actionFailed`,{detail:ez(e)}))}}async commitReadyChatAfterRender(e,t){let n=LR(e,t);await this.updateComplete,this.unreadConnected&&RR(this.state)===n&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(N(this.state),this.state.sessions);WR(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncUnreadPresence(){let e=yd({machineIds:this.state.machines.map(e=>e.id),projectionFor:e=>this.sessionUnread.projection(e),selectedMachineId:N(this.state),projects:this.state.projects,workspaces:this.state.workspaces,workspacesByProjectId:this.state.workspacesByProjectId});Td(e,this.unreadPresence)||(this.unreadPresence=e)}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=LR(e,t);if(RR(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 Be(this.ownerDocument)}connectedCallback(){super.connectedCallback(),this.normalAuthInitSeq+=1,this.stylesheetRuntime.connect(this.ownerDocument),xe(),this.declarativeThemesReady.then(async e=>{if(await be.ready,!this.isConnected||!be.started)return;!this.themePolicyFromApplication&&e!==void 0&&this.applyThemeCatalogPolicy(e),this.themeConfigReady=!0,this.activeThemeId=this.ownerDocument.documentElement.dataset.piWebTheme??``;let t=this.ownerDocument.documentElement.style.colorScheme;this.activeThemeId!==``&&(t===`light`||t===`dark`)&&(this.activeThemeColorScheme=t,this.syncFileIcons()),this.applyPreferredTheme(!1),this.revealAfterRender()}),this.syncNavigationOrder(),this.unreadConnected=!0,window.addEventListener(`popstate`,this.onPopState),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,bR),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()},fR)),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 zt.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=C(`ui.piWebApp.failedToCheckNormalModePassword`,`Failed to check normal-mode password: {errorMessageerror}`,{errorMessageerror:ez(t)})}finally{this.isConnected&&e===this.normalAuthInitSeq&&(this.normalAuthLoading=!1)}}}disconnectedCallback(){this.workspaceNavigationGeneration+=1,this.normalAuthInitSeq+=1,this.authenticatedAppRunning=!1,ye(),this.themeRequest?.abort(),this.stylesheetRuntime.disconnect(()=>{this.activeThemeId!==``&&(this.activeThemeId=``,ae(),this.activeThemeColorScheme=this.startupColorScheme())}),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.renderedUnreadCompletion=void 0,this.unreadRenderGeneration+=1,this.requestedUnreadSnapshot=void 0,this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,bR),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(!UR(this.state,e))return;let t=this.state;this.state={...this.state,...e};let n=this.pendingProjectNavigation;n?.seq===this.navigationSelectionSeq&&!n.cancelled&&n.target===void 0&&t.isLoadingWorkspaces&&!this.state.isLoadingWorkspaces&&this.state.workspaceResolution!==void 0&&(n.target=this.state.workspaceResolution.status!==`degraded`&&this.state.workspaces.length===1?`sessions`:`workspaces`,this.focusNavigationTarget(n.target,()=>n.seq===this.navigationSelectionSeq&&!n.cancelled)),YR(t)!==YR(this.state)&&(this.cancelWorkspaceDeletionRefresh(),this.state={...this.state,workspaceDeletionRuns:{}}),(N(t)!==N(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 r=NR(t.status)!==NR(this.state.status);this.state.modelDialog!==void 0&&(r||!this.modelDialogOriginIsCurrent(this.state.modelDialog.origin))&&(this.state={...this.state,modelDialog:void 0}),this.state.thinkingDialog!==void 0&&(r||!this.modelDialogOriginIsCurrent(this.state.thinkingDialog.origin))&&(this.state={...this.state,thinkingDialog:void 0}),RR(t)!==RR(this.state)&&(this.manuallyUnreadChatIdentity=void 0,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.renderedUnreadCompletion=void 0,this.unreadRenderGeneration+=1,this.requestedUnreadSnapshot=void 0,this.displayedChatIdentity=void 0),zR(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.syncUnreadPresence(),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),BR(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),(N(t)!==N(this.state)||t.selectedProject?.id!==this.state.selectedProject?.id||t.selectedWorkspace?.id!==this.state.selectedWorkspace?.id)&&this.syncNavigationOrder()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=vo();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(N(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(e=!1){if(e){this.realtime.reconnect();for(let e of this.machineRealtimeSockets.values())e.reconnect()}await zl([this.renegotiateUnreadMachines(),this.sessions.resumeSelectedSession({reconnect:e}),this.sessions.refreshCurrentWorkspaceSessions(N(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=mR){this.apiScope!==`management`&&(this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.piWebStatusController.refresh().finally(()=>{this.schedulePiWebStatusRetry()})},e))}schedulePiWebStatusRetry(){this.isConnected&&this.state.piWebStatus?.components.sessiond.available===!1&&this.schedulePiWebStatusRefresh(5e3)}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshWorkspaceActivity(e=N(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?[N(this.state)]:this.state.machines.filter(e=>HR(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)})},pR))}async refreshSelectedTranscript(){let e=this.state.selectedSession;e!==void 0&&e.archived!==!0&&this.isChatVisible()&&document.visibilityState===`visible`&&await this.sessions.refreshSelectedSession(e.id,{silent:!0})}async refreshMachineStatusSnapshots(){let e=this.state.machines.length===0?[N(this.state)]:this.state.machines.filter(e=>HR(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{let e=await qt.config();he(e),Vt(e).catch(e=>{console.warn(`Failed to apply gateway localization policy`,e)}),this.applyClientConfig(e.effectiveConfig)}catch(e){console.warn(`Failed to load PI WEB config`,e)}finally{this.themeConfigReady=!0,this.applyPreferredTheme(!1)}}applyThemeCatalogPolicy(e){he({effectiveConfig:{...e.defaultTheme===void 0?{}:{defaultTheme:e.defaultTheme}},...e.enforcedBy===void 0?{}:{enforcedSettings:{"/defaultTheme":e.enforcedBy}}}),this.configuredThemePreference=e.defaultTheme}applyClientConfig(e){this.themeConfigReady=!0,this.themePolicyFromApplication=!0,this.configuredThemePreference=e.defaultTheme,this.applyPreferredTheme(!1),this.shortcutConfig=e.shortcuts??{},this.defaultStreamingBehavior=e.defaultStreamingBehavior??`steer`,this.quietMode=e.quietMode===!0,this.workspaceUploadDefaultFolder=Pt(e),this.workspaceAttachmentsDefaultFolder=ke(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 zt.setup(e.password):t===`change`?await zt.changePassword(e.currentPassword??``,e.password):await zt.login(e.password);let n=await zt.status();this.normalAuthStatus=n,this.normalAuthDialogMode=void 0,n.authenticated&&this.startAuthenticatedApp()}catch(e){this.normalAuthError=ez(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 zl([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.effectiveWorkspaceTool();e!==void 0&&await this.invalidateWorkspacePanels(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e,t,n=`current-url`){let r=this.restoreRouteFor(vo(),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}=Fd(e,t,vo(),Ja(),N(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=N(this.state),o=e.projectId===void 0||e.projectId===``?KR():n,s=this.beginNavigationOperation(wR),c=this.beginNavigationOperation(_R);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`,r=()=>Mu.t(`machineNotFound`,{id:n});this.setContentError(e,r);let i=j(n);this.state.browserErrors[wr(i)]===void 0&&(t===``?this.browserErrors.reportLocalized(i,r):this.browserErrors.report(i,t));return}if(!u.isCurrent())return;let n=this.loadPluginsForSelectedMachine();n.catch(()=>void 0);let a=yo({...e,tool:void 0},()=>void 0),c=e.view!==void 0&&a.view===void 0,l=jR(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)||N(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});let n=a.projectId,r=()=>Mu.t(`projectNotFound`,{id:n});this.setContentError(e,this.projects.loadErrors.get(N(this.state))??r);let i=j(N(this.state));this.state.browserErrors[wr(i)]===void 0&&this.browserErrors.reportLocalized(i,r),await m();return}let ee=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,te=ee!==void 0&&this.state.selectedWorkspace?.projectId===ee.projectId&&this.state.selectedWorkspace.id===ee.id?this.sessions.preferredSession(ee.path,this.state.sessions,a.sessionId):void 0,ne;if(te===void 0?ne=ee===void 0?await this.workspaces.selectProject(h,{workspaceId:a.workspaceId,sessionId:a.sessionId,updateUrl:!1,navigation:u}):await this.workspaces.selectWorkspace(ee,{sessionId:a.sessionId,updateUrl:!1,navigation:u}):await this.sessions.selectSession(te,{deferChatLoading:a.sessionId===void 0,updateUrl:!1,navigation:u}),u.isCurrent()&&this.setContentError(e,ne??``),!this.isCurrentRouteRestore(d,s))return;let re=await m();re!==void 0&&await this.finishWorkspaceRouteRestore(o,re)}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),N(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=vo(),t=this.observedNavigationRoute;if(t!==void 0){let n=gR.filter(n=>qR(t,n)!==qR(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(vR),this.routeRestoreSeq+=1}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?KR():{contributionQuery:Ja()}}isPendingSessionStartRouteCurrent(e){return _o(vo(),e)}commitPendingSessionStartNavigation(e,t){this.isPendingSessionStartRouteCurrent(e)&&(this.syncNavigationFreshness(),So({...vo(),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=XR(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=j(t),r=this.state.browserErrors[wr(n)],i=()=>this.state.browserErrors[wr(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>=hR.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,i=j(n),a=wr(i),o=this.state.browserErrors[a],s=o===void 0?void 0:this.remoteRouteRestoreDetails.get(o),c=this.state.machineStatuses[n]?.error??(s===void 0?o?.message:s.detail),l=t.exhausted===!0?`exhausted`:`reconnecting`;this.browserErrors.reportLocalized(i,()=>Mu.t(l,{machine:r??Mu.t(`remoteMachine`),detail:c??``,hasDetail:c===void 0?`no`:`yes`}));let u=this.state.browserErrors[a];u!==void 0&&this.remoteRouteRestoreDetails.set(u,{detail:c})}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(N(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`)!==N(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 nz(),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(Ru(this.state,t),e)}rememberCurrentMachineNavigation(){this.machineNavigation.remember(Ru(this.state,this.currentContributionQueryForState()))}writeWorkspaceRouteSurfaceToUrl(e){Za(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)??Lu(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=vo();return{...e,machineId:e.machineId??`local`}}navigationSelectionMatchesUrl(e,t=!1){let n=vo();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=vo();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?go(t.expected?.sessionId)?(So({...vo(),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=Ru(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=Ru(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=Ru(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[wr(j(N(this.state)))];return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&(this.state.error!==``||t!==void 0)}openWorkspaceTool(e,t={}){let n=N(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=Ru(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=N(this.state),n=this.state.selectedWorkspace;if(n===void 0){let n=this.maintenanceTerminal(`core`,t,this.beginNavigationOperation(vR));n===void 0?this.browserErrors.reportLocalized(j(t),()=>XO(t).message):n.open(e)}else this.workspaceTerminal(`core`,n,t).open(e)}workspacePanelSourceQueryIds(e){let t=[...this.plugins.getWorkspacePanels(),...this.plugins.getApplicationPanels()].find(t=>t.id===e)?.sourceContributionId;return t===void 0||t===e?[]:[t]}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:pw(i.binding,t,n);if(i===void 0||a===void 0){let e=XO(n);return Object.freeze({open:()=>{r?.isCurrent()!==!1&&this.browserErrors.reportLocalized(j(n),()=>e.message)},runCommand:()=>Promise.reject(e)})}let o=e=>N(this.state)===n&&(r===void 0||this.state.selectedProject?.id===t.projectId&&this.state.selectedWorkspace?.id===t.id&&xo(vo(),{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({...ER(r),generation:this.workspaceNavigationGeneration}).open(e)},runCommand:e=>{if(!o(e.open===!0))return Promise.reject(Error(C(`ui.main.4971c700c4fd`,`Workspace panel context is no longer current`)));let t={...ER(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??[],...this.workspacePanelSourceQueryIds(n.contributionId)],a=this.selectedWorkspaceRouteIdentity(),o={machineId:e,projectId:t.projectId,workspaceId:t.id},s=Xa(a!==void 0&&MR(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(N(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)}maintenanceTerminal(e,t,n){let r=this.requiredTerminalByMachine.get(t),i=r?.facade.createMaintenanceTerminal?.bind(r.facade),a=r===void 0?void 0:mw(r.binding,t)?.forScope({kind:`machine`});if(r===void 0||i===void 0||a===void 0)return;let o=()=>N(this.state)===t&&n.isCurrent(),s=i({origin:e,machineId:t,registrationPluginId:r.binding.registrationPluginId,peer:a,host:{navigateApplicationContribution:e=>o()?(this.publishWorkspaceTool(e),!0):!1}});return Object.freeze({open:e=>{o()&&s.open(e)},runCommand:async e=>{if(!o())throw Error(`Maintenance terminal context is no longer current`);try{return await s.runCommand(e)}catch(e){throw o()&&this.setState({error:e instanceof Error?e.message:String(e)}),e}}})}terminalCommandRunsForOrigin(e,t=N(this.state)){let n=JR(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=>{N(this.state)===t&&this.openTerminal(e)}};return this.terminalCommandRunRuntimes.set(n,r),r}let i=EA(e,{api:{runTerminalCommand:(e,n)=>ut.runTerminalCommand(e,n,t),listCommandRuns:e=>ut.listCommandRuns(e,t),getCommandRun:e=>ut.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 XO(e);if(N(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=pw(n.binding,r,e);if(i===void 0)throw XO(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=Ru(this.state,this.currentContributionQueryForState());this.commitMachineNavigationSnapshot({...n,view:e}),this.retireRouteRestoreForSynchronousNavigation(),this.setState({mainView:e})}openSettings(e=`general`){bA(e),this.settingsSection=e}closeSettings(){this.settingsSection=void 0,bA(void 0)}navigateSettings(e){this.settingsSection=e,bA(e)}restoreSettingsRoute(){this.settingsSection=yA()}handleWorkspaceChange(e,t){(N(e)!==N(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,N(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(N(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(N(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=N(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.sessions.refreshCurrentWorkspaceSessions(e,{recoverNetwork:!0}),N(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)}),this.navigationOrder.refreshSessionPins(e).catch(()=>void 0)},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 Tc(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)}),this.navigationOrder.refreshSessionPins(t).catch(()=>void 0)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=N(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>VR(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`session-pins.changed`?this.navigationOrder.load({kind:`sessionPins`,machineId:e,projectId:t.projectId,workspaceId:t.workspaceId}).catch(()=>void 0):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===`session-pins.changed`)this.handleMachineActivityEvent(e,t);else 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`)N(this.state)===e&&this.state.selectedProject?.id===t.projectId&&(this.workspaces.refreshSelectedProjectTopology(),this.sessions.refreshCurrentWorkspaceSessions(e,{recoverNetwork:!0}));else if(GR(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!==N(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,FR(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.closeSessionCleanupDialog(),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,JSON.stringify(pf(e)),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(),DR()]}renderWorkspacePanel(){let e=this.state.selectedWorkspace,t=e===void 0?this.workspacePanelEmptyState():void 0,n=this.visibleWorkspacePanels();return D`
3716
+ `}syncSelectedSessionReadState(){let e=this.state.selectedSession;if(e===void 0)return;let t=N(this.state);if(this.manuallyUnreadChatIdentity===RR(t,e)||!this.isSessionSeen(t,e))return;let n=this.renderedTranscript;if(n?.sessionId!==e.id||n.messages!==this.state.messages||n.start!==this.state.messagePageStart||n.end!==this.state.messagePageEnd)return;let r=this.sessionUnread.completion(t,e);if(r===void 0)return;let i=this.renderedUnreadCompletion;if(i!==void 0&&JSON.stringify(i)===JSON.stringify(r)){this.sessionUnread.acknowledgeRendered(t,e,i,{start:n.start,end:n.end,total:this.state.messagePageTotal,leafId:this.state.messagePageLeafId});return}let a=JSON.stringify([t,r]);this.requestedUnreadSnapshot!==a&&(this.requestedUnreadSnapshot=a,this.sessions.refreshSelectedSession(e.id,{silent:!0}))}async commitUnreadCompletionAfterRender(e,t,n,r){let i=this.state.messages;await this.updateComplete,this.unreadConnected&&r===this.unreadRenderGeneration&&zR(this.state)===RR(e,t)&&this.state.messages===i&&(this.renderedUnreadCompletion=n,this.syncSelectedSessionReadState())}markSessionsRead(e){let t=N(this.state);for(let n of e)this.manuallyUnreadChatIdentity===RR(t,n)&&(this.manuallyUnreadChatIdentity=void 0),this.sessionUnread.acknowledge(t,n)}async markSessionUnread(e){let t=N(this.state),n=RR(t,e);zR(this.state)===n&&(this.manuallyUnreadChatIdentity=n);try{await this.sessionUnread.markUnread(t,e)}catch(e){this.manuallyUnreadChatIdentity===n&&(this.manuallyUnreadChatIdentity=void 0),this.browserErrors.reportLocalized(j(t),()=>sR.t(`actionFailed`,{detail:tz(e)}))}}async commitReadyChatAfterRender(e,t){let n=RR(e,t);await this.updateComplete,this.unreadConnected&&zR(this.state)===n&&(this.readyChatIdentity=n,this.syncSelectedSessionReadState())}syncUnreadSessionIds(){let e=this.sessionUnread.unreadSessionIds(N(this.state),this.state.sessions);GR(e,this.unreadSessionIds)||(this.unreadSessionIds=e)}syncUnreadPresence(){let e=yd({machineIds:this.state.machines.map(e=>e.id),projectionFor:e=>this.sessionUnread.projection(e),selectedMachineId:N(this.state),projects:this.state.projects,workspaces:this.state.workspaces,workspacesByProjectId:this.state.workspacesByProjectId});Td(e,this.unreadPresence)||(this.unreadPresence=e)}isSessionSeen(e,t){if(!this.unreadConnected)return!1;let n=RR(e,t);if(zR(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 Be(this.ownerDocument)}connectedCallback(){super.connectedCallback(),this.normalAuthInitSeq+=1,this.stylesheetRuntime.connect(this.ownerDocument),xe(),this.declarativeThemesReady.then(async e=>{if(await be.ready,!this.isConnected||!be.started)return;!this.themePolicyFromApplication&&e!==void 0&&this.applyThemeCatalogPolicy(e),this.themeConfigReady=!0,this.activeThemeId=this.ownerDocument.documentElement.dataset.piWebTheme??``;let t=this.ownerDocument.documentElement.style.colorScheme;this.activeThemeId!==``&&(t===`light`||t===`dark`)&&(this.activeThemeColorScheme=t,this.syncFileIcons()),this.applyPreferredTheme(!1),this.revealAfterRender()}),this.syncNavigationOrder(),this.unreadConnected=!0,window.addEventListener(`popstate`,this.onPopState),this.browserResume.connect(),window.addEventListener(`keydown`,this.onKeyDown,xR),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()},pR)),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 zt.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=C(`ui.piWebApp.failedToCheckNormalModePassword`,`Failed to check normal-mode password: {errorMessageerror}`,{errorMessageerror:tz(t)})}finally{this.isConnected&&e===this.normalAuthInitSeq&&(this.normalAuthLoading=!1)}}}disconnectedCallback(){this.workspaceNavigationGeneration+=1,this.normalAuthInitSeq+=1,this.authenticatedAppRunning=!1,this.navigationOrder.reset(),ye(),this.themeRequest?.abort(),this.stylesheetRuntime.disconnect(()=>{this.activeThemeId!==``&&(this.activeThemeId=``,ae(),this.activeThemeColorScheme=this.startupColorScheme())}),this.unreadConnected=!1,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.renderedUnreadCompletion=void 0,this.unreadRenderGeneration+=1,this.requestedUnreadSnapshot=void 0,this.sessionUnread.retainMachines(new Set),window.removeEventListener(`popstate`,this.onPopState),this.browserResume.disconnect(),window.removeEventListener(`keydown`,this.onKeyDown,xR),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(!WR(this.state,e))return;let t=this.state;this.state={...this.state,...e};let n=this.pendingProjectNavigation;n?.seq===this.navigationSelectionSeq&&!n.cancelled&&n.target===void 0&&t.isLoadingWorkspaces&&!this.state.isLoadingWorkspaces&&this.state.workspaceResolution!==void 0&&(n.target=this.state.workspaceResolution.status!==`degraded`&&this.state.workspaces.length===1?`sessions`:`workspaces`,this.focusNavigationTarget(n.target,()=>n.seq===this.navigationSelectionSeq&&!n.cancelled)),XR(t)!==XR(this.state)&&(this.cancelWorkspaceDeletionRefresh(),this.state={...this.state,workspaceDeletionRuns:{}}),(N(t)!==N(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 r=PR(t.status)!==PR(this.state.status);this.state.modelDialog!==void 0&&(r||!this.modelDialogOriginIsCurrent(this.state.modelDialog.origin))&&(this.state={...this.state,modelDialog:void 0}),this.state.thinkingDialog!==void 0&&(r||!this.modelDialogOriginIsCurrent(this.state.thinkingDialog.origin))&&(this.state={...this.state,thinkingDialog:void 0}),zR(t)!==zR(this.state)&&(this.manuallyUnreadChatIdentity=void 0,this.committedChatIdentity=void 0,this.readyChatIdentity=void 0,this.renderedUnreadCompletion=void 0,this.unreadRenderGeneration+=1,this.requestedUnreadSnapshot=void 0,this.displayedChatIdentity=void 0),BR(t,this.state)&&this.syncSessionUnreadMachines(),this.syncUnreadSessionIds(),this.syncUnreadPresence(),this.handleWorkspaceChange(t,this.state),this.handleMachineChange(t,this.state),VR(t,this.state)&&this.syncMachineActivitySubscriptions(),this.notifications.syncEnvironment(t,this.state),(N(t)!==N(this.state)||t.selectedProject?.id!==this.state.selectedProject?.id||t.selectedWorkspace?.id!==this.state.selectedWorkspace?.id)&&this.syncNavigationOrder()}async loadProjectsAndRestoreRoute(){this.restoreSettingsRoute();let e=vo();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(N(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(e=!1){if(e){this.realtime.reconnect();for(let e of this.machineRealtimeSockets.values())e.reconnect()}await zl([this.renegotiateUnreadMachines(),this.sessions.resumeSelectedSession({reconnect:e}),this.sessions.refreshCurrentWorkspaceSessions(N(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=hR){this.apiScope!==`management`&&(this.clearScheduledPiWebStatusRefresh(),this.piWebStatusDeferredTimer=window.setTimeout(()=>{this.piWebStatusDeferredTimer=void 0,this.piWebStatusController.refresh().finally(()=>{this.schedulePiWebStatusRetry()})},e))}schedulePiWebStatusRetry(){this.isConnected&&this.state.piWebStatus?.components.sessiond.available===!1&&this.schedulePiWebStatusRefresh(5e3)}clearScheduledPiWebStatusRefresh(){this.piWebStatusDeferredTimer!==void 0&&(window.clearTimeout(this.piWebStatusDeferredTimer),this.piWebStatusDeferredTimer=void 0)}async refreshWorkspaceActivity(e=N(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?[N(this.state)]:this.state.machines.filter(e=>UR(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)})},mR))}async refreshSelectedTranscript(){let e=this.state.selectedSession;e!==void 0&&e.archived!==!0&&this.isChatVisible()&&document.visibilityState===`visible`&&await this.sessions.refreshSelectedSession(e.id,{silent:!0})}async refreshMachineStatusSnapshots(){let e=this.state.machines.length===0?[N(this.state)]:this.state.machines.filter(e=>UR(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{let e=await qt.config();he(e),Vt(e).catch(e=>{console.warn(`Failed to apply gateway localization policy`,e)}),this.applyClientConfig(e.effectiveConfig)}catch(e){console.warn(`Failed to load PI WEB config`,e)}finally{this.themeConfigReady=!0,this.applyPreferredTheme(!1)}}applyThemeCatalogPolicy(e){he({effectiveConfig:{...e.defaultTheme===void 0?{}:{defaultTheme:e.defaultTheme}},...e.enforcedBy===void 0?{}:{enforcedSettings:{"/defaultTheme":e.enforcedBy}}}),this.configuredThemePreference=e.defaultTheme}applyClientConfig(e){this.themeConfigReady=!0,this.themePolicyFromApplication=!0,this.configuredThemePreference=e.defaultTheme,this.applyPreferredTheme(!1),this.shortcutConfig=e.shortcuts??{},this.defaultStreamingBehavior=e.defaultStreamingBehavior??`steer`,this.quietMode=e.quietMode===!0,this.workspaceUploadDefaultFolder=Pt(e),this.workspaceAttachmentsDefaultFolder=ke(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 zt.setup(e.password):t===`change`?await zt.changePassword(e.currentPassword??``,e.password):await zt.login(e.password);let n=await zt.status();this.normalAuthStatus=n,this.normalAuthDialogMode=void 0,n.authenticated&&this.startAuthenticatedApp()}catch(e){this.normalAuthError=tz(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 zl([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.effectiveWorkspaceTool();e!==void 0&&await this.invalidateWorkspacePanels(e)}hardReloadApp(){window.location.reload()}async restoreRoute(e,t,n=`current-url`){let r=this.restoreRouteFor(vo(),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}=Fd(e,t,vo(),Ja(),N(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=N(this.state),o=e.projectId===void 0||e.projectId===``?qR():n,s=this.beginNavigationOperation(TR),c=this.beginNavigationOperation(vR);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`,r=()=>Mu.t(`machineNotFound`,{id:n});this.setContentError(e,r);let i=j(n);this.state.browserErrors[wr(i)]===void 0&&(t===``?this.browserErrors.reportLocalized(i,r):this.browserErrors.report(i,t));return}if(!u.isCurrent())return;let n=this.loadPluginsForSelectedMachine();n.catch(()=>void 0);let a=yo({...e,tool:void 0},()=>void 0),c=e.view!==void 0&&a.view===void 0,l=MR(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)||N(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});let n=a.projectId,r=()=>Mu.t(`projectNotFound`,{id:n});this.setContentError(e,this.projects.loadErrors.get(N(this.state))??r);let i=j(N(this.state));this.state.browserErrors[wr(i)]===void 0&&this.browserErrors.reportLocalized(i,r),await m();return}let ee=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,te=ee!==void 0&&this.state.selectedWorkspace?.projectId===ee.projectId&&this.state.selectedWorkspace.id===ee.id?this.sessions.preferredSession(ee.path,this.state.sessions,a.sessionId):void 0,ne;if(te===void 0?ne=ee===void 0?await this.workspaces.selectProject(h,{workspaceId:a.workspaceId,sessionId:a.sessionId,updateUrl:!1,navigation:u}):await this.workspaces.selectWorkspace(ee,{sessionId:a.sessionId,updateUrl:!1,navigation:u}):await this.sessions.selectSession(te,{deferChatLoading:a.sessionId===void 0,updateUrl:!1,navigation:u}),u.isCurrent()&&this.setContentError(e,ne??``),!this.isCurrentRouteRestore(d,s))return;let re=await m();re!==void 0&&await this.finishWorkspaceRouteRestore(o,re)}finally{this.routeRestoreDepth=Math.max(0,this.routeRestoreDepth-1),N(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=vo(),t=this.observedNavigationRoute;if(t!==void 0){let n=_R.filter(n=>JR(t,n)!==JR(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(yR),this.routeRestoreSeq+=1}readWorkspaceRouteSurface(e){return e.projectId===void 0||e.projectId===``?qR():{contributionQuery:Ja()}}isPendingSessionStartRouteCurrent(e){return _o(vo(),e)}commitPendingSessionStartNavigation(e,t){this.isPendingSessionStartRouteCurrent(e)&&(this.syncNavigationFreshness(),So({...vo(),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=ZR(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=j(t),r=this.state.browserErrors[wr(n)],i=()=>this.state.browserErrors[wr(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>=gR.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,i=j(n),a=wr(i),o=this.state.browserErrors[a],s=o===void 0?void 0:this.remoteRouteRestoreDetails.get(o),c=this.state.machineStatuses[n]?.error??(s===void 0?o?.message:s.detail),l=t.exhausted===!0?`exhausted`:`reconnecting`;this.browserErrors.reportLocalized(i,()=>Mu.t(l,{machine:r??Mu.t(`remoteMachine`),detail:c??``,hasDetail:c===void 0?`no`:`yes`}));let u=this.state.browserErrors[a];u!==void 0&&this.remoteRouteRestoreDetails.set(u,{detail:c})}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(N(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`)!==N(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 rz(),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(Ru(this.state,t),e)}rememberCurrentMachineNavigation(){this.machineNavigation.remember(Ru(this.state,this.currentContributionQueryForState()))}writeWorkspaceRouteSurfaceToUrl(e){Za(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)??Lu(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=vo();return{...e,machineId:e.machineId??`local`}}navigationSelectionMatchesUrl(e,t=!1){let n=vo();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=vo();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?go(t.expected?.sessionId)?(So({...vo(),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=Ru(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=Ru(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=Ru(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[wr(j(N(this.state)))];return e.projectId!==void 0&&this.state.selectedProject?.id!==e.projectId&&(this.state.error!==``||t!==void 0)}openWorkspaceTool(e,t={}){let n=N(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=Ru(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=N(this.state),n=this.state.selectedWorkspace;if(n===void 0){let n=this.maintenanceTerminal(`core`,t,this.beginNavigationOperation(yR));n===void 0?this.browserErrors.reportLocalized(j(t),()=>XO(t).message):n.open(e)}else this.workspaceTerminal(`core`,n,t).open(e)}workspacePanelSourceQueryIds(e){let t=[...this.plugins.getWorkspacePanels(),...this.plugins.getApplicationPanels()].find(t=>t.id===e)?.sourceContributionId;return t===void 0||t===e?[]:[t]}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:pw(i.binding,t,n);if(i===void 0||a===void 0){let e=XO(n);return Object.freeze({open:()=>{r?.isCurrent()!==!1&&this.browserErrors.reportLocalized(j(n),()=>e.message)},runCommand:()=>Promise.reject(e)})}let o=e=>N(this.state)===n&&(r===void 0||this.state.selectedProject?.id===t.projectId&&this.state.selectedWorkspace?.id===t.id&&xo(vo(),{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({...DR(r),generation:this.workspaceNavigationGeneration}).open(e)},runCommand:e=>{if(!o(e.open===!0))return Promise.reject(Error(C(`ui.main.4971c700c4fd`,`Workspace panel context is no longer current`)));let t={...DR(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??[],...this.workspacePanelSourceQueryIds(n.contributionId)],a=this.selectedWorkspaceRouteIdentity(),o={machineId:e,projectId:t.projectId,workspaceId:t.id},s=Xa(a!==void 0&&NR(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(N(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)}maintenanceTerminal(e,t,n){let r=this.requiredTerminalByMachine.get(t),i=r?.facade.createMaintenanceTerminal?.bind(r.facade),a=r===void 0?void 0:mw(r.binding,t)?.forScope({kind:`machine`});if(r===void 0||i===void 0||a===void 0)return;let o=()=>N(this.state)===t&&n.isCurrent(),s=i({origin:e,machineId:t,registrationPluginId:r.binding.registrationPluginId,peer:a,host:{navigateApplicationContribution:e=>o()?(this.publishWorkspaceTool(e),!0):!1}});return Object.freeze({open:e=>{o()&&s.open(e)},runCommand:async e=>{if(!o())throw Error(`Maintenance terminal context is no longer current`);try{return await s.runCommand(e)}catch(e){throw o()&&this.setState({error:e instanceof Error?e.message:String(e)}),e}}})}terminalCommandRunsForOrigin(e,t=N(this.state)){let n=YR(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=>{N(this.state)===t&&this.openTerminal(e)}};return this.terminalCommandRunRuntimes.set(n,r),r}let i=EA(e,{api:{runTerminalCommand:(e,n)=>ut.runTerminalCommand(e,n,t),listCommandRuns:e=>ut.listCommandRuns(e,t),getCommandRun:e=>ut.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 XO(e);if(N(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=pw(n.binding,r,e);if(i===void 0)throw XO(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=Ru(this.state,this.currentContributionQueryForState());this.commitMachineNavigationSnapshot({...n,view:e}),this.retireRouteRestoreForSynchronousNavigation(),this.setState({mainView:e})}openSettings(e=`general`){bA(e),this.settingsSection=e}closeSettings(){this.settingsSection=void 0,bA(void 0)}navigateSettings(e){this.settingsSection=e,bA(e)}restoreSettingsRoute(){this.settingsSection=yA()}handleWorkspaceChange(e,t){(N(e)!==N(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.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(N(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(N(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=N(this.state);this.realtime.connect(t=>{this.handleRealtimeEvent(e,t)},()=>{this.sessions.refreshCurrentWorkspaceSessions(e,{recoverNetwork:!0}),N(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)}),this.navigationOrder.refreshSessionPins(e).catch(()=>void 0)},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 Tc(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)}),this.navigationOrder.refreshSessionPins(t).catch(()=>void 0)},t),this.machineRealtimeSockets.set(t,e)}}closeMachineActivitySockets(){for(let e of this.machineRealtimeSockets.values())e.close();this.machineRealtimeSockets.clear()}machineActivitySubscriptionIds(){let e=N(this.state);return new Set(this.state.machines.filter(t=>t.id!==e).filter(e=>HR(e,this.state.machineStatuses[e.id])).map(e=>e.id))}handleMachineActivityEvent(e,t){t.type===`session-pins.changed`?this.navigationOrder.load({kind:`sessionPins`,machineId:e,projectId:t.projectId,workspaceId:t.workspaceId}).catch(()=>void 0):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===`session-pins.changed`)this.handleMachineActivityEvent(e,t);else 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`)N(this.state)===e&&this.state.selectedProject?.id===t.projectId&&(this.workspaces.refreshSelectedProjectTopology(),this.sessions.refreshCurrentWorkspaceSessions(e,{recoverNetwork:!0}));else if(KR(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!==N(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,IR(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.closeSessionCleanupDialog(),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,JSON.stringify(pf(e)),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(),OR()]}renderWorkspacePanel(){let e=this.state.selectedWorkspace,t=e===void 0?this.workspacePanelEmptyState():void 0,n=this.visibleWorkspacePanels();return D`
3717
3717
  <workspace-panel
3718
3718
  id="workspace-panel"
3719
3719
  @session-notice-dismiss=${this.handleNoticeDismiss}
@@ -3764,7 +3764,7 @@ This only removes it from this PI WEB gateway.`,`Confirmation for forgetting a r
3764
3764
  .onResizeEnd=${this.workspacePanelActions.resizeEnd}
3765
3765
  .onReset=${this.workspacePanelActions.reset}
3766
3766
  ></app-panel-edge-control>
3767
- `}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-SR-xR);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&&_t(n,Lt.sessionsQueueMessageActions)}canCleanupSessions(){let e=this.selectedMachineRuntime();return this.apiScope===`management`&&this.state.selectedProject===void 0?!1:e?.ok===!0}hasAuthoritativeSessionPersistence(){return Nc(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=N(this.state)){return e===`local`||this.state.machineRuntimes[e]?.ok===!0}archivedDeleteUnavailableMessage(){let e=this.state.selectedMachine?.name??C(`client.sessionCleanupUi.this.machine.74a83f`,`this machine`);return C(`ui.piWebApp.updateAndRestartPiWebOnBeforeDeleting`,`Update and restart Pi-Web on {machineName} before deleting archived sessions.`,{machineName:e})}sessionCleanupUnavailableMessage(){return id(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[N(this.state)]}openSessionCleanupDialog(){this.sessionCleanupRequestEpoch+=1,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.sessionCleanupRequestEpoch+=1,this.sessionCleanupDialog=void 0}isCurrentSessionCleanupRequest(e,t){return this.sessionCleanupDialog!==void 0&&this.sessionCleanupRequestEpoch===e&&N(this.state)===t}async previewSessionCleanup(e){if(this.sessionCleanupDialog===void 0)return;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=N(this.state),r=++this.sessionCleanupRequestEpoch;this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!0,running:!1,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let e=await Tt.cleanupPreview(t,n);if(!this.isCurrentSessionCleanupRequest(r,n))return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:e,previewRequest:t,result:void 0,loading:!1,error:``}}catch(e){this.isCurrentSessionCleanupRequest(r,n)&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:()=>L.t(`previewFailed`,{error:ez(e)})})}}async runSessionCleanup(e){let t=this.sessionCleanupRequestForCurrentProject(e),n=this.sessionCleanupDialog;if(n===void 0||n.running===!0)return;if(n.preview===void 0||Qu(n.previewRequest)!==Qu(t)){this.sessionCleanupDialog={...n,error:()=>L.t(`previewRequired`)};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...n,error:this.sessionCleanupUnavailableMessage(),running:!1};return}let r=N(this.state),i=++this.sessionCleanupRequestEpoch;this.sessionCleanupDialog={...n,running:!0,error:``};try{let e=await Tt.cleanup(t,r);if(N(this.state)!==r)return;this.isCurrentSessionCleanupRequest(i,r)&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:void 0,previewRequest:void 0,result:e,running:!1,error:``}),await this.sessions.applySessionCleanupResult(e,r)}catch(e){this.isCurrentSessionCleanupRequest(i,r)&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:()=>L.t(`runFailed`,{error:ez(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=N(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=pi(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:mi(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:N(this.state),projectId:n.projectId,workspaceId:n.id},i=Xj(this.state.sessions,this.state.pinnedSessionIds);this.navigationOrder.mutate(r,n=>{let r=pi(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:mi(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=Tf(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 D`
3767
+ `}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-CR-SR);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&&_t(n,Lt.sessionsQueueMessageActions)}canCleanupSessions(){let e=this.selectedMachineRuntime();return this.apiScope===`management`&&this.state.selectedProject===void 0?!1:e?.ok===!0}hasAuthoritativeSessionPersistence(){return Nc(this.selectedMachineRuntime())}supportsWorkspaceFileSuggestions(e=N(this.state)){return e===`local`||this.state.machineRuntimes[e]?.ok===!0}archivedDeleteUnavailableMessage(){let e=this.state.selectedMachine?.name??C(`client.sessionCleanupUi.this.machine.74a83f`,`this machine`);return C(`ui.piWebApp.updateAndRestartPiWebOnBeforeDeleting`,`Update and restart Pi-Web on {machineName} before deleting archived sessions.`,{machineName:e})}sessionCleanupUnavailableMessage(){return id(this.state.selectedMachine?.name)}selectedMachineRuntime(){return this.state.machineRuntimes[N(this.state)]}openSessionCleanupDialog(){this.sessionCleanupRequestEpoch+=1,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.sessionCleanupRequestEpoch+=1,this.sessionCleanupDialog=void 0}isCurrentSessionCleanupRequest(e,t){return this.sessionCleanupDialog!==void 0&&this.sessionCleanupRequestEpoch===e&&N(this.state)===t}async previewSessionCleanup(e){if(this.sessionCleanupDialog===void 0)return;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=N(this.state),r=++this.sessionCleanupRequestEpoch;this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!0,running:!1,error:``,preview:void 0,previewRequest:void 0,result:void 0};try{let e=await Tt.cleanupPreview(t,n);if(!this.isCurrentSessionCleanupRequest(r,n))return;this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:e,previewRequest:t,result:void 0,loading:!1,error:``}}catch(e){this.isCurrentSessionCleanupRequest(r,n)&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,loading:!1,error:()=>L.t(`previewFailed`,{error:tz(e)})})}}async runSessionCleanup(e){let t=this.sessionCleanupRequestForCurrentProject(e),n=this.sessionCleanupDialog;if(n===void 0||n.running===!0)return;if(n.preview===void 0||Qu(n.previewRequest)!==Qu(t)){this.sessionCleanupDialog={...n,error:()=>L.t(`previewRequired`)};return}if(!this.canCleanupSessions()){this.sessionCleanupDialog={...n,error:this.sessionCleanupUnavailableMessage(),running:!1};return}let r=N(this.state),i=++this.sessionCleanupRequestEpoch;this.sessionCleanupDialog={...n,running:!0,error:``};try{let e=await Tt.cleanup(t,r);if(N(this.state)!==r)return;this.isCurrentSessionCleanupRequest(i,r)&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,preview:void 0,previewRequest:void 0,result:e,running:!1,error:``}),await this.sessions.applySessionCleanupResult(e,r)}catch(e){this.isCurrentSessionCleanupRequest(i,r)&&(this.sessionCleanupDialog={...this.sessionCleanupDialog,running:!1,error:()=>L.t(`runFailed`,{error:tz(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(){let e=N(this.state),t=this.apiScope===`normal`?[{kind:`projects`,machineId:e}]:[],n=this.state.selectedProject,r=this.state.selectedWorkspace;return n!==void 0&&this.apiScope===`normal`&&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=pi(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:mi(e,i,t,o,n<0?`before`:`after`)}).catch(()=>void 0)}toggleSessionPin(e){let t=this.state.selectedWorkspace;if(e.persisted===!1||e.cwd!==t?.path)return;let n={kind:`sessionPins`,machineId:N(this.state),projectId:t.projectId,workspaceId:t.id};this.navigationOrder.mutate(n,t=>t.includes(e.id)?t.filter(t=>t!==e.id):[...t,e.id]).catch(()=>void 0)}moveSessionPin(e,t){let n=this.state.selectedWorkspace;if(e.cwd!==n?.path)return;let r={kind:`sessionPins`,machineId:N(this.state),projectId:n.projectId,workspaceId:n.id},i=this.state.sessions;this.navigationOrder.mutate(r,n=>{let r=Zj(i,n),a=r.indexOf(e.id),o=a<0?void 0:r[a+t];if(o===void 0)return n;let s=mi(r,r,e.id,o,t<0?`before`:`after`),c=e=>{let t=Xj(i,[e])[0],n=t===void 0?-1:s.indexOf(t);return n<0?s.length:n};return[...n].sort((e,t)=>c(e)-c(t))}).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=Tf(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 D`
3768
3768
  <app-navigation-panel
3769
3769
  .presentationRuntime=${this.plugins.uiPresentation}
3770
3770
  .presentationContext=${this.uiPresentationContext()}
@@ -3788,8 +3788,8 @@ This only removes it from this PI WEB gateway.`,`Confirmation for forgetting a r
3788
3788
  .selectedWorkspace=${this.state.selectedWorkspace}
3789
3789
  .deletingWorkspaceIds=${this.deletingWorkspaceIds}
3790
3790
  .sessions=${this.state.sessions}
3791
- .pinnedSessionIds=${this.state.pinnedSessionIds}
3792
- .pinnedRootIds=${hr([this.navigationOrderVersion,N(this.state),this.state.selectedProject?.id,this.state.selectedWorkspace?.id],()=>r===void 0?[]:[...this.navigationOrder.ids(r)])}
3791
+ .pinnedSessionIds=${hr([this.navigationOrderVersion,N(this.state),this.state.selectedProject?.id,this.state.selectedWorkspace?.id],()=>r===void 0?[]:[...this.navigationOrder.ids(r)])}
3792
+ .pinnedRootIds=${hr([this.state.sessions,this.navigationOrderVersion,N(this.state),this.state.selectedProject?.id,this.state.selectedWorkspace?.id],()=>r===void 0?[]:Zj(this.state.sessions,this.navigationOrder.ids(r)))}
3793
3793
  .projectSelectionLoading=${this.pendingProjectNavigation?.seq===this.navigationSelectionSeq&&this.state.isLoadingWorkspaces}
3794
3794
  .sessionsLoading=${this.pendingProjectNavigation?.seq===this.navigationSelectionSeq&&this.state.selectedWorkspace!==void 0&&this.state.sessions.length===0}
3795
3795
  .sessionStatuses=${this.state.sessionStatuses}
@@ -3826,7 +3826,7 @@ This only removes it from this PI WEB gateway.`,`Confirmation for forgetting a r
3826
3826
  .onCloseProject=${this.navigationActions.closeProject}
3827
3827
  .onMoveProject=${this.apiScope===`normal`?this.navigationActions.moveProject:void 0}
3828
3828
  .onMoveWorkspace=${this.apiScope===`normal`?this.navigationActions.moveWorkspace:void 0}
3829
- .onMoveSessionPin=${this.apiScope===`normal`?this.navigationActions.moveSessionPin:void 0}
3829
+ .onMoveSessionPin=${this.navigationActions.moveSessionPin}
3830
3830
  .onSelectWorkspace=${this.navigationActions.selectWorkspace}
3831
3831
  .onDeleteWorkspace=${this.navigationActions.deleteWorkspace}
3832
3832
  .onArchivedCollapsed=${this.navigationActions.archivedCollapsed}
@@ -3851,7 +3851,7 @@ This only removes it from this PI WEB gateway.`,`Confirmation for forgetting a r
3851
3851
  .onFocusNavigationTarget=${this.navigationActions.focusNavigationTarget}
3852
3852
  .onCancelKeyboardNavigation=${this.navigationActions.cancelKeyboardNavigation}
3853
3853
  ></app-navigation-panel>
3854
- `}cancelAutomaticProjectNavigation(){this.pendingProjectNavigation!==void 0&&(this.pendingProjectNavigation.cancelled=!0)}openNavigationSection(e){this.cancelAutomaticProjectNavigation(),this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq,a,o=this.appShell.isMobileNavigationLayout&&e===`projects`?{seq:r,target:void 0,cancelled:!1}:void 0;this.pendingProjectNavigation=o;try{if(await this.withChatScrollTransition(async()=>{o===void 0?this.navigationSections.advanceAfterSelection(e):this.navigationSections.expand(`projects`),a=await n()},i),!i()||a===!1||o!==void 0&&(o.target!==void 0||o.cancelled))return;await this.focusNavigationTarget(t,i)}finally{this.pendingProjectNavigation===o&&(this.pendingProjectNavigation=void 0)}}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=N(this.state);if(n===void 0)return;let i=()=>t===this.navigationSelectionSeq&&e()&&N(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(Sr(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`&&!ZL(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 nz(),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 nz(),n()&&(this.sessions.isChatLoadDeferred&&await nz(),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=N(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&&N(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:D`
3854
+ `}cancelAutomaticProjectNavigation(){this.pendingProjectNavigation!==void 0&&(this.pendingProjectNavigation.cancelled=!0)}openNavigationSection(e){this.cancelAutomaticProjectNavigation(),this.navigationSections.open(e,()=>{this.selectMainView(`navigation`)})}async selectNavigationItem(e,t,n){let r=++this.navigationSelectionSeq,i=()=>r===this.navigationSelectionSeq,a,o=this.appShell.isMobileNavigationLayout&&e===`projects`?{seq:r,target:void 0,cancelled:!1}:void 0;this.pendingProjectNavigation=o;try{if(await this.withChatScrollTransition(async()=>{o===void 0?this.navigationSections.advanceAfterSelection(e):this.navigationSections.expand(`projects`),a=await n()},i),!i()||a===!1||o!==void 0&&(o.target!==void 0||o.cancelled))return;await this.focusNavigationTarget(t,i)}finally{this.pendingProjectNavigation===o&&(this.pendingProjectNavigation=void 0)}}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=N(this.state);if(n===void 0)return;let i=()=>t===this.navigationSelectionSeq&&e()&&N(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(Sr(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`&&!QL(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 rz(),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 rz(),n()&&(this.sessions.isChatLoadDeferred&&await rz(),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=N(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&&N(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:D`
3855
3855
  <session-tree-navigator
3856
3856
  .tree=${e.treeDialog}
3857
3857
  .onNavigate=${(e,t)=>this.navigateSessionTree(e,t)}
@@ -3859,11 +3859,11 @@ This only removes it from this PI WEB gateway.`,`Confirmation for forgetting a r
3859
3859
  .onAbort=${()=>this.sessions.abortTreeNavigation()}
3860
3860
  .onCancel=${()=>{this.closeSessionTreeNavigator()}}
3861
3861
  ></session-tree-navigator>
3862
- `}visibleWorkspacePanels(){let e=this.plugins.getApplicationPanels().flatMap(e=>{let t=this.createApplicationPanelContext(e.id,e.sourceContributionId);return e.visible?.(t)??!0?[{...e,badge:()=>e.badge?.(t),render:()=>e.render(t)}]:[]}),t=this.state.selectedWorkspace;if(t!==void 0){let n=this.createWorkspacePanelContext(t);e.push(...this.plugins.getWorkspacePanels().filter(e=>e.visible?.(n)??!0).map(e=>({...e,badge:()=>e.badge?.(n),render:()=>e.render(n)})))}return e.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:k.t(`loadingProjects`),body:k.t(`lookingForProjects`)}:e===void 0?this.state.projects.length===0?{title:k.t(`noProjects`),body:k.t(`addProjectHint`)}:{title:k.t(`selectProject`),body:k.t(`chooseProject`)}:this.state.isLoadingWorkspaces?{title:k.t(`loadingWorkspaces`),body:k.t(`preparingTools`,{project:e.name})}:this.state.workspaces.length===0?{title:C(`ui.piWebApp.noWorkspacesFound`,`No workspaces found`),body:C(`ui.piWebApp.noWorkspacesAvailableForTrySelectingOrAdding`,`No workspaces available for {name}. Try selecting or adding the project again.`,{name:e.name})}:{title:C(`ui.workspacePanel.selectWorkspace`,`Select workspace`),body:C(`ui.piWebApp.selectAWorkspaceInToViewFilesGit`,`Select a workspace in {name} to view files, Git, or terminals.`,{name:e.name})}}sessionEmptyMessage(){return this.contentError()===``?this.state.isLoadingProjects?Mu.t(`loadingProjects`):this.state.selectedWorkspace===void 0?this.state.selectedProject===void 0?this.state.projects.length===0?Mu.t(`addProject`):Mu.t(`selectProject`):Mu.t(`selectWorkspace`):Mu.t(`selectSession`):this.contentError()}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){let t=FR(this.state),n=r=>{let i=pw(r,e,t.id);return eO({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t),projects:aw(cn,t.id),...i===void 0?{}:{peer:i},host:this.createWorkspaceHost()},n)};return n(IR())}sessionLabelItems(e){let t=this.state.selectedWorkspace;if(t===void 0)return[];let n=FR(this.state),r=i=>{let a=pw(i,t,n.id);return tO({machine:n,workspace:t,session:pn(e),state:this.state,files:this.createWorkspaceFiles(t,n),projects:aw(cn,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(IR()))}createWorkspaceFiles(e,t){return pk(Et,e,t.id,{managementMode:this.apiScope===`management`,defaultUploadFolder:an(e.effectiveConfig,this.workspaceUploadDefaultFolder),onInvalidate:n=>{this.invalidateWorkspaceResources(e,t,n)}})}createWorkspaceHost(){return{requestRender:()=>{this.invalidateWorkspaceSurface()}}}createApplicationPanelContext(e,t=e,n){let r=FR(this.state),i=this.state.selectedWorkspace,a=o=>{let s=this.beginNavigationOperation(vR),c=this.maintenanceTerminal(o,r.id,s);return QD({...c===void 0?{}:{maintenanceTerminal:c},machine:r,state:this.state,projects:aw(cn,r.id),...i===void 0?{}:{workspace:i},...i===void 0||e===void 0?{}:{navigation:this.createWorkspacePanelNavigation(i,r,e,t===void 0?[]:[t],n,s)},...i===void 0||!this.terminalAvailableForMachine(r.id)?{}:{terminal:this.workspaceTerminal(o,i,r.id,s)},navigate:(e,t)=>this.navigate(e,t),prompt:this.createPromptEditor(o,r.id),host:this.createWorkspaceHost()},a)};return a(`core`)}createWorkspacePanelContext(e,t=FR(this.state),n){let r=t.id,i=(a,o,s=[])=>{let c=this.beginNavigationOperation(vR),l=this.workspaceNavigationGeneration,u={...c,isCurrent:()=>c.isCurrent()&&l===this.workspaceNavigationGeneration},d=pw(a,e,r);return $D({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:aw(cn,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(IR())}invalidateWorkspacePanels(e,t){let n=this.plugins.getApplicationPanels().filter(t=>e===void 0||t.id===e).map(async e=>{let n=this.createApplicationPanelContext(e.id,e.sourceContributionId,t);(e.visible?.(n)??!0)&&await e.onInvalidate?.(n)}),r=this.state.selectedWorkspace;return Promise.all([...n,...r===void 0?[]:[this.plugins.invalidateWorkspacePanels(this.createWorkspacePanelContext(r,FR(this.state),t),e)]]).then(()=>void 0)}invalidateWorkspaceResources(e,t,n){return this.plugins.invalidateWorkspaceResources(this.createWorkspacePanelContext(e,t),n)}getActions(){return CA(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:C(`ui.piWebApp.changeNormalModePassword`,`Change normal-mode password`),description:C(`ui.piWebApp.changeTheLocalPasswordRequiredForNormalMode`,`Change the local password required for normal mode`),group:C(`client.actions.preferences.57907a`,`Preferences`),enabled:this.normalAuthStatus?.authenticated===!0,run:()=>{this.normalAuthDialogMode=`change`,this.normalAuthError=``}}]}sessionActions(){return[{id:`app.sessions.cleanup`,get title(){return L.t(`actionTitle`)},get description(){return L.t(`actionDescription`)},get group(){return L.t(`eyebrow`)},...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.reset-navigation-panel-size`,get title(){return ir.t(`resetNavigationTitle`)},get description(){return ir.t(`resetNavigationDescription`)},get group(){return ir.t(`groupView`)},run:()=>{this.resetResizablePanel(`navigation`)}},{id:`app.layout.reset-workspace-panel-size`,get title(){return ir.t(`resetWorkspaceTitle`)},get description(){return ir.t(`resetWorkspaceDescription`)},get group(){return ir.t(`groupView`)},run:()=>{this.resetResizablePanel(`workspace`)}},{id:`app.layout.reset-panel-sizes`,get title(){return ir.t(`resetAllTitle`)},get description(){return ir.t(`resetAllDescription`)},get group(){return ir.t(`groupView`)},run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:`app.navigation.open`,get title(){return ir.t(`openNavigationTitle`)},get description(){return ir.t(`openNavigationDescription`)},get group(){return ir.t(`groupNavigation`)},run:()=>{this.showNavigation()}},{id:`app.navigation.focus-machines`,get title(){return ir.t(`focusMachinesTitle`)},get description(){return ir.t(`focusMachinesDescription`)},shortcut:`mod+g m`,get group(){return ir.t(`groupNavigation`)},run:()=>this.focusNavigationSection(`machines`)},{id:`app.navigation.focus-projects`,get title(){return ir.t(`focusProjectsTitle`)},get description(){return ir.t(`focusProjectsDescription`)},shortcut:`mod+g p`,get group(){return ir.t(`groupNavigation`)},run:()=>this.focusNavigationSection(`projects`)},{id:`app.navigation.focus-workspaces`,get title(){return ir.t(`focusWorkspacesTitle`)},get description(){return ir.t(`focusWorkspacesDescription`)},shortcut:`mod+g w`,get group(){return ir.t(`groupNavigation`)},run:()=>this.focusNavigationSection(`workspaces`)},{id:`app.navigation.focus-sessions`,get title(){return ir.t(`focusSessionsTitle`)},get description(){return ir.t(`focusSessionsDescription`)},shortcut:`mod+g s`,get group(){return ir.t(`groupNavigation`)},run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){let e=this.gatewayPluginLoadPromise;if(e!==void 0)return e;this.gatewayPluginLoadAttemptComplete=!1;let t=Promise.all([this.builtInPluginsReady,this.declarativeThemesReady]).then(()=>this.pluginLoads.ensureGatewayLoaded()).then(e=>{this.gatewayPluginLoadAttemptComplete=!0,this.applyPreferredTheme(!1),!e&&this.gatewayPluginLoadPromise===t&&(this.gatewayPluginLoadPromise=void 0)});return this.gatewayPluginLoadPromise=t,t}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(n?.ok===!0&&!_t(n,Lt.pluginLifecycle)){let n=()=>GO.t(`lifecycleRequired`,{name: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)!==nn,r=e.declarations.filter(t),i=await this.plugins.registerBatch(e.registrations.filter(t),{declarations:r,failures:ZR(e,r)});this.pluginLoadErrors.delete(n),i.failures.length>0&&this.pluginLoadErrors.set(n,i.failures.map(e=>ez(e.error)).join(`
3863
- `));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=>ez(e.error));this.pluginLoadErrors.delete(n),i.length>0&&this.pluginLoadErrors.set(n,i.join(`
3864
- `));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=ZR(e,o),c=e.terminalMode===`required`?e.failures.find(({entry:e})=>e.id===nn):void 0;if(c!==void 0)return this.verifiedPluginModeByMachine.delete(n),this.clearRequiredTerminal(n),this.reconcilePluginLoadSelection(r),this.applyPreferredTheme(!1),this.setRequiredPluginFailure(n,()=>GO.t(`terminalLoadFailed`,{detail:ez(c.error)})),this.requestUpdate(),!1;let l=n===`local`?nn:hn(n,nn);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 new KO(()=>GO.t(`capabilityLost`));if(r!==void 0){let t=$R(r,n);if(!QR(e.binding,t))throw new KO(()=>GO.t(`revisionChanged`))}this.requiredTerminalByMachine.set(n,e)}else{if(r===void 0)throw new KO(()=>GO.t(`registrationMissing`));let e=$R(r,n),i=o.find(({id:e})=>e===l);if(i===void 0)throw new KO(()=>GO.t(`declarationMissing`));let a=(await this.plugins.registerBatch([r],{declarations:[i],failures:s.filter(({declaration:e})=>e.id===l),requiredCapabilities:[{registrationPluginId:l,capability:qO}]})).failures.find(({declaration:e})=>e.id===l);if(a!==void 0)throw t=a.phase,a.error;let c=this.plugins.resolveCapability(l,qO),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,()=>GO.t(`terminalActivationFailed`,{phase:t,detail:ez(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(ez(e.error)),this.pluginLoadErrors.set(n,i.join(`
3865
- `)),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,()=>GO.t(`terminalMissingAfterActivation`))):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 ${typeof e==`function`?e():e}`,t),this.pluginLoadErrors.set(n,ez(t)),this.verifiedPluginModeByMachine.delete(n),this.clearRequiredTerminal(n),this.reconcilePluginLoadSelection(r),this.applyPreferredTheme(!1),this.setRequiredPluginFailure(n,()=>GO.t(`loadFailed`,{source:typeof e==`function`?e():e,detail:ez(t)})),this.requestUpdate(),!1}}reconcilePluginLoadSelection(e){DR()===e&&this.reconcileWorkspacePanelSelection()}setRequiredPluginFailure(e,t){this.requiredPluginFailureByMachine.set(e,t),this.dismissedRequiredPluginFailureByMachine.delete(e),N(this.state)===e&&this.requestUpdate()}clearRequiredPluginFailure(e){this.requiredPluginFailureByMachine.delete(e)&&(this.dismissedRequiredPluginFailureByMachine.delete(e),N(this.state)===e&&this.requestUpdate())}displayedError(){if(this.state.error!==``)return this.state.error;let e=N(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=N(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),N(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!==N(this.state))return!1;let n=t??`local`,r=this.verifiedPluginModeByMachine.get(n);return e===(n===`local`?`pi-web.terminal`:hn(n,`pi-web.terminal`))?r===`required`&&this.terminalAvailableForMachine(n):r===`recovery-disabled`||r===`required`&&this.terminalAvailableForMachine(n)}createPromptEditor(e=`core`,t=N(this.state)){let n=this.state.selectedSession,r=n!==void 0&&n.archived!==!0&&!go(n.id)&&t===N(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=>ZD({state:this.state,projects:aw(cn,N(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().finally(()=>{this.schedulePiWebStatusRetry()}),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=N(this.state),n=Sr(t,e.projectId,e.id);if(!bf(e)){this.browserErrors.reportLocalized(n,()=>oR.t(`workspaceRemovalUnavailable`));return}if(Ef(this.state,e))return;let r=e.removal,i=Sf(e);if(r===void 0||i===void 0||!confirm(i))return;let a=this.beginNavigationOperation(gR);try{let n=await Et.deleteWorkspace(e.projectId,e.id,r.precondition,t),i=this.apiScope===`management`?Ot(n):this.requiredTerminalComposition(t).facade.parseCommandRun(n);if(N(this.state)!==t||!this.recordWorkspaceDeletionRun(i,t))return;let o=await this.workspaceForCommandRun(i,t);if(N(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=ez(r);if(this.apiScope===`management`||!(r instanceof ne)||i.startsWith(`Session daemon unavailable:`)){this.browserErrors.reportLocalized(n,()=>oR.t(`workspaceRemovalFailed`,{detail:ez(r)}));return}let a=C(`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.reportLocalized(n,()=>oR.t(`workspaceRemovalFailed`,{detail:ez(r)}))}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)),N(this.state)===t&&this.state.selectedProject?.id===e.projectId)return n.find(t=>t.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(N(this.state)!==t||this.state.selectedProject?.id!==e.projectId)return!1;let n=Df(e);return n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling(),!0)}async refreshWorkspaceDeletionRuns(){let e=N(this.state),t=this.state.selectedProject,n=YR(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&&bf(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)Of(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&&Of(e));if(n.length>0&&a.length===0)return;let o=Cf(),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 ut.listCommandRuns({...o,projectId:t.id,workspaceId:n.id},e,{signal:r.signal});let i=c===void 0?void 0:pw(c.binding,n,e);if(i===void 0||c===void 0)throw XO(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]||Of(n)&&p.has(n.workspaceId))).map(([,e])=>e),h=wf([...f.flatMap(e=>e.value),...m].filter(t=>!this.handledWorkspaceDeletionRunIds.has(JR(e,t.id))));this.setState({workspaceDeletionRuns:h});for(let n of Object.values(h))Of(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&&YR(this.state)===n?(this.workspaceDeletionPollTimer!==void 0&&window.clearTimeout(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,queueMicrotask(()=>{i===this.workspaceDeletionRefreshGeneration&&YR(this.state)===n&&this.refreshWorkspaceDeletionRuns()})):this.updateWorkspaceDeletionPolling()}}}workspaceDeletionRefreshIsCurrent(e,t,n,r){return this.workspaceDeletionRefreshAbort===r&&!r.signal.aborted&&n===this.workspaceDeletionRefreshGeneration&&N(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=N(this.state),t=Date.now(),n=1/0;for(let r of Object.values(this.state.workspaceDeletionRuns)){let i=JR(e,r.id);if(this.handledWorkspaceDeletionRunIds.has(i))continue;if(Of(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=JR(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(a))return;let o=Df(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=Sr(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=yR[Math.min(o-1,yR.length-1)]??1e4;this.workspaceDeletionReconcileRetries.set(a,{attempt:o,retryAt:Date.now()+l}),this.browserErrors.reportLocalized(c,()=>oR.t(`workspaceRemovalRefreshFailed`,{detail:ez(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:tz(this.state.workspaceDeletionRuns,o)})}else e.status===`failed`&&(this.workspaceDeletionReconcileRetries.delete(a),this.handledWorkspaceDeletionRunIds.add(a))}}openMachineDialog(){this.machineNameEditTarget=void 0,this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){(this.machineNameEditTarget===void 0?await this.machines.addMachine(e):await this.machines.updateMachine(this.machineNameEditTarget.id,e.name))!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(oR.t(`removeMachine`,{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=TR(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=>{console.warn(`Action failed: ${e.id}`,t),this.browserErrors.reportLocalized({kind:`global`},()=>oR.t(`actionFailed`,{detail:ez(t)}))})}async openModelDialog(){let e=this.state.selectedSession;if(e===void 0)return;let t={machineId:N(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,get title(){return A.t(`selectModel`)},...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 NR(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,get label(){return i===t?A.t(`currentModel`,{model:r}):r},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){de().enforcedBy===void 0&&this.plugins.getThemes().some(t=>t.id===e.themeId)&&(this.localThemePreference={...e},ye(),this.applyPreferredTheme(!0))}useDefaultTheme(){de().enforcedBy===void 0&&(this.localThemePreference=void 0,ye(),le(),this.applyPreferredTheme(!1))}registerThemeCatalog(e,t=!1){t||(this.themeRequest?.abort(),this.themeRequest=void 0),this.declarativeThemes=t&&this.declarativeThemes!==void 0?ie(this.declarativeThemes,e):e,this.plugins.setDeclarativeThemes(this.declarativeThemes.themes.map(e=>JC(e)),this.declarativeThemes.themePairs.map(e=>JC(e))),this.requestUpdate()}loadPreferredThemeIfNeeded(e){let t=this.themePreference,n=e.some(e=>e.id===t.themeId);if(this.requestedThemeId!==t.themeId||n){if(this.themeRequest?.abort(),this.themeRequest=void 0,this.requestedThemeId===t.themeId||(this.requestedThemeId=t.themeId,n||this.declarativeThemes!==void 0&&t.themeId===me(this.declarativeThemes,void 0).themeId))return;let e=new AbortController;this.themeRequest=e,fe(t,e.signal).then(t=>{!e.signal.aborted&&this.isConnected&&(this.registerThemeCatalog(t.catalog,!0),ge(t.stylesheets))}).catch(t=>{e.signal.aborted||console.warn(`Could not load the preferred theme; keeping the available palette`,t)}).finally(()=>{this.themeRequest===e&&(this.themeRequest=void 0,this.requestUpdate())})}}syncPluginStylesheets(){if(!this.isConnected||(this.stylesheetRuntime.update(this.plugins.getStylesheets(N(this.state))),be.pending))return;let e=this.plugins.getThemes();if(this.activeThemeId!==``&&!e.some(e=>e.id===this.activeThemeId)&&this.stylesheetRuntime.clearTheme(()=>{this.activeThemeId=``,ae(),this.activeThemeColorScheme=this.startupColorScheme(),this.syncFileIcons()}),this.themeConfigReady&&this.loadPreferredThemeIfNeeded(e),this.themeRequest!==void 0){this.stylesheetRuntime.suspendTheme();return}let t=this.themeConfigReady?this.resolveCurrentThemePreference(e).activeTheme:void 0;t===void 0?this.stylesheetRuntime.suspendTheme():this.stylesheetRuntime.updateTheme(t,()=>{this.activeThemeId=t.id,this.activeThemeColorScheme=t.colorScheme,pe(t),this.syncFileIcons(),this.revealAfterRender()})}selectFileIconTheme(e){(e===void 0||e===`none`||this.plugins.getFileIconThemes().some(t=>t.id===e))&&(this.fileIconPreference=e,we(e),this.syncFileIcons())}syncFileIcons(){this.fileIcons.update(this.plugins.getFileIconThemes(),this.fileIconPreference,this.activeThemeColorScheme)}applyPreferredTheme(e){e&&se(this.themePreference),this.syncPluginStylesheets()}resolveCurrentThemePreference(e=this.plugins.getThemes()){return ce({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight(),pending:!0})}revealAfterRender(){this.updateComplete.then(()=>{this.isConnected&&ve()})}startupColorScheme(){return this.systemPrefersLight()?`light`:`dark`}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}async openThinkingDialog(){let e=this.state.selectedSession===void 0?{machineId:N(this.state),sessionId:``,cwd:``}:{machineId:N(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,get title(){return A.t(`selectThinking`)},origin:e,selectedValue:n,defaultsLoading:!0,options:t.map(e=>{let t=Kt(e,C);return{value:e,label:`${on(e,C)}${e===n?C(`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,t){let n=e===`model`?this.state.modelDialog:this.state.thinkingDialog;if(n===void 0||!this.modelDialogOriginIsCurrent(n.origin))return;let{instanceId:r,origin:i}=n;if(e===`model`){let e=t.indexOf(`/`);if(e<=0)return;let n=await this.sessions.setSessionDefaults({provider:t.slice(0,e),modelId:t.slice(e+1)}),a=this.state.modelDialog;if(n?.defaultProvider===void 0||n.defaultModel===void 0||a?.instanceId!==r||!this.modelDialogOriginIsCurrent(i))return;this.setState({modelDialog:{...a,defaultValue:`${n.defaultProvider}/${n.defaultModel}`,defaultsLoading:!1}});return}if(!tn(t))return;let a=await this.sessions.setSessionDefaults({thinkingLevel:t}),o=this.state.thinkingDialog;a?.defaultThinkingLevel!==void 0&&o?.instanceId===r&&this.modelDialogOriginIsCurrent(i)&&this.setState({thinkingDialog:{...o,defaultValue:a.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=>!Eo(e.target,s)||!this.plugins.promptChipOwnerAvailable(e.pluginId,s.machineId)))return!1;let c=await this.sessions.send(Do(e,a),t,n,r,i,s);return c&&this.plugins.promptChips.consume(a),c}selectedPromptChips(){let e=N(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=N(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===N(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=qu(N(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=Kl(e.selectedNotificationInbox)),D`
3866
- <chat-view .onNavigationChange=${this.handleChatNavigationChange} .quietMode=${this.quietMode} .behaviors=${this.chatBehaviors} .canMutateQueuedMessages=${this.canMutateQueueMessage(t,N(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.getChatContentRendering(N(e))} .transcriptRenderers=${this.plugins.getTranscriptRenderers(N(e))} .contentRendererVersion=${this.plugins.contentRendererVersion} .machineId=${N(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===RR(e)} .pendingDialogs=${e.pendingDialogs} .closedDialogs=${e.closedDialogs} .onAnswerDialog=${this.handleAnswerDialog} .onCancelDialog=${this.handleCancelDialog} .onDismissClosedDialog=${this.handleDismissClosedDialog} .askDraftSessionId=${M(N(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(N(e))} .messageActionContext=${this.messageActionContext(e)} .onDismissNotification=${this.handleDismissNotification} .onDismissAllNotifications=${this.handleDismissAllNotifications} .onLoadMore=${this.handleLoadEarlierMessages}></chat-view>
3862
+ `}visibleWorkspacePanels(){let e=this.plugins.getApplicationPanels().flatMap(e=>{let t=this.createApplicationPanelContext(e.id,e.sourceContributionId);return e.visible?.(t)??!0?[{...e,badge:()=>e.badge?.(t),render:()=>e.render(t)}]:[]}),t=this.state.selectedWorkspace;if(t!==void 0){let n=this.createWorkspacePanelContext(t);e.push(...this.plugins.getWorkspacePanels().filter(e=>e.visible?.(n)??!0).map(e=>({...e,badge:()=>e.badge?.(n),render:()=>e.render(n)})))}return e.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:k.t(`loadingProjects`),body:k.t(`lookingForProjects`)}:e===void 0?this.state.projects.length===0?{title:k.t(`noProjects`),body:k.t(`addProjectHint`)}:{title:k.t(`selectProject`),body:k.t(`chooseProject`)}:this.state.isLoadingWorkspaces?{title:k.t(`loadingWorkspaces`),body:k.t(`preparingTools`,{project:e.name})}:this.state.workspaces.length===0?{title:C(`ui.piWebApp.noWorkspacesFound`,`No workspaces found`),body:C(`ui.piWebApp.noWorkspacesAvailableForTrySelectingOrAdding`,`No workspaces available for {name}. Try selecting or adding the project again.`,{name:e.name})}:{title:C(`ui.workspacePanel.selectWorkspace`,`Select workspace`),body:C(`ui.piWebApp.selectAWorkspaceInToViewFilesGit`,`Select a workspace in {name} to view files, Git, or terminals.`,{name:e.name})}}sessionEmptyMessage(){return this.contentError()===``?this.state.isLoadingProjects?Mu.t(`loadingProjects`):this.state.selectedWorkspace===void 0?this.state.selectedProject===void 0?this.state.projects.length===0?Mu.t(`addProject`):Mu.t(`selectProject`):Mu.t(`selectWorkspace`):Mu.t(`selectSession`):this.contentError()}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){let t=IR(this.state),n=r=>{let i=pw(r,e,t.id);return eO({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t),projects:aw(cn,t.id),...i===void 0?{}:{peer:i},host:this.createWorkspaceHost()},n)};return n(LR())}sessionLabelItems(e){let t=this.state.selectedWorkspace;if(t===void 0)return[];let n=IR(this.state),r=i=>{let a=pw(i,t,n.id);return tO({machine:n,workspace:t,session:pn(e),state:this.state,files:this.createWorkspaceFiles(t,n),projects:aw(cn,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(LR()))}createWorkspaceFiles(e,t){return pk(Et,e,t.id,{managementMode:this.apiScope===`management`,defaultUploadFolder:an(e.effectiveConfig,this.workspaceUploadDefaultFolder),onInvalidate:n=>{this.invalidateWorkspaceResources(e,t,n)}})}createWorkspaceHost(){return{requestRender:()=>{this.invalidateWorkspaceSurface()}}}createApplicationPanelContext(e,t=e,n){let r=IR(this.state),i=this.state.selectedWorkspace,a=o=>{let s=this.beginNavigationOperation(yR),c=this.maintenanceTerminal(o,r.id,s);return QD({...c===void 0?{}:{maintenanceTerminal:c},machine:r,state:this.state,projects:aw(cn,r.id),...i===void 0?{}:{workspace:i},...i===void 0||e===void 0?{}:{navigation:this.createWorkspacePanelNavigation(i,r,e,t===void 0?[]:[t],n,s)},...i===void 0||!this.terminalAvailableForMachine(r.id)?{}:{terminal:this.workspaceTerminal(o,i,r.id,s)},navigate:(e,t)=>this.navigate(e,t),prompt:this.createPromptEditor(o,r.id),host:this.createWorkspaceHost()},a)};return a(`core`)}createWorkspacePanelContext(e,t=IR(this.state),n){let r=t.id,i=(a,o,s=[])=>{let c=this.beginNavigationOperation(yR),l=this.workspaceNavigationGeneration,u={...c,isCurrent:()=>c.isCurrent()&&l===this.workspaceNavigationGeneration},d=pw(a,e,r);return $D({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:aw(cn,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(LR())}invalidateWorkspacePanels(e,t){let n=this.plugins.getApplicationPanels().filter(t=>e===void 0||t.id===e).map(async e=>{let n=this.createApplicationPanelContext(e.id,e.sourceContributionId,t);(e.visible?.(n)??!0)&&await e.onInvalidate?.(n)}),r=this.state.selectedWorkspace;return Promise.all([...n,...r===void 0?[]:[this.plugins.invalidateWorkspacePanels(this.createWorkspacePanelContext(r,IR(this.state),t),e)]]).then(()=>void 0)}invalidateWorkspaceResources(e,t,n){return this.plugins.invalidateWorkspaceResources(this.createWorkspacePanelContext(e,t),n)}getActions(){return CA(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:C(`ui.piWebApp.changeNormalModePassword`,`Change normal-mode password`),description:C(`ui.piWebApp.changeTheLocalPasswordRequiredForNormalMode`,`Change the local password required for normal mode`),group:C(`client.actions.preferences.57907a`,`Preferences`),enabled:this.normalAuthStatus?.authenticated===!0,run:()=>{this.normalAuthDialogMode=`change`,this.normalAuthError=``}}]}sessionActions(){return[{id:`app.sessions.cleanup`,get title(){return L.t(`actionTitle`)},get description(){return L.t(`actionDescription`)},get group(){return L.t(`eyebrow`)},...this.canCleanupSessions()?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.reset-navigation-panel-size`,get title(){return ir.t(`resetNavigationTitle`)},get description(){return ir.t(`resetNavigationDescription`)},get group(){return ir.t(`groupView`)},run:()=>{this.resetResizablePanel(`navigation`)}},{id:`app.layout.reset-workspace-panel-size`,get title(){return ir.t(`resetWorkspaceTitle`)},get description(){return ir.t(`resetWorkspaceDescription`)},get group(){return ir.t(`groupView`)},run:()=>{this.resetResizablePanel(`workspace`)}},{id:`app.layout.reset-panel-sizes`,get title(){return ir.t(`resetAllTitle`)},get description(){return ir.t(`resetAllDescription`)},get group(){return ir.t(`groupView`)},run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:`app.navigation.open`,get title(){return ir.t(`openNavigationTitle`)},get description(){return ir.t(`openNavigationDescription`)},get group(){return ir.t(`groupNavigation`)},run:()=>{this.showNavigation()}},{id:`app.navigation.focus-machines`,get title(){return ir.t(`focusMachinesTitle`)},get description(){return ir.t(`focusMachinesDescription`)},shortcut:`mod+g m`,get group(){return ir.t(`groupNavigation`)},run:()=>this.focusNavigationSection(`machines`)},{id:`app.navigation.focus-projects`,get title(){return ir.t(`focusProjectsTitle`)},get description(){return ir.t(`focusProjectsDescription`)},shortcut:`mod+g p`,get group(){return ir.t(`groupNavigation`)},run:()=>this.focusNavigationSection(`projects`)},{id:`app.navigation.focus-workspaces`,get title(){return ir.t(`focusWorkspacesTitle`)},get description(){return ir.t(`focusWorkspacesDescription`)},shortcut:`mod+g w`,get group(){return ir.t(`groupNavigation`)},run:()=>this.focusNavigationSection(`workspaces`)},{id:`app.navigation.focus-sessions`,get title(){return ir.t(`focusSessionsTitle`)},get description(){return ir.t(`focusSessionsDescription`)},shortcut:`mod+g s`,get group(){return ir.t(`groupNavigation`)},run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){let e=this.gatewayPluginLoadPromise;if(e!==void 0)return e;this.gatewayPluginLoadAttemptComplete=!1;let t=Promise.all([this.builtInPluginsReady,this.declarativeThemesReady]).then(()=>this.pluginLoads.ensureGatewayLoaded()).then(e=>{this.gatewayPluginLoadAttemptComplete=!0,this.applyPreferredTheme(!1),!e&&this.gatewayPluginLoadPromise===t&&(this.gatewayPluginLoadPromise=void 0)});return this.gatewayPluginLoadPromise=t,t}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(n?.ok===!0&&!_t(n,Lt.pluginLifecycle)){let n=()=>GO.t(`lifecycleRequired`,{name: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)!==nn,r=e.declarations.filter(t),i=await this.plugins.registerBatch(e.registrations.filter(t),{declarations:r,failures:QR(e,r)});this.pluginLoadErrors.delete(n),i.failures.length>0&&this.pluginLoadErrors.set(n,i.failures.map(e=>tz(e.error)).join(`
3863
+ `));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=>tz(e.error));this.pluginLoadErrors.delete(n),i.length>0&&this.pluginLoadErrors.set(n,i.join(`
3864
+ `));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=QR(e,o),c=e.terminalMode===`required`?e.failures.find(({entry:e})=>e.id===nn):void 0;if(c!==void 0)return this.verifiedPluginModeByMachine.delete(n),this.clearRequiredTerminal(n),this.reconcilePluginLoadSelection(r),this.applyPreferredTheme(!1),this.setRequiredPluginFailure(n,()=>GO.t(`terminalLoadFailed`,{detail:tz(c.error)})),this.requestUpdate(),!1;let l=n===`local`?nn:hn(n,nn);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 new KO(()=>GO.t(`capabilityLost`));if(r!==void 0){let t=ez(r,n);if(!$R(e.binding,t))throw new KO(()=>GO.t(`revisionChanged`))}this.requiredTerminalByMachine.set(n,e)}else{if(r===void 0)throw new KO(()=>GO.t(`registrationMissing`));let e=ez(r,n),i=o.find(({id:e})=>e===l);if(i===void 0)throw new KO(()=>GO.t(`declarationMissing`));let a=(await this.plugins.registerBatch([r],{declarations:[i],failures:s.filter(({declaration:e})=>e.id===l),requiredCapabilities:[{registrationPluginId:l,capability:qO}]})).failures.find(({declaration:e})=>e.id===l);if(a!==void 0)throw t=a.phase,a.error;let c=this.plugins.resolveCapability(l,qO),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,()=>GO.t(`terminalActivationFailed`,{phase:t,detail:tz(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(tz(e.error)),this.pluginLoadErrors.set(n,i.join(`
3865
+ `)),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,()=>GO.t(`terminalMissingAfterActivation`))):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 ${typeof e==`function`?e():e}`,t),this.pluginLoadErrors.set(n,tz(t)),this.verifiedPluginModeByMachine.delete(n),this.clearRequiredTerminal(n),this.reconcilePluginLoadSelection(r),this.applyPreferredTheme(!1),this.setRequiredPluginFailure(n,()=>GO.t(`loadFailed`,{source:typeof e==`function`?e():e,detail:tz(t)})),this.requestUpdate(),!1}}reconcilePluginLoadSelection(e){OR()===e&&this.reconcileWorkspacePanelSelection()}setRequiredPluginFailure(e,t){this.requiredPluginFailureByMachine.set(e,t),this.dismissedRequiredPluginFailureByMachine.delete(e),N(this.state)===e&&this.requestUpdate()}clearRequiredPluginFailure(e){this.requiredPluginFailureByMachine.delete(e)&&(this.dismissedRequiredPluginFailureByMachine.delete(e),N(this.state)===e&&this.requestUpdate())}displayedError(){if(this.state.error!==``)return this.state.error;let e=N(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=N(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),N(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!==N(this.state))return!1;let n=t??`local`,r=this.verifiedPluginModeByMachine.get(n);return e===(n===`local`?`pi-web.terminal`:hn(n,`pi-web.terminal`))?r===`required`&&this.terminalAvailableForMachine(n):r===`recovery-disabled`||r===`required`&&this.terminalAvailableForMachine(n)}createPromptEditor(e=`core`,t=N(this.state)){let n=this.state.selectedSession,r=n!==void 0&&n.archived!==!0&&!go(n.id)&&t===N(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=>ZD({state:this.state,projects:aw(cn,N(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().finally(()=>{this.schedulePiWebStatusRetry()}),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=N(this.state),n=Sr(t,e.projectId,e.id);if(!bf(e)){this.browserErrors.reportLocalized(n,()=>sR.t(`workspaceRemovalUnavailable`));return}if(Ef(this.state,e))return;let r=e.removal,i=Sf(e);if(r===void 0||i===void 0||!confirm(i))return;let a=this.beginNavigationOperation(_R);try{let n=await Et.deleteWorkspace(e.projectId,e.id,r.precondition,t),i=this.apiScope===`management`?Ot(n):this.requiredTerminalComposition(t).facade.parseCommandRun(n);if(N(this.state)!==t||!this.recordWorkspaceDeletionRun(i,t))return;let o=await this.workspaceForCommandRun(i,t);if(N(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=tz(r);if(this.apiScope===`management`||!(r instanceof ne)||i.startsWith(`Session daemon unavailable:`)){this.browserErrors.reportLocalized(n,()=>sR.t(`workspaceRemovalFailed`,{detail:tz(r)}));return}let a=C(`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.reportLocalized(n,()=>sR.t(`workspaceRemovalFailed`,{detail:tz(r)}))}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)),N(this.state)===t&&this.state.selectedProject?.id===e.projectId)return n.find(t=>t.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(N(this.state)!==t||this.state.selectedProject?.id!==e.projectId)return!1;let n=Df(e);return n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling(),!0)}async refreshWorkspaceDeletionRuns(){let e=N(this.state),t=this.state.selectedProject,n=XR(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&&bf(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)Of(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&&Of(e));if(n.length>0&&a.length===0)return;let o=Cf(),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 ut.listCommandRuns({...o,projectId:t.id,workspaceId:n.id},e,{signal:r.signal});let i=c===void 0?void 0:pw(c.binding,n,e);if(i===void 0||c===void 0)throw XO(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]||Of(n)&&p.has(n.workspaceId))).map(([,e])=>e),h=wf([...f.flatMap(e=>e.value),...m].filter(t=>!this.handledWorkspaceDeletionRunIds.has(YR(e,t.id))));this.setState({workspaceDeletionRuns:h});for(let n of Object.values(h))Of(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&&XR(this.state)===n?(this.workspaceDeletionPollTimer!==void 0&&window.clearTimeout(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,queueMicrotask(()=>{i===this.workspaceDeletionRefreshGeneration&&XR(this.state)===n&&this.refreshWorkspaceDeletionRuns()})):this.updateWorkspaceDeletionPolling()}}}workspaceDeletionRefreshIsCurrent(e,t,n,r){return this.workspaceDeletionRefreshAbort===r&&!r.signal.aborted&&n===this.workspaceDeletionRefreshGeneration&&N(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=N(this.state),t=Date.now(),n=1/0;for(let r of Object.values(this.state.workspaceDeletionRuns)){let i=YR(e,r.id);if(this.handledWorkspaceDeletionRunIds.has(i))continue;if(Of(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=YR(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(a))return;let o=Df(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=Sr(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=bR[Math.min(o-1,bR.length-1)]??1e4;this.workspaceDeletionReconcileRetries.set(a,{attempt:o,retryAt:Date.now()+l}),this.browserErrors.reportLocalized(c,()=>sR.t(`workspaceRemovalRefreshFailed`,{detail:tz(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:nz(this.state.workspaceDeletionRuns,o)})}else e.status===`failed`&&(this.workspaceDeletionReconcileRetries.delete(a),this.handledWorkspaceDeletionRunIds.add(a))}}openMachineDialog(){this.machineNameEditTarget=void 0,this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){(this.machineNameEditTarget===void 0?await this.machines.addMachine(e):await this.machines.updateMachine(this.machineNameEditTarget.id,e.name))!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(sR.t(`removeMachine`,{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=ER(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=>{console.warn(`Action failed: ${e.id}`,t),this.browserErrors.reportLocalized({kind:`global`},()=>sR.t(`actionFailed`,{detail:tz(t)}))})}async openModelDialog(){let e=this.state.selectedSession;if(e===void 0)return;let t={machineId:N(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,get title(){return A.t(`selectModel`)},...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 PR(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,get label(){return i===t?A.t(`currentModel`,{model:r}):r},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){de().enforcedBy===void 0&&this.plugins.getThemes().some(t=>t.id===e.themeId)&&(this.localThemePreference={...e},ye(),this.applyPreferredTheme(!0))}useDefaultTheme(){de().enforcedBy===void 0&&(this.localThemePreference=void 0,ye(),le(),this.applyPreferredTheme(!1))}registerThemeCatalog(e,t=!1){t||(this.themeRequest?.abort(),this.themeRequest=void 0),this.declarativeThemes=t&&this.declarativeThemes!==void 0?ie(this.declarativeThemes,e):e,this.plugins.setDeclarativeThemes(this.declarativeThemes.themes.map(e=>JC(e)),this.declarativeThemes.themePairs.map(e=>JC(e))),this.requestUpdate()}loadPreferredThemeIfNeeded(e){let t=this.themePreference,n=e.some(e=>e.id===t.themeId);if(this.requestedThemeId!==t.themeId||n){if(this.themeRequest?.abort(),this.themeRequest=void 0,this.requestedThemeId===t.themeId||(this.requestedThemeId=t.themeId,n||this.declarativeThemes!==void 0&&t.themeId===me(this.declarativeThemes,void 0).themeId))return;let e=new AbortController;this.themeRequest=e,fe(t,e.signal).then(t=>{!e.signal.aborted&&this.isConnected&&(this.registerThemeCatalog(t.catalog,!0),ge(t.stylesheets))}).catch(t=>{e.signal.aborted||console.warn(`Could not load the preferred theme; keeping the available palette`,t)}).finally(()=>{this.themeRequest===e&&(this.themeRequest=void 0,this.requestUpdate())})}}syncPluginStylesheets(){if(!this.isConnected||(this.stylesheetRuntime.update(this.plugins.getStylesheets(N(this.state))),be.pending))return;let e=this.plugins.getThemes();if(this.activeThemeId!==``&&!e.some(e=>e.id===this.activeThemeId)&&this.stylesheetRuntime.clearTheme(()=>{this.activeThemeId=``,ae(),this.activeThemeColorScheme=this.startupColorScheme(),this.syncFileIcons()}),this.themeConfigReady&&this.loadPreferredThemeIfNeeded(e),this.themeRequest!==void 0){this.stylesheetRuntime.suspendTheme();return}let t=this.themeConfigReady?this.resolveCurrentThemePreference(e).activeTheme:void 0;t===void 0?this.stylesheetRuntime.suspendTheme():this.stylesheetRuntime.updateTheme(t,()=>{this.activeThemeId=t.id,this.activeThemeColorScheme=t.colorScheme,pe(t),this.syncFileIcons(),this.revealAfterRender()})}selectFileIconTheme(e){(e===void 0||e===`none`||this.plugins.getFileIconThemes().some(t=>t.id===e))&&(this.fileIconPreference=e,we(e),this.syncFileIcons())}syncFileIcons(){this.fileIcons.update(this.plugins.getFileIconThemes(),this.fileIconPreference,this.activeThemeColorScheme)}applyPreferredTheme(e){e&&se(this.themePreference),this.syncPluginStylesheets()}resolveCurrentThemePreference(e=this.plugins.getThemes()){return ce({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight(),pending:!0})}revealAfterRender(){this.updateComplete.then(()=>{this.isConnected&&ve()})}startupColorScheme(){return this.systemPrefersLight()?`light`:`dark`}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}async openThinkingDialog(){let e=this.state.selectedSession===void 0?{machineId:N(this.state),sessionId:``,cwd:``}:{machineId:N(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,get title(){return A.t(`selectThinking`)},origin:e,selectedValue:n,defaultsLoading:!0,options:t.map(e=>{let t=Kt(e,C);return{value:e,label:`${on(e,C)}${e===n?C(`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,t){let n=e===`model`?this.state.modelDialog:this.state.thinkingDialog;if(n===void 0||!this.modelDialogOriginIsCurrent(n.origin))return;let{instanceId:r,origin:i}=n;if(e===`model`){let e=t.indexOf(`/`);if(e<=0)return;let n=await this.sessions.setSessionDefaults({provider:t.slice(0,e),modelId:t.slice(e+1)}),a=this.state.modelDialog;if(n?.defaultProvider===void 0||n.defaultModel===void 0||a?.instanceId!==r||!this.modelDialogOriginIsCurrent(i))return;this.setState({modelDialog:{...a,defaultValue:`${n.defaultProvider}/${n.defaultModel}`,defaultsLoading:!1}});return}if(!tn(t))return;let a=await this.sessions.setSessionDefaults({thinkingLevel:t}),o=this.state.thinkingDialog;a?.defaultThinkingLevel!==void 0&&o?.instanceId===r&&this.modelDialogOriginIsCurrent(i)&&this.setState({thinkingDialog:{...o,defaultValue:a.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=>!Eo(e.target,s)||!this.plugins.promptChipOwnerAvailable(e.pluginId,s.machineId)))return!1;let c=await this.sessions.send(Do(e,a),t,n,r,i,s);return c&&this.plugins.promptChips.consume(a),c}selectedPromptChips(){let e=N(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=N(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===N(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=qu(N(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=Kl(e.selectedNotificationInbox)),D`
3866
+ <chat-view .onNavigationChange=${this.handleChatNavigationChange} .quietMode=${this.quietMode} .behaviors=${this.chatBehaviors} .canMutateQueuedMessages=${this.canMutateQueueMessage(t,N(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.getChatContentRendering(N(e))} .transcriptRenderers=${this.plugins.getTranscriptRenderers(N(e))} .contentRendererVersion=${this.plugins.contentRendererVersion} .machineId=${N(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===zR(e)} .pendingDialogs=${e.pendingDialogs} .closedDialogs=${e.closedDialogs} .onAnswerDialog=${this.handleAnswerDialog} .onCancelDialog=${this.handleCancelDialog} .onDismissClosedDialog=${this.handleDismissClosedDialog} .askDraftSessionId=${M(N(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(N(e))} .messageActionContext=${this.messageActionContext(e)} .onDismissNotification=${this.handleDismissNotification} .onDismissAllNotifications=${this.handleDismissAllNotifications} .onLoadMore=${this.handleLoadEarlierMessages}></chat-view>
3867
3867
  `}renderStatusBar(e){return D`<status-bar slot="status" .status=${e.status}></status-bar>`}renderContextBar(){return this.appShell.isMobileNavigationLayout?D`
3868
3868
  <app-context-bar
3869
3869
  .presentationRuntime=${this.plugins.uiPresentation}
@@ -3892,7 +3892,7 @@ This only removes it from this PI WEB gateway.`,`Confirmation for forgetting a r
3892
3892
  .selectedTab=${r}
3893
3893
  .onSelect=${this.selectNavigationTab}
3894
3894
  ></app-mobile-main-tabs>
3895
- `}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=gA(e,this.resolvedNavigationPreferences().pinnedIds),n=this.selectedNavigationTab()){return _A(e,t,n)}mobileMainTabs(e=this.visibleWorkspacePanels()){let t=Dj(this.state.sessions,this.unreadSessionIds);return[{id:`navigation`,label:k.t(`sessions`),icon:`navigation`,className:`navigation-tab`,...t===0?{}:{badge:t,badgeLabel:k.t(`unread`,{count:t}),badgeTone:`unread`}},{id:`chat`,label:k.t(`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=N(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 D`<app-refresh-control .onReload=${this.handleReloadApp}></app-refresh-control>`}renderServerNoticeBanners(){let e=N(this.state),t=this.serverNotices.projection(e),n=t?.status===`fresh`?kd(t.notices,Or(this.state)):[];return n.length===0?null:D`${n.map(t=>dR(Wd(t),()=>{this.serverNotices.dismiss(e,t.id)},t.severity))}`}renderBrowserErrorBanners(e){let t=this.visibleBrowserErrorsForCurrentRoute(e);return t.length===0?null:D`${t.map(e=>dR(e.displayMessage?.()??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===N(this.state)?this.sessions.refreshSelectedSession(t.sessionId,{recoverNetwork:!0}):t.kind===`workspace`&&e.recovery===`workspace-sessions-refresh`&&t.machineId===N(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=Er(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 D`
3895
+ `}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=gA(e,this.resolvedNavigationPreferences().pinnedIds),n=this.selectedNavigationTab()){return _A(e,t,n)}mobileMainTabs(e=this.visibleWorkspacePanels()){let t=Dj(this.state.sessions,this.unreadSessionIds);return[{id:`navigation`,label:k.t(`sessions`),icon:`navigation`,className:`navigation-tab`,...t===0?{}:{badge:t,badgeLabel:k.t(`unread`,{count:t}),badgeTone:`unread`}},{id:`chat`,label:k.t(`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=N(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 D`<app-refresh-control .onReload=${this.handleReloadApp}></app-refresh-control>`}renderServerNoticeBanners(){let e=N(this.state),t=this.serverNotices.projection(e),n=t?.status===`fresh`?kd(t.notices,Or(this.state)):[];return n.length===0?null:D`${n.map(t=>fR(Wd(t),()=>{this.serverNotices.dismiss(e,t.id)},t.severity))}`}renderBrowserErrorBanners(e){let t=this.visibleBrowserErrorsForCurrentRoute(e);return t.length===0?null:D`${t.map(e=>fR(e.displayMessage?.()??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===N(this.state)?this.sessions.refreshSelectedSession(t.sessionId,{recoverNetwork:!0}):t.kind===`workspace`&&e.recovery===`workspace-sessions-refresh`&&t.machineId===N(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=Er(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 D`
3896
3896
  <div class=${`${this.panelCollapse.shellClass(t)}${this.isDesktopSideBySideLayout()?``:` two-column-layout`}`} style=${this.panelResize.shellStyle({navigation:this.resizablePanelConstraints(`navigation`),workspace:this.resizablePanelConstraints(`workspace`)})}>
3897
3897
  <aside id="navigation-panel">${this.appShell.isMobileNavigationLayout?null:this.renderNavigationPanel()}</aside>
3898
3898
  ${this.renderNavigationPanelEdgeControl()}
@@ -3902,10 +3902,10 @@ This only removes it from this PI WEB gateway.`,`Confirmation for forgetting a r
3902
3902
  ${this.unknownRouteView()===void 0?null:D`<div class="error warning" role="alert"><span class="error-text">${Mu.t(`unknownView`,{view:this.unknownRouteView()??``})}</span></div>`}
3903
3903
  ${this.renderServerNoticeBanners()}
3904
3904
  ${this.apiScope===`management`?null:pr(ur(e.machines,e.machineRuntimes))}
3905
- ${dR(this.displayedError(),()=>{this.dismissDisplayedError()})}
3905
+ ${fR(this.displayedError(),()=>{this.dismissDisplayedError()})}
3906
3906
  ${this.renderBrowserErrorBanners(e)}
3907
3907
  <div class="mobile-navigation-panel">${this.appShell.isMobileNavigationLayout?this.renderNavigationPanel():null}</div>
3908
- ${e.selectedSession&&this.contentError()===``&&!this.sessions.isChatLoadDeferred&&(this.isChatVisible()||this.displayedChatIdentity===RR(e))?D`
3908
+ ${e.selectedSession&&this.contentError()===``&&!this.sessions.isChatLoadDeferred&&(this.isChatVisible()||this.displayedChatIdentity===zR(e))?D`
3909
3909
  ${this.isChatVisible()?D`<conversation-sync-notice .state=${e.conversationSync} .onRetry=${()=>{this.sessions.resumeSelectedSession({reconnect:!0})}}></conversation-sync-notice>`:null}
3910
3910
  <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}>
3911
3911
  ${this.renderChatView(e,e.selectedSession)}
@@ -3918,7 +3918,7 @@ This only removes it from this PI WEB gateway.`,`Confirmation for forgetting a r
3918
3918
  ${e.commandDialog===void 0?null:D`<command-picker .title=${e.commandDialog.title} .options=${e.commandDialog.options} .onPick=${t=>this.sessions.respondToCommand(e.commandDialog?.requestId??``,t)} .onCancel=${()=>{this.sessions.cancelCommand()}}></command-picker>`}
3919
3919
  ${e.modelDialog===void 0?null:e.modelDialog.catalog===void 0?D`<command-picker title=${e.modelDialog.title} .searchable=${!0} .options=${e.modelDialog.options} .selectedValue=${e.modelDialog.selectedValue} .defaultValue=${e.modelDialog.defaultValue} .defaultsLoading=${e.modelDialog.defaultsLoading===!0} .onPick=${e=>{this.pickModel(e)}} .onSetDefault=${this.handleSetDefaultModel} .onCancel=${()=>{this.setState({modelDialog:void 0})}}></command-picker>`:D`<model-picker title=${e.modelDialog.title} .options=${e.modelDialog.options} .catalog=${e.modelDialog.catalog} .selectedValue=${e.modelDialog.selectedValue} .defaultValue=${e.modelDialog.defaultValue} .defaultsLoading=${e.modelDialog.defaultsLoading===!0} .onPick=${e=>{this.pickModel(e)}} .onSetDefault=${this.handleSetDefaultModel} .onToggleEnabled=${this.handleToggleModelEnabled} .onSetScope=${this.handleSetModelScope} .onCancel=${()=>{this.setState({modelDialog:void 0})}}></model-picker>`}
3920
3920
  ${e.thinkingDialog===void 0?null:D`<command-picker title=${e.thinkingDialog.title} .options=${e.thinkingDialog.options} .selectedValue=${e.thinkingDialog.selectedValue} .defaultValue=${e.thinkingDialog.defaultValue} .defaultsLoading=${e.thinkingDialog.defaultsLoading===!0} .onPick=${e=>{this.pickThinking(e)}} .onSetDefault=${this.handleSetDefaultThinking} .onCancel=${()=>{this.setState({thinkingDialog:void 0})}}></command-picker>`}
3921
- `:e.selectedSession!==void 0&&this.contentError()===``&&this.isChatVisible()&&this.sessions.isChatLoadDeferred?D`<div class="empty" role="status">${oR.t(`loadingConversation`)}</div>`:D`<div class=${this.contentError()===``?`empty`:`empty route-target-error`} role=${this.contentError()===``?`status`:`alert`}>${this.sessionEmptyMessage()}</div>`}
3921
+ `:e.selectedSession!==void 0&&this.contentError()===``&&this.isChatVisible()&&this.sessions.isChatLoadDeferred?D`<div class="empty" role="status">${sR.t(`loadingConversation`)}</div>`:D`<div class=${this.contentError()===``?`empty`:`empty route-target-error`} role=${this.contentError()===``?`status`:`alert`}>${this.sessionEmptyMessage()}</div>`}
3922
3922
  </main>
3923
3923
  ${this.renderWorkspacePanelEdgeControl()}
3924
3924
  ${hr(this.workspaceSurfaceInputs(),()=>this.renderWorkspacePanel())}
@@ -3949,4 +3949,4 @@ This only removes it from this PI WEB gateway.`,`Confirmation for forgetting a r
3949
3949
  .onSubmit=${e=>{this.submitNormalAuth(e)}}
3950
3950
  .onCancel=${()=>{this.normalAuthDialogMode=void 0,this.normalAuthError=``}}
3951
3951
  ></normal-auth-dialog>
3952
- `}static{this.styles=Qd}invalidateNavigationSelection(){this.navigationSelectionSeq+=1}refreshableMachineIds(){return this.state.machines.length===0?[N(this.state)]:this.state.machines.filter(e=>HR(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(N(this.state));if(o&&s!==void 0){let e=this.state.selectedWorkspace,t=e===void 0?j(N(this.state)):Sr(N(this.state),e.projectId,e.id);this.state.browserErrors[wr(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&&MR(t,n)?e.contributionQuery??{}:{}}replaceNavigationUrl(e=this.currentContributionQueryForState()){this.replaceMachineNavigationSnapshot(Ru(this.state,e))}commitMachineNavigationSnapshot(e,t){this.syncNavigationFreshness(),this.machineNavigation.remember(e),So(zu(e),{...t,contributionQuery:e.surface.contributionQuery??{}}),this.syncNavigationFreshness()}currentContributionQueryForState(){let e=this.selectedWorkspaceRouteIdentity();return e===void 0||!xo(vo(),e)?{}:Ja()}selectedWorkspaceRouteIdentity(e=this.state.selectedWorkspace,t=FR(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=zu(e),n=this.navigationRouteMatchesUrl(t);this.navigationSurfaceMatchesUrl(e.surface)||this.writeWorkspaceRouteSurfaceToUrl(e.surface),n||So(t,{replace:!0}),this.syncNavigationFreshness()}navigationRouteMatchesUrl(e){let t=vo();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=vo();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())&&DR()===e.url}navigationSurfaceMatchesUrl(e){return kR(Ja(),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 XO(e);return t}requiredTerminalPanelId(e){return`${this.requiredTerminalComposition(e).binding.registrationPluginId}:${CR}`}createPanelActions(e){return{toggle:()=>{let t=ze(this.ownerDocument)?.getAttribute(`data-panel-toggle`)===e;e===`navigation`?this.panelCollapse.toggleNavigationPanel():(this.panelCollapse.toggleWorkspacePanel(),this.panelCollapse.workspacePanelCollapsed&&this.effectiveMainView()===`workspace`&&this.selectMainView(`chat`)),t&&this.focusPanelToggle(e)},resizeStart:()=>this.startPanelResize(e),resize:t=>{this.panelResize.resizePanel(e,t,{persist:!1})},resizeEnd:()=>{this.panelResize.persistPanelSizes()},reset:()=>{this.resetResizablePanel(e)}}}async focusPanelToggle(e){if(await this.updateComplete,Be(this.ownerDocument))return;let t=(e===`navigation`?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed)?`app-mobile-main-tabs`:e===`navigation`?`aside app-navigation-panel`:`workspace-panel`,n=this.renderRoot.querySelector(t);if(!(n instanceof O))return;await n.updateComplete;let r=n.shadowRoot?.querySelector(`[data-panel-toggle="${e}"]`);r!=null&&Re(r)}availableWorkspacePanelId(e,t=this.visibleWorkspacePanels()){return t.find(t=>t.id===e)?.id}unavailableRouteTool(e=this.visibleWorkspacePanels()){let t=vo();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=vo();return t.tool===void 0?(ho(t.view)===void 0?this.resolveBrowserAppRoute(t).tool:void 0)??this.state.workspaceTool??e[0]?.id:this.resolveBrowserAppRoute(t).tool}unknownRouteView(){let e=vo();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`:vo().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(){if(this.contentLoadOutcome?.destination!==this.contentDestination(vo()))return``;let e=this.contentLoadOutcome.error;return typeof e==`function`?e():e}workspaceContentError(){if(this.state.selectedWorkspace===void 0)return this.contentError();let e=vo(),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(N(this.state))??this.requiredPluginFailureByMachine.get(N(this.state))?.()??C(`ui.main.4d914bb120b8`,`Workspace panel unavailable: {arg0}`,{arg0:t??n??`unknown`}):``}workspacePanelContextIsCurrent(e,t,n){return N(this.state)===t.id&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.id&&xo(vo(),{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&&MR(o,i.identity)?Ka(i.query,n,r):xo(vo(),o)?Ga(n,r):Object.freeze({}),c=s;return Object.freeze({version:1,contributionId:n,query:s,set:(e,t,i)=>{if(!eo(e))throw Error(C(`ui.main.2241ac67c24f`,`Invalid contribution navigation parameter: {arg0}`,{arg0:e}));if(!a.isCurrent())return!1;let s=this.selectedWorkspaceRouteIdentity();return s===void 0||!MR(o,s)||!xo(vo(),o)||!kR(Ga(n,r),c)?!1:(Qa(n,r,e,t,i)&&(c=Ga(n,r),this.rememberCurrentMachineNavigation(),this.requestUpdate()),!0)}})}invalidateSelectedWorkspaceFiles(){let e=this.state.selectedWorkspace;return e===void 0?Promise.resolve():this.invalidateWorkspaceResources(e,FR(this.state),{reason:`manual`,resources:[`workspace.files`]})}workspaceSurfaceActions(){return[{id:`core:workspace.refresh-current`,get title(){return ir.t(`refreshTitle`)},shortcut:`mod+shift+r`,get group(){return ir.t(`groupWorkspace`)},enabled:this.state.selectedWorkspace!==void 0,run:()=>this.refreshCurrentWorkspaceSurface()}]}visibleBrowserErrorsForCurrentRoute(e){return kr(e.browserErrors,OR(e,vo()))}resolveBrowserAppRoute(e){let t=e=>this.plugins.resolveWorkspacePanelRouteId(e,N(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 yo(n===void 0?e:{...e,view:`workspace`,tool:e.tool??n},t)}messageActionContext(e){let t=mn(e).selectedSession;if(t===void 0)return;let n={machine:Object.freeze(FR(e)),session:Object.freeze({...t,busy:e.sendingPrompts[t.id]===!0||Pr(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=mn(n).selectedWorkspace,o=i===void 0?void 0:pw(e,i,r),s=()=>N(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:aw(cn,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}}}};g([y({attribute:!1})],$.prototype,`chatBehaviors`,void 0),g([v()],$.prototype,`state`,void 0),g([Te(`chat-view`)],$.prototype,`chatView`,void 0),g([v()],$.prototype,`machineNameEditTarget`,void 0),g([v()],$.prototype,`chatNavigation`,void 0),g([v()],$.prototype,`queuedMessageActionTarget`,void 0),g([v()],$.prototype,`messageRevertTarget`,void 0),g([Te(`prompt-editor`)],$.prototype,`promptEditor`,void 0),g([Te(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),g([Te(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),g([Te(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),g([v()],$.prototype,`unreadSessionIds`,void 0),g([v()],$.prototype,`unreadPresence`,void 0),g([v()],$.prototype,`readyChatIdentity`,void 0),g([v()],$.prototype,`navigationOrderVersion`,void 0),g([v()],$.prototype,`pendingProjectNavigation`,void 0),g([v()],$.prototype,`fileIconPreference`,void 0),g([v()],$.prototype,`localThemePreference`,void 0),g([v()],$.prototype,`configuredThemePreference`,void 0),g([v()],$.prototype,`activeThemeId`,void 0),g([v()],$.prototype,`navigationPreferences`,void 0),g([v()],$.prototype,`navigationDialogOpen`,void 0),g([v()],$.prototype,`isRefreshingApp`,void 0),g([v()],$.prototype,`sessionCleanupDialog`,void 0),g([v()],$.prototype,`sessionSearchDialogOpen`,void 0),g([v()],$.prototype,`settingsSection`,void 0),g([v()],$.prototype,`normalAuthStatus`,void 0),g([v()],$.prototype,`normalAuthLoading`,void 0),g([v()],$.prototype,`normalAuthError`,void 0),g([v()],$.prototype,`normalAuthDialogMode`,void 0),g([v()],$.prototype,`shortcutConfig`,void 0),g([v()],$.prototype,`defaultStreamingBehavior`,void 0),g([v()],$.prototype,`quietMode`,void 0),g([v()],$.prototype,`workspaceUploadDefaultFolder`,void 0),g([v()],$.prototype,`workspaceAttachmentsDefaultFolder`,void 0),g([v()],$.prototype,`workspaceSurfaceRevision`,void 0),$=g([_(`pi-web-app`)],$);function NR(e){let t=e?.model?.provider,n=e?.model?.id;return t!==void 0&&n!==void 0?`${t}/${n}`:void 0}function PR(){let e=p()?`management`:`normal`;return f(e),e}function FR(e){let t=e.selectedMachine;return t===void 0?{id:`local`,name:C(`ui.piWebApp.local`,`Local`),kind:`local`}:{id:t.id,name:t.name,kind:t.kind}}function IR(){return{registrationPluginId:`core`,sourcePluginId:`core`}}function LR(e,t){return JSON.stringify([e,t.id,t.cwd])}function RR(e){let t=e.selectedSession;return t===void 0?void 0:LR(N(e),t)}function zR(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function BR(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function VR(e,t){return HR(e,t)}function HR(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function UR(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function WR(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function GR(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function KR(){return{}}function qR(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 JR(e,t){return JSON.stringify([e,t])}function YR(e){let t=e.selectedProject?.id;if(t!==void 0)return JSON.stringify([e.selectedMachine?.id??`local`,t])}function XR(e){return hR[Math.min(e,hR.length-1)]??3e4}function ZR(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 QR(e,t){return e.registrationPluginId===t.registrationPluginId&&e.sourcePluginId===t.sourcePluginId&&e.backendRevision===t.backendRevision&&e.pairedRequestVersion===t.pairedRequestVersion&&e.pairedChannelVersion===t.pairedChannelVersion&&e.pairedResourceVersion===t.pairedResourceVersion}function $R(e,t){let n=t===`local`?nn:hn(t,nn),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:nn,backendRevision:e.backendRevision,pairedRequestVersion:1,pairedChannelVersion:1})}function ez(e){return e instanceof Error?e.message:String(e)}function tz(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function nz(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}export{$ as PiWebApp};
3952
+ `}static{this.styles=Qd}invalidateNavigationSelection(){this.navigationSelectionSeq+=1}refreshableMachineIds(){return this.state.machines.length===0?[N(this.state)]:this.state.machines.filter(e=>UR(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(N(this.state));if(o&&s!==void 0){let e=this.state.selectedWorkspace,t=e===void 0?j(N(this.state)):Sr(N(this.state),e.projectId,e.id);this.state.browserErrors[wr(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&&NR(t,n)?e.contributionQuery??{}:{}}replaceNavigationUrl(e=this.currentContributionQueryForState()){this.replaceMachineNavigationSnapshot(Ru(this.state,e))}commitMachineNavigationSnapshot(e,t){this.syncNavigationFreshness(),this.machineNavigation.remember(e),So(zu(e),{...t,contributionQuery:e.surface.contributionQuery??{}}),this.syncNavigationFreshness()}currentContributionQueryForState(){let e=this.selectedWorkspaceRouteIdentity();return e===void 0||!xo(vo(),e)?{}:Ja()}selectedWorkspaceRouteIdentity(e=this.state.selectedWorkspace,t=IR(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=zu(e),n=this.navigationRouteMatchesUrl(t);this.navigationSurfaceMatchesUrl(e.surface)||this.writeWorkspaceRouteSurfaceToUrl(e.surface),n||So(t,{replace:!0}),this.syncNavigationFreshness()}navigationRouteMatchesUrl(e){let t=vo();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=vo();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())&&OR()===e.url}navigationSurfaceMatchesUrl(e){return AR(Ja(),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 XO(e);return t}requiredTerminalPanelId(e){return`${this.requiredTerminalComposition(e).binding.registrationPluginId}:${wR}`}createPanelActions(e){return{toggle:()=>{let t=ze(this.ownerDocument)?.getAttribute(`data-panel-toggle`)===e;e===`navigation`?this.panelCollapse.toggleNavigationPanel():(this.panelCollapse.toggleWorkspacePanel(),this.panelCollapse.workspacePanelCollapsed&&this.effectiveMainView()===`workspace`&&this.selectMainView(`chat`)),t&&this.focusPanelToggle(e)},resizeStart:()=>this.startPanelResize(e),resize:t=>{this.panelResize.resizePanel(e,t,{persist:!1})},resizeEnd:()=>{this.panelResize.persistPanelSizes()},reset:()=>{this.resetResizablePanel(e)}}}async focusPanelToggle(e){if(await this.updateComplete,Be(this.ownerDocument))return;let t=(e===`navigation`?this.panelCollapse.navigationPanelCollapsed:this.panelCollapse.workspacePanelCollapsed)?`app-mobile-main-tabs`:e===`navigation`?`aside app-navigation-panel`:`workspace-panel`,n=this.renderRoot.querySelector(t);if(!(n instanceof O))return;await n.updateComplete;let r=n.shadowRoot?.querySelector(`[data-panel-toggle="${e}"]`);r!=null&&Re(r)}availableWorkspacePanelId(e,t=this.visibleWorkspacePanels()){return t.find(t=>t.id===e)?.id}unavailableRouteTool(e=this.visibleWorkspacePanels()){let t=vo();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=vo();return t.tool===void 0?(ho(t.view)===void 0?this.resolveBrowserAppRoute(t).tool:void 0)??this.state.workspaceTool??e[0]?.id:this.resolveBrowserAppRoute(t).tool}unknownRouteView(){let e=vo();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`:vo().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(){if(this.contentLoadOutcome?.destination!==this.contentDestination(vo()))return``;let e=this.contentLoadOutcome.error;return typeof e==`function`?e():e}workspaceContentError(){if(this.state.selectedWorkspace===void 0)return this.contentError();let e=vo(),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(N(this.state))??this.requiredPluginFailureByMachine.get(N(this.state))?.()??C(`ui.main.4d914bb120b8`,`Workspace panel unavailable: {arg0}`,{arg0:t??n??`unknown`}):``}workspacePanelContextIsCurrent(e,t,n){return N(this.state)===t.id&&this.state.selectedProject?.id===e.projectId&&this.state.selectedWorkspace?.id===e.id&&xo(vo(),{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&&NR(o,i.identity)?Ka(i.query,n,r):xo(vo(),o)?Ga(n,r):Object.freeze({}),c=s;return Object.freeze({version:1,contributionId:n,query:s,set:(e,t,i)=>{if(!eo(e))throw Error(C(`ui.main.2241ac67c24f`,`Invalid contribution navigation parameter: {arg0}`,{arg0:e}));if(!a.isCurrent())return!1;let s=this.selectedWorkspaceRouteIdentity();return s===void 0||!NR(o,s)||!xo(vo(),o)||!AR(Ga(n,r),c)?!1:(Qa(n,r,e,t,i)&&(c=Ga(n,r),this.rememberCurrentMachineNavigation(),this.requestUpdate()),!0)}})}invalidateSelectedWorkspaceFiles(){let e=this.state.selectedWorkspace;return e===void 0?Promise.resolve():this.invalidateWorkspaceResources(e,IR(this.state),{reason:`manual`,resources:[`workspace.files`]})}workspaceSurfaceActions(){return[{id:`core:workspace.refresh-current`,get title(){return ir.t(`refreshTitle`)},shortcut:`mod+shift+r`,get group(){return ir.t(`groupWorkspace`)},enabled:this.state.selectedWorkspace!==void 0,run:()=>this.refreshCurrentWorkspaceSurface()}]}visibleBrowserErrorsForCurrentRoute(e){return kr(e.browserErrors,kR(e,vo()))}resolveBrowserAppRoute(e){let t=e=>this.plugins.resolveWorkspacePanelRouteId(e,N(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 yo(n===void 0?e:{...e,view:`workspace`,tool:e.tool??n},t)}messageActionContext(e){let t=mn(e).selectedSession;if(t===void 0)return;let n={machine:Object.freeze(IR(e)),session:Object.freeze({...t,busy:e.sendingPrompts[t.id]===!0||Pr(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=mn(n).selectedWorkspace,o=i===void 0?void 0:pw(e,i,r),s=()=>N(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:aw(cn,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}}}};g([y({attribute:!1})],$.prototype,`chatBehaviors`,void 0),g([v()],$.prototype,`state`,void 0),g([Te(`chat-view`)],$.prototype,`chatView`,void 0),g([v()],$.prototype,`machineNameEditTarget`,void 0),g([v()],$.prototype,`chatNavigation`,void 0),g([v()],$.prototype,`queuedMessageActionTarget`,void 0),g([v()],$.prototype,`messageRevertTarget`,void 0),g([Te(`prompt-editor`)],$.prototype,`promptEditor`,void 0),g([Te(`app-navigation-panel`)],$.prototype,`navigationPanel`,void 0),g([Te(`#navigation-panel`)],$.prototype,`navigationPanelFrame`,void 0),g([Te(`#workspace-panel`)],$.prototype,`workspacePanelFrame`,void 0),g([v()],$.prototype,`unreadSessionIds`,void 0),g([v()],$.prototype,`unreadPresence`,void 0),g([v()],$.prototype,`readyChatIdentity`,void 0),g([v()],$.prototype,`navigationOrderVersion`,void 0),g([v()],$.prototype,`pendingProjectNavigation`,void 0),g([v()],$.prototype,`fileIconPreference`,void 0),g([v()],$.prototype,`localThemePreference`,void 0),g([v()],$.prototype,`configuredThemePreference`,void 0),g([v()],$.prototype,`activeThemeId`,void 0),g([v()],$.prototype,`navigationPreferences`,void 0),g([v()],$.prototype,`navigationDialogOpen`,void 0),g([v()],$.prototype,`isRefreshingApp`,void 0),g([v()],$.prototype,`sessionCleanupDialog`,void 0),g([v()],$.prototype,`sessionSearchDialogOpen`,void 0),g([v()],$.prototype,`settingsSection`,void 0),g([v()],$.prototype,`normalAuthStatus`,void 0),g([v()],$.prototype,`normalAuthLoading`,void 0),g([v()],$.prototype,`normalAuthError`,void 0),g([v()],$.prototype,`normalAuthDialogMode`,void 0),g([v()],$.prototype,`shortcutConfig`,void 0),g([v()],$.prototype,`defaultStreamingBehavior`,void 0),g([v()],$.prototype,`quietMode`,void 0),g([v()],$.prototype,`workspaceUploadDefaultFolder`,void 0),g([v()],$.prototype,`workspaceAttachmentsDefaultFolder`,void 0),g([v()],$.prototype,`workspaceSurfaceRevision`,void 0),$=g([_(`pi-web-app`)],$);function PR(e){let t=e?.model?.provider,n=e?.model?.id;return t!==void 0&&n!==void 0?`${t}/${n}`:void 0}function FR(){let e=p()?`management`:`normal`;return f(e),e}function IR(e){let t=e.selectedMachine;return t===void 0?{id:`local`,name:C(`ui.piWebApp.local`,`Local`),kind:`local`}:{id:t.id,name:t.name,kind:t.kind}}function LR(){return{registrationPluginId:`core`,sourcePluginId:`core`}}function RR(e,t){return JSON.stringify([e,t.id,t.cwd])}function zR(e){let t=e.selectedSession;return t===void 0?void 0:RR(N(e),t)}function BR(e,t){return e.machines!==t.machines||e.machineRuntimes!==t.machineRuntimes}function VR(e,t){return e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||(e.selectedMachine?.id??`local`)!==(t.selectedMachine?.id??`local`)}function HR(e,t){return UR(e,t)}function UR(e,t){if(e.kind===`local`)return!0;let n=t?.status??e.status;return n===void 0||n===`unknown`||n===`online`}function WR(e,t){return Object.entries(t).some(([t,n])=>Reflect.get(e,t)!==n)}function GR(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function KR(e){return e.type===`terminal.created`||e.type===`terminal.exited`||e.type===`terminal.closed`}function qR(){return{}}function JR(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 YR(e,t){return JSON.stringify([e,t])}function XR(e){let t=e.selectedProject?.id;if(t!==void 0)return JSON.stringify([e.selectedMachine?.id??`local`,t])}function ZR(e){return gR[Math.min(e,gR.length-1)]??3e4}function QR(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 $R(e,t){return e.registrationPluginId===t.registrationPluginId&&e.sourcePluginId===t.sourcePluginId&&e.backendRevision===t.backendRevision&&e.pairedRequestVersion===t.pairedRequestVersion&&e.pairedChannelVersion===t.pairedChannelVersion&&e.pairedResourceVersion===t.pairedResourceVersion}function ez(e,t){let n=t===`local`?nn:hn(t,nn),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:nn,backendRevision:e.backendRevision,pairedRequestVersion:1,pairedChannelVersion:1})}function tz(e){return e instanceof Error?e.message:String(e)}function nz(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function rz(){return new Promise(e=>requestAnimationFrame(()=>{e()}))}export{$ as PiWebApp};