@chainingintention/pi-web-cn 2.202610.3 → 2.202610.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -24,7 +24,7 @@ import{$ as e,$t as t,A as n,At as r,B as i,Bt as a,C as o,Ct as s,D as c,Dt as
|
|
|
24
24
|
`)}function zo(e,t){let n=Eo(t);if(n!==void 0)return bo(e,n,!0);let r=mi(t);return r.length===0&&e.at(-1)?.parts.at(-1)?.type===`askUserQuestion`?li([...e,t]):[...e,...r]}function Bo(e,t){let n=e.at(-1);return Vo(e,t)?e:n?.role===t.role&&t.role!==`skill`?[...e.slice(0,-1),{...n,parts:[...n.parts,...t.parts]}]:[...e,t]}function Vo(e,t){let n=No(t);if(t.role!==`skill`||n.length===0)return!1;let r=Uo(e)+1;return n.every(t=>Ho(e,t,r))}function Ho(e,t,n){for(let r=e.length-1;r>=n;r--)if(No(e[r]).some(e=>Fo(e,t)))return!0;return!1}function Uo(e){for(let t=e.length-1;t>=0;t--)if(e[t]?.role===`user`)return t;return-1}function Wo(e){return typeof e==`object`&&!!e}function Go(e,t){return Wo(e)?e[t]:void 0}function Ko(e,t){let n=Go(e,t);return typeof n==`string`?n:void 0}function qo(e,t){let n=Go(e,t);return typeof n==`boolean`?n:void 0}var Jo=`pi-web:chat-history:v2:`,Yo=18e5;function Xo(e){try{let t=sessionStorage.getItem(as(e));if(t===null||t===``)return;let n=JSON.parse(t);if(!os(n))return;if(Date.now()-n.savedAt>Yo){sessionStorage.removeItem(as(e));return}return{messages:n.messages,start:n.start,total:n.total,...n.leafId===void 0?{}:{leafId:n.leafId}}}catch{return}}function Zo(e,t){try{sessionStorage.setItem(as(e),JSON.stringify({...t,savedAt:Date.now()}))}catch{}}function Qo(e){try{sessionStorage.removeItem(as(e))}catch{}}function $o(e,t){if(e===void 0||!ss(e))return t;if(!ss(t))return e;if(t.leafId!==e.leafId||ns(e,t))return t;let n=Math.min(e.start,t.start),r=Math.max(e.start+e.messages.length,t.start+t.messages.length),i=Array(r-n);return is(i,n,e),is(i,n,t),rs(i)?t:{start:n,total:Math.max(e.total,t.total),messages:i,...t.leafId===void 0?{}:{leafId:t.leafId}}}function es(e,t){if(!ss(e)||!ss(t)||e.leafId!==t.leafId)return!1;let n=e.start+e.messages.length;if(n>t.total)return!1;if(e.total===0)return!0;let r=Math.max(e.start,t.start),i=Math.min(n,t.start+t.messages.length);return r<i&&JSON.stringify(e.messages.slice(r-e.start,i-e.start))===JSON.stringify(t.messages.slice(r-t.start,i-t.start))}function ts(e,t){if(e===void 0||!ss(t)||e.leafId!==t.leafId||t.total!==e.total)return!1;let n=t.start-e.start;return n<0||n+t.messages.length!==e.messages.length?!1:JSON.stringify(t.messages)===JSON.stringify(e.messages.slice(n))}function ns(e,t){return e.total>t.total&&e.start===0&&t.start===0&&t.messages.length===t.total}function rs(e){for(let t=0;t<e.length;t+=1)if(!(t in e)||e[t]===void 0)return!0;return!1}function is(e,t,n){n.messages.forEach((r,i)=>{e[n.start-t+i]=r})}function as(e){return`${Jo}${e}`}function os(e){if(typeof e!=`object`||!e||!(`messages`in e)||!(`start`in e)||!(`total`in e)||!(`savedAt`in e))return!1;let{messages:t,start:n,total:r,savedAt:i}=e;return Array.isArray(t)&&(!(`leafId`in e)||e.leafId===null||typeof e.leafId==`string`)&&typeof n==`number`&&typeof r==`number`&&typeof i==`number`&&ss({messages:t,start:n,total:r})}function ss(e){return Number.isInteger(e.start)&&Number.isInteger(e.total)&&e.start>=0&&e.total>=e.start&&e.messages.length<=e.total-e.start&&!e.messages.some(cs)}function cs(e){return typeof e==`object`&&!!e&&`role`in e&&`parts`in e&&!(`content`in e)&&typeof e.role==`string`&&Array.isArray(e.parts)}var ls={read:Xo,write:Zo,remove:Qo},us=class{constructor(e=ls){this.cache=e,this.rawHistoryPages=new Map,this.historyRevisions=new Map}cachedView(e){return ds(this.rawHistoryPage(e))}indexedView(e){return ds(this.rawHistoryPage(e),!0)}mergeHistory(e,t){return this.storeHistory(e,$o(this.rawHistoryPage(e),t))}mergeSnapshot(e,t){let n=this.rawHistoryPage(e);if(n!==void 0&&!es(n,t))return this.discard(e),this.storeHistory(e,t);let r=$o(n,t);return this.storeHistory(e,{...r,total:t.total})}storeHistory(e,t){return this.rawHistoryPages.set(e,t),this.cache.write(e,t),ds(t)}applyLiveEvent(e,t){return fo(e,t)}seedStreamingPartial(e,t){return uo(e,t)}historyRevision(e){return this.historyRevisions.get(e)??0}discard(e){this.historyRevisions.set(e,this.historyRevision(e)+1),this.rawHistoryPages.delete(e),this.cache.remove?.(e)}rawHistoryPage(e){let t=this.rawHistoryPages.get(e)??this.cache.read(e);return t!==void 0&&this.rawHistoryPages.set(e,t),t}};function ds(e,t=!1){let n=e?.start??0;return{messages:li(e?.messages??[],t||e!==void 0?n:void 0),messagePageStart:n,messagePageEnd:n+(e?.messages.length??0),messagePageTotal:e?.total??0,messagePageLeafId:e?.leafId}}function fs(e){return{builtin:D(`ui.settingsPluginsPanel.bundled`,`Bundled`),extension:D(`ui.main.17d13aa49d71`,`Extension`),prompt:D(`ui.main.2f0bb1238738`,`Prompt`),skill:D(`ui.chatView.skill`,`Skill`)}[e]}function ps(e,t=e.length){let n=e.slice(0,t),r=ys(n,t);if(r!==void 0)return r;let i=bs(n,t);if(i!==void 0)return i;let a=Math.max(n.lastIndexOf(` `),n.lastIndexOf(`
|
|
25
25
|
`))+1,o=n.slice(a);if(n.slice(0,a).endsWith(`@ `))return{kind:`file`,query:o,from:a-2,to:t,fileScope:`all`,allPrefix:`@ `};if(o.startsWith(`/`)&&a===0)return{kind:`command`,query:o.slice(1),from:a,to:t};if(o.startsWith(`!@`))return{kind:`file`,query:o.slice(2),from:a,to:t,fileScope:`all`,allPrefix:`!@`};if(o.startsWith(`@`))return{kind:`file`,query:o.slice(1),from:a,to:t,fileScope:`tracked`};if(o.startsWith(`#`))return{kind:`model`,query:o.slice(1),from:a,to:t}}var ms=12;function hs(e,t){let n=t.toLowerCase(),r=[];for(let t of e)if(gs(t)&&_s(t,n)&&(r.push({insertText:`#${t.provider}/${t.id}`,detail:t.provider,...t.name!==void 0&&t.name!==``&&t.name!==t.id?{description:t.name}:{}}),r.length>=ms))break;return r}function gs(e){return typeof e.provider==`string`&&e.provider!==``&&typeof e.id==`string`&&e.id!==``}function _s(e,t){return`${e.provider}/${e.id}`.toLowerCase().includes(t)||e.id.toLowerCase().includes(t)||(e.name?.toLowerCase().includes(t)??!1)}function vs(e,t,n){let r=n??`@`;return!t&&!e.includes(` `)?`${r}${e}`:`${r}"${e}"`}function ys(e,t){let n=e.lastIndexOf(`"`);if(n===-1)return;let r=e.slice(0,n);if(r.endsWith(`!@`))return{kind:`file`,query:e.slice(n+1),from:r.length-2,to:t,fileScope:`all`,allPrefix:`!@`,quoted:!0};if(r.endsWith(`@`))return{kind:`file`,query:e.slice(n+1),from:r.length-1,to:t,fileScope:`tracked`,quoted:!0};if(r.endsWith(`@ `))return{kind:`file`,query:e.slice(n+1),from:r.length-2,to:t,fileScope:`all`,allPrefix:`@ `,quoted:!0}}function bs(e,t){let n=e.lastIndexOf(`
|
|
26
26
|
`)+1,r=e.slice(n),i=xs(r,`@ `),a=xs(r,`!@`),o=Math.max(i,a);if(o===-1)return;let s=o===a?`!@`:`@ `,c=n+o,l=c+s.length;return{kind:`file`,query:e.slice(l),from:c,to:t,fileScope:`all`,allPrefix:s}}function xs(e,t){for(let n=e.lastIndexOf(t);n>=0;n=e.lastIndexOf(t,n-1))if(n===0||Ss(e[n-1]))return n;return-1}function Ss(e){return e===` `||e===` `}function Cs(e){let t=e.trimStart();if(t.startsWith(`!@`))return{kind:`file`};if(t.startsWith(`!`))return{kind:`shell`,excludeFromContext:t.startsWith(`!!`)};if(Es(e).startsWith(`/`))return{kind:`command`};let n=ps(e);return n?.kind===`file`?{kind:`file`}:n?.kind===`model`?{kind:`model`}:{kind:`normal`}}function ws(e){return Cs(e).kind===`shell`}function Ts(e,t){return e.kind===t.kind?e.kind===`shell`&&t.kind===`shell`?e.excludeFromContext===t.excludeFromContext:!0:!1}function Es(e){let t=Math.max(e.lastIndexOf(` `),e.lastIndexOf(`
|
|
27
|
-
`))+1;return e.slice(t)}var Ds=class{constructor(e=`normal`){this.scope=e,this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId=`local`}connect(e,t,n,r=`local`,i){this.close(),this.machineId=r,this.session=e,this.onEvent=t,this.onReconnect=n,this.onInitialOpen=i,this.shouldReconnect=!0,this.open()}setHandler(e){this.onEvent=e}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Fs(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.onInitialOpen=void 0,this.hasOpened=!1,this.machineId=`local`}open(){let e=this.session;if(e===void 0||e.id===``||e.cwd===``||!this.shouldReconnect)return;let t=zn(e,this.machineId,this.scope);this.socket=t,t.onopen=()=>{if(this.socket!==t)return;this.reconnectDelay=500;let e=this.hasOpened;this.hasOpened=!0,e?this.onReconnect?.():this.onInitialOpen?.()},t.onmessage=n=>void this.handleMessage(n.data,t,e),t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t,n){let r=ks(await Ps(e));this.socket===t&&r!==void 0&&(r.type===`session.diagnostic`?console.error(`[PI WEB] Session diagnostic`,{machineId:this.machineId,sessionId:n.id,cwd:n.cwd,message:r.message}):(r.type!==`notifications.inbox`||n.id===r.summary.sessionId&&n.cwd===r.summary.cwd)&&this.onEvent?.(r))}},Os=class{constructor(e=`normal`){this.scope=e,this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId=`local`}connect(e,t,n=`local`){this.close(),this.machineId=n,this.onEvent=e,this.onOpen=t,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Fs(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId=`local`}open(){if(!this.shouldReconnect)return;let e=Bn(this.machineId,this.scope);this.socket=e,e.onopen=()=>{this.socket===e&&(this.reconnectDelay=500,this.onOpen?.())},e.onmessage=t=>void this.handleMessage(t.data,e),e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t){let n=As(await Ps(e));this.socket===t&&n!==void 0&&this.onEvent?.(n)}};function ks(e){let t=Ns(e);if(t===`notifications.inbox`)return Ms(()=>he(e));if(t===`dialog.opened`)return Ms(()=>ae(e));if(t===`dialog.closed`)return Ms(()=>ee(e));let n=Ms(()=>a(e));return n===void 0?void 0:js(n,e)}function As(e){if(Ns(e)===`notices.updated`)return Ms(()=>p(e));if(Ns(e)===`sessions.unread`)return Ms(()=>Se(e));if(Ns(e)===`session.startup`)return Ms(()=>jt(e));if(typeof e==`object`&&e){if(Ns(e)===`terminal.created`||Ns(e)===`terminal.exited`){if(!(`terminal`in e))return;let t=Ms(()=>xe(e.terminal));return t===void 0?void 0:{type:Ns(e)===`terminal.created`?`terminal.created`:`terminal.exited`,terminal:t}}if(Ns(e)===`terminal.closed`)return!(`terminalId`in e)||typeof e.terminalId!=`string`||e.terminalId===``||!(`cwd`in e)||typeof e.cwd!=`string`||e.cwd===``?void 0:{type:`terminal.closed`,terminalId:e.terminalId,cwd:e.cwd};if(Ns(e)===`workspace.activity`){if(!(`activity`in e))return;let t=Ms(()=>we(e.activity));return t===void 0?void 0:{type:`workspace.activity`,activity:t}}}return Ms(()=>fe(e))}function js(e,t){return typeof t!=`object`||!t||!(`seq`in t)?e:typeof t.seq==`number`?{...e,seq:t.seq}:e}function Ms(e){try{return e()}catch{return}}function Ns(e){if(typeof e!=`object`||!e||!(`type`in e))return``;let t=e.type;return typeof t==`string`?t:``}async function Ps(e){try{return typeof e==`string`?JSON.parse(e):e instanceof Blob?JSON.parse(await e.text()):e instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(e)):void 0}catch{return}}function Fs(e){e!==void 0&&(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING?e.onopen=()=>{e.close()}:e.close())}function Is(e){return e?.ok===!0}function Ls(e){return{authoritative:Is(e)}}function Rs(e,t,n={}){if(e===void 0)return`unknown`;let r=(t?.sessionId===e.id?t.persisted:void 0)??e.persisted;return r===!0?`persisted`:r===!1||$r(e)?`transient`:n.authoritative===!0?`unknown`:`persisted`}function zs(e,t,n){return e!==void 0&&e.archived!==!0&&Rs(e,t,n)===`persisted`}function Bs(e,t,n){return e!==void 0&&e.archived!==!0&&Rs(e,t,n)===`transient`}function Vs(){try{return typeof sessionStorage>`u`?void 0:sessionStorage}catch{return}}var Hs=class{constructor(e,t,n=Vs()){this.storageKey=e,this.storage=n,this.values=new Map;for(let[r,i]of Ws(e,t,n))this.values.set(r,i)}get(e){return this.values.get(e)}set(e,t){this.values.set(e,t),this.save()}delete(e){this.values.delete(e),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}let e={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(e))}catch{}}};function Us(e){return typeof e==`string`&&e!==``?e:void 0}function Ws(e,t,n){try{let r=n?.getItem(e);if(r==null||r===``)return[];let i=JSON.parse(r);if(!Gs(i))return[];let a=[];for(let e of i.entries){let n=e[0],r=t(e[1]);r!==void 0&&a.push([n,r])}return a}catch{return[]}}function Gs(e){return!Ks(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`&&e[0]!==``)}function Ks(e){return typeof e==`object`&&!!e}var qs=class{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}},Js=`pi-web:session-selection:v1`,Ys=class{constructor(e=Vs()){this.sessionIdsByCwd=new Hs(Js,Us,e)}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}};function Xs(e,t){let n=t?.targetSessionId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestSessionId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>e.archived!==!0):e.find(e=>e.archived!==!0)}function Zs(e,t){return t?.archived===!0&&!e.some(e=>e.archived!==!0)}function Qs(e,t,n){return $s(e,[t],n)}function $s(e,t,n){let r=new Set(t);return e.map(e=>r.has(e.id)?{...e,archived:!0,archivedAt:n}:e)}function ec(e,t,n){return tc(e,t,[n])}function tc(e,t,n){if(t===void 0||!n.includes(t))return{type:`unchanged`};let r=new Set(n),i=e.find(e=>!r.has(e.id)&&e.archived!==!0);return i===void 0?{type:`clear`}:{type:`select`,session:i}}var nc=/timed out|operation was aborted|request cancelled/i;function rc(e){return e instanceof te&&(e.status===504||e.status===499)||e instanceof Error&&nc.test(e.message)}function ic(e){return rc(e)?D(`ui.main.634a1618e706`,`The session daemon request timed out. The conversation is still running.`):e instanceof Error?e.message:String(e)}var ac=[500,1500,3e3],oc=Symbol(`retired-read`);async function sc(e,t,n,r=!0){let i=()=>n?.aborted!==!0&&t(),a=0;for(;i();)try{let t=await cc(e(),n);return t!==oc&&i()?t:void 0}catch(e){if(n?.aborted===!0||r&&!t())return;let i=ac[a];if(!r||!(e instanceof Oe)||i===void 0)throw e;let o;try{await cc(new Promise(e=>{o=setTimeout(e,i)}),n)}finally{o!==void 0&&clearTimeout(o)}a+=1}}function cc(e,t){if(t===void 0)return e;let n=()=>void 0,r=new Promise(e=>{n=()=>{e(oc)},t.addEventListener(`abort`,n,{once:!0}),t.aborted&&n()});return Promise.race([e,r]).finally(()=>{t.removeEventListener(`abort`,n)})}var lc=100,uc=500,dc=5e3,fc=[`machine`,`project`,`workspace`,`session`],pc=[`machine`,`project`,`workspace`,`session`],mc=class{constructor(e,t,n,r=new qs,i={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessionSelection=r,this.selectedSessionLoadDeferred=!1,this.selectionSeq=0,this.pendingTreeActions=new Set,this.disposed=!1,this.pendingTranscriptEvents=[],this.selectedReadGeneration=0,this.workspaceReadGeneration=0,this.selectedReadRecoveries=new Set,this.workspaceReadRecoveries=new Set,this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.sessionRefreshInFlight=!1,this.searchSeq=0,this.searchTargetSeq=0,this.pendingQueuedSendSeq=0,this.pendingSessionStarts=new Map,this.suppressedCreatedSessions=new Map,this.selectedSessionRefreshes=new gr,this.workspaceSessionRefreshes=new gr,this.socket=i.socket??new Ds,this.api=i.api??x,this.transcripts=i.transcripts??new us,this.transcriptSnapshot=i.transcriptSnapshot??((...e)=>this.api.transcriptSnapshot(...e)),this.notifications=i.notifications,this.automaticSessionCandidates=i.automaticSessionCandidates??(e=>e),this.replacePromptEditorText=i.replacePromptEditorText,this.canMutateQueueMessage=i.canMutateQueueMessage??(()=>!1),this.onSelectedSessionReady=i.onSelectedSessionReady,this.observeSessionSnapshot=i.observeSessionSnapshot,this.isChatVisible=i.isChatVisible??(()=>!0),this.isPendingSessionStartRouteCurrent=i.isPendingSessionStartRouteCurrent,this.onPendingSessionStartCommitted=i.onPendingSessionStartCommitted,this.onModelScopeChanged=i.onModelScopeChanged,this.navigateToSession=i.navigateToSession,this.captureNavigation=i.captureNavigation,this.beginNavigationOperation=i.beginNavigationOperation,this.browserErrors=new $n(e,t)}applyGlobalEvent(e){e.type===`status.update`?this.queueStatusUpdate(e.status):e.type===`activity.update`?this.queueActivityUpdate(e.activity):e.type===`session.created`?this.applyCreatedSession(e.session):e.type===`session.name`?this.applySessionName(e.sessionId,e.name):e.type===`models.changed`?this.onModelScopeChanged?.(e.revision):e.type===`session.startup`&&this.queueStartupProgress(e)}dispose(){this.disposed=!0,this.retireReadRecoveries([`machine`]),this.selectedSessionLoadDeferred=!1,this.selectionSeq+=1,this.searchSeq+=1,this.stopPolling(),this.searchTimer!==void 0&&clearTimeout(this.searchTimer),this.searchTimer=void 0,this.selectedSessionJoinNavigation=void 0,this.socket.close(),this.clearPendingUpdates()}updatePolling(){this.stopPolling(),this.getState().selectedWorkspace!==void 0&&(this.sessionPollTimer=setInterval(()=>{this.sessionRefreshInFlight||(this.sessionRefreshInFlight=!0,this.refreshCurrentWorkspaceSessions().finally(()=>{this.sessionRefreshInFlight=!1}))},dc))}clearActiveSession(){this.retireReadRecoveries([`session`]),this.selectedSessionLoadDeferred=!1,this.selectionSeq+=1,this.selectedSessionJoinNavigation=void 0,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0})}deselectSession(e){let t=this.getState(),n=t.selectedSession?.cwd??t.selectedWorkspace?.path;e?.forgetRememberedSelection===!0&&n!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(n)),this.clearActiveSession(),e?.updateUrl!==!1&&this.updateUrl()}async selectSessionAfterNavigation(e,t,n){this.navigateToSession===void 0?await this.selectSession(e,{updateUrl:n?.updateUrl}):await this.navigateToSession(e,{...n?.updateUrl===!1?{replace:!0}:{},expected:t})}async clearSessionAfterNavigation(e){if(!this.navigationSelectionMatchesState(e))return;let t=this.getState().selectedSession?.cwd??this.getState().selectedWorkspace?.path;this.navigateToSession===void 0?this.deselectSession({forgetRememberedSelection:!0}):(t!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(t)),await this.navigateToSession(void 0,{expected:e}))}async clearSelectionAfterArchivedCollapse(){let e=this.getState();Zs(this.automaticSessionCandidates(e.sessions),e.selectedSession)&&await this.clearSessionAfterNavigation(this.navigationSelection())}async startSession(e){let t=this.getState().selectedWorkspace;if(!t)return;let n=M(this.getState()),r=typeof e==`function`?e:void 0,i=typeof e==`function`?void 0:e,a=i?.updateUrl!==!1,o=this.createPendingSessionStart(t,n,this.navigationSelection(),a);this.pendingSessionStarts.set(o.tempId,o),this.insertAndSelectPendingSession(o.session,i),a&&(o.expectedNavigation=this.navigationSelection()),o.navigation=this.beginNavigationOperation?.(fc);try{if(r!==void 0&&!await r()){this.cancelUnstartedSession(o);return}let e=await this.api.startSession(t.path,n,o.tempId);await this.resolvePendingSessionStart(o.tempId,e)}catch(e){this.failPendingSessionStart(o.tempId,e)}}async refreshPinnedSessions(e,t=M(this.getState())){try{let n=await this.api.pinned(e,t);if(M(this.getState())!==t||this.getState().selectedWorkspace?.path!==e)return;this.setState({pinnedSessionIds:n.sessionIds})}catch{M(this.getState())===t&&this.getState().selectedWorkspace?.path===e&&this.setState({pinnedSessionIds:[]})}}togglePinned(e){if(e.persisted===!1)return;let t=this.getState(),n=t.pinnedSessionIds.includes(e.id),r=n?t.pinnedSessionIds.filter(t=>t!==e.id):[...t.pinnedSessionIds,e.id],i=M(t);this.setState({pinnedSessionIds:r}),(async()=>{try{let t=n?await this.api.unpin(e,i):await this.api.pin(e,i),r=this.getState();if(M(r)!==i||r.selectedWorkspace?.path!==e.cwd)return;let a=t.pinned;this.setState({pinnedSessionIds:a?[...new Set([...this.getState().pinnedSessionIds,e.id])]:this.getState().pinnedSessionIds.filter(t=>t!==e.id)})}catch(t){let r=this.getState();if(M(r)!==i||r.selectedWorkspace?.path!==e.cwd)return;this.setState({pinnedSessionIds:n?[...new Set([...r.pinnedSessionIds,e.id])]:r.pinnedSessionIds.filter(t=>t!==e.id)}),this.reportSessionError(e,i,t)}})()}searchSessions(e){let t=this.getState(),n=t.selectedWorkspace,r=M(t);this.searchSeq+=1;let i=this.searchSeq;this.searchTimer!==void 0&&clearTimeout(this.searchTimer),this.searchTimer=void 0,this.setState({sessionSearchQuery:e,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``});let a=e.trim();n!==void 0&&a!==``&&(this.setState({isSearchingSessions:!0}),this.searchTimer=setTimeout(()=>{this.searchTimer=void 0,this.performSessionSearch(i,a,n.id,n.path,r)},250))}async performSessionSearch(e,t,n,r,i){try{let a=await this.api.searchContent(r,t,i),o=this.getState();if(e!==this.searchSeq||M(o)!==i||o.selectedWorkspace?.id!==n||o.sessionSearchQuery.trim()!==t)return;this.setState({sessionSearchResults:a,isSearchingSessions:!1})}catch(t){let r=this.getState();if(e!==this.searchSeq||M(r)!==i||r.selectedWorkspace?.id!==n)return;this.setState({sessionSearchResults:{results:[],matchCount:0,truncated:!1},isSearchingSessions:!1,sessionSearchError:String(t)})}}preferredSession(e,t,n){if(Ca(n)){let t=this.pendingSessionStarts.get(n);return t!==void 0&&!t.discarded&&t.cwd===e&&this.isCurrentPendingStart(t)?t.session:void 0}let r=this.sessionSelection.latestSessionId(this.workspaceSelectionKey(e));return n!==void 0&&n!==``||r!==void 0&&r!==``&&t.some(e=>e.id===r)?Xs(t,{targetSessionId:n,latestSessionId:r}):Xs(this.automaticSessionCandidates(t))}canReuseSelectedSession(){return!this.disposed&&Nc(this.selectedSessionJoinNavigation)}get isChatLoadDeferred(){return this.selectedSessionLoadDeferred}async loadSelectedSession(){if(this.disposed||!this.selectedSessionLoadDeferred||!this.isChatVisible())return;let e=this.getState().selectedSession;if(e===void 0)return;let t=this.beginNavigationOperation?.(pc);await this.selectSession(e,{updateUrl:!1,navigation:t})}async selectSession(e,t){if(this.disposed||!Nc(t?.navigation))return;if(this.retireReadRecoveries([`session`]),I(e)){this.selectClientPendingStartSession(e,t);return}let n=M(this.getState()),r=this.captureSessionErrorOwner(e);this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)});let i=++this.selectionSeq;this.selectedSessionJoinNavigation=t?.navigation,this.socket.close(),this.streamWatermark=void 0,this.clearPendingUpdates(),this.selectedSessionLoadDeferred=t?.deferChatLoading===!0||!this.isChatVisible(),this.selectedSessionLoadDeferred?this.notifications?.clearSelectedSession():this.notifications?.prepareSelectedSession(e,n);let a=this.sessionCacheKey(e.id),o=this.selectedSessionLoadDeferred?{messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,messagePageLeafId:void 0}:this.transcripts.cachedView(a);if(this.setState({selectedSession:e,sessionSearchTarget:void 0,...o,isLoadingEarlierMessages:!1,...t?.preserveTreeDialog===!0?{}:{treeDialog:void 0},status:e.archived===!0?void 0:this.getState().sessionStatuses[e.id],activity:e.archived===!0?void 0:this.getState().sessionActivities[e.id],pendingDialogs:e.archived===!0?[]:this.getState().sessionStatuses[e.id]?.pendingDialogs??[],closedDialogs:[],availableThinkingLevels:[]}),this.selectedSessionLoadDeferred){this.selectedSessionJoinNavigation=void 0,t?.updateUrl!==!1&&this.updateUrl();return}let s=!1;try{if(e.archived===!0){let o=this.browserErrors.captureRecovery(Kn(n,e.id,r),`session-refresh`),s=await this.api.messages(e,{limit:lc},n),c=this.getState().selectedSession;if(i!==this.selectionSeq||M(this.getState())!==n||c?.id!==e.id||c.cwd!==e.cwd||c.path!==e.path||c.archived!==e.archived||!Nc(t?.navigation))return;this.browserErrors.clearRecovered(o);let l=this.transcripts.mergeHistory(a,s);this.setState({...l,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingDialogs:[],closedDialogs:[]}),this.onSelectedSessionReady?.({machineId:n,session:e}),t?.updateUrl!==!1&&this.updateUrl();return}this.socket.connect(e,t=>{this.isCurrentSessionSelection(e.id,n,i)&&this.applyEvent(t)},()=>{this.isCurrentSessionSelection(e.id,n,i)&&this.isSelectedSessionScope(e,n)&&this.refreshSelectedSession(e.id,{recoverNetwork:!0})},n,()=>{let t=this.getState().selectedSession;this.isCurrentSessionSelection(e.id,n,i)&&t?.cwd===e.cwd&&t.path===e.path&&this.refreshSessionNotifications(e,n)}),s=!0;let o={session:e,machineId:n,selectionSeq:i,errorOwner:r,...t?.navigation===void 0?{}:{navigation:t.navigation}};if(t?.propagateRefreshError===!0)await this.requestSelectedSessionRefresh(o);else if(!await this.joinSelectedSessionSnapshot(o))return;if(!this.isCurrentRefreshTarget(o)||!Nc(t?.navigation))return;this.refreshAvailableThinkingLevels(),this.onSelectedSessionReady?.({machineId:n,session:e}),t?.updateUrl!==!1&&this.updateUrl()}catch(a){let o=Nc(t?.navigation);if(!o||i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id){if(this.reportSessionError(e,n,a,r),t?.propagateRefreshError===!0&&o&&this.isSelectedSessionIdentity(e.id,n))throw a;return}if($r(e)&&Mc(a)){await this.recreateCachedNewSession(e,t,i,r);return}if(this.reportSessionError(e,n,a,r),t?.propagateRefreshError===!0)throw a}finally{let r=Nc(t?.navigation);i===this.selectionSeq&&r&&(this.selectedSessionJoinNavigation=void 0),s&&!Nc(t?.navigation)&&this.isCurrentSessionSelection(e.id,n,i)&&this.socket.close()}}async loadEarlierMessages(){let e=this.getState(),t=e.selectedSession;if(!t||e.isLoadingEarlierMessages||e.messagePageStart<=0)return;let n=M(e),r=this.captureSessionErrorOwner(t),i=this.selectionSeq,a=j(n,t.id),o=this.transcripts.historyRevision(a),s=()=>{let e=this.getState();return!this.disposed&&i===this.selectionSeq&&M(e)===n&&e.selectedSession?.id===t.id&&e.selectedSession.cwd===t.cwd&&e.selectedSession.path===t.path&&e.selectedSession.archived===t.archived};this.setState({isLoadingEarlierMessages:!0});try{let r=await this.api.messages(t,{before:e.messagePageStart,limit:lc},n);if(!s()||this.transcripts.historyRevision(a)!==o)return;let i=this.transcripts.mergeHistory(a,r);this.setState(i)}catch(e){if(!s())return;this.reportSessionError(t,n,e,r)}finally{s()&&this.setState({isLoadingEarlierMessages:!1})}}async send(e,t,n,r=`inline`,i,a){let o=this.getState(),s=o.selectedSession;if(!s||s.archived===!0||a!==void 0&&(!Ma(a,{machineId:M(o),sessionId:s.id,cwd:s.cwd})||I(s)))return!1;let c=e.trim(),l=n!==void 0&&n.length>0,u=a!==void 0;if(I(s))return!l&&c.startsWith(`/`)?this.enqueuePendingSessionSend(s,{type:`command`,text:e}):!l&&ws(e)?this.enqueuePendingSessionSend(s,{type:`shell`,text:e}):this.enqueuePendingSessionSend(s,{type:`prompt`,text:e,streamingBehavior:t,attachments:n,delivery:r,folder:i}),!1;if(!u&&!l&&c.startsWith(`/`))return await this.runCommand(e),!1;if(!u&&!l&&ws(e))return await this.runShell(e),!1;let d=M(this.getState()),f=this.captureSessionErrorOwner(s);return this.deliverPromptToSession(s,e,t,n,r,i,d,{markSending:l||u},f)}markSendingPrompt(e,t){let n=this.getState().sendingPrompts;t?n[e]!==!0&&this.setState({sendingPrompts:{...n,[e]:!0}}):e in n&&this.setState({sendingPrompts:_c(n,e)})}async runShell(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;if(I(t)){this.enqueuePendingSessionSend(t,{type:`shell`,text:e});return}let n=M(this.getState()),r=this.captureSessionErrorOwner(t);await this.deliverShellToSession(t,e,n,{optimisticLine:!0},r)}async runCommand(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;if(I(t)){this.enqueuePendingSessionSend(t,{type:`command`,text:e});return}let n=M(this.getState()),r=this.captureSessionErrorOwner(t);await this.deliverCommandToSession(t,e,n,{applyResult:!0},r)}async renameSession(e,t){let n=t.trim();if(n===``||!zs(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let r=M(this.getState()),i=this.getState().selectedWorkspace,a=this.captureSessionErrorOwner(e);try{let t=await this.api.runCommand(e,`/name ${n}`,r);if(t.type===`done`){let a=this.getState();if(this.disposed||M(a)!==r||a.selectedWorkspace?.id!==i?.id||a.selectedWorkspace?.projectId!==i?.projectId||a.selectedWorkspace?.path!==i?.path||!a.sessions.some(t=>t.id===e.id&&t.cwd===e.cwd&&t.path===e.path))return;this.applySessionName(e.id,t.session?.name??n);return}this.reportSessionError(e,r,t.type===`unsupported`?t.message:D(`client.sessionController.failed.to.rename.session.702159`,`Failed to rename session`),a)}catch(t){this.reportSessionError(e,r,t,a)}}enqueuePendingSessionSend(e,t){let n=this.pendingSessionStarts.get(e.id);if(n===void 0||n.discarded){let t=this.captureSessionErrorOwner(e,n?.originWorkspace);this.reportSessionError(e,e.machineId,D(`client.sessionController.the.backend.session.is.not.ready.to.send.queued.messages.copy.your.mes.22460a`,`The backend session is not ready to send queued messages. Copy your messages before discarding this failed start.`),t);return}let r={...t,id:`pending-send-${String(++this.pendingQueuedSendSeq)}`};n.queuedSends.push(r);let i=this.getState(),a=i.clientQueuedSessionMessages[e.id]??[],o=Sc(e.id,n.queuedSends.length);this.setState({clientQueuedSessionMessages:{...i.clientQueuedSessionMessages,[e.id]:[...a,wc(r)]},sessionActivities:{...i.sessionActivities,[e.id]:o},activity:i.selectedSession?.id===e.id?o:i.activity,error:``})}async flushQueuedPendingSends(e,t,n,r){for(let i of n){if(!await this.deliverQueuedPendingSend(e,t,i,r))return;this.dropNextQueuedSessionMessage(e.id)}}async deliverQueuedPendingSend(e,t,n,r){return n.type===`prompt`?this.deliverPromptToSession(e,n.text,n.streamingBehavior,n.attachments,n.delivery,n.folder,t,{markSending:!0},r):n.type===`shell`?this.deliverShellToSession(e,n.text,t,{optimisticLine:!0},r):this.deliverCommandToSession(e,n.text,t,{applyResult:!0},r)}async deliverPromptToSession(e,t,n,r,i,a,o,s,c){let l=r!==void 0&&r.length>0;s.markSending&&this.markSendingPrompt(e.id,!0);try{if(l&&i===`folder`){let i=(await this.api.saveAttachments(e,r,o,a)).map(e=>vs(e.path,!1)).join(` `),s=t===``?i:`${t}\n\n${i}`;await this.api.prompt(e,s,n,o)}else await this.api.prompt(e,t,n,o,r);return this.markCachedNewSessionPersisted(e),!0}catch(t){return this.reportSessionError(e,o,t,c),!1}finally{s.markSending&&this.markSendingPrompt(e.id,!1)}}async deliverShellToSession(e,t,n,r,i){r.optimisticLine&&this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ui(`user`,t)]});try{return await this.api.shell(e,t,n),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ui(`system`,ic(t))]}),this.reportSessionError(e,n,t,i),!1}}async deliverCommandToSession(e,t,n,r,i){let a=this.navigationSelection();this.markSendingPrompt(e.id,!0);try{let o=await this.api.runCommand(e,t,n);return r.applyResult&&this.isSelectedSessionIdentity(e.id,n)?await this.applyCommandResult(o,a):(o.type===`select`||o.type===`tree`)&&this.reportSessionError(e,n,D(`client.sessionController.queued.command.requires.input.open.the.session.and.run.it.again.2a98cf`,`Queued command "{value1}" requires input; open the session and run it again.`,{value1:t}),i),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ui(`system`,ic(t))]}),this.reportSessionError(e,n,t,i),!1}finally{this.markSendingPrompt(e.id,!1)}}dropNextQueuedSessionMessage(e){let t=this.getState(),n=t.clientQueuedSessionMessages[e]??[];if(n.length===0)return;let r=n.slice(1);this.setState({clientQueuedSessionMessages:r.length===0?_c(t.clientQueuedSessionMessages,e):{...t.clientQueuedSessionMessages,[e]:r}})}async respondToCommand(e,t){let n=this.getState().selectedSession;if(!n)return;let r=M(this.getState()),i=this.captureSessionErrorOwner(n),a=this.navigationSelection();this.setState({commandDialog:void 0});try{let i=await this.api.respondToCommand(n,e,t,r);this.isSelectedSessionIdentity(n.id,r)&&await this.applyCommandResult(i,a)}catch(e){this.reportSessionError(n,r,e,i)}}cancelCommand(){this.setState({commandDialog:void 0})}async actOnMessage(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0||I(r))return;let i=M(n),a=this.selectionSeq,o=this.captureSessionErrorOwner(r),s;try{if(s=await this.api.runCommand(r,`/tree`,i),s.type!==`tree`)throw Error(`message`in s?s.message:D(`ui.main.8bcdd03f7054`,`Session history is unavailable.`));if(!s.tree.nodes.some(t=>t.id===e))throw Error(D(`ui.main.e92706bbbf62`,`This message is no longer available in session history.`))}catch(e){throw this.reportSessionError(r,i,e,o),e}this.isCurrentSessionSelection(r.id,i,a)&&this.isSelectedSessionScope(r,i)&&(t===`fork`?await this.forkSessionTree(e,s.tree,!0):await this.navigateSessionTree(e,{mode:`none`},s.tree,!0))}async navigateTree(e,t){return this.navigateSessionTree(e,t,this.getState().treeDialog)}async navigateSessionTree(e,t,n,r){let i=this.getState(),a=i.selectedSession;if(a===void 0||n===void 0||a.archived===!0||I(a))throw Error(D(`client.sessionController.session.tree.navigator.is.no.longer.available.34846d`,`Session tree navigator is no longer available`));let o={...a},s=M(i),c=this.captureSessionErrorOwner(o),l={machineId:s,sessionId:o.id};this.setTreeActionPending(l,!0);try{let i=await this.api.navigateTree(o,{targetId:e,expectedLeafId:n.activeLeafId,summary:t,...r===void 0?{}:{retainCheckpoint:r}},s);return await this.applySessionTreeNavigationResult(o,s,i,n),i}catch(e){throw this.reportSessionError(o,s,e,c),e}finally{this.setTreeActionPending(l,!1)}}async applySessionTreeNavigationResult(e,t,n,r){if(n.cancelled||this.disposed)return;if(this.hasDraftIdentityConflict(e,t)){this.reportSessionError(e,t,D(`client.sessionController.queueContextChanged`,`The conversation context changed before the result returned. The current draft was preserved.`));return}let i=j(t,e.id),a=n.editorText;if(a!==void 0&&za(i,a),this.transcripts.discard(i),!this.isSelectedSessionScope(e,t))return;this.clearPendingUpdates();let o=this.selectionSeq,s=()=>this.isCurrentSessionSelection(e.id,t,o)&&this.isSelectedSessionScope(e,t),c=(async()=>{a!==void 0&&s()&&await this.replacePromptEditorText?.({machineId:t,sessionId:e.id,text:a,isCurrent:s})})(),[l,u]=await Promise.allSettled([c,this.requestSelectedSessionRefresh({session:e,machineId:t,selectionSeq:o,errorOwner:this.captureSessionErrorOwner(e)})]);if(s()){if(l.status===`rejected`)throw l.reason;if(u.status===`rejected`)throw u.reason;this.getState().treeDialog===r&&this.setState({treeDialog:void 0})}}async forkFromTree(e){return this.forkSessionTree(e,this.getState().treeDialog)}async forkSessionTree(e,t,n){let r=this.getState(),i=r.selectedSession;if(i===void 0||t===void 0||i.archived===!0||I(i))throw Error(D(`client.sessionController.session.tree.navigator.is.no.longer.available.34846d`,`Session tree navigator is no longer available`));let a={...i},o=M(r),s=this.captureSessionErrorOwner(a),c=this.navigationSelection(),l={machineId:o,sessionId:a.id};this.setTreeActionPending(l,!0);try{let r=await this.api.forkTree(a,{entryId:e,expectedLeafId:t.activeLeafId,...n===void 0?{}:{retainCheckpoint:n}},o);return await this.applySessionTreeForkResult(a,o,r,c,t),r}catch(e){throw this.reportSessionError(a,o,e,s),e}finally{this.setTreeActionPending(l,!1)}}async applySessionTreeForkResult(e,t,n,r,i){if(n.cancelled)return;let a=j(t,e.id),o=n.session;if(o.id===e.id){await this.applySessionTreeNavigationResult(e,t,{cancelled:!1,...n.promptDraft===void 0?{}:{editorText:n.promptDraft}},i);return}if(n.promptDraft!==void 0&&za(j(t,o.id),n.promptDraft),this.transcripts.discard(a),!this.isSelectedSessionScope(e,t))return;let s=[o,...this.getState().sessions.filter(e=>e.id!==o.id)];this.setState({sessions:s}),this.navigateToSession===void 0?(this.setState({treeDialog:void 0}),await this.selectSession(o)):await this.navigateToSession(o,{expected:r})&&this.isSelectedSessionIdentity(o.id,t)&&this.getState().treeDialog===i&&this.setState({treeDialog:void 0})}async abortTreeNavigation(){let e=this.getState(),t=e.selectedSession;if(t===void 0||e.treeDialog===void 0||I(t))return;let n=M(e),r=this.captureSessionErrorOwner(t);try{await this.api.abort(t,n)}catch(e){throw this.reportSessionError(t,n,e,r),e}}closeTreeDialog(){this.setState({treeDialog:void 0})}applySessionStatus(e){this.applyStatus(e)}archiveScopeProjectId(){return Gt()?this.getState().selectedProject?.id:void 0}async useSuggestedInput(e,t){if(!this.isSelectedSessionIdentity(t,e))return;let n=this.getState(),r=n.selectedSession,i=n.status?.sessionId===t?n.status.suggestedInput:void 0;if(r===void 0||i===void 0)return;let a=this.captureSessionErrorOwner(r);za(j(e,t),i);try{await this.replacePromptEditorText?.({machineId:e,sessionId:t,text:i})}catch(t){this.reportSessionError(r,e,t,a)}}invalidateSessionTree(){let e=this.getState(),t=e.selectedSession,n=M(e);t!==void 0&&this.isSelectedSessionIdentity(t.id,n)&&(this.transcripts.discard(j(n,t.id)),this.clearPendingUpdates(),this.refreshSelectedSession(t.id),e.treeDialog!==void 0&&!this.hasPendingTreeAction(n,t.id)&&this.setState({treeDialog:void 0}))}hasPendingTreeAction(e,t){return[...this.pendingTreeActions].some(n=>n.machineId===e&&n.sessionId===t)}setTreeActionPending(e,t){t?this.pendingTreeActions.add(e):this.pendingTreeActions.delete(e),this.disposed||this.setState({pendingTreeActions:[...this.pendingTreeActions]})}async archiveSession(e=this.getState().selectedSession){if(!e)return;let t=this.statusForSession(e),n=this.sessionPersistenceOptions();if(Bs(e,t,n)){await this.deleteCachedNewSession(e);return}if(!zs(e,t,n))return;let r=M(this.getState()),i=this.captureSessionErrorOwner(e);try{await this.api.archive(e,r,this.archiveScopeProjectId());let t=this.getState(),n=Qs(t.sessions,e.id,new Date().toISOString()),i=ec(this.automaticSessionCandidates(n),t.selectedSession?.id,e.id);this.setState({sessions:n});let a=this.navigationSelection();i.type===`select`?await this.selectSessionAfterNavigation(i.session,a):i.type===`clear`&&await this.clearSessionAfterNavigation(a)}catch(t){this.reportSessionError(e,r,t,i)}}async archiveSessionWithDescendants(e=this.getState().selectedSession){if(e===void 0||!zs(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{let n=await this.api.archiveWithDescendants(e,t,this.archiveScopeProjectId()),r=n.sessionIds!==void 0&&n.sessionIds.length>0?n.sessionIds:[e.id],i=this.getState(),a=$s(i.sessions,r,new Date().toISOString()),o=tc(this.automaticSessionCandidates(a),i.selectedSession?.id,r);this.setState({sessions:a});let s=this.navigationSelection();o.type===`select`?await this.selectSessionAfterNavigation(o.session,s):o.type===`clear`&&await this.clearSessionAfterNavigation(s)}catch(r){this.reportSessionError(e,t,r,n)}}async archiveSessions(e){let t=this.sessionPersistenceOptions(),n=Dc(e).filter(e=>zs(e,this.statusForSession(e),t));if(n.length===0)return;let r=M(this.getState()),i=this.getState().selectedWorkspace,a=n[0];if(a===void 0)return;let o=this.captureSessionErrorOwner(a,i);try{let{succeededIds:e,failures:t,generatedAt:s}=await this.archiveSessionBatch(n,r);if(e.length>0){let t=this.getState(),n=$s(t.sessions,e,s??new Date().toISOString()),r=tc(this.automaticSessionCandidates(n),t.selectedSession?.id,e);this.setState({sessions:n});let i=this.navigationSelection();r.type===`select`?await this.selectSessionAfterNavigation(r.session,i):r.type===`clear`&&await this.clearSessionAfterNavigation(i)}this.applyBulkSessionFailures(D(`ui.sessionCleanupDialog.archive`,`Archive`),t,r,i,a,o)}catch(e){this.reportWorkspaceOrSessionError(i,a,r,D(`client.sessionController.archive.failed.aaa500`,`Archive failed: {value1}`,{value1:kc(e)}),o)}}async deleteArchivedSessions(e){let t=Dc(e).filter(e=>e.archived===!0);if(t.length===0)return;let n=M(this.getState()),r=this.getState().selectedWorkspace,i=t[0];if(i===void 0)return;let a=this.captureSessionErrorOwner(i,r);try{let{succeededIds:e,failures:o}=await this.deleteArchivedSessionBatch(t,n);if(e.length>0){let r=new Set(e),i=this.getState(),a=i.sessions.filter(e=>!r.has(e.id));if(this.setState({sessions:a}),i.selectedSession!==void 0&&r.has(i.selectedSession.id)){let e=this.navigationSelection(),t=this.automaticSessionCandidates(a),n=t.find(e=>e.archived!==!0)??t[0];n===void 0?await this.clearSessionAfterNavigation(e):await this.selectSessionAfterNavigation(n,e)}await this.refreshPinnedSessions(t[0]?.cwd??``,n)}this.applyBulkSessionFailures(D(`ui.sessionList.delete`,`Delete`),o,n,r,i,a)}catch(e){this.reportWorkspaceOrSessionError(r,i,n,D(`client.sessionController.delete.failed.59ec26`,`Delete failed: {value1}`,{value1:kc(e)}),a)}}async archiveSessionBatch(e,t){let n=await this.api.archiveMany(e,t,this.archiveScopeProjectId());return{succeededIds:n.archivedSessionIds,failures:Oc(n.failures),generatedAt:n.generatedAt}}async deleteArchivedSessionBatch(e,t){let n=await this.api.deleteArchivedMany(e,t,this.archiveScopeProjectId());return{succeededIds:n.deletedSessionIds,failures:Oc(n.failures)}}async applySessionCleanupResult(e,t=M(this.getState())){if(M(this.getState())!==t)return;let n=e.archivedSessionIds,r=e.deletedSessionIds;if(n.length>0||r.length>0){let t=this.getState(),i=new Set(r),a=[...n,...r],o=$s(t.sessions,n,e.generatedAt).filter(e=>!i.has(e.id)),s=t.selectedSession!==void 0&&a.includes(t.selectedSession.id);this.setState({sessions:o,sessionStatuses:vc(t.sessionStatuses,a),sessionActivities:vc(t.sessionActivities,a),...s?{status:void 0,activity:void 0,pendingDialogs:[],closedDialogs:[]}:{}});let c=this.navigationSelection();if(t.selectedSession!==void 0&&i.has(t.selectedSession.id)){let e=this.automaticSessionCandidates(o),t=e.find(e=>e.archived!==!0)??e[0];t===void 0?await this.clearSessionAfterNavigation(c):await this.selectSessionAfterNavigation(t,c)}else{let e=tc(this.automaticSessionCandidates(o),t.selectedSession?.id,n);e.type===`select`?await this.selectSessionAfterNavigation(e.session,c):e.type===`clear`&&await this.clearSessionAfterNavigation(c)}}await this.refreshCurrentWorkspaceSessions(t)}retireReadRecoveries(e){let t=e.some(e=>e===`machine`||e===`project`||e===`workspace`);if(t||e.includes(`session`)){this.selectedReadGeneration+=1;for(let e of this.selectedReadRecoveries)e.abort();this.selectedReadRecoveries.clear(),this.refreshEventBuffer=void 0}if(t){this.workspaceReadGeneration+=1;for(let e of this.workspaceReadRecoveries)e.abort();this.workspaceReadRecoveries.clear()}}async refreshCurrentWorkspaceSessions(e=M(this.getState()),t){let n=this.getState().selectedWorkspace;if(n===void 0)return;let r=this.workspaceReadGeneration,i=this.beginNavigationOperation?.([`machine`,`project`,`workspace`]),a=()=>!this.disposed&&r===this.workspaceReadGeneration&&Nc(i)&&M(this.getState())===e&&this.getState().selectedWorkspace?.id===n.id&&this.getState().selectedWorkspace?.projectId===n.projectId&&this.getState().selectedWorkspace?.path===n.path,o=Gn(e,n.projectId,n.id);try{await this.workspaceSessionRefreshes.request(JSON.stringify([e,n.projectId,n.id,n.path]),async()=>{if(!a())return;let r=this.browserErrors.captureRecovery(o,`workspace-sessions-refresh`),i=()=>this.api.sessions(n.path,e),s=new AbortController;this.workspaceReadRecoveries.add(s);let c;try{c=await sc(i,a,s.signal,t?.recoverNetwork===!0)}finally{this.workspaceReadRecoveries.delete(s)}if(c===void 0||!a())return;this.browserErrors.clearRecovered(r);let l=Qr(n.path,c,e).filter(t=>!this.isSuppressedCreatedSession(t,e)),u=this.mergePendingStartSessions(n.path,l,e),d=this.getState().selectedSession;this.setState({sessions:u}),this.refreshPinnedSessions(n.path,e);let f=this.navigationSelection();if(d===void 0)return;let p=u.find(e=>e.id===d.id);if(p!==void 0){p!==d&&this.setState({selectedSession:p});return}let m=this.automaticSessionCandidates(u),h=m.find(e=>e.archived!==!0)??m[0];h===void 0?await this.clearSessionAfterNavigation(f):await this.selectSessionAfterNavigation(h,f)})}catch(i){if(this.disposed||r!==this.workspaceReadGeneration||t?.recoverNetwork===!0&&!a())return;if(i instanceof Oe){this.browserErrors.report(o,D(`client.sessionController.sessionListRefreshUnavailable`,`The session list could not be refreshed. Check your connection and retry.`),`workspace-sessions-refresh`);return}if(rc(i)){console.warn(`Workspace session list refresh timed out`,{machineId:e,workspaceId:n.id,errorCategory:`session-list-refresh`});return}this.reportWorkspaceError(n,e,i)}}stopPolling(){this.sessionPollTimer!==void 0&&clearInterval(this.sessionPollTimer),this.sessionPollTimer=void 0,this.sessionRefreshInFlight=!1}async deleteCachedNewSession(e=this.getState().selectedSession){if(e===void 0||!Bs(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=I(e)?this.pendingSessionStarts.get(e.id):void 0;t===void 0?this.api.stop(e,M(this.getState())).catch(()=>{}):(t.discarded=!0,t.queuedSends=[]),Zr(e.id,M(this.getState())),Ba(this.sessionCacheKey(e.id)),Ka(this.sessionCacheKey(e.id));let n=this.getState(),r=n.sessions.filter(t=>t.id!==e.id);if(this.setState({sessions:r,sessionStatuses:_c(n.sessionStatuses,e.id),sessionActivities:gc(n.sessionActivities,e.id),sendingPrompts:_c(n.sendingPrompts,e.id),clientQueuedSessionMessages:_c(n.clientQueuedSessionMessages,e.id)}),this.getState().selectedSession?.id!==e.id)return;let i=this.navigationSelection(),a=this.automaticSessionCandidates(r),o=a.find(e=>e.archived!==!0)??a[0];o===void 0?await this.clearSessionAfterNavigation(i):await this.selectSessionAfterNavigation(o,i)}async restoreSession(e=this.getState().selectedSession){if(!e)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e),r=this.selectionSeq,i=this.beginNavigationOperation?.(pc);try{await this.api.restore(e,t,this.archiveScopeProjectId())}catch(r){this.reportSessionError(e,t,r,n);return}if(!this.isCurrentRestoreOperation(t,r,i))return;let a={...e};delete a.archived,delete a.archivedAt;let o=this.getState().selectedSession?.id===a.id;this.replaceSession(a),o&&await this.selectSession(a,{updateUrl:!1,...i===void 0?{}:{navigation:i}})}async reloadSession(e=this.getState().selectedSession){if(e===void 0||!zs(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.reloadSession(e,t),this.transcripts.discard(j(t,e.id)),this.isSelectedSessionIdentity(e.id,t)&&await this.selectSession(e,{updateUrl:!1})}catch(r){this.reportSessionError(e,t,r,n)}}async detachParent(e=this.getState().selectedSession){if(e?.parentSessionPath===void 0)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.detachParent(e,t);let n=this.getState();if(this.disposed||M(n)!==t)return;let r=t=>{if(t.id!==e.id||t.cwd!==e.cwd)return t;let n={...t};return delete n.parentSessionPath,delete n.agentSubsession,n};this.setState({sessions:n.sessions.map(r),selectedSession:n.selectedSession===void 0?void 0:r(n.selectedSession)})}catch(r){this.reportSessionError(e,t,r,n)}}async listModels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{return(await this.api.models(e,t)).models}catch(r){return this.reportSessionError(e,t,r,n),[]}}async listModelCatalog(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{return(await this.api.modelCatalog(e,t)).models}catch(r){return this.reportSessionError(e,t,r,n),[]}}async setModelEnabled(e,t,n){let r=this.getState().selectedSession;if(!r||r.archived===!0)return;let i=M(this.getState()),a=this.captureSessionErrorOwner(r);try{return(await this.api.setModelEnabled(r,e,t,n,i)).models}catch(e){this.reportSessionError(r,i,e,a);return}}async setModelScope(e){let t=this.getState(),n=t.selectedSession;if(!n||n.archived===!0)return;let r=M(t),i=this.captureSessionErrorOwner(n);try{return(await this.api.setModelScope(n,e,r)).models}catch(e){this.reportSessionError(n,r,e,i);return}}async getSessionDefaults(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{return await this.api.getSessionDefaults(e,t)}catch(r){this.reportSessionError(e,t,r,n);return}}async setSessionDefaults(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;let n=M(this.getState()),r=this.captureSessionErrorOwner(t);try{return await this.api.setSessionDefaults(t,e,n)}catch(e){this.reportSessionError(t,n,e,r);return}}async setModel(e,t){let n=this.getState().selectedSession;if(!n||n.archived===!0)return;let r=M(this.getState()),i=this.captureSessionErrorOwner(n);try{let i=await this.api.setModel(n,e,t,r);if(M(this.getState())!==r)return;this.applyStatus(i),this.isSelectedSessionIdentity(n.id,r)&&await this.refreshAvailableThinkingLevels()}catch(e){this.reportSessionError(n,r,e,i)}}async cycleModel(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;let n=M(this.getState()),r=this.captureSessionErrorOwner(t);try{let r=await this.api.cycleModel(t,e,n);if(M(this.getState())!==n)return;this.applyStatus(r),this.isSelectedSessionIdentity(t.id,n)&&await this.refreshAvailableThinkingLevels()}catch(e){this.reportSessionError(t,n,e,r)}}async listThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{return(await this.api.thinkingLevels(e,t)).levels}catch(r){return this.reportSessionError(e,t,r,n),[]}}async refreshAvailableThinkingLevels(){let e=this.getState().selectedSession,t=M(this.getState());if(!e||e.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}let n=await this.listThinkingLevels();this.isSelectedSessionIdentity(e.id,t)&&this.setState({availableThinkingLevels:n})}async setThinkingLevel(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;let n=M(this.getState()),r=this.captureSessionErrorOwner(t);try{let r=await this.api.setThinkingLevel(t,e,n);if(M(this.getState())!==n)return;this.applyStatus(r)}catch(e){this.reportSessionError(t,n,e,r)}}async cycleThinkingLevel(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{let n=await this.api.cycleThinkingLevel(e,t);if(M(this.getState())!==t)return;this.applyStatus(n)}catch(r){this.reportSessionError(e,t,r,n)}}async mutateQueuedMessage(e,t,n){let r=this.getState(),i=r.selectedSession;if(i===void 0||i.archived===!0||I(i))return;let a={...i},o=M(r);if(!this.isSelectedSessionScope(a,o)||!this.canMutateQueueMessage(a,o)||r.status?.queueMessageActionsUnavailable!==void 0)return;let s=n.map(e=>({...e}));if(!Number.isInteger(t)||t<0||t>=s.length)return;let c=s[t]?.text??``,l=this.selectionSeq,u=this.captureSessionErrorOwner(a),d=()=>this.isCurrentSessionSelection(a.id,o,l)&&this.isSelectedSessionScope(a,o)&&this.canMutateQueueMessage(a,o)&&this.getState().status?.queueMessageActionsUnavailable===void 0;try{let n=await this.api.mutateQueuedMessage(a,{action:e,index:t,expectedQueue:s},o);if(this.disposed)return;if(n.sessionId!==a.id)throw Error(D(`client.sessionController.queueResponseMismatch`,`The queue response belongs to a different conversation.`));if(!this.canMutateQueueMessage(a,o))throw Error(D(`client.sessionController.queueActionsUnavailable`,`Queued message actions are no longer available.`));if(this.hasDraftIdentityConflict(a,o))throw Error(D(`client.sessionController.queueContextChanged`,`The conversation context changed before the result returned. The current draft was preserved.`));e===`edit`&&(za(j(o,a.id),c),d()&&await this.replacePromptEditorText?.({machineId:o,sessionId:a.id,text:c,isCurrent:d})),d()&&this.applyStatus(n)}catch(e){this.disposed||this.reportSessionError(a,o,e,u)}}async clearServerQueue(){let e=this.getState(),t=e.selectedSession;if(t===void 0||t.archived===!0||I(t))return;let n=M(e),r=this.captureSessionErrorOwner(t),i=this.selectionSeq;try{let e=await this.api.clearQueue(t,n);this.isCurrentSessionSelection(t.id,n,i)&&this.applyStatus(e)}catch(e){this.reportSessionError(t,n,e,r)}}async dismissWarning(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||I(n))return;let r=M(t),i=this.captureSessionErrorOwner(n),a=this.selectionSeq;try{let t=await this.api.dismissWarning(n,e,r);this.isCurrentSessionSelection(n.id,r,a)&&this.applyStatus(t)}catch(e){this.reportSessionError(n,r,e,i)}}submitAsk(e,t){return this.sendAskResponse(e,(n,r)=>this.api.submitAsk(n,e,t,r))}cancelAsk(e){return this.sendAskResponse(e,(t,n)=>this.api.cancelAsk(t,e,n))}answerDialog(e,t){return this.closeOpenDialog(e,(n,r)=>this.api.answerDialog(n,e,t,r))}cancelDialog(e){return this.closeOpenDialog(e,(t,n)=>this.api.cancelDialog(t,e,n))}async closeOpenDialog(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0)return;if(I(r)){await this.closePendingStartDialog(r,e,t);return}let i=M(n),a=this.captureSessionErrorOwner(r),o=this.selectionSeq;try{let e=await t(r,i);if(!this.isCurrentSessionSelection(r.id,i,o))return;this.recordDialogOutcome(e.outcome),this.applyStatus(e.sessionStatus)}catch(e){this.reportSessionError(r,i,e,a)}}async closePendingStartDialog(e,t,n){let r=this.pendingSessionStarts.get(e.id),i=r?.backendSessionId;if(r===void 0||i===void 0)return;let a=this.captureSessionErrorOwner(e,r.originWorkspace),o=this.selectionSeq;try{let t=await n({...e,id:i},r.machineId);if(o!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;this.recordDialogOutcome(t.outcome),this.applyPendingStartStatus(r,t.sessionStatus)}catch(t){this.reportSessionError(e,r.machineId,t,a)}}recordDialogOutcome(e){if(e===void 0)return;let t=this.getState().pendingDialogs.find(t=>t.dialogId===e.dialogId);t!==void 0&&this.recordClosedDialog({dialog:t,reason:e.reason,...e.answer===void 0?{}:{answer:e.answer}})}async sendAskResponse(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0||I(r))return;let i=M(n),a=this.captureSessionErrorOwner(r),o=this.selectionSeq;try{let n=await t(r,i);Qa(j(i,r.id),e),this.isCurrentSessionSelection(r.id,i,o)&&this.applyStatus(n)}catch(e){this.reportSessionError(r,i,e,a)}}async stopActiveWork(){let e=this.getState().selectedSession;if(!e)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.abort(e,t)}catch(r){this.reportSessionError(e,t,r,n)}}refreshSelectedSession(e=this.getState().selectedSession?.id,t){let n=this.getState().selectedSession;if(e===void 0||n?.id!==e||this.selectedSessionLoadDeferred||n.archived===!0||I(n))return Promise.resolve();let r=M(this.getState()),i={session:n,machineId:r,selectionSeq:this.selectionSeq,errorOwner:this.captureSessionErrorOwner(n),...t?.recoverNetwork===!0?{recoverNetwork:!0}:{}},a=this.selectedReadGeneration;return this.requestSelectedSessionRefresh(i).catch(e=>{this.disposed||a!==this.selectedReadGeneration||t?.recoverNetwork===!0&&!this.isCurrentRefreshTarget(i)||(t?.silent===!0?console.warn(`Selected session background refresh failed`,{machineId:r,sessionId:n.id,errorCategory:`session-refresh`}):e instanceof Oe?this.browserErrors.report(Kn(r,n.id,i.errorOwner),D(`client.sessionController.conversationRefreshUnavailable`,`The conversation could not be refreshed. Check your connection and retry.`),`session-refresh`):this.reportSessionError(i.session,i.machineId,e,i.errorOwner))})}bufferRefreshEvents(e){if(this.refreshEventBuffer!==void 0&&this.isCurrentRefreshTarget(this.refreshEventBuffer.target))return this.refreshEventBuffer;this.flushPendingUpdates();let t={target:e,events:[],pendingDialogs:this.getState().pendingDialogs};return this.refreshEventBuffer=t,t}async refreshSessionNotifications(e,t){try{await this.notifications?.refreshSelectedSession(e,t)}catch{console.warn(`Selected session notification refresh failed`,{machineId:t,sessionId:e.id,errorCategory:`notification-refresh`})}}async joinSelectedSessionSnapshot(e){let t=!1,n,r=new Promise(e=>{n=()=>{t=!0,e(!0)}}),i={selectionSeq:e.selectionSeq,complete:n};this.initialSnapshotReady=i;let a=this.requestSelectedSessionRefresh(e).then(()=>t,n=>{if(!t)throw n;return this.reportSessionError(e.session,e.machineId,n,e.errorOwner),!0});try{return await Promise.race([r,a])}finally{this.initialSnapshotReady===i&&(this.initialSnapshotReady=void 0)}}requestSelectedSessionRefresh(e){if(!this.isCurrentRefreshTarget(e))return Promise.resolve();let t=j(e.machineId,e.session.id),n=this.selectedReadGeneration,r=()=>n===this.selectedReadGeneration&&this.isCurrentRefreshTarget(e);return this.selectedSessionRecoveryTarget!==void 0&&this.isCurrentRefreshTarget(this.selectedSessionRecoveryTarget)||this.bufferRefreshEvents(e),Promise.resolve().then(()=>{if(r())return this.refreshSessionNotifications(e.session,e.machineId)}),this.selectedSessionRefreshes.request(t,async()=>{if(!r())return;let n=new AbortController;this.selectedReadRecoveries.add(n),e.recoverNetwork===!0&&(this.selectedSessionRecoveryTarget=e);try{await sc(()=>this.readSelectedSessionSnapshot(e,t,()=>r()&&!n.signal.aborted,n.signal),r,n.signal,e.recoverNetwork===!0)}finally{this.selectedReadRecoveries.delete(n),this.selectedSessionRecoveryTarget===e&&(this.selectedSessionRecoveryTarget=void 0)}})}async readSelectedSessionSnapshot(e,t,n,r){let i=this.bufferRefreshEvents(e),a=this.transcripts.historyRevision(t),o=this.observeSessionSnapshot?.(e.machineId,e.session.id),s,c=this.browserErrors.captureRecovery(Kn(e.machineId,e.session.id,e.errorOwner),`session-refresh`),l=!1,u=()=>{if(!l&&(l=!0,this.refreshEventBuffer===i&&(this.refreshEventBuffer=void 0),n()))for(let e of i.events){if(!n())break;this.applyEvent(e)}};r?.addEventListener(`abort`,u,{once:!0});try{let r=await this.transcriptSnapshot(e.session,{limit:lc},e.machineId);if(!n()||this.transcripts.historyRevision(t)!==a)return;this.browserErrors.clearRecovered(c);let{page:l,status:u}=r;if(this.preserveBufferedDialogOutcomes(i,r.seq),!this.isUnchangedSelectedRefresh(e,t,l,u,r)){let n=this.transcripts.mergeSnapshot(t,l),i=this.transcripts.seedStreamingPartial(n.messages,r.partial);this.streamWatermark={sessionId:e.session.id,seq:r.seq},this.setState({...n,messages:i,status:u,activity:this.getState().sessionActivities[e.session.id]}),this.applyStatus(u),this.lastAppliedSelectedRefresh={selectionSeq:e.selectionSeq,partialJson:hc(r)}}s=this.transcripts.historyRevision(t),o?.(u)}finally{r?.removeEventListener(`abort`,u),u()}this.transcripts.historyRevision(t)===s&&n()&&this.initialSnapshotReady?.selectionSeq===e.selectionSeq&&this.initialSnapshotReady.complete()}preserveBufferedDialogOutcomes(e,t){let n=new Map(e.pendingDialogs.map(e=>[e.dialogId,e]));for(let r of e.events)if(!(r.seq===void 0||r.seq>t||this.isStreamEventBelowWatermark(r))&&(r.type===`dialog.opened`&&n.set(r.dialog.dialogId,r.dialog),r.type===`dialog.closed`)){let e=n.get(r.dialogId);e!==void 0&&this.recordClosedDialog({dialog:e,reason:r.reason,...r.answer===void 0?{}:{answer:r.answer}}),n.delete(r.dialogId)}}isUnchangedSelectedRefresh(e,t,n,r,i){let a=this.lastAppliedSelectedRefresh;return a?.selectionSeq!==e.selectionSeq||i.seq<(this.streamWatermark?.seq??0)||hc(i)!==a.partialJson||!ts(this.transcripts.rawHistoryPage(t),n)||JSON.stringify(r)!==JSON.stringify(this.getState().status)?!1:this.getState().sessionActivities[r.sessionId]?.phase!==`active`||rr(r)}isCurrentRefreshTarget(e){let t=this.getState().selectedSession;return this.isCurrentSessionSelection(e.session.id,e.machineId,e.selectionSeq)&&t?.cwd===e.session.cwd&&t.path===e.session.path&&t.archived===e.session.archived&&Nc(e.navigation)}isCurrentSessionSelection(e,t,n){return n===this.selectionSeq&&this.isSelectedSessionIdentity(e,t)}isCurrentRestoreOperation(e,t,n){return t===this.selectionSeq&&M(this.getState())===e&&Nc(n)}isSelectedSessionIdentity(e,t){if(this.disposed)return!1;let n=this.getState(),r=n.selectedSession;return M(n)===t&&r?.id===e&&r.archived!==!0&&!I(r)}isSelectedSessionScope(e,t){let n=this.getState().selectedSession;return this.isSelectedSessionIdentity(e.id,t)&&n?.cwd===e.cwd&&n.path===e.path}hasDraftIdentityConflict(e,t){let n=this.getState(),r=n.selectedSession;return M(n)===t&&r?.id===e.id&&(r.cwd!==e.cwd||r.path!==e.path)}reportSessionError(e,t,n,r={cwd:e.cwd}){this.browserErrors.report(Kn(t,e.id,r),ic(n))}captureSessionErrorOwner(e,t=this.workspaceForSessionError(e)){return{cwd:e.cwd,...t===void 0?{}:{projectId:t.projectId,workspaceId:t.id}}}workspaceForSessionError(e){let t=this.getState();return[t.selectedWorkspace,...t.workspaces,...Object.values(t.workspacesByProjectId).flat()].find(t=>t?.path===e.cwd)}reportWorkspaceError(e,t,n){this.browserErrors.report(Gn(t,e.projectId,e.id),ic(n))}applyBulkSessionFailures(e,t,n,r,i,a){t.length!==0&&this.reportWorkspaceOrSessionError(r,i,n,D(`client.sessionController.failed.for.sessions.5ef9b2`,`{value1} failed for {value2} sessions: {value3}`,{value1:e,value2:String(t.length),value3:t.join(`;`)}),a)}reportWorkspaceOrSessionError(e,t,n,r,i){e===void 0?t!==void 0&&this.reportSessionError(t,n,r,i):this.reportWorkspaceError(e,n,r)}sessionCacheKey(e){return j(M(this.getState()),e)}statusForSession(e){if(e===void 0)return;let t=this.getState();return t.status?.sessionId===e.id&&t.selectedSession?.id===e.id?t.status:t.sessionStatuses[e.id]}sessionPersistenceOptions(){let e=this.getState();return Ls(e.machineRuntimes[M(e)])}workspaceSelectionKey(e){return`${M(this.getState())}:${e}`}replaceSession(e){let t=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(t=>t.id===e.id?e:t),selectedSession:t?.id===e.id?e:t})}navigationSelection(){if(this.captureNavigation!==void 0)return this.captureNavigation();let e=this.getState();return{machineId:M(e),projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id}}navigationSelectionMatchesState(e){let t=this.navigationSelection();return t.machineId===e.machineId&&t.projectId===e.projectId&&t.workspaceId===e.workspaceId&&t.sessionId===e.sessionId&&t.tool===e.tool&&t.view===e.view}createPendingSessionStart(e,t,n,r){let i=`creating:${Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,`0`)).join(``)}`,a=new Date().toISOString(),o={id:i,path:`pi-web://pending-session/${i}`,cwd:e.path,persisted:!1,name:D(`client.sessionController.new.session.c57c30`,`New session`),created:a,modified:a,messageCount:0,firstMessage:``,clientPendingStart:!0,machineId:t};return{tempId:i,originWorkspace:e,workspaceId:e.id,cwd:e.path,machineId:t,expectedNavigation:n,pendingUrlPublished:r,session:o,queuedSends:[],discarded:!1}}insertAndSelectPendingSession(e,t){let n=this.getState();this.selectClientPendingStartSession(e,{activity:Sc(e.id),sessions:[e,...n.sessions.filter(t=>t.id!==e.id)],updateUrl:t?.updateUrl})}selectClientPendingStartSession(e,t){this.retireReadRecoveries([`session`]),this.selectedSessionLoadDeferred=!1,this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)}),this.selectionSeq+=1,this.selectedSessionJoinNavigation=void 0,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates();let n=this.getState(),r=this.pendingSessionStarts.get(e.id),i=t?.activity??n.sessionActivities[e.id]??(r===void 0?void 0:Sc(e.id,r.queuedSends.length));this.setState({sessions:t?.sessions??(n.sessions.some(t=>t.id===e.id)?n.sessions:[e,...n.sessions]),selectedSession:e,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:i,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0,...i===void 0?{}:{sessionActivities:{...n.sessionActivities,[e.id]:i}},error:``}),r?.backendSessionId!==void 0&&this.connectPendingStartSocket(r),t?.updateUrl!==!1&&this.updateUrl()}async resolvePendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.queuedSends.splice(0),i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId,t.id);if(n.discarded){Ba(j(n.machineId,e)),Ka(j(n.machineId,e)),this.setState({clientQueuedSessionMessages:_c(this.getState().clientQueuedSessionMessages,e)}),this.applyReleasedCreatedSessions(i,n.machineId),this.api.stop(t,n.machineId).catch(()=>{});return}Yr(t,n.machineId),Va(j(n.machineId,e),j(n.machineId,t.id)),qa(j(n.machineId,e),j(n.machineId,t.id));let a=Xr(t,n.machineId),o=this.captureSessionErrorOwner(t,n.originWorkspace);if(!this.isCurrentPendingStart(n)){this.setState({clientQueuedSessionMessages:_c(this.getState().clientQueuedSessionMessages,e)}),await this.flushQueuedPendingSends(a,n.machineId,r,o);return}let s=this.getState(),c=s.selectedSession?.id===e,l={machineId:n.machineId,projectId:n.originWorkspace.projectId,workspaceId:n.workspaceId,sessionId:e},u=c&&(this.navigateToSession!==void 0||!n.pendingUrlPublished),d=c&&!u&&(this.isPendingSessionStartRouteCurrent?.(l)??!0);c&&!u&&!d&&this.clearActiveSession(),this.setState({sessions:bc(s.sessions,e,a),sessionActivities:gc(s.sessionActivities,e),sendingPrompts:yc(s.sendingPrompts,e,a.id),clientQueuedSessionMessages:yc(s.clientQueuedSessionMessages,e,a.id),...d?{selectedSession:a,status:s.sessionStatuses[a.id],activity:s.sessionActivities[a.id],pendingDialogs:s.sessionStatuses[a.id]?.pendingDialogs??[],closedDialogs:[]}:{},error:``}),this.applyReleasedCreatedSessions(i,n.machineId),u?await this.reconcileCompletedPendingSelection(n,a):d&&(this.onPendingSessionStartCommitted?.(l,a),this.onPendingSessionStartCommitted===void 0&&this.updateUrl({replace:!0}),await this.selectSession(a,{updateUrl:!1,navigation:n.navigation})),await this.flushQueuedPendingSends(a,n.machineId,r,o)}async reconcileCompletedPendingSelection(e,t){let n=e.navigation;if(!e.pendingUrlPublished&&!Nc(n))this.clearUnreconciledPendingSelection(e,t);else if(e.expectedNavigation=this.pendingStartExpectedNavigation(e),this.navigateToSession!==void 0)try{let r=await this.navigateToSession(t,{...e.pendingUrlPublished?{replace:!0,creationHandoff:!0}:{},expected:e.expectedNavigation});if(r&&this.getState().selectedSession?.id!==e.tempId)return;this.clearUnreconciledPendingSelection(e,t,r||e.pendingUrlPublished||!Nc(n)?void 0:D(`ui.main.0a71e48cd0f9`,`Session started, but its navigation changed before selection completed. Select it from the session list.`))}catch(n){this.clearUnreconciledPendingSelection(e,t,D(`ui.main.d15d396c9633`,`Session started but could not be selected: {arg0}`,{arg0:kc(n)}))}else try{if(await this.selectSession(t,{updateUrl:!1,navigation:n}),!Nc(n)){this.clearUnreconciledPendingSelection(e,t);return}if(this.getState().selectedSession?.id!==t.id){this.clearUnreconciledPendingSelection(e,t,D(`ui.main.8cd247b86afd`,`Session started, but its selection changed before navigation completed. Select it from the session list.`));return}this.updateUrl(e.pendingUrlPublished?{replace:!0}:void 0)}catch(n){this.clearUnreconciledPendingSelection(e,t,D(`ui.main.d15d396c9633`,`Session started but could not be selected: {arg0}`,{arg0:kc(n)}))}}pendingStartExpectedNavigation(e){return e.pendingUrlPublished?{machineId:e.machineId,projectId:e.originWorkspace.projectId,workspaceId:e.workspaceId,sessionId:e.tempId}:{...this.navigationSelection(),sessionId:e.expectedNavigation.sessionId}}clearUnreconciledPendingSelection(e,t,n){let r=this.getState().selectedSession?.id;(r===e.tempId||r===t.id)&&(this.clearActiveSession(),n!==void 0&&this.browserErrors.report(Gn(e.machineId,e.originWorkspace.projectId,e.workspaceId),n))}cancelUnstartedSession(e){if(this.pendingSessionStarts.get(e.tempId)!==e)return;this.pendingSessionStarts.delete(e.tempId),e.discarded=!0,e.queuedSends=[],Zr(e.tempId,e.machineId);let t=j(e.machineId,e.tempId);Ba(t),Ka(t);let n=this.getState(),r=n.selectedSession?.id===e.tempId;if(this.setState({sessions:n.sessions.filter(t=>t.id!==e.tempId),sessionStatuses:_c(n.sessionStatuses,e.tempId),sessionActivities:gc(n.sessionActivities,e.tempId),sendingPrompts:_c(n.sendingPrompts,e.tempId),clientQueuedSessionMessages:_c(n.clientQueuedSessionMessages,e.tempId)}),!r)return;this.clearActiveSession();let i={machineId:e.machineId,projectId:e.originWorkspace.projectId,workspaceId:e.workspaceId,sessionId:e.tempId};(this.isPendingSessionStartRouteCurrent?.(i)??!0)&&this.updateUrl({replace:!0})}failPendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.discarded;n.discarded=!0,this.getState().selectedSession?.id===e&&this.socket.close();let i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId),a=this.isCurrentPendingStart(n);if(r){a&&this.applyReleasedCreatedSessions(i,n.machineId);return}let o=kc(t),s=D(`client.sessionController.failed.to.start.session.881118`,`Failed to start session: {value1}`,{value1:o});if(!a){this.browserErrors.report(Gn(n.machineId,n.originWorkspace.projectId,n.originWorkspace.id),s);return}let c=this.getState(),l=Cc(e,o,n.queuedSends.length),u=c.sessions.some(t=>t.id===e);this.setState({sessions:u?c.sessions:[n.session,...c.sessions],sessionActivities:{...c.sessionActivities,[e]:l},activity:c.selectedSession?.id===e?l:c.activity,...c.selectedSession?.id===e?{pendingDialogs:[]}:{}}),this.reportSessionError(n.session,n.machineId,s,this.captureSessionErrorOwner(n.session,n.originWorkspace)),this.applyReleasedCreatedSessions(i,n.machineId)}isCurrentPendingStart(e){let t=this.getState();return M(t)===e.machineId&&t.selectedWorkspace?.id===e.workspaceId&&t.selectedWorkspace.projectId===e.originWorkspace.projectId}hasPendingStartFor(e,t){return Array.from(this.pendingSessionStarts.values()).some(n=>n.cwd===e&&n.machineId===t)}isSuppressedCreatedSession(e,t){let n=this.suppressedCreatedSessions.get(e.id);return n?.session.cwd===e.cwd&&n.machineId===t}takeSuppressedCreatedSessionsFor(e,t,n){if(n!==void 0&&this.suppressedCreatedSessions.delete(n),this.hasPendingStartFor(e,t))return[];let r=[];for(let[n,i]of this.suppressedCreatedSessions)i.session.cwd===e&&i.machineId===t&&(this.suppressedCreatedSessions.delete(n),r.push(i.session));return r}applyReleasedCreatedSessions(e,t){if(e.length===0||M(this.getState())!==t)return;let n=this.getState();if(n.selectedWorkspace===void 0)return;let r=new Set(n.sessions.map(e=>e.id)),i=e.filter(e=>e.cwd===n.selectedWorkspace?.path&&!r.has(e.id));i.length!==0&&this.setState({sessions:[...i.reverse(),...n.sessions]})}mergePendingStartSessions(e,t,n){let r=this.getState().sessions.filter(t=>I(t)&&t.cwd===e&&t.machineId===n);if(r.length===0)return t;let i=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!i.has(e.id))]}async recreateCachedNewSession(e,t,n=this.selectionSeq,r=this.captureSessionErrorOwner(e)){let i=M(this.getState()),a=this.navigationSelection();try{let r=await this.api.startSession(e.cwd,i);if(!this.isCurrentSessionSelection(e.id,i,n)||!this.isSelectedSessionScope(e,i)||!Nc(t?.navigation))return;Yr(r,i),Va(j(i,e.id),j(i,r.id)),qa(j(i,e.id),j(i,r.id)),Zr(e.id,i);let o=Xr(r,i);if(this.setState({sessions:[o,...this.getState().sessions.filter(t=>t.id!==e.id&&t.id!==r.id)],error:``}),this.navigateToSession!==void 0){let r=this.navigationSelection();!await this.navigateToSession(o,{...t?.updateUrl===!1?{replace:!0}:{},expected:{...a,tool:r.tool,view:r.view}})&&this.isCurrentSessionSelection(e.id,i,n)&&this.clearActiveSession()}else await this.selectSession(o,{updateUrl:!1}),this.updateUrl(t?.updateUrl===!1?{replace:!0}:void 0)}catch(t){this.reportSessionError(e,i,t,r)}}markCachedNewSessionPersisted(e){if(!$r(e))return;let t=this.getState().sessions.find(t=>t.id===e.id)??e;this.replaceSession(ei(t))}async applyCommandResult(e,t){if(e.type===`select`){this.setState({commandDialog:e});return}if(e.type===`tree`){this.setState({treeDialog:e.tree});return}let n=(e.type,e.message);if(n!==void 0&&n!==``&&this.setState({messages:[...this.getState().messages,ui(e.type===`unsupported`?`system`:`tool`,n)]}),e.type===`done`&&e.session){e.promptDraft!==void 0&&za(this.sessionCacheKey(e.session.id),e.promptDraft);let n=this.getState().selectedSession,r=[e.session,...this.getState().sessions.filter(t=>t.id!==e.session?.id)];if(this.setState({sessions:r,...n?.id===e.session.id?{selectedSession:e.session}:{}}),n?.id===e.session.id||!this.navigationSelectionMatchesState(t))return;this.navigateToSession===void 0?await this.selectSession(e.session):await this.navigateToSession(e.session,{expected:t})}}applyCreatedSession(e){let t=this.getState();if(t.selectedWorkspace?.path!==e.cwd||t.sessions.some(t=>t.id===e.id))return;let n=M(t);this.hasPendingStartFor(e.cwd,n)?this.suppressedCreatedSessions.set(e.id,{session:e,machineId:n}):this.setState({sessions:[e,...t.sessions]})}applyActivity(e){this.setState({sessionActivities:{...this.getState().sessionActivities,[e.sessionId]:e},activity:this.getState().selectedSession?.id===e.sessionId?e:this.getState().activity})}applyStatus(e){let t=this.getState(),n=t.selectedSession?.id===e.sessionId,r=t.sessionActivities[e.sessionId]?.phase===`active`&&!rr(e);this.setState({sessionStatuses:{...t.sessionStatuses,[e.sessionId]:e},...Ac(t,e.sessionId,e.messageCount),...r?{sessionActivities:gc(t.sessionActivities,e.sessionId)}:{},status:n?e:t.status,activity:n&&r?void 0:t.activity,...n?{pendingDialogs:e.pendingDialogs??[]}:{}})}applyOpenedDialog(e){let t=this.getState();t.selectedSession===void 0||t.pendingDialogs.some(t=>t.dialogId===e.dialogId)||this.setState({pendingDialogs:[...t.pendingDialogs,e]})}applyClosedDialog(e,t,n){let r=this.getState().pendingDialogs.find(t=>t.dialogId===e);r!==void 0&&this.recordClosedDialog({dialog:r,reason:t,...n===void 0?{}:{answer:n}})}recordClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e.dialog.dialogId)||this.setState({pendingDialogs:t.pendingDialogs.filter(t=>t.dialogId!==e.dialog.dialogId),closedDialogs:[...t.closedDialogs,e]})}dismissClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e)&&this.setState({closedDialogs:t.closedDialogs.filter(t=>t.dialog.dialogId!==e)})}applySessionName(e,t){let n=n=>{if(n.id!==e)return n;let r={...n};return t===void 0||t===``?delete r.name:r.name=t,r},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(n),selectedSession:r===void 0?void 0:n(r)})}applyEvent(e){if(e.type===`session.diagnostic`){console.warn(e.message);return}if(e.type===`notifications.inbox`){this.notifications?.applyInboxEvent(M(this.getState()),e);return}if(e.type===`command.output`&&this.notifications?.shouldFilterLegacyNotification(M(this.getState()),e.notificationId)===!0)return;let t=this.refreshEventBuffer;if(t!==void 0&&this.isCurrentRefreshTarget(t.target)){t.events.push(e);return}if(this.isStreamEventBelowWatermark(e))return;if(e.type===`session.tree.changed`){this.invalidateSessionTree();return}if(e.type===`status.update`){this.queueStatusUpdate(e.status);return}if(e.type===`activity.update`){this.queueActivityUpdate(e.activity);return}if(jc(e)){this.queueTranscriptEvent(e);return}if(this.flushPendingUpdates(),e.type===`dialog.opened`){this.applyOpenedDialog(e.dialog);return}if(e.type===`dialog.closed`){this.applyClosedDialog(e.dialogId,e.reason,e.answer);return}let n=this.transcripts.applyLiveEvent(this.getState().messages,e);n?this.setState({messages:n}):e.type===`session.name`&&this.applySessionName(e.sessionId,e.name)}queueTranscriptEvent(e){this.pendingTranscriptEvents.push(e),this.schedulePendingFlush()}queueStatusUpdate(e){this.pendingStatusBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueActivityUpdate(e){this.pendingActivityBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueStartupProgress(e){if(this.getState().sessions.some(t=>t.id===e.activity.sessionId)){this.queueActivityUpdate(e.activity);return}let t=e.startupToken===void 0?void 0:this.pendingSessionStarts.get(e.startupToken);t===void 0||t.discarded||(this.learnPendingStartBackendSession(t,e.activity.sessionId),this.queueActivityUpdate(e.activity.phase===`idle`?Sc(t.tempId,t.queuedSends.length):xc(e.activity,t.tempId)))}learnPendingStartBackendSession(e,t){t!==``&&e.backendSessionId===void 0&&(e.backendSessionId=t,this.getState().selectedSession?.id===e.tempId&&this.connectPendingStartSocket(e))}connectPendingStartSocket(e){let t=e.backendSessionId;if(t===void 0||e.discarded)return;let n={id:t,cwd:e.cwd};this.socket.connect(n,t=>{this.applyPendingStartEvent(e,t)},()=>{this.resyncPendingStartDialogs(e)},e.machineId),this.resyncPendingStartDialogs(e)}resyncPendingStartDialogs(e){let t=e.backendSessionId;t!==void 0&&this.api.status({id:t,cwd:e.cwd},e.machineId).then(t=>{if(e.discarded||this.getState().selectedSession?.id!==e.tempId)return;this.applyStatus(t);let n=this.getState(),r=new Set([...n.pendingDialogs.map(e=>e.dialogId),...n.closedDialogs.map(e=>e.dialog.dialogId)]),i=(t.pendingDialogs??[]).filter(e=>!r.has(e.dialogId));i.length>0&&this.setState({pendingDialogs:[...n.pendingDialogs,...i]})},()=>void 0)}applyPendingStartEvent(e,t){e.discarded||this.getState().selectedSession?.id!==e.tempId||(t.type===`dialog.opened`?this.applyOpenedDialog(t.dialog):t.type===`dialog.closed`?this.applyClosedDialog(t.dialogId,t.reason,t.answer):t.type===`status.update`&&this.applyPendingStartStatus(e,t.status))}applyPendingStartStatus(e,t){this.applyStatus(t),!(e.discarded||this.getState().selectedSession?.id!==e.tempId)&&this.setState({pendingDialogs:t.pendingDialogs??[]})}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){if(this.pendingTranscriptEvents.length>0){let e=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let t=this.getState().messages;for(let n of e)t=this.transcripts.applyLiveEvent(t,n)??t;t!==this.getState().messages&&this.setState({messages:t})}if(this.pendingActivityBySession.size>0){let e=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(let t of e)this.applyActivity(t)}if(this.pendingStatusBySession.size>0){let e=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(let t of e)this.applyStatus(t)}}clearPendingUpdates(){this.refreshEventBuffer=void 0,this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=void 0)}isStreamEventBelowWatermark(e){if(e.type===`session.name`||e.type===`session.error`||e.type===`command.output`||e.type===`session.tree.changed`)return!1;let t=this.streamWatermark;return t===void 0||t.sessionId!==this.getState().selectedSession?.id?!1:e.seq!==void 0&&e.seq<=t.seq}async selectSearchMatch(e,t,n){await this.selectSessionAfterNavigation(e,this.navigationSelection());let r=M(this.getState()),i=this.captureSessionErrorOwner(e),a=this.selectionSeq;try{for(;this.isCurrentSearchJump(e.id,r,a)&&this.getState().messagePageStart>t.messageIndex;){let t=this.getState().messagePageStart,n=await this.api.messages(e,{before:t,limit:uc},r);if(!this.isCurrentSearchJump(e.id,r,a))return;let i=this.transcripts.mergeHistory(this.sessionCacheKey(e.id),n);if(this.setState(i),i.messagePageStart>=t)break}}catch(t){this.reportSessionError(e,r,t,i);return}this.isCurrentSearchJump(e.id,r,a)&&this.setState({...this.transcripts.indexedView(this.sessionCacheKey(e.id)),sessionSearchTarget:{sessionId:e.id,messageIndex:t.messageIndex,query:n,requestId:++this.searchTargetSeq}})}isCurrentSearchJump(e,t,n){return this.selectionSeq===n&&M(this.getState())===t&&this.getState().selectedSession?.id===e}};function hc(e){return JSON.stringify(e.partial??null)}function gc(e,t){return _c(e,t)}function _c(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function vc(e,t){if(t.length===0)return e;let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function yc(e,t,n){if(t===n||!(t in e))return e;let r=e[t];return r===void 0?e:{..._c(e,t),[n]:r}}function bc(e,t,n){let r=[],i=!1;for(let a of e)a.id===t?i||=(r.push(n),!0):a.id!==n.id&&r.push(a);return i?r:[n,...r]}function I(e){return e!==void 0&&`clientPendingStart`in e&&e.clientPendingStart===!0}function xc(e,t){return{sessionId:t,phase:e.phase,label:e.label,...e.detail===void 0?{}:{detail:e.detail},at:e.at}}function Sc(e,t=0){return{sessionId:e,phase:`active`,label:D(`activity.creating`,`Creating session`),detail:t>0?D(`client.sessionController.will.send.queued.messages.when.the.backend.session.is.ready.f49381`,`Will send {value1} queued messages when the backend session is ready`,{value1:String(t)}):D(`client.sessionController.waiting.for.the.backend.session.3a8a3d`,`Waiting for the backend session`),at:new Date().toISOString()}}function Cc(e,t,n=0){let r=n>0?D(`client.sessionController.queued.messages.retained.below.2194c6`,` · {value1} queued messages retained below`,{value1:String(n)}):``;return{sessionId:e,phase:`error`,label:D(`client.sessionController.session.creation.failed.aff35c`,`Session creation failed`),detail:`${t}${r}`,at:new Date().toISOString()}}function wc(e){if(e.type===`prompt`){let t=e.attachments?.length??0;return{kind:e.streamingBehavior===`steer`?`steer`:`followUp`,text:Tc(e.text,e.attachments),...t>0?{hasAttachments:!0,attachmentCount:t}:{}}}return{kind:`followUp`,text:e.text}}function Tc(e,t){let n=Ec(t);return n===void 0?e:e.trim()===``?n:`${e}\n\n${n}`}function Ec(e){if(e===void 0||e.length===0)return;let t=e.map(e=>e.name?.trim()).filter(e=>e!==void 0&&e!==``),n=e.length,r=D(`client.sessionController.attachments.092014`,`{value1} attachments`,{value1:String(n)});if(t.length===0)return D(`client.sessionController.queued.6fc044`,`[Queued {value1}]`,{value1:r});let i=t.slice(0,3).join(`、`),a=t.length>3?D(`client.sessionController.plus.more.675fd5`,`, plus {value1} more`,{value1:String(t.length-3)}):``;return D(`client.sessionController.queued.871266`,`[Queued {value1}: {value2}{value3}]`,{value1:r,value2:i,value3:a})}function Dc(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function Oc(e){return e.map(e=>`${e.sessionId}: ${e.error}`)}function kc(e){return e instanceof Error?e.message:String(e)}function Ac(e,t,n){if(n===void 0)return{};let r=e.sessions.some(e=>e.id===t&&e.messageCount!==n)?e.sessions.map(e=>e.id===t?{...e,messageCount:n}:e):void 0,i=e.selectedSession?.id===t&&e.selectedSession.messageCount!==n?{...e.selectedSession,messageCount:n}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...i===e.selectedSession?{}:{selectedSession:i}}}function jc(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`||e.type===`shell.chunk`}function Mc(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`session not found`)||t.includes(D(`session.notFound`,`Session not found`))}function Nc(e){return e===void 0||e.isCurrent()}var Pc=class{constructor(){this.active=new Map,this.revisions=new Map,this.generation=0}observe(e,t){let n=t.type===`status.update`?t.status.sessionId:t.activity.sessionId,r=JSON.stringify([e,n]);this.revisions.set(r,(this.revisions.get(r)??0)+1);let i=this.active.get(r),a={statusActive:i?.statusActive??!1,activityActive:i?.activityActive??!1};if(t.type===`status.update`?(a.statusActive=rr(t.status),a.statusActive||(a.activityActive=!1)):a.activityActive=rr(void 0,t.activity),a.statusActive||a.activityActive)this.active.set(r,a);else return this.active.delete(r),i===void 0?void 0:n}snapshotObserver(e,t){let n=JSON.stringify([e,t]),r=this.revisions.get(n),i=this.generation;return a=>{if(a.sessionId===t&&i===this.generation&&this.revisions.get(n)===r)return this.observe(e,{type:`status.update`,status:a})}}clear(){this.active.clear(),this.revisions.clear(),this.generation+=1}};async function Fc(e){let t=await Promise.allSettled(e),n=[];for(let e of t)e.status===`rejected`&&n.push(e.reason);if(n.length===1)throw n[0];if(n.length>1)throw AggregateError(n,n.map(e=>e instanceof Error?e.message:String(e)).join(`; `))}var Ic={order:0,overflowWatermark:0};function Lc(e){return{...e,status:`loading`,catalogRevision:0,notifications:[],dismissThrough:Ic,optimisticDismissedIds:[],announcements:[]}}function Rc(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)throw Error(`Notification inbox snapshot does not match the selected session`);let r=e!==void 0&&Qc(e,t)&&e.daemonInstanceId===n.daemonInstanceId;return{...t,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:n.notifications,dismissThrough:n.dismissThrough,optimisticDismissedIds:r?e.optimisticDismissedIds:[],...r&&e.optimisticDismissAllThrough!==void 0?{optimisticDismissAllThrough:e.optimisticDismissAllThrough}:{},announcements:r?e.announcements:[]}}function zc(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)return{value:e??Lc(t),needsRefresh:!1,changed:!1};if(e===void 0||!Qc(e,t))return{value:el(t),needsRefresh:!0,changed:!0};if(e.daemonInstanceId!==n.daemonInstanceId)return{value:el(t),needsRefresh:!0,changed:e.status!==`stale`||e.daemonInstanceId!==void 0||e.notifications.length>0};let r=e.summary?.inboxRevision??0;if(n.summary.inboxRevision<=r)return{value:e,needsRefresh:!1,changed:!1};if(e.status!==`fresh`||n.summary.inboxRevision!==r+1||n.delta.kind===`resync`)return{value:{...e,status:`stale`},needsRefresh:!0,changed:e.status!==`stale`};let i,a;switch(n.delta.kind){case`added`:{let t=n.delta;if(e.notifications.some(e=>e.id===t.notification.id))return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};i=[t.notification,...e.notifications].filter(e=>e.id!==t.evictedNotificationId).sort((e,t)=>t.order-e.order).slice(0,100),a={id:`${n.daemonInstanceId}:${String(n.summary.inboxRevision)}:${t.notification.id}`,severity:t.notification.severity,message:t.notification.message};break}case`dismissed`:{let t=new Set(n.delta.notificationIds);i=e.notifications.filter(e=>!t.has(e.id));break}case`cleared`:i=[]}let o=i[0]?.order??0;if(!tl(i,n.summary)||n.dismissThrough.order!==o||n.dismissThrough.overflowWatermark<n.summary.discardedCount)return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};let s=a===void 0?e.announcements:[...e.announcements,a].slice(-100);return{value:{...e,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:i,dismissThrough:n.dismissThrough,announcements:s},needsRefresh:!1,changed:!0}}function Bc(e){if(e?.status!==`fresh`||e.daemonInstanceId===void 0||e.summary===void 0)return;let t=new Set(e.optimisticDismissedIds),n=e.optimisticDismissAllThrough,r=e.notifications.filter(e=>!t.has(e.id)&&(n===void 0||e.order>n.order)),i=rl(e.summary.discardedCount,e.dismissThrough.overflowWatermark,n?.overflowWatermark);return r.length===0&&t.size>0&&(i=0),{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd,daemonInstanceId:e.daemonInstanceId,notifications:r,retainedCount:r.length,discardedCount:i,...il(nl(r)),dismissThrough:e.dismissThrough,pendingDismissedIds:t,dismissAllPending:n!==void 0,announcements:e.announcements}}function Vc(e){return e===`error`?D(`client.sessionNotifications.error.0bc1fb`,`Error`):e===`warning`?D(`client.sessionNotifications.warning.a8b7a4`,`Warning`):D(`client.sessionNotifications.info.e70286`,`Info`)}function Hc(e){return D(`client.sessionNotifications.notification.received.0cb785`,`{value1} notification received.`,{value1:Vc(e.severity)})}function Uc(e){return e.retainedCount+e.discardedCount}function Wc(e){return D(`client.sessionNotifications.notifications.38c528`,`Notifications ({value1})`,{value1:String(Uc(e))})}function Gc(e){let t=e.message.replace(/\s+/gu,` `).trim();if(t===``)return D(`client.sessionNotifications.dismiss.notification.137f92`,`Dismiss {value1} notification`,{value1:Vc(e.severity)});let n=Array.from(t),r=n.length<=80?t:`${n.slice(0,79).join(``).trimEnd()}…`;return D(`client.sessionNotifications.dismiss.notification.600367`,`Dismiss notification: {value1}`,{value1:r})}function Kc(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1)return{kind:`header`};let r=e[n+1];if(r!==void 0)return{kind:`notification`,notificationId:r.id};let i=e[n-1];return i===void 0?{kind:`header`}:{kind:`notification`,notificationId:i.id}}function qc(e){return JSON.stringify([e.machineId,e.cwd,e.sessionId])}function Jc(e,t){return e.has(qc(t))}function Yc(e,t,n){let r=new Set(e),i=qc(t);return n?r.add(i):r.delete(i),r}function Xc(e){return D(`client.sessionNotifications.older.notifications.not.shown.7c54ee`,`{value1} older notifications not shown.`,{value1:String(e)})}function Zc(e){if(!e.truncated)return;let t=Lt/1024;return D(`client.sessionNotifications.message.truncated.at.kib.ac3119`,`Message truncated at {value1} KiB.`,{value1:String(t)})}function Qc(e,t){return e.machineId===t.machineId&&e.sessionId===t.sessionId&&e.cwd===t.cwd}function $c(e,t){if(e===`error`||t===`error`)return`error`;if(e===`warning`||t===`warning`)return`warning`;if(e===`info`||t===`info`)return`info`}function el(e){return{...Lc(e),status:`stale`}}function tl(e,t){return e.length===t.retainedCount&&nl(e)===t.highestSeverity}function nl(e){let t;for(let n of e)t=$c(t,n.severity);return t}function rl(e,t,n){if(e===0||n===void 0)return e;let r=t-e+1;return e-Math.max(0,Math.min(e,n-r+1))}function il(e){return e===void 0?{}:{highestSeverity:e}}var al=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.acceptedSupportByMachine=new Set,this.selectedGeneration=0,this.dismissingNotificationIds=new Set,this.dismissAllPending=!1,this.disposed=!1,this.api=n.api??x,this.onBackgroundError=n.onBackgroundError??((e,t)=>{console.warn(e,t)})}dispose(){this.disposed=!0,this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.acceptedSupportByMachine.clear(),this.dismissingNotificationIds.clear(),this.dismissAllPending=!1}prepareSelectedSession(e,t){this.selectedGeneration+=1,this.selectedTarget=e.archived===!0?void 0:{machineId:t,sessionId:e.id,cwd:e.cwd},this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.selectedTarget===void 0||!this.machineSupportsNotifications(t)?this.setState({selectedNotificationInbox:void 0}):this.setState({selectedNotificationInbox:Lc(this.selectedTarget)})}clearSelectedSession(){this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.setState({selectedNotificationInbox:void 0})}refreshSelectedSession(e,t){let n=this.selectedTarget;if(this.disposed||n?.machineId!==t||n.sessionId!==e.id||n.cwd!==e.cwd||!this.machineSupportsNotifications(t)||!this.machineIsReachable(t))return Promise.resolve();let r=this.selectedGeneration,i=this.selectedRefresh;if(i?.generation===r)return i.trailing=!0,i.promise;this.ensureSelectedProjection(n);let a={generation:r,promise:Promise.resolve(),trailing:!1};return a.promise=this.runSelectedRefresh(a,n).finally(()=>{this.selectedRefresh===a&&(this.selectedRefresh=void 0)}),this.selectedRefresh=a,a.promise}applyInboxEvent(e,t){let n=this.selectedTarget;if(n?.machineId!==e||n.sessionId!==t.summary.sessionId||n.cwd!==t.summary.cwd)return;this.acceptedSupportByMachine.add(e);let r=this.selectedJoin;if(r?.generation===this.selectedGeneration){r.events.push(t);return}let i=zc(this.getState().selectedNotificationInbox,n,t);i.changed&&this.setState({selectedNotificationInbox:i.value}),i.needsRefresh&&this.scheduleSelectedRefresh(n)}syncEnvironment(e,t){if(this.disposed)return;e.machines!==t.machines&&this.pruneRemovedMachines(t.machines);let n=e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||e.machineRuntimes!==t.machineRuntimes,r=this.selectedTarget;if(!n||r===void 0)return;let i=this.machineSupportsNotificationsInState(e,r.machineId)&&this.machineIsReachableInState(e,r.machineId);!this.machineSupportsNotifications(r.machineId)||!this.machineIsReachable(r.machineId)?this.markSelectedStale(r):(this.ensureSelectedProjection(r),i&&this.getState().selectedNotificationInbox?.status===`fresh`||this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId))}shouldFilterLegacyNotification(e,t){return t!==void 0&&t!==``&&this.machineSupportsNotifications(e)}async dismissNotification(e){let t=this.getState().selectedNotificationInbox,n=Bc(t);if(t===void 0||n===void 0||this.dismissAllPending||this.dismissingNotificationIds.has(e)||!n.notifications.some(t=>t.id===e))return;let r=ol(t),i=this.selectedGeneration;this.dismissingNotificationIds.add(e),this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:[...new Set([...t.optimisticDismissedIds,e])]}));try{let t=await this.api.dismissNotification({id:r.sessionId,cwd:r.cwd},n.daemonInstanceId,e,r.machineId);this.isCurrentTarget(r,i)&&this.applyMutationSnapshot(r,t,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)}))}catch(t){this.isCurrentTarget(r,i)&&(this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)})),this.setState({error:D(`client.sessionNotificationController.failed.to.dismiss.notification.080d8f`,`Failed to dismiss notification: {value1}`,{value1:cl(t)})}),await this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId))}finally{this.dismissingNotificationIds.delete(e)}}async dismissAll(){let e=this.getState().selectedNotificationInbox,t=Bc(e);if(e===void 0||t===void 0||this.dismissAllPending||t.retainedCount+t.discardedCount===0)return;let n=ol(e),r=this.selectedGeneration,i={...e.dismissThrough};this.dismissAllPending=!0,this.patchSelectedOverlay(n,e=>({...e,optimisticDismissAllThrough:i}));try{let e=await this.api.dismissAllNotifications({id:n.sessionId,cwd:n.cwd},t.daemonInstanceId,i,n.machineId);this.isCurrentTarget(n,r)&&this.applyMutationSnapshot(n,e,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t})}catch(e){this.isCurrentTarget(n,r)&&(this.patchSelectedOverlay(n,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t}),this.setState({error:D(`client.sessionNotificationController.failed.to.dismiss.session.notifications.5621de`,`Failed to dismiss session notifications: {value1}`,{value1:cl(e)})}),await this.refreshSelectedSession({id:n.sessionId,cwd:n.cwd},n.machineId))}finally{r===this.selectedGeneration&&(this.dismissAllPending=!1)}}async runSelectedRefresh(e,t){do{e.trailing=!1;let n={generation:e.generation,events:[]};this.selectedJoin=n;try{let r=await this.api.notificationInbox({id:t.sessionId,cwd:t.cwd},t.machineId);if(!this.isCurrentTarget(t,e.generation))return;if(!this.machineSupportsNotifications(t.machineId)||!this.machineIsReachable(t.machineId)){this.markSelectedStale(t);return}this.acceptedSupportByMachine.add(t.machineId);let i=this.getState().selectedNotificationInbox,a=i===void 0||sl(i,t,r)?Rc(i,t,r):i;for(let r of[...n.events].sort((e,t)=>e.summary.inboxRevision-t.summary.inboxRevision)){let n=zc(a,t,r);a=n.value,n.needsRefresh&&(e.trailing=!0)}this.setState({selectedNotificationInbox:a})}catch(n){if(this.isCurrentTarget(t,e.generation)){let e=this.getState().selectedNotificationInbox;e!==void 0&&Qc(e,t)&&e.status!==`stale`&&this.setState({selectedNotificationInbox:{...e,status:`stale`}}),this.onBackgroundError(`Failed to refresh notifications for session ${t.sessionId}`,n)}return}finally{this.selectedJoin===n&&(this.selectedJoin=void 0)}}while(e.trailing&&this.isCurrentTarget(t,e.generation)&&this.machineIsReachable(t.machineId))}applyMutationSnapshot(e,t,n){let r=this.getState().selectedNotificationInbox;if(r===void 0||!Qc(r,e))return;if(!this.machineSupportsNotifications(e.machineId)||!this.machineIsReachable(e.machineId)){this.setState({selectedNotificationInbox:{...n(r),status:`stale`}});return}let i=sl(r,e,t)?Rc(r,e,t):r;this.setState({selectedNotificationInbox:n(i)})}patchSelectedOverlay(e,t){let n=this.getState().selectedNotificationInbox;n!==void 0&&Qc(n,e)&&this.setState({selectedNotificationInbox:t(n)})}ensureSelectedProjection(e){let t=this.getState().selectedNotificationInbox;t!==void 0&&Qc(t,e)||this.setState({selectedNotificationInbox:Lc(e)})}scheduleSelectedRefresh(e){queueMicrotask(()=>{!this.disposed&&this.selectedTarget!==void 0&&Qc(this.selectedTarget,e)&&this.refreshSelectedSession({id:e.sessionId,cwd:e.cwd},e.machineId)})}markSelectedStale(e){let t=this.getState().selectedNotificationInbox;t!==void 0&&Qc(t,e)&&t.status!==`stale`&&this.setState({selectedNotificationInbox:{...t,status:`stale`}})}pruneRemovedMachines(e){let t=new Set(e.map(e=>e.id));t.size===0&&t.add(`local`);for(let e of[...this.acceptedSupportByMachine])t.has(e)||this.acceptedSupportByMachine.delete(e)}isCurrentTarget(e,t){return!this.disposed&&t===this.selectedGeneration&&this.selectedTarget!==void 0&&Qc(this.selectedTarget,e)}machineSupportsNotifications(e){return this.machineSupportsNotificationsInState(this.getState(),e)}machineSupportsNotificationsInState(e,t){return this.acceptedSupportByMachine.has(t)||e.machineRuntimes[t]?.ok===!0}machineIsReachable(e){return this.machineIsReachableInState(this.getState(),e)}machineIsReachableInState(e,t){let n=e.machines.find(e=>e.id===t);if(t===`local`||n?.kind===`local`)return!0;let r=e.machineStatuses[t]?.status??n?.status;return r===void 0||r===`unknown`||r===`online`}};function ol(e){return{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd}}function sl(e,t,n){return!Qc(e,t)||e.daemonInstanceId!==n.daemonInstanceId||e.summary===void 0||n.summary.inboxRevision>=e.summary.inboxRevision}function cl(e){return e instanceof Error?e.message:String(e)}function ll(e){return e?.status!==`folder`}var ul=class{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}},dl=`pi-web:workspace-selection:v1`,fl=class{constructor(e=Vs()){this.workspaceIdsByProject=new Hs(dl,Us,e)}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}};function pl(e,t){let n=t?.targetWorkspaceId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestWorkspaceId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e[0]:e[0]}var ml=50,hl=[`machine`,`project`,`workspace`,`session`],gl=class{constructor(e,t,n,r,i=new ul,a={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessions=r,this.workspaceSelection=i,this.workspaceListRequests=new Map,this.api=a.api??x,this.navigateToWorkspace=a.navigateToWorkspace,this.captureNavigation=a.captureNavigation,this.beginNavigationOperation=a.beginNavigationOperation,this.onBackgroundError=a.onBackgroundError??((e,t)=>{console.warn(e,t)}),this.browserErrors=new $n(e,t),this.topologyRefreshes=new gr(a.topologyRefreshDebounceMs??ml)}clearSelection(e){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,workspaceResolution:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...Hn()}),e?.updateUrl!==!1&&this.updateUrl()}forgetProject(e){let t=M(this.getState());this.browserErrors.discard(Wn(t,e)),this.workspaceSelection.forgetProject(hr(t,e));let n=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([t])=>t!==e));this.setState({workspacesByProjectId:n})}async selectProject(e,t){let n=t?.navigation??this.beginNavigationOperation?.(hl);if(!this.navigationIsCurrent(n)||!vl(t))return;let r=M(this.getState()),i=Wn(r,e.id);this.sessions.clearActiveSession(),this.setState({selectedProject:e,workspaceResolution:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...Hn()});let a=this.beginWorkspaceListRequest(e.id,r);try{let o=t?.signal===void 0?await this.api.workspaceResolution(e.id,r):await this.api.workspaceResolution(e.id,r,{signal:t.signal}),s=[...o.workspaces];if(!a()||!this.navigationIsCurrent(n)||!vl(t)||M(this.getState())!==r||this.getState().selectedProject?.id!==e.id)return;if(this.setState({workspaceResolution:o,workspaces:s,workspacesByProjectId:{...this.getState().workspacesByProjectId,[e.id]:s},isLoadingWorkspaces:!1}),o.status===`degraded`)throw Sl(o);let c=pl(s,{targetWorkspaceId:t?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(hr(r,e.id))});if(c)return await this.selectWorkspace(c,{...t,sessionId:t?.sessionId,updateUrl:t?.updateUrl,navigation:n});if(t?.workspaceId!==void 0&&t.workspaceId!==``)return this.browserErrors.report(i,D(`ui.main.06529052d1e0`,`Workspace not found: {arg0}`,{arg0:t.workspaceId})),D(`ui.main.06529052d1e0`,`Workspace not found: {arg0}`,{arg0:t.workspaceId});t?.updateUrl!==!1&&this.navigationIsCurrent(n)&&this.updateUrl()}catch(a){return this.navigationIsCurrent(n)&&vl(t)&&M(this.getState())===r&&this.getState().selectedProject?.id===e.id&&this.setState({isLoadingWorkspaces:!1}),t?.signal?.aborted!==!0&&this.browserErrors.report(i,String(a)),String(a)}}async selectWorkspace(e,t){let n=t?.navigation??this.beginNavigationOperation?.(hl);if(!this.navigationIsCurrent(n)||!vl(t))return;let r=M(this.getState()),i=Gn(r,e.projectId,e.id);this.workspaceSelection.rememberWorkspace({...e,projectId:hr(r,e.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:e,isLoadingWorkspaces:!1,...Hn()});try{let a=t?.signal===void 0?await this.api.sessions(e.path,r):await this.api.sessions(e.path,r,{signal:t.signal}),o=Qr(e.path,a,r);if(!this.navigationIsCurrent(n)||!vl(t)||M(this.getState())!==r||this.getState().selectedWorkspace?.id!==e.id||this.getState().selectedProject?.id!==e.projectId)return;this.setState({sessions:o});let s=this.sessions.preferredSession(e.path,o,t?.sessionId);if(!this.navigationIsCurrent(n)||!vl(t))return;if(s)await this.sessions.selectSession(s,{deferChatLoading:!0,updateUrl:t?.updateUrl,...n===void 0?{}:{navigation:n}});else if(t?.sessionId!==void 0&&t.sessionId!==``)return this.browserErrors.report(i,D(`ui.main.0041c3cf98cd`,`Session not found: {arg0}`,{arg0:t.sessionId})),D(`ui.main.0041c3cf98cd`,`Session not found: {arg0}`,{arg0:t.sessionId});else t?.updateUrl!==!1&&this.updateUrl()}catch(e){return t?.signal?.aborted!==!0&&this.browserErrors.report(i,String(e)),String(e)}}async refreshProjectWorkspaces(e,t=M(this.getState()),n){return(await this.refreshProjectWorkspaceList(e,t,n)).workspaces}async refreshProjectWorkspaceList(e,t,n){if(!vl(n))return{workspaces:[],isCurrent:()=>!1};let r=this.getState().projects.find(t=>t.id===e);if(r===void 0)throw Error(D(`client.workspaceController.project.not.found.3b6bf4`,`Project not found`));let i=this.beginWorkspaceListRequest(e,t),a=n?.signal===void 0?await this.api.workspaceResolution(r.id,t):await this.api.workspaceResolution(r.id,t,{signal:n.signal}),o=[...a.workspaces];if(i()&&vl(n)&&M(this.getState())===t){if(this.getState().selectedProject?.id===r.id&&this.setState({workspaceResolution:a}),a.status===`degraded`)throw Sl(a);this.applyProjectWorkspaces(r.id,o)}return{workspaces:o,isCurrent:i}}async refreshSelectedProjectTopology(){let e=this.getState(),t=e.selectedProject;if(t===void 0||e.isLoadingWorkspaces)return;let n=M(e);await this.topologyRefreshes.request(hr(n,t.id),async()=>{if(this.getState().isLoadingWorkspaces)return;let e=this.beginWorkspaceListRequest(t.id,n);try{let r=await this.api.workspaceResolution(t.id,n),i=this.getState();if(!e()||M(i)!==n||i.selectedProject?.id!==t.id)return;if(this.setState({workspaceResolution:r}),r.status===`degraded`)throw Sl(r);this.applyProjectWorkspaces(t.id,[...r.workspaces])}catch(e){this.onBackgroundError(`Failed to refresh workspaces for project ${t.id} on ${n}`,e)}})}async refreshAfterWorkspaceDeleted(e,t,n=M(this.getState()),r){if(!vl(r))return;let i=this.beginNavigationOperation?.(hl),{workspaces:a,isCurrent:o}=await this.refreshProjectWorkspaceList(e,n,r);if(!o()||!this.navigationIsCurrent(i)||!vl(r))return;let s=this.getState();if(M(s)!==n||s.selectedProject?.id!==e||s.selectedWorkspace?.id!==t)return;let c=_l(this.getState(),this.captureNavigation),l=yl(a);this.navigateToWorkspace===void 0?l===void 0?this.navigationIsCurrent(i)&&vl(r)&&this.clearSelection():await this.selectWorkspace(l,{...r,...i===void 0?{}:{navigation:i}}):await this.navigateToWorkspace(l,{expected:c})}beginWorkspaceListRequest(e,t){let n=hr(t,e),r=(this.workspaceListRequests.get(n)??0)+1;return this.workspaceListRequests.set(n,r),()=>this.workspaceListRequests.get(n)===r}applyProjectWorkspaces(e,t){let n=this.getState(),r={...n.workspacesByProjectId,[e]:t};n.selectedProject?.id===e?this.setState({workspaces:t,workspacesByProjectId:r,...this.refreshedSelection(n.selectedWorkspace,t)}):this.setState({workspacesByProjectId:r})}refreshedSelection(e,t){if(e===void 0)return;let n=t.find(t=>t.id===e.id);if(!(n===void 0||bl(e,n)))return{selectedWorkspace:n}}navigationIsCurrent(e){return e===void 0||e.isCurrent()}};function _l(e,t){return t?.()??{machineId:M(e),projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,...e.selectedSession===void 0||Reflect.get(e.selectedSession,`clientPendingStart`)!==!0?{sessionId:e.selectedSession?.id}:{}}}function vl(e){return e?.signal?.aborted!==!0&&e?.isCurrent?.()!==!1}function yl(e){return e.find(e=>e.isMain)??e[0]}function bl(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>bl(e,t[n]));if(!xl(e)||!xl(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&bl(e[n],t[n]))}function xl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Sl(e){return Error(e.diagnostics.map(({message:e})=>e).join(`; `)||D(`client.workspaceController.authorityDegraded`,`Workspace authority is degraded`))}var Cl=`core.workspace.files--file`,wl=`core.workspace.terminal--terminal`,Tl=`pi-web:machine-navigation:v1`,El=class{constructor(e=Vs()){this.snapshotsByMachine=new Hs(Tl,jl,e)}latest(e){let t=this.snapshotsByMachine.get(e);return t?.machineId===e?Al(t):void 0}remember(e){this.snapshotsByMachine.set(e.machineId,Al(e))}forget(e){this.snapshotsByMachine.delete(e)}};function Dl(e){return{machineId:e,surface:{}}}function Ol(e,t={}){let n=e.selectedWorkspace===void 0?{}:ra(t),r=e.selectedSession?.id;return{machineId:e.selectedMachine?.id??`local`,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:r,tool:e.workspaceTool,view:e.mainView,surface:{...Object.keys(n).length===0?{}:{contributionQuery:n}}}}function kl(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view}}function Al(e){let t=e.surface.contributionQuery;return{...e,surface:{...e.surface,...t===void 0?{}:{contributionQuery:ra(t)}}}}function jl(e){if(!Il(e))return;let t=Fl(e,`machineId`);if(t===void 0)return;let n=Fl(e,`view`),r=n===`files`||n===`core:workspace.files`?`core:workspace.files`:n===`git`||n===`core:workspace.git`?`core:workspace.git`:n===`terminal`||n===`core:workspace.terminal`?`core:workspace.terminal`:void 0,i=Nl(Fl(e,`tool`))??r,a=Sa(n)??(r===void 0?void 0:`workspace`);return{machineId:t,projectId:Fl(e,`projectId`),workspaceId:Fl(e,`workspaceId`),sessionId:Fl(e,`sessionId`),...i===void 0?{}:{tool:i},...a===void 0?{}:{view:a},surface:Ml(e.surface)}}function Ml(e){if(!Il(e))return{};let t=Il(e.contributionQuery)?e.contributionQuery:{},n=Fl(e,`selectedFilePath`),r=Fl(e,`selectedTerminalId`),i=Fl(e,`selectedDiffPath`),a=ra({...n===void 0?{}:{[Cl]:n},...r===void 0?{}:{[wl]:r},...i===void 0?{}:{"core.workspace.git--diff":i},...t});return{...Object.keys(a).length===0?{}:{contributionQuery:a}}}function Nl(e){return Pl(e)?e:void 0}function Pl(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Fl(e,t){let n=e[t];return typeof n==`string`&&n!==``?n:void 0}function Il(e){return typeof e==`object`&&!!e}function Ll(e,t,n){if(t!==void 0&&zl(t.path)===zl(n.cwd))return{machineId:e,projectId:t.projectId,workspaceId:t.id,root:t.path}}function Rl(e,t){let n=e.trim();if(n===``||/^[#?]/.test(n)||n.startsWith(`//`)||/^[a-z][a-z\d+.-]*:/i.test(n))return;let r;try{r=decodeURIComponent(n.split(/[?#]/,1)[0]??``)}catch{return}if(r===``||/[\\\u0000-\u001f\u007f]/.test(r))return;if(r.startsWith(`/`)){let e=`${zl(t.root)}/`;if(!r.startsWith(e)||(r=r.slice(e.length),r===``))return}let i=r.split(`/`).filter(e=>e!==``&&e!==`.`).join(`/`);return i===``?void 0:i}function zl(e){return e.replace(/\/+$/,``)}var Bl={archiveIdleEnabled:!0,archiveIdleDays:`30`,deleteArchivedEnabled:!1,deleteArchivedDays:`90`};function Vl(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:D(`client.sessionCleanupUi.enable.at.least.one.cleanup.action.d2ce50`,`Enable at least one cleanup action.`)};let t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){let n=Zl(e.archiveIdleDays,D(`client.sessionCleanupUi.archive.idle.sessions.after.6d41ea`,`Archive idle sessions after`));if(typeof n==`string`)return{ok:!1,error:n};t.archiveIdleDays=n}if(e.deleteArchivedEnabled){let n=Zl(e.deleteArchivedDays,D(`client.sessionCleanupUi.delete.archived.sessions.after.923bee`,`Delete archived sessions after`));if(typeof n==`string`)return{ok:!1,error:n};t.deleteArchivedDays=n}return{ok:!0,request:t}}function Hl(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null,projectId:e?.projectId??null})}function Ul(e){if(e.canCleanup===!1||e.loading===!0||e.running===!0||e.preview===void 0)return!1;let t=Vl(e.draft);if(!t.ok)return!1;if(e.previewRequest===void 0){if(e.canCleanup!==!0||!Wl(e.draft,e.preview))return!1}else if(Ql(t.request)!==Ql(e.previewRequest))return!1;return Gl(e.preview)}function Wl(e,t){let n=Vl(e);return n.ok?Ql(n.request)===Ql(t.thresholds):!1}function Gl(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function Kl(e,t){let n=e.projects.map(e=>e.cwd);if(t===void 0)return n;let r=new Set(t);return n.filter(e=>r.has(e))}function ql(e,t){let n=new Set(Kl(e,t)),r=e.projects.filter(e=>n.has(e.cwd));return{...e,projects:r,totals:r.reduce((e,t)=>({archiveCount:e.archiveCount+t.archiveCount,deleteCount:e.deleteCount+t.deleteCount}),{archiveCount:0,deleteCount:0})}}function Jl(e,t){return t(Yl(e))}function Yl(e){let t=e.totals.archiveCount,n=e.totals.deleteCount,r=[];t>0&&r.push(D(`client.sessionCleanupUi.archive.idle.sessions.27a4f1`,`archive {value1} idle sessions`,{value1:String(t)})),n>0&&r.push(D(`client.sessionCleanupUi.permanently.delete.archived.sessions.360209`,`permanently delete {value1} archived sessions`,{value1:String(n)}));let i=r.length===0?D(`client.sessionCleanupUi.run.cleanup.233f8e`,`run cleanup`):r.join(D(`client.sessionCleanupUi.and.2f4b60`,` and `));return D(`client.sessionCleanupUi.run.cleanup.and.permanent.deletion.only.applies.to.archived.sessions.a.9775e2`,`Run cleanup and {value1}?
|
|
27
|
+
`))+1;return e.slice(t)}var Ds=class{constructor(e=`normal`){this.scope=e,this.reconnectDelay=500,this.shouldReconnect=!1,this.hasOpened=!1,this.machineId=`local`}connect(e,t,n,r=`local`,i){this.close(),this.machineId=r,this.session=e,this.onEvent=t,this.onReconnect=n,this.onInitialOpen=i,this.shouldReconnect=!0,this.open()}setHandler(e){this.onEvent=e}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Fs(this.socket),this.socket=void 0,this.session=void 0,this.onEvent=void 0,this.onReconnect=void 0,this.onInitialOpen=void 0,this.hasOpened=!1,this.machineId=`local`}open(){let e=this.session;if(e===void 0||e.id===``||e.cwd===``||!this.shouldReconnect)return;let t=zn(e,this.machineId,this.scope);this.socket=t,t.onopen=()=>{if(this.socket!==t)return;this.reconnectDelay=500;let e=this.hasOpened;this.hasOpened=!0,e?this.onReconnect?.():this.onInitialOpen?.()},t.onmessage=n=>void this.handleMessage(n.data,t,e),t.onerror=()=>{t.close()},t.onclose=()=>{this.socket===t&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t,n){let r=ks(await Ps(e));this.socket===t&&r!==void 0&&(r.type===`session.diagnostic`?console.error(`[PI WEB] Session diagnostic`,{machineId:this.machineId,sessionId:n.id,cwd:n.cwd,message:r.message}):(r.type!==`notifications.inbox`||n.id===r.summary.sessionId&&n.cwd===r.summary.cwd)&&this.onEvent?.(r))}},Os=class{constructor(e=`normal`){this.scope=e,this.reconnectDelay=500,this.shouldReconnect=!1,this.machineId=`local`}connect(e,t,n=`local`){this.close(),this.machineId=n,this.onEvent=e,this.onOpen=t,this.shouldReconnect=!0,this.open()}close(){this.shouldReconnect=!1,window.clearTimeout(this.reconnectTimer),Fs(this.socket),this.socket=void 0,this.onEvent=void 0,this.onOpen=void 0,this.machineId=`local`}open(){if(!this.shouldReconnect)return;let e=Bn(this.machineId,this.scope);this.socket=e,e.onopen=()=>{this.socket===e&&(this.reconnectDelay=500,this.onOpen?.())},e.onmessage=t=>void this.handleMessage(t.data,e),e.onerror=()=>{e.close()},e.onclose=()=>{this.socket===e&&(this.socket=void 0,this.scheduleReconnect())}}scheduleReconnect(){if(!this.shouldReconnect)return;window.clearTimeout(this.reconnectTimer);let e=this.reconnectDelay;this.reconnectDelay=Math.min(this.reconnectDelay*1.6,5e3),this.reconnectTimer=window.setTimeout(()=>{this.open()},e)}async handleMessage(e,t){let n=As(await Ps(e));this.socket===t&&n!==void 0&&this.onEvent?.(n)}};function ks(e){let t=Ns(e);if(t===`notifications.inbox`)return Ms(()=>he(e));if(t===`dialog.opened`)return Ms(()=>ae(e));if(t===`dialog.closed`)return Ms(()=>ee(e));let n=Ms(()=>a(e));return n===void 0?void 0:js(n,e)}function As(e){if(Ns(e)===`notices.updated`)return Ms(()=>p(e));if(Ns(e)===`sessions.unread`)return Ms(()=>Se(e));if(Ns(e)===`session.startup`)return Ms(()=>jt(e));if(typeof e==`object`&&e){if(Ns(e)===`terminal.created`||Ns(e)===`terminal.exited`){if(!(`terminal`in e))return;let t=Ms(()=>xe(e.terminal));return t===void 0?void 0:{type:Ns(e)===`terminal.created`?`terminal.created`:`terminal.exited`,terminal:t}}if(Ns(e)===`terminal.closed`)return!(`terminalId`in e)||typeof e.terminalId!=`string`||e.terminalId===``||!(`cwd`in e)||typeof e.cwd!=`string`||e.cwd===``?void 0:{type:`terminal.closed`,terminalId:e.terminalId,cwd:e.cwd};if(Ns(e)===`workspace.activity`){if(!(`activity`in e))return;let t=Ms(()=>we(e.activity));return t===void 0?void 0:{type:`workspace.activity`,activity:t}}}return Ms(()=>fe(e))}function js(e,t){return typeof t!=`object`||!t||!(`seq`in t)?e:typeof t.seq==`number`?{...e,seq:t.seq}:e}function Ms(e){try{return e()}catch{return}}function Ns(e){if(typeof e!=`object`||!e||!(`type`in e))return``;let t=e.type;return typeof t==`string`?t:``}async function Ps(e){try{return typeof e==`string`?JSON.parse(e):e instanceof Blob?JSON.parse(await e.text()):e instanceof ArrayBuffer?JSON.parse(new TextDecoder().decode(e)):void 0}catch{return}}function Fs(e){e!==void 0&&(e.onmessage=null,e.onerror=null,e.onclose=null,e.readyState===WebSocket.CONNECTING?e.onopen=()=>{e.close()}:e.close())}function Is(e){return e?.ok===!0}function Ls(e){return{authoritative:Is(e)}}function Rs(e,t,n={}){if(e===void 0)return`unknown`;let r=(t?.sessionId===e.id?t.persisted:void 0)??e.persisted;return r===!0?`persisted`:r===!1||$r(e)?`transient`:n.authoritative===!0?`unknown`:`persisted`}function zs(e,t,n){return e!==void 0&&e.archived!==!0&&Rs(e,t,n)===`persisted`}function Bs(e,t,n){return e!==void 0&&e.archived!==!0&&Rs(e,t,n)===`transient`}function Vs(){try{return typeof sessionStorage>`u`?void 0:sessionStorage}catch{return}}var Hs=class{constructor(e,t,n=Vs()){this.storageKey=e,this.storage=n,this.values=new Map;for(let[r,i]of Ws(e,t,n))this.values.set(r,i)}get(e){return this.values.get(e)}set(e,t){this.values.set(e,t),this.save()}delete(e){this.values.delete(e),this.save()}entries(){return[...this.values.entries()]}save(){try{if(this.values.size===0){this.storage?.removeItem(this.storageKey);return}let e={version:1,entries:[...this.values.entries()]};this.storage?.setItem(this.storageKey,JSON.stringify(e))}catch{}}};function Us(e){return typeof e==`string`&&e!==``?e:void 0}function Ws(e,t,n){try{let r=n?.getItem(e);if(r==null||r===``)return[];let i=JSON.parse(r);if(!Gs(i))return[];let a=[];for(let e of i.entries){let n=e[0],r=t(e[1]);r!==void 0&&a.push([n,r])}return a}catch{return[]}}function Gs(e){return!Ks(e)||e.version!==1||!Array.isArray(e.entries)?!1:e.entries.every(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`&&e[0]!==``)}function Ks(e){return typeof e==`object`&&!!e}var qs=class{constructor(){this.sessionIdsByCwd=new Map}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}},Js=`pi-web:session-selection:v1`,Ys=class{constructor(e=Vs()){this.sessionIdsByCwd=new Hs(Js,Us,e)}latestSessionId(e){return this.sessionIdsByCwd.get(e)}rememberSession(e){this.sessionIdsByCwd.set(e.cwd,e.id)}forgetWorkspace(e){this.sessionIdsByCwd.delete(e)}};function Xs(e,t){let n=t?.targetSessionId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestSessionId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e.find(e=>e.archived!==!0):e.find(e=>e.archived!==!0)}function Zs(e,t){return t?.archived===!0&&!e.some(e=>e.archived!==!0)}function Qs(e,t,n){return $s(e,[t],n)}function $s(e,t,n){let r=new Set(t);return e.map(e=>r.has(e.id)?{...e,archived:!0,archivedAt:n}:e)}function ec(e,t,n){return tc(e,t,[n])}function tc(e,t,n){if(t===void 0||!n.includes(t))return{type:`unchanged`};let r=new Set(n),i=e.find(e=>!r.has(e.id)&&e.archived!==!0);return i===void 0?{type:`clear`}:{type:`select`,session:i}}var nc=/timed out|operation was aborted|request cancelled/i;function rc(e){return e instanceof te&&(e.status===504||e.status===499)||e instanceof Error&&nc.test(e.message)}function ic(e){return rc(e)?D(`ui.main.634a1618e706`,`The session daemon request timed out. The conversation is still running.`):e instanceof Error?e.message:String(e)}var ac=[500,1500,3e3],oc=Symbol(`retired-read`);async function sc(e,t,n,r=!0){let i=()=>n?.aborted!==!0&&t(),a=0;for(;i();)try{let t=await cc(e(),n);return t!==oc&&i()?t:void 0}catch(e){if(n?.aborted===!0||r&&!t())return;let i=ac[a];if(!r||!(e instanceof Oe)||i===void 0)throw e;let o;try{await cc(new Promise(e=>{o=setTimeout(e,i)}),n)}finally{o!==void 0&&clearTimeout(o)}a+=1}}function cc(e,t){if(t===void 0)return e;let n=()=>void 0,r=new Promise(e=>{n=()=>{e(oc)},t.addEventListener(`abort`,n,{once:!0}),t.aborted&&n()});return Promise.race([e,r]).finally(()=>{t.removeEventListener(`abort`,n)})}var lc=100,uc=500,dc=5e3,fc=[`machine`,`project`,`workspace`,`session`],pc=[`machine`,`project`,`workspace`,`session`],mc=class{constructor(e,t,n,r=new qs,i={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessionSelection=r,this.selectedSessionLoadDeferred=!1,this.selectionSeq=0,this.pendingTreeActions=new Set,this.disposed=!1,this.pendingTranscriptEvents=[],this.selectedReadGeneration=0,this.workspaceReadGeneration=0,this.selectedReadRecoveries=new Set,this.workspaceReadRecoveries=new Set,this.pendingStatusBySession=new Map,this.pendingActivityBySession=new Map,this.sessionRefreshInFlight=!1,this.searchSeq=0,this.searchTargetSeq=0,this.pendingQueuedSendSeq=0,this.pendingSessionStarts=new Map,this.suppressedCreatedSessions=new Map,this.selectedSessionRefreshes=new gr,this.workspaceSessionRefreshes=new gr,this.socket=i.socket??new Ds,this.api=i.api??x,this.transcripts=i.transcripts??new us,this.transcriptSnapshot=i.transcriptSnapshot??((...e)=>this.api.transcriptSnapshot(...e)),this.notifications=i.notifications,this.automaticSessionCandidates=i.automaticSessionCandidates??(e=>e),this.replacePromptEditorText=i.replacePromptEditorText,this.canMutateQueueMessage=i.canMutateQueueMessage??(()=>!1),this.onSelectedSessionReady=i.onSelectedSessionReady,this.observeSessionSnapshot=i.observeSessionSnapshot,this.isChatVisible=i.isChatVisible??(()=>!0),this.isPendingSessionStartRouteCurrent=i.isPendingSessionStartRouteCurrent,this.onPendingSessionStartCommitted=i.onPendingSessionStartCommitted,this.onModelScopeChanged=i.onModelScopeChanged,this.navigateToSession=i.navigateToSession,this.captureNavigation=i.captureNavigation,this.beginNavigationOperation=i.beginNavigationOperation,this.browserErrors=new $n(e,t)}applyGlobalEvent(e){e.type===`status.update`?this.queueStatusUpdate(e.status):e.type===`activity.update`?this.queueActivityUpdate(e.activity):e.type===`session.created`?this.applyCreatedSession(e.session):e.type===`session.name`?this.applySessionName(e.sessionId,e.name):e.type===`models.changed`?this.onModelScopeChanged?.(e.revision):e.type===`session.startup`&&this.queueStartupProgress(e)}dispose(){this.disposed=!0,this.retireReadRecoveries([`machine`]),this.selectedSessionLoadDeferred=!1,this.selectionSeq+=1,this.searchSeq+=1,this.stopPolling(),this.searchTimer!==void 0&&clearTimeout(this.searchTimer),this.searchTimer=void 0,this.selectedSessionJoinNavigation=void 0,this.socket.close(),this.clearPendingUpdates()}updatePolling(){this.stopPolling(),this.getState().selectedWorkspace!==void 0&&(this.sessionPollTimer=setInterval(()=>{this.sessionRefreshInFlight||(this.sessionRefreshInFlight=!0,this.refreshCurrentWorkspaceSessions().finally(()=>{this.sessionRefreshInFlight=!1}))},dc))}clearActiveSession(){this.retireReadRecoveries([`session`]),this.selectedSessionLoadDeferred=!1,this.selectionSeq+=1,this.selectedSessionJoinNavigation=void 0,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates(),this.setState({selectedSession:void 0,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0})}deselectSession(e){let t=this.getState(),n=t.selectedSession?.cwd??t.selectedWorkspace?.path;e?.forgetRememberedSelection===!0&&n!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(n)),this.clearActiveSession(),e?.updateUrl!==!1&&this.updateUrl()}async selectSessionAfterNavigation(e,t,n){this.navigateToSession===void 0?await this.selectSession(e,{updateUrl:n?.updateUrl}):await this.navigateToSession(e,{...n?.updateUrl===!1?{replace:!0}:{},expected:t})}async clearSessionAfterNavigation(e){if(!this.navigationSelectionMatchesState(e))return;let t=this.getState().selectedSession?.cwd??this.getState().selectedWorkspace?.path;this.navigateToSession===void 0?this.deselectSession({forgetRememberedSelection:!0}):(t!==void 0&&this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(t)),await this.navigateToSession(void 0,{expected:e}))}async clearSelectionAfterArchivedCollapse(){let e=this.getState();Zs(this.automaticSessionCandidates(e.sessions),e.selectedSession)&&await this.clearSessionAfterNavigation(this.navigationSelection())}async startSession(e){let t=this.getState().selectedWorkspace;if(!t)return;let n=M(this.getState()),r=typeof e==`function`?e:void 0,i=typeof e==`function`?void 0:e,a=i?.updateUrl!==!1,o=this.createPendingSessionStart(t,n,this.navigationSelection(),a);this.pendingSessionStarts.set(o.tempId,o),this.insertAndSelectPendingSession(o.session,i),a&&(o.expectedNavigation=this.navigationSelection()),o.navigation=this.beginNavigationOperation?.(fc);try{if(r!==void 0&&!await r()){this.cancelUnstartedSession(o);return}let e=await this.api.startSession(t.path,n,o.tempId);await this.resolvePendingSessionStart(o.tempId,e)}catch(e){this.failPendingSessionStart(o.tempId,e)}}async refreshPinnedSessions(e,t=M(this.getState())){try{let n=await this.api.pinned(e,t);if(M(this.getState())!==t||this.getState().selectedWorkspace?.path!==e)return;this.setState({pinnedSessionIds:n.sessionIds})}catch{M(this.getState())===t&&this.getState().selectedWorkspace?.path===e&&this.setState({pinnedSessionIds:[]})}}togglePinned(e){if(e.persisted===!1)return;let t=this.getState(),n=t.pinnedSessionIds.includes(e.id),r=n?t.pinnedSessionIds.filter(t=>t!==e.id):[...t.pinnedSessionIds,e.id],i=M(t);this.setState({pinnedSessionIds:r}),(async()=>{try{let t=n?await this.api.unpin(e,i):await this.api.pin(e,i),r=this.getState();if(M(r)!==i||r.selectedWorkspace?.path!==e.cwd)return;let a=t.pinned;this.setState({pinnedSessionIds:a?[...new Set([...this.getState().pinnedSessionIds,e.id])]:this.getState().pinnedSessionIds.filter(t=>t!==e.id)})}catch(t){let r=this.getState();if(M(r)!==i||r.selectedWorkspace?.path!==e.cwd)return;this.setState({pinnedSessionIds:n?[...new Set([...r.pinnedSessionIds,e.id])]:r.pinnedSessionIds.filter(t=>t!==e.id)}),this.reportSessionError(e,i,t)}})()}searchSessions(e){let t=this.getState(),n=t.selectedWorkspace,r=M(t);this.searchSeq+=1;let i=this.searchSeq;this.searchTimer!==void 0&&clearTimeout(this.searchTimer),this.searchTimer=void 0,this.setState({sessionSearchQuery:e,sessionSearchResults:void 0,isSearchingSessions:!1,sessionSearchError:``});let a=e.trim();n!==void 0&&a!==``&&(this.setState({isSearchingSessions:!0}),this.searchTimer=setTimeout(()=>{this.searchTimer=void 0,this.performSessionSearch(i,a,n.id,n.path,r)},250))}async performSessionSearch(e,t,n,r,i){try{let a=await this.api.searchContent(r,t,i),o=this.getState();if(e!==this.searchSeq||M(o)!==i||o.selectedWorkspace?.id!==n||o.sessionSearchQuery.trim()!==t)return;this.setState({sessionSearchResults:a,isSearchingSessions:!1})}catch(t){let r=this.getState();if(e!==this.searchSeq||M(r)!==i||r.selectedWorkspace?.id!==n)return;this.setState({sessionSearchResults:{results:[],matchCount:0,truncated:!1},isSearchingSessions:!1,sessionSearchError:String(t)})}}preferredSession(e,t,n){if(Ca(n)){let t=this.pendingSessionStarts.get(n);return t!==void 0&&!t.discarded&&t.cwd===e&&this.isCurrentPendingStart(t)?t.session:void 0}if(n!==void 0&&n!==``)return Xs(t,{targetSessionId:n});let r=Gt()?t.filter(e=>!$r(e)):t,i=this.sessionSelection.latestSessionId(this.workspaceSelectionKey(e));return i!==void 0&&i!==``&&r.some(e=>e.id===i)?Xs(r,{latestSessionId:i}):Xs(this.automaticSessionCandidates(r))}canReuseSelectedSession(){return!this.disposed&&Nc(this.selectedSessionJoinNavigation)}get isChatLoadDeferred(){return this.selectedSessionLoadDeferred}async loadSelectedSession(){if(this.disposed||!this.selectedSessionLoadDeferred||!this.isChatVisible())return;let e=this.getState().selectedSession;if(e===void 0)return;let t=this.beginNavigationOperation?.(pc);await this.selectSession(e,{updateUrl:!1,navigation:t})}async selectSession(e,t){if(this.disposed||!Nc(t?.navigation))return;if(this.retireReadRecoveries([`session`]),I(e)){this.selectClientPendingStartSession(e,t);return}let n=M(this.getState()),r=this.captureSessionErrorOwner(e);this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)});let i=++this.selectionSeq;this.selectedSessionJoinNavigation=t?.navigation,this.socket.close(),this.streamWatermark=void 0,this.clearPendingUpdates(),this.selectedSessionLoadDeferred=t?.deferChatLoading===!0||!this.isChatVisible(),this.selectedSessionLoadDeferred?this.notifications?.clearSelectedSession():this.notifications?.prepareSelectedSession(e,n);let a=this.sessionCacheKey(e.id),o=this.selectedSessionLoadDeferred?{messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,messagePageLeafId:void 0}:this.transcripts.cachedView(a);if(this.setState({selectedSession:e,sessionSearchTarget:void 0,...o,isLoadingEarlierMessages:!1,...t?.preserveTreeDialog===!0?{}:{treeDialog:void 0},status:e.archived===!0?void 0:this.getState().sessionStatuses[e.id],activity:e.archived===!0?void 0:this.getState().sessionActivities[e.id],pendingDialogs:e.archived===!0?[]:this.getState().sessionStatuses[e.id]?.pendingDialogs??[],closedDialogs:[],availableThinkingLevels:[]}),this.selectedSessionLoadDeferred){this.selectedSessionJoinNavigation=void 0,t?.updateUrl!==!1&&this.updateUrl();return}let s=!1;try{if(e.archived===!0){let o=this.browserErrors.captureRecovery(Kn(n,e.id,r),`session-refresh`),s=await this.api.messages(e,{limit:lc},n),c=this.getState().selectedSession;if(i!==this.selectionSeq||M(this.getState())!==n||c?.id!==e.id||c.cwd!==e.cwd||c.path!==e.path||c.archived!==e.archived||!Nc(t?.navigation))return;this.browserErrors.clearRecovered(o);let l=this.transcripts.mergeHistory(a,s);this.setState({...l,isLoadingEarlierMessages:!1,status:void 0,activity:void 0,pendingDialogs:[],closedDialogs:[]}),this.onSelectedSessionReady?.({machineId:n,session:e}),t?.updateUrl!==!1&&this.updateUrl();return}this.socket.connect(e,t=>{this.isCurrentSessionSelection(e.id,n,i)&&this.applyEvent(t)},()=>{this.isCurrentSessionSelection(e.id,n,i)&&this.isSelectedSessionScope(e,n)&&this.refreshSelectedSession(e.id,{recoverNetwork:!0})},n,()=>{let t=this.getState().selectedSession;this.isCurrentSessionSelection(e.id,n,i)&&t?.cwd===e.cwd&&t.path===e.path&&this.refreshSessionNotifications(e,n)}),s=!0;let o={session:e,machineId:n,selectionSeq:i,errorOwner:r,...t?.navigation===void 0?{}:{navigation:t.navigation}};if(t?.propagateRefreshError===!0)await this.requestSelectedSessionRefresh(o);else if(!await this.joinSelectedSessionSnapshot(o))return;if(!this.isCurrentRefreshTarget(o)||!Nc(t?.navigation))return;this.refreshAvailableThinkingLevels(),this.onSelectedSessionReady?.({machineId:n,session:e}),t?.updateUrl!==!1&&this.updateUrl()}catch(a){let o=Nc(t?.navigation);if(!o||i!==this.selectionSeq||this.getState().selectedSession?.id!==e.id){if(this.reportSessionError(e,n,a,r),t?.propagateRefreshError===!0&&o&&this.isSelectedSessionIdentity(e.id,n))throw a;return}if($r(e)&&Mc(a)){await this.recreateCachedNewSession(e,t,i,r);return}if(this.reportSessionError(e,n,a,r),t?.propagateRefreshError===!0)throw a}finally{let r=Nc(t?.navigation);i===this.selectionSeq&&r&&(this.selectedSessionJoinNavigation=void 0),s&&!Nc(t?.navigation)&&this.isCurrentSessionSelection(e.id,n,i)&&this.socket.close()}}async loadEarlierMessages(){let e=this.getState(),t=e.selectedSession;if(!t||e.isLoadingEarlierMessages||e.messagePageStart<=0)return;let n=M(e),r=this.captureSessionErrorOwner(t),i=this.selectionSeq,a=j(n,t.id),o=this.transcripts.historyRevision(a),s=()=>{let e=this.getState();return!this.disposed&&i===this.selectionSeq&&M(e)===n&&e.selectedSession?.id===t.id&&e.selectedSession.cwd===t.cwd&&e.selectedSession.path===t.path&&e.selectedSession.archived===t.archived};this.setState({isLoadingEarlierMessages:!0});try{let r=await this.api.messages(t,{before:e.messagePageStart,limit:lc},n);if(!s()||this.transcripts.historyRevision(a)!==o)return;let i=this.transcripts.mergeHistory(a,r);this.setState(i)}catch(e){if(!s())return;this.reportSessionError(t,n,e,r)}finally{s()&&this.setState({isLoadingEarlierMessages:!1})}}async send(e,t,n,r=`inline`,i,a){let o=this.getState(),s=o.selectedSession;if(!s||s.archived===!0||a!==void 0&&(!Ma(a,{machineId:M(o),sessionId:s.id,cwd:s.cwd})||I(s)))return!1;let c=e.trim(),l=n!==void 0&&n.length>0,u=a!==void 0;if(I(s))return!l&&c.startsWith(`/`)?this.enqueuePendingSessionSend(s,{type:`command`,text:e}):!l&&ws(e)?this.enqueuePendingSessionSend(s,{type:`shell`,text:e}):this.enqueuePendingSessionSend(s,{type:`prompt`,text:e,streamingBehavior:t,attachments:n,delivery:r,folder:i}),!1;if(!u&&!l&&c.startsWith(`/`))return await this.runCommand(e),!1;if(!u&&!l&&ws(e))return await this.runShell(e),!1;let d=M(this.getState()),f=this.captureSessionErrorOwner(s);return this.deliverPromptToSession(s,e,t,n,r,i,d,{markSending:l||u},f)}markSendingPrompt(e,t){let n=this.getState().sendingPrompts;t?n[e]!==!0&&this.setState({sendingPrompts:{...n,[e]:!0}}):e in n&&this.setState({sendingPrompts:_c(n,e)})}async runShell(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;if(I(t)){this.enqueuePendingSessionSend(t,{type:`shell`,text:e});return}let n=M(this.getState()),r=this.captureSessionErrorOwner(t);await this.deliverShellToSession(t,e,n,{optimisticLine:!0},r)}async runCommand(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;if(I(t)){this.enqueuePendingSessionSend(t,{type:`command`,text:e});return}let n=M(this.getState()),r=this.captureSessionErrorOwner(t);await this.deliverCommandToSession(t,e,n,{applyResult:!0},r)}async renameSession(e,t){let n=t.trim();if(n===``||!zs(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let r=M(this.getState()),i=this.getState().selectedWorkspace,a=this.captureSessionErrorOwner(e);try{let t=await this.api.runCommand(e,`/name ${n}`,r);if(t.type===`done`){let a=this.getState();if(this.disposed||M(a)!==r||a.selectedWorkspace?.id!==i?.id||a.selectedWorkspace?.projectId!==i?.projectId||a.selectedWorkspace?.path!==i?.path||!a.sessions.some(t=>t.id===e.id&&t.cwd===e.cwd&&t.path===e.path))return;this.applySessionName(e.id,t.session?.name??n);return}this.reportSessionError(e,r,t.type===`unsupported`?t.message:D(`client.sessionController.failed.to.rename.session.702159`,`Failed to rename session`),a)}catch(t){this.reportSessionError(e,r,t,a)}}enqueuePendingSessionSend(e,t){let n=this.pendingSessionStarts.get(e.id);if(n===void 0||n.discarded){let t=this.captureSessionErrorOwner(e,n?.originWorkspace);this.reportSessionError(e,e.machineId,D(`client.sessionController.the.backend.session.is.not.ready.to.send.queued.messages.copy.your.mes.22460a`,`The backend session is not ready to send queued messages. Copy your messages before discarding this failed start.`),t);return}let r={...t,id:`pending-send-${String(++this.pendingQueuedSendSeq)}`};n.queuedSends.push(r);let i=this.getState(),a=i.clientQueuedSessionMessages[e.id]??[],o=Sc(e.id,n.queuedSends.length);this.setState({clientQueuedSessionMessages:{...i.clientQueuedSessionMessages,[e.id]:[...a,wc(r)]},sessionActivities:{...i.sessionActivities,[e.id]:o},activity:i.selectedSession?.id===e.id?o:i.activity,error:``})}async flushQueuedPendingSends(e,t,n,r){for(let i of n){if(!await this.deliverQueuedPendingSend(e,t,i,r))return;this.dropNextQueuedSessionMessage(e.id)}}async deliverQueuedPendingSend(e,t,n,r){return n.type===`prompt`?this.deliverPromptToSession(e,n.text,n.streamingBehavior,n.attachments,n.delivery,n.folder,t,{markSending:!0},r):n.type===`shell`?this.deliverShellToSession(e,n.text,t,{optimisticLine:!0},r):this.deliverCommandToSession(e,n.text,t,{applyResult:!0},r)}async deliverPromptToSession(e,t,n,r,i,a,o,s,c){let l=r!==void 0&&r.length>0;s.markSending&&this.markSendingPrompt(e.id,!0);try{if(l&&i===`folder`){let i=(await this.api.saveAttachments(e,r,o,a)).map(e=>vs(e.path,!1)).join(` `),s=t===``?i:`${t}\n\n${i}`;await this.api.prompt(e,s,n,o)}else await this.api.prompt(e,t,n,o,r);return this.markCachedNewSessionPersisted(e),!0}catch(t){return this.reportSessionError(e,o,t,c),!1}finally{s.markSending&&this.markSendingPrompt(e.id,!1)}}async deliverShellToSession(e,t,n,r,i){r.optimisticLine&&this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ui(`user`,t)]});try{return await this.api.shell(e,t,n),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ui(`system`,ic(t))]}),this.reportSessionError(e,n,t,i),!1}}async deliverCommandToSession(e,t,n,r,i){let a=this.navigationSelection();this.markSendingPrompt(e.id,!0);try{let o=await this.api.runCommand(e,t,n);return r.applyResult&&this.isSelectedSessionIdentity(e.id,n)?await this.applyCommandResult(o,a):(o.type===`select`||o.type===`tree`)&&this.reportSessionError(e,n,D(`client.sessionController.queued.command.requires.input.open.the.session.and.run.it.again.2a98cf`,`Queued command "{value1}" requires input; open the session and run it again.`,{value1:t}),i),this.markCachedNewSessionPersisted(e),!0}catch(t){return this.getState().selectedSession?.id===e.id&&this.setState({messages:[...this.getState().messages,ui(`system`,ic(t))]}),this.reportSessionError(e,n,t,i),!1}finally{this.markSendingPrompt(e.id,!1)}}dropNextQueuedSessionMessage(e){let t=this.getState(),n=t.clientQueuedSessionMessages[e]??[];if(n.length===0)return;let r=n.slice(1);this.setState({clientQueuedSessionMessages:r.length===0?_c(t.clientQueuedSessionMessages,e):{...t.clientQueuedSessionMessages,[e]:r}})}async respondToCommand(e,t){let n=this.getState().selectedSession;if(!n)return;let r=M(this.getState()),i=this.captureSessionErrorOwner(n),a=this.navigationSelection();this.setState({commandDialog:void 0});try{let i=await this.api.respondToCommand(n,e,t,r);this.isSelectedSessionIdentity(n.id,r)&&await this.applyCommandResult(i,a)}catch(e){this.reportSessionError(n,r,e,i)}}cancelCommand(){this.setState({commandDialog:void 0})}async actOnMessage(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0||I(r))return;let i=M(n),a=this.selectionSeq,o=this.captureSessionErrorOwner(r),s;try{if(s=await this.api.runCommand(r,`/tree`,i),s.type!==`tree`)throw Error(`message`in s?s.message:D(`ui.main.8bcdd03f7054`,`Session history is unavailable.`));if(!s.tree.nodes.some(t=>t.id===e))throw Error(D(`ui.main.e92706bbbf62`,`This message is no longer available in session history.`))}catch(e){throw this.reportSessionError(r,i,e,o),e}this.isCurrentSessionSelection(r.id,i,a)&&this.isSelectedSessionScope(r,i)&&(t===`fork`?await this.forkSessionTree(e,s.tree,!0):await this.navigateSessionTree(e,{mode:`none`},s.tree,!0))}async navigateTree(e,t){return this.navigateSessionTree(e,t,this.getState().treeDialog)}async navigateSessionTree(e,t,n,r){let i=this.getState(),a=i.selectedSession;if(a===void 0||n===void 0||a.archived===!0||I(a))throw Error(D(`client.sessionController.session.tree.navigator.is.no.longer.available.34846d`,`Session tree navigator is no longer available`));let o={...a},s=M(i),c=this.captureSessionErrorOwner(o),l={machineId:s,sessionId:o.id};this.setTreeActionPending(l,!0);try{let i=await this.api.navigateTree(o,{targetId:e,expectedLeafId:n.activeLeafId,summary:t,...r===void 0?{}:{retainCheckpoint:r}},s);return await this.applySessionTreeNavigationResult(o,s,i,n),i}catch(e){throw this.reportSessionError(o,s,e,c),e}finally{this.setTreeActionPending(l,!1)}}async applySessionTreeNavigationResult(e,t,n,r){if(n.cancelled||this.disposed)return;if(this.hasDraftIdentityConflict(e,t)){this.reportSessionError(e,t,D(`client.sessionController.queueContextChanged`,`The conversation context changed before the result returned. The current draft was preserved.`));return}let i=j(t,e.id),a=n.editorText;if(a!==void 0&&za(i,a),this.transcripts.discard(i),!this.isSelectedSessionScope(e,t))return;this.clearPendingUpdates();let o=this.selectionSeq,s=()=>this.isCurrentSessionSelection(e.id,t,o)&&this.isSelectedSessionScope(e,t),c=(async()=>{a!==void 0&&s()&&await this.replacePromptEditorText?.({machineId:t,sessionId:e.id,text:a,isCurrent:s})})(),[l,u]=await Promise.allSettled([c,this.requestSelectedSessionRefresh({session:e,machineId:t,selectionSeq:o,errorOwner:this.captureSessionErrorOwner(e)})]);if(s()){if(l.status===`rejected`)throw l.reason;if(u.status===`rejected`)throw u.reason;this.getState().treeDialog===r&&this.setState({treeDialog:void 0})}}async forkFromTree(e){return this.forkSessionTree(e,this.getState().treeDialog)}async forkSessionTree(e,t,n){let r=this.getState(),i=r.selectedSession;if(i===void 0||t===void 0||i.archived===!0||I(i))throw Error(D(`client.sessionController.session.tree.navigator.is.no.longer.available.34846d`,`Session tree navigator is no longer available`));let a={...i},o=M(r),s=this.captureSessionErrorOwner(a),c=this.navigationSelection(),l={machineId:o,sessionId:a.id};this.setTreeActionPending(l,!0);try{let r=await this.api.forkTree(a,{entryId:e,expectedLeafId:t.activeLeafId,...n===void 0?{}:{retainCheckpoint:n}},o);return await this.applySessionTreeForkResult(a,o,r,c,t),r}catch(e){throw this.reportSessionError(a,o,e,s),e}finally{this.setTreeActionPending(l,!1)}}async applySessionTreeForkResult(e,t,n,r,i){if(n.cancelled)return;let a=j(t,e.id),o=n.session;if(o.id===e.id){await this.applySessionTreeNavigationResult(e,t,{cancelled:!1,...n.promptDraft===void 0?{}:{editorText:n.promptDraft}},i);return}if(n.promptDraft!==void 0&&za(j(t,o.id),n.promptDraft),this.transcripts.discard(a),!this.isSelectedSessionScope(e,t))return;let s=[o,...this.getState().sessions.filter(e=>e.id!==o.id)];this.setState({sessions:s}),this.navigateToSession===void 0?(this.setState({treeDialog:void 0}),await this.selectSession(o)):await this.navigateToSession(o,{expected:r})&&this.isSelectedSessionIdentity(o.id,t)&&this.getState().treeDialog===i&&this.setState({treeDialog:void 0})}async abortTreeNavigation(){let e=this.getState(),t=e.selectedSession;if(t===void 0||e.treeDialog===void 0||I(t))return;let n=M(e),r=this.captureSessionErrorOwner(t);try{await this.api.abort(t,n)}catch(e){throw this.reportSessionError(t,n,e,r),e}}closeTreeDialog(){this.setState({treeDialog:void 0})}applySessionStatus(e){this.applyStatus(e)}archiveScopeProjectId(){return Gt()?this.getState().selectedProject?.id:void 0}async useSuggestedInput(e,t){if(!this.isSelectedSessionIdentity(t,e))return;let n=this.getState(),r=n.selectedSession,i=n.status?.sessionId===t?n.status.suggestedInput:void 0;if(r===void 0||i===void 0)return;let a=this.captureSessionErrorOwner(r);za(j(e,t),i);try{await this.replacePromptEditorText?.({machineId:e,sessionId:t,text:i})}catch(t){this.reportSessionError(r,e,t,a)}}invalidateSessionTree(){let e=this.getState(),t=e.selectedSession,n=M(e);t!==void 0&&this.isSelectedSessionIdentity(t.id,n)&&(this.transcripts.discard(j(n,t.id)),this.clearPendingUpdates(),this.refreshSelectedSession(t.id),e.treeDialog!==void 0&&!this.hasPendingTreeAction(n,t.id)&&this.setState({treeDialog:void 0}))}hasPendingTreeAction(e,t){return[...this.pendingTreeActions].some(n=>n.machineId===e&&n.sessionId===t)}setTreeActionPending(e,t){t?this.pendingTreeActions.add(e):this.pendingTreeActions.delete(e),this.disposed||this.setState({pendingTreeActions:[...this.pendingTreeActions]})}async archiveSession(e=this.getState().selectedSession){if(!e)return;let t=this.statusForSession(e),n=this.sessionPersistenceOptions();if(Bs(e,t,n)){await this.deleteCachedNewSession(e);return}if(!zs(e,t,n))return;let r=M(this.getState()),i=this.captureSessionErrorOwner(e);try{await this.api.archive(e,r,this.archiveScopeProjectId());let t=this.getState(),n=Qs(t.sessions,e.id,new Date().toISOString()),i=ec(this.automaticSessionCandidates(n),t.selectedSession?.id,e.id);this.setState({sessions:n});let a=this.navigationSelection();i.type===`select`?await this.selectSessionAfterNavigation(i.session,a):i.type===`clear`&&await this.clearSessionAfterNavigation(a)}catch(t){this.reportSessionError(e,r,t,i)}}async archiveSessionWithDescendants(e=this.getState().selectedSession){if(e===void 0||!zs(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{let n=await this.api.archiveWithDescendants(e,t,this.archiveScopeProjectId()),r=n.sessionIds!==void 0&&n.sessionIds.length>0?n.sessionIds:[e.id],i=this.getState(),a=$s(i.sessions,r,new Date().toISOString()),o=tc(this.automaticSessionCandidates(a),i.selectedSession?.id,r);this.setState({sessions:a});let s=this.navigationSelection();o.type===`select`?await this.selectSessionAfterNavigation(o.session,s):o.type===`clear`&&await this.clearSessionAfterNavigation(s)}catch(r){this.reportSessionError(e,t,r,n)}}async archiveSessions(e){let t=this.sessionPersistenceOptions(),n=Dc(e).filter(e=>zs(e,this.statusForSession(e),t));if(n.length===0)return;let r=M(this.getState()),i=this.getState().selectedWorkspace,a=n[0];if(a===void 0)return;let o=this.captureSessionErrorOwner(a,i);try{let{succeededIds:e,failures:t,generatedAt:s}=await this.archiveSessionBatch(n,r);if(e.length>0){let t=this.getState(),n=$s(t.sessions,e,s??new Date().toISOString()),r=tc(this.automaticSessionCandidates(n),t.selectedSession?.id,e);this.setState({sessions:n});let i=this.navigationSelection();r.type===`select`?await this.selectSessionAfterNavigation(r.session,i):r.type===`clear`&&await this.clearSessionAfterNavigation(i)}this.applyBulkSessionFailures(D(`ui.sessionCleanupDialog.archive`,`Archive`),t,r,i,a,o)}catch(e){this.reportWorkspaceOrSessionError(i,a,r,D(`client.sessionController.archive.failed.aaa500`,`Archive failed: {value1}`,{value1:kc(e)}),o)}}async deleteArchivedSessions(e){let t=Dc(e).filter(e=>e.archived===!0);if(t.length===0)return;let n=M(this.getState()),r=this.getState().selectedWorkspace,i=t[0];if(i===void 0)return;let a=this.captureSessionErrorOwner(i,r);try{let{succeededIds:e,failures:o}=await this.deleteArchivedSessionBatch(t,n);if(e.length>0){let r=new Set(e),i=this.getState(),a=i.sessions.filter(e=>!r.has(e.id));if(this.setState({sessions:a}),i.selectedSession!==void 0&&r.has(i.selectedSession.id)){let e=this.navigationSelection(),t=this.automaticSessionCandidates(a),n=t.find(e=>e.archived!==!0)??t[0];n===void 0?await this.clearSessionAfterNavigation(e):await this.selectSessionAfterNavigation(n,e)}await this.refreshPinnedSessions(t[0]?.cwd??``,n)}this.applyBulkSessionFailures(D(`ui.sessionList.delete`,`Delete`),o,n,r,i,a)}catch(e){this.reportWorkspaceOrSessionError(r,i,n,D(`client.sessionController.delete.failed.59ec26`,`Delete failed: {value1}`,{value1:kc(e)}),a)}}async archiveSessionBatch(e,t){let n=await this.api.archiveMany(e,t,this.archiveScopeProjectId());return{succeededIds:n.archivedSessionIds,failures:Oc(n.failures),generatedAt:n.generatedAt}}async deleteArchivedSessionBatch(e,t){let n=await this.api.deleteArchivedMany(e,t,this.archiveScopeProjectId());return{succeededIds:n.deletedSessionIds,failures:Oc(n.failures)}}async applySessionCleanupResult(e,t=M(this.getState())){if(M(this.getState())!==t)return;let n=e.archivedSessionIds,r=e.deletedSessionIds;if(n.length>0||r.length>0){let t=this.getState(),i=new Set(r),a=[...n,...r],o=$s(t.sessions,n,e.generatedAt).filter(e=>!i.has(e.id)),s=t.selectedSession!==void 0&&a.includes(t.selectedSession.id);this.setState({sessions:o,sessionStatuses:vc(t.sessionStatuses,a),sessionActivities:vc(t.sessionActivities,a),...s?{status:void 0,activity:void 0,pendingDialogs:[],closedDialogs:[]}:{}});let c=this.navigationSelection();if(t.selectedSession!==void 0&&i.has(t.selectedSession.id)){let e=this.automaticSessionCandidates(o),t=e.find(e=>e.archived!==!0)??e[0];t===void 0?await this.clearSessionAfterNavigation(c):await this.selectSessionAfterNavigation(t,c)}else{let e=tc(this.automaticSessionCandidates(o),t.selectedSession?.id,n);e.type===`select`?await this.selectSessionAfterNavigation(e.session,c):e.type===`clear`&&await this.clearSessionAfterNavigation(c)}}await this.refreshCurrentWorkspaceSessions(t)}retireReadRecoveries(e){let t=e.some(e=>e===`machine`||e===`project`||e===`workspace`);if(t||e.includes(`session`)){this.selectedReadGeneration+=1;for(let e of this.selectedReadRecoveries)e.abort();this.selectedReadRecoveries.clear(),this.refreshEventBuffer=void 0}if(t){this.workspaceReadGeneration+=1;for(let e of this.workspaceReadRecoveries)e.abort();this.workspaceReadRecoveries.clear()}}async refreshCurrentWorkspaceSessions(e=M(this.getState()),t){let n=this.getState().selectedWorkspace;if(n===void 0)return;let r=this.workspaceReadGeneration,i=this.beginNavigationOperation?.([`machine`,`project`,`workspace`]),a=()=>!this.disposed&&r===this.workspaceReadGeneration&&Nc(i)&&M(this.getState())===e&&this.getState().selectedWorkspace?.id===n.id&&this.getState().selectedWorkspace?.projectId===n.projectId&&this.getState().selectedWorkspace?.path===n.path,o=Gn(e,n.projectId,n.id);try{await this.workspaceSessionRefreshes.request(JSON.stringify([e,n.projectId,n.id,n.path]),async()=>{if(!a())return;let r=this.browserErrors.captureRecovery(o,`workspace-sessions-refresh`),i=()=>this.api.sessions(n.path,e),s=new AbortController;this.workspaceReadRecoveries.add(s);let c;try{c=await sc(i,a,s.signal,t?.recoverNetwork===!0)}finally{this.workspaceReadRecoveries.delete(s)}if(c===void 0||!a())return;this.browserErrors.clearRecovered(r);let l=Qr(n.path,c,e).filter(t=>!this.isSuppressedCreatedSession(t,e)),u=this.mergePendingStartSessions(n.path,l,e),d=this.getState().selectedSession;this.setState({sessions:u}),this.refreshPinnedSessions(n.path,e);let f=this.navigationSelection();if(d===void 0)return;let p=u.find(e=>e.id===d.id);if(p!==void 0){p!==d&&this.setState({selectedSession:p});return}let m=this.automaticSessionCandidates(u),h=m.find(e=>e.archived!==!0)??m[0];h===void 0?await this.clearSessionAfterNavigation(f):await this.selectSessionAfterNavigation(h,f)})}catch(i){if(this.disposed||r!==this.workspaceReadGeneration||t?.recoverNetwork===!0&&!a())return;if(i instanceof Oe){this.browserErrors.report(o,D(`client.sessionController.sessionListRefreshUnavailable`,`The session list could not be refreshed. Check your connection and retry.`),`workspace-sessions-refresh`);return}if(rc(i)){console.warn(`Workspace session list refresh timed out`,{machineId:e,workspaceId:n.id,errorCategory:`session-list-refresh`});return}this.reportWorkspaceError(n,e,i)}}stopPolling(){this.sessionPollTimer!==void 0&&clearInterval(this.sessionPollTimer),this.sessionPollTimer=void 0,this.sessionRefreshInFlight=!1}async deleteCachedNewSession(e=this.getState().selectedSession){if(e===void 0||!Bs(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=I(e)?this.pendingSessionStarts.get(e.id):void 0;t===void 0?this.api.stop(e,M(this.getState())).catch(()=>{}):(t.discarded=!0,t.queuedSends=[]),Zr(e.id,M(this.getState())),Ba(this.sessionCacheKey(e.id)),Ka(this.sessionCacheKey(e.id));let n=this.getState(),r=n.sessions.filter(t=>t.id!==e.id);if(this.setState({sessions:r,sessionStatuses:_c(n.sessionStatuses,e.id),sessionActivities:gc(n.sessionActivities,e.id),sendingPrompts:_c(n.sendingPrompts,e.id),clientQueuedSessionMessages:_c(n.clientQueuedSessionMessages,e.id)}),this.getState().selectedSession?.id!==e.id)return;let i=this.navigationSelection(),a=this.automaticSessionCandidates(r),o=a.find(e=>e.archived!==!0)??a[0];o===void 0?await this.clearSessionAfterNavigation(i):await this.selectSessionAfterNavigation(o,i)}async restoreSession(e=this.getState().selectedSession){if(!e)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e),r=this.selectionSeq,i=this.beginNavigationOperation?.(pc);try{await this.api.restore(e,t,this.archiveScopeProjectId())}catch(r){this.reportSessionError(e,t,r,n);return}if(!this.isCurrentRestoreOperation(t,r,i))return;let a={...e};delete a.archived,delete a.archivedAt;let o=this.getState().selectedSession?.id===a.id;this.replaceSession(a),o&&await this.selectSession(a,{updateUrl:!1,...i===void 0?{}:{navigation:i}})}async reloadSession(e=this.getState().selectedSession){if(e===void 0||!zs(e,this.statusForSession(e),this.sessionPersistenceOptions()))return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.reloadSession(e,t),this.transcripts.discard(j(t,e.id)),this.isSelectedSessionIdentity(e.id,t)&&await this.selectSession(e,{updateUrl:!1})}catch(r){this.reportSessionError(e,t,r,n)}}async detachParent(e=this.getState().selectedSession){if(e?.parentSessionPath===void 0)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.detachParent(e,t);let n=this.getState();if(this.disposed||M(n)!==t)return;let r=t=>{if(t.id!==e.id||t.cwd!==e.cwd)return t;let n={...t};return delete n.parentSessionPath,delete n.agentSubsession,n};this.setState({sessions:n.sessions.map(r),selectedSession:n.selectedSession===void 0?void 0:r(n.selectedSession)})}catch(r){this.reportSessionError(e,t,r,n)}}async listModels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{return(await this.api.models(e,t)).models}catch(r){return this.reportSessionError(e,t,r,n),[]}}async listModelCatalog(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{return(await this.api.modelCatalog(e,t)).models}catch(r){return this.reportSessionError(e,t,r,n),[]}}async setModelEnabled(e,t,n){let r=this.getState().selectedSession;if(!r||r.archived===!0)return;let i=M(this.getState()),a=this.captureSessionErrorOwner(r);try{return(await this.api.setModelEnabled(r,e,t,n,i)).models}catch(e){this.reportSessionError(r,i,e,a);return}}async setModelScope(e){let t=this.getState(),n=t.selectedSession;if(!n||n.archived===!0)return;let r=M(t),i=this.captureSessionErrorOwner(n);try{return(await this.api.setModelScope(n,e,r)).models}catch(e){this.reportSessionError(n,r,e,i);return}}async getSessionDefaults(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{return await this.api.getSessionDefaults(e,t)}catch(r){this.reportSessionError(e,t,r,n);return}}async setSessionDefaults(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;let n=M(this.getState()),r=this.captureSessionErrorOwner(t);try{return await this.api.setSessionDefaults(t,e,n)}catch(e){this.reportSessionError(t,n,e,r);return}}async setModel(e,t){let n=this.getState().selectedSession;if(!n||n.archived===!0)return;let r=M(this.getState()),i=this.captureSessionErrorOwner(n);try{let i=await this.api.setModel(n,e,t,r);if(M(this.getState())!==r)return;this.applyStatus(i),this.isSelectedSessionIdentity(n.id,r)&&await this.refreshAvailableThinkingLevels()}catch(e){this.reportSessionError(n,r,e,i)}}async cycleModel(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;let n=M(this.getState()),r=this.captureSessionErrorOwner(t);try{let r=await this.api.cycleModel(t,e,n);if(M(this.getState())!==n)return;this.applyStatus(r),this.isSelectedSessionIdentity(t.id,n)&&await this.refreshAvailableThinkingLevels()}catch(e){this.reportSessionError(t,n,e,r)}}async listThinkingLevels(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return[];let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{return(await this.api.thinkingLevels(e,t)).levels}catch(r){return this.reportSessionError(e,t,r,n),[]}}async refreshAvailableThinkingLevels(){let e=this.getState().selectedSession,t=M(this.getState());if(!e||e.archived===!0){this.getState().availableThinkingLevels.length>0&&this.setState({availableThinkingLevels:[]});return}let n=await this.listThinkingLevels();this.isSelectedSessionIdentity(e.id,t)&&this.setState({availableThinkingLevels:n})}async setThinkingLevel(e){let t=this.getState().selectedSession;if(!t||t.archived===!0)return;let n=M(this.getState()),r=this.captureSessionErrorOwner(t);try{let r=await this.api.setThinkingLevel(t,e,n);if(M(this.getState())!==n)return;this.applyStatus(r)}catch(e){this.reportSessionError(t,n,e,r)}}async cycleThinkingLevel(){let e=this.getState().selectedSession;if(!e||e.archived===!0)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{let n=await this.api.cycleThinkingLevel(e,t);if(M(this.getState())!==t)return;this.applyStatus(n)}catch(r){this.reportSessionError(e,t,r,n)}}async mutateQueuedMessage(e,t,n){let r=this.getState(),i=r.selectedSession;if(i===void 0||i.archived===!0||I(i))return;let a={...i},o=M(r);if(!this.isSelectedSessionScope(a,o)||!this.canMutateQueueMessage(a,o)||r.status?.queueMessageActionsUnavailable!==void 0)return;let s=n.map(e=>({...e}));if(!Number.isInteger(t)||t<0||t>=s.length)return;let c=s[t]?.text??``,l=this.selectionSeq,u=this.captureSessionErrorOwner(a),d=()=>this.isCurrentSessionSelection(a.id,o,l)&&this.isSelectedSessionScope(a,o)&&this.canMutateQueueMessage(a,o)&&this.getState().status?.queueMessageActionsUnavailable===void 0;try{let n=await this.api.mutateQueuedMessage(a,{action:e,index:t,expectedQueue:s},o);if(this.disposed)return;if(n.sessionId!==a.id)throw Error(D(`client.sessionController.queueResponseMismatch`,`The queue response belongs to a different conversation.`));if(!this.canMutateQueueMessage(a,o))throw Error(D(`client.sessionController.queueActionsUnavailable`,`Queued message actions are no longer available.`));if(this.hasDraftIdentityConflict(a,o))throw Error(D(`client.sessionController.queueContextChanged`,`The conversation context changed before the result returned. The current draft was preserved.`));e===`edit`&&(za(j(o,a.id),c),d()&&await this.replacePromptEditorText?.({machineId:o,sessionId:a.id,text:c,isCurrent:d})),d()&&this.applyStatus(n)}catch(e){this.disposed||this.reportSessionError(a,o,e,u)}}async clearServerQueue(){let e=this.getState(),t=e.selectedSession;if(t===void 0||t.archived===!0||I(t))return;let n=M(e),r=this.captureSessionErrorOwner(t),i=this.selectionSeq;try{let e=await this.api.clearQueue(t,n);this.isCurrentSessionSelection(t.id,n,i)&&this.applyStatus(e)}catch(e){this.reportSessionError(t,n,e,r)}}async dismissWarning(e){let t=this.getState(),n=t.selectedSession;if(n===void 0||I(n))return;let r=M(t),i=this.captureSessionErrorOwner(n),a=this.selectionSeq;try{let t=await this.api.dismissWarning(n,e,r);this.isCurrentSessionSelection(n.id,r,a)&&this.applyStatus(t)}catch(e){this.reportSessionError(n,r,e,i)}}submitAsk(e,t){return this.sendAskResponse(e,(n,r)=>this.api.submitAsk(n,e,t,r))}cancelAsk(e){return this.sendAskResponse(e,(t,n)=>this.api.cancelAsk(t,e,n))}answerDialog(e,t){return this.closeOpenDialog(e,(n,r)=>this.api.answerDialog(n,e,t,r))}cancelDialog(e){return this.closeOpenDialog(e,(t,n)=>this.api.cancelDialog(t,e,n))}async closeOpenDialog(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0)return;if(I(r)){await this.closePendingStartDialog(r,e,t);return}let i=M(n),a=this.captureSessionErrorOwner(r),o=this.selectionSeq;try{let e=await t(r,i);if(!this.isCurrentSessionSelection(r.id,i,o))return;this.recordDialogOutcome(e.outcome),this.applyStatus(e.sessionStatus)}catch(e){this.reportSessionError(r,i,e,a)}}async closePendingStartDialog(e,t,n){let r=this.pendingSessionStarts.get(e.id),i=r?.backendSessionId;if(r===void 0||i===void 0)return;let a=this.captureSessionErrorOwner(e,r.originWorkspace),o=this.selectionSeq;try{let t=await n({...e,id:i},r.machineId);if(o!==this.selectionSeq||this.getState().selectedSession?.id!==e.id)return;this.recordDialogOutcome(t.outcome),this.applyPendingStartStatus(r,t.sessionStatus)}catch(t){this.reportSessionError(e,r.machineId,t,a)}}recordDialogOutcome(e){if(e===void 0)return;let t=this.getState().pendingDialogs.find(t=>t.dialogId===e.dialogId);t!==void 0&&this.recordClosedDialog({dialog:t,reason:e.reason,...e.answer===void 0?{}:{answer:e.answer}})}async sendAskResponse(e,t){let n=this.getState(),r=n.selectedSession;if(r===void 0||r.archived===!0||I(r))return;let i=M(n),a=this.captureSessionErrorOwner(r),o=this.selectionSeq;try{let n=await t(r,i);Qa(j(i,r.id),e),this.isCurrentSessionSelection(r.id,i,o)&&this.applyStatus(n)}catch(e){this.reportSessionError(r,i,e,a)}}async stopActiveWork(){let e=this.getState().selectedSession;if(!e)return;let t=M(this.getState()),n=this.captureSessionErrorOwner(e);try{await this.api.abort(e,t)}catch(r){this.reportSessionError(e,t,r,n)}}refreshSelectedSession(e=this.getState().selectedSession?.id,t){let n=this.getState().selectedSession;if(e===void 0||n?.id!==e||this.selectedSessionLoadDeferred||n.archived===!0||I(n))return Promise.resolve();let r=M(this.getState()),i={session:n,machineId:r,selectionSeq:this.selectionSeq,errorOwner:this.captureSessionErrorOwner(n),...t?.recoverNetwork===!0?{recoverNetwork:!0}:{}},a=this.selectedReadGeneration;return this.requestSelectedSessionRefresh(i).catch(e=>{this.disposed||a!==this.selectedReadGeneration||t?.recoverNetwork===!0&&!this.isCurrentRefreshTarget(i)||(t?.silent===!0?console.warn(`Selected session background refresh failed`,{machineId:r,sessionId:n.id,errorCategory:`session-refresh`}):e instanceof Oe?this.browserErrors.report(Kn(r,n.id,i.errorOwner),D(`client.sessionController.conversationRefreshUnavailable`,`The conversation could not be refreshed. Check your connection and retry.`),`session-refresh`):this.reportSessionError(i.session,i.machineId,e,i.errorOwner))})}bufferRefreshEvents(e){if(this.refreshEventBuffer!==void 0&&this.isCurrentRefreshTarget(this.refreshEventBuffer.target))return this.refreshEventBuffer;this.flushPendingUpdates();let t={target:e,events:[],pendingDialogs:this.getState().pendingDialogs};return this.refreshEventBuffer=t,t}async refreshSessionNotifications(e,t){try{await this.notifications?.refreshSelectedSession(e,t)}catch{console.warn(`Selected session notification refresh failed`,{machineId:t,sessionId:e.id,errorCategory:`notification-refresh`})}}async joinSelectedSessionSnapshot(e){let t=!1,n,r=new Promise(e=>{n=()=>{t=!0,e(!0)}}),i={selectionSeq:e.selectionSeq,complete:n};this.initialSnapshotReady=i;let a=this.requestSelectedSessionRefresh(e).then(()=>t,n=>{if(!t)throw n;return this.reportSessionError(e.session,e.machineId,n,e.errorOwner),!0});try{return await Promise.race([r,a])}finally{this.initialSnapshotReady===i&&(this.initialSnapshotReady=void 0)}}requestSelectedSessionRefresh(e){if(!this.isCurrentRefreshTarget(e))return Promise.resolve();let t=j(e.machineId,e.session.id),n=this.selectedReadGeneration,r=()=>n===this.selectedReadGeneration&&this.isCurrentRefreshTarget(e);return this.selectedSessionRecoveryTarget!==void 0&&this.isCurrentRefreshTarget(this.selectedSessionRecoveryTarget)||this.bufferRefreshEvents(e),Promise.resolve().then(()=>{if(r())return this.refreshSessionNotifications(e.session,e.machineId)}),this.selectedSessionRefreshes.request(t,async()=>{if(!r())return;let n=new AbortController;this.selectedReadRecoveries.add(n),e.recoverNetwork===!0&&(this.selectedSessionRecoveryTarget=e);try{await sc(()=>this.readSelectedSessionSnapshot(e,t,()=>r()&&!n.signal.aborted,n.signal),r,n.signal,e.recoverNetwork===!0)}finally{this.selectedReadRecoveries.delete(n),this.selectedSessionRecoveryTarget===e&&(this.selectedSessionRecoveryTarget=void 0)}})}async readSelectedSessionSnapshot(e,t,n,r){let i=this.bufferRefreshEvents(e),a=this.transcripts.historyRevision(t),o=this.observeSessionSnapshot?.(e.machineId,e.session.id),s,c=this.browserErrors.captureRecovery(Kn(e.machineId,e.session.id,e.errorOwner),`session-refresh`),l=!1,u=()=>{if(!l&&(l=!0,this.refreshEventBuffer===i&&(this.refreshEventBuffer=void 0),n()))for(let e of i.events){if(!n())break;this.applyEvent(e)}};r?.addEventListener(`abort`,u,{once:!0});try{let r=await this.transcriptSnapshot(e.session,{limit:lc},e.machineId);if(!n()||this.transcripts.historyRevision(t)!==a)return;this.browserErrors.clearRecovered(c);let{page:l,status:u}=r;if(this.preserveBufferedDialogOutcomes(i,r.seq),!this.isUnchangedSelectedRefresh(e,t,l,u,r)){let n=this.transcripts.mergeSnapshot(t,l),i=this.transcripts.seedStreamingPartial(n.messages,r.partial);this.streamWatermark={sessionId:e.session.id,seq:r.seq},this.setState({...n,messages:i,status:u,activity:this.getState().sessionActivities[e.session.id]}),this.applyStatus(u),this.lastAppliedSelectedRefresh={selectionSeq:e.selectionSeq,partialJson:hc(r)}}s=this.transcripts.historyRevision(t),o?.(u)}finally{r?.removeEventListener(`abort`,u),u()}this.transcripts.historyRevision(t)===s&&n()&&this.initialSnapshotReady?.selectionSeq===e.selectionSeq&&this.initialSnapshotReady.complete()}preserveBufferedDialogOutcomes(e,t){let n=new Map(e.pendingDialogs.map(e=>[e.dialogId,e]));for(let r of e.events)if(!(r.seq===void 0||r.seq>t||this.isStreamEventBelowWatermark(r))&&(r.type===`dialog.opened`&&n.set(r.dialog.dialogId,r.dialog),r.type===`dialog.closed`)){let e=n.get(r.dialogId);e!==void 0&&this.recordClosedDialog({dialog:e,reason:r.reason,...r.answer===void 0?{}:{answer:r.answer}}),n.delete(r.dialogId)}}isUnchangedSelectedRefresh(e,t,n,r,i){let a=this.lastAppliedSelectedRefresh;return a?.selectionSeq!==e.selectionSeq||i.seq<(this.streamWatermark?.seq??0)||hc(i)!==a.partialJson||!ts(this.transcripts.rawHistoryPage(t),n)||JSON.stringify(r)!==JSON.stringify(this.getState().status)?!1:this.getState().sessionActivities[r.sessionId]?.phase!==`active`||rr(r)}isCurrentRefreshTarget(e){let t=this.getState().selectedSession;return this.isCurrentSessionSelection(e.session.id,e.machineId,e.selectionSeq)&&t?.cwd===e.session.cwd&&t.path===e.session.path&&t.archived===e.session.archived&&Nc(e.navigation)}isCurrentSessionSelection(e,t,n){return n===this.selectionSeq&&this.isSelectedSessionIdentity(e,t)}isCurrentRestoreOperation(e,t,n){return t===this.selectionSeq&&M(this.getState())===e&&Nc(n)}isSelectedSessionIdentity(e,t){if(this.disposed)return!1;let n=this.getState(),r=n.selectedSession;return M(n)===t&&r?.id===e&&r.archived!==!0&&!I(r)}isSelectedSessionScope(e,t){let n=this.getState().selectedSession;return this.isSelectedSessionIdentity(e.id,t)&&n?.cwd===e.cwd&&n.path===e.path}hasDraftIdentityConflict(e,t){let n=this.getState(),r=n.selectedSession;return M(n)===t&&r?.id===e.id&&(r.cwd!==e.cwd||r.path!==e.path)}reportSessionError(e,t,n,r={cwd:e.cwd}){this.browserErrors.report(Kn(t,e.id,r),ic(n))}captureSessionErrorOwner(e,t=this.workspaceForSessionError(e)){return{cwd:e.cwd,...t===void 0?{}:{projectId:t.projectId,workspaceId:t.id}}}workspaceForSessionError(e){let t=this.getState();return[t.selectedWorkspace,...t.workspaces,...Object.values(t.workspacesByProjectId).flat()].find(t=>t?.path===e.cwd)}reportWorkspaceError(e,t,n){this.browserErrors.report(Gn(t,e.projectId,e.id),ic(n))}applyBulkSessionFailures(e,t,n,r,i,a){t.length!==0&&this.reportWorkspaceOrSessionError(r,i,n,D(`client.sessionController.failed.for.sessions.5ef9b2`,`{value1} failed for {value2} sessions: {value3}`,{value1:e,value2:String(t.length),value3:t.join(`;`)}),a)}reportWorkspaceOrSessionError(e,t,n,r,i){e===void 0?t!==void 0&&this.reportSessionError(t,n,r,i):this.reportWorkspaceError(e,n,r)}sessionCacheKey(e){return j(M(this.getState()),e)}statusForSession(e){if(e===void 0)return;let t=this.getState();return t.status?.sessionId===e.id&&t.selectedSession?.id===e.id?t.status:t.sessionStatuses[e.id]}sessionPersistenceOptions(){let e=this.getState();return Ls(e.machineRuntimes[M(e)])}workspaceSelectionKey(e){return`${M(this.getState())}:${e}`}replaceSession(e){let t=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(t=>t.id===e.id?e:t),selectedSession:t?.id===e.id?e:t})}navigationSelection(){if(this.captureNavigation!==void 0)return this.captureNavigation();let e=this.getState();return{machineId:M(e),projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:e.selectedSession?.id}}navigationSelectionMatchesState(e){let t=this.navigationSelection();return t.machineId===e.machineId&&t.projectId===e.projectId&&t.workspaceId===e.workspaceId&&t.sessionId===e.sessionId&&t.tool===e.tool&&t.view===e.view}createPendingSessionStart(e,t,n,r){let i=`creating:${Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,`0`)).join(``)}`,a=new Date().toISOString(),o={id:i,path:`pi-web://pending-session/${i}`,cwd:e.path,persisted:!1,name:D(`client.sessionController.new.session.c57c30`,`New session`),created:a,modified:a,messageCount:0,firstMessage:``,clientPendingStart:!0,machineId:t};return{tempId:i,originWorkspace:e,workspaceId:e.id,cwd:e.path,machineId:t,expectedNavigation:n,pendingUrlPublished:r,session:o,queuedSends:[],discarded:!1}}insertAndSelectPendingSession(e,t){let n=this.getState();this.selectClientPendingStartSession(e,{activity:Sc(e.id),sessions:[e,...n.sessions.filter(t=>t.id!==e.id)],updateUrl:t?.updateUrl})}selectClientPendingStartSession(e,t){this.retireReadRecoveries([`session`]),this.selectedSessionLoadDeferred=!1,this.sessionSelection.rememberSession({...e,cwd:this.workspaceSelectionKey(e.cwd)}),this.selectionSeq+=1,this.selectedSessionJoinNavigation=void 0,this.socket.close(),this.notifications?.clearSelectedSession(),this.streamWatermark=void 0,this.clearPendingUpdates();let n=this.getState(),r=this.pendingSessionStarts.get(e.id),i=t?.activity??n.sessionActivities[e.id]??(r===void 0?void 0:Sc(e.id,r.queuedSends.length));this.setState({sessions:t?.sessions??(n.sessions.some(t=>t.id===e.id)?n.sessions:[e,...n.sessions]),selectedSession:e,messages:[],messagePageStart:0,messagePageEnd:0,messagePageTotal:0,isLoadingEarlierMessages:!1,status:void 0,activity:i,pendingDialogs:[],closedDialogs:[],availableThinkingLevels:[],treeDialog:void 0,...i===void 0?{}:{sessionActivities:{...n.sessionActivities,[e.id]:i}},error:``}),r?.backendSessionId!==void 0&&this.connectPendingStartSocket(r),t?.updateUrl!==!1&&this.updateUrl()}async resolvePendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.queuedSends.splice(0),i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId,t.id);if(n.discarded){Ba(j(n.machineId,e)),Ka(j(n.machineId,e)),this.setState({clientQueuedSessionMessages:_c(this.getState().clientQueuedSessionMessages,e)}),this.applyReleasedCreatedSessions(i,n.machineId),this.api.stop(t,n.machineId).catch(()=>{});return}Yr(t,n.machineId),Va(j(n.machineId,e),j(n.machineId,t.id)),qa(j(n.machineId,e),j(n.machineId,t.id));let a=Xr(t,n.machineId),o=this.captureSessionErrorOwner(t,n.originWorkspace);if(!this.isCurrentPendingStart(n)){this.setState({clientQueuedSessionMessages:_c(this.getState().clientQueuedSessionMessages,e)}),await this.flushQueuedPendingSends(a,n.machineId,r,o);return}let s=this.getState(),c=s.selectedSession?.id===e,l={machineId:n.machineId,projectId:n.originWorkspace.projectId,workspaceId:n.workspaceId,sessionId:e},u=c&&(this.navigateToSession!==void 0||!n.pendingUrlPublished),d=c&&!u&&(this.isPendingSessionStartRouteCurrent?.(l)??!0);c&&!u&&!d&&this.clearActiveSession(),this.setState({sessions:bc(s.sessions,e,a),sessionActivities:gc(s.sessionActivities,e),sendingPrompts:yc(s.sendingPrompts,e,a.id),clientQueuedSessionMessages:yc(s.clientQueuedSessionMessages,e,a.id),...d?{selectedSession:a,status:s.sessionStatuses[a.id],activity:s.sessionActivities[a.id],pendingDialogs:s.sessionStatuses[a.id]?.pendingDialogs??[],closedDialogs:[]}:{},error:``}),this.applyReleasedCreatedSessions(i,n.machineId),u?await this.reconcileCompletedPendingSelection(n,a):d&&(this.onPendingSessionStartCommitted?.(l,a),this.onPendingSessionStartCommitted===void 0&&this.updateUrl({replace:!0}),await this.selectSession(a,{updateUrl:!1,navigation:n.navigation})),await this.flushQueuedPendingSends(a,n.machineId,r,o)}async reconcileCompletedPendingSelection(e,t){let n=e.navigation;if(!e.pendingUrlPublished&&!Nc(n))this.clearUnreconciledPendingSelection(e,t);else if(e.expectedNavigation=this.pendingStartExpectedNavigation(e),this.navigateToSession!==void 0)try{let r=await this.navigateToSession(t,{...e.pendingUrlPublished?{replace:!0,creationHandoff:!0}:{},expected:e.expectedNavigation});if(r&&this.getState().selectedSession?.id!==e.tempId)return;this.clearUnreconciledPendingSelection(e,t,r||e.pendingUrlPublished||!Nc(n)?void 0:D(`ui.main.0a71e48cd0f9`,`Session started, but its navigation changed before selection completed. Select it from the session list.`))}catch(n){this.clearUnreconciledPendingSelection(e,t,D(`ui.main.d15d396c9633`,`Session started but could not be selected: {arg0}`,{arg0:kc(n)}))}else try{if(await this.selectSession(t,{updateUrl:!1,navigation:n}),!Nc(n)){this.clearUnreconciledPendingSelection(e,t);return}if(this.getState().selectedSession?.id!==t.id){this.clearUnreconciledPendingSelection(e,t,D(`ui.main.8cd247b86afd`,`Session started, but its selection changed before navigation completed. Select it from the session list.`));return}this.updateUrl(e.pendingUrlPublished?{replace:!0}:void 0)}catch(n){this.clearUnreconciledPendingSelection(e,t,D(`ui.main.d15d396c9633`,`Session started but could not be selected: {arg0}`,{arg0:kc(n)}))}}pendingStartExpectedNavigation(e){return e.pendingUrlPublished?{machineId:e.machineId,projectId:e.originWorkspace.projectId,workspaceId:e.workspaceId,sessionId:e.tempId}:{...this.navigationSelection(),sessionId:e.expectedNavigation.sessionId}}clearUnreconciledPendingSelection(e,t,n){let r=this.getState().selectedSession?.id;(r===e.tempId||r===t.id)&&(this.clearActiveSession(),n!==void 0&&this.browserErrors.report(Gn(e.machineId,e.originWorkspace.projectId,e.workspaceId),n))}cancelUnstartedSession(e){if(this.pendingSessionStarts.get(e.tempId)!==e)return;this.pendingSessionStarts.delete(e.tempId),e.discarded=!0,e.queuedSends=[],Zr(e.tempId,e.machineId);let t=j(e.machineId,e.tempId);Ba(t),Ka(t);let n=this.getState(),r=n.selectedSession?.id===e.tempId;if(this.setState({sessions:n.sessions.filter(t=>t.id!==e.tempId),sessionStatuses:_c(n.sessionStatuses,e.tempId),sessionActivities:gc(n.sessionActivities,e.tempId),sendingPrompts:_c(n.sendingPrompts,e.tempId),clientQueuedSessionMessages:_c(n.clientQueuedSessionMessages,e.tempId)}),!r)return;this.clearActiveSession();let i={machineId:e.machineId,projectId:e.originWorkspace.projectId,workspaceId:e.workspaceId,sessionId:e.tempId};(this.isPendingSessionStartRouteCurrent?.(i)??!0)&&this.updateUrl({replace:!0})}failPendingSessionStart(e,t){let n=this.pendingSessionStarts.get(e);if(n===void 0)return;this.pendingSessionStarts.delete(e);let r=n.discarded;n.discarded=!0,this.getState().selectedSession?.id===e&&this.socket.close();let i=this.takeSuppressedCreatedSessionsFor(n.cwd,n.machineId),a=this.isCurrentPendingStart(n);if(r){a&&this.applyReleasedCreatedSessions(i,n.machineId);return}let o=kc(t),s=D(`client.sessionController.failed.to.start.session.881118`,`Failed to start session: {value1}`,{value1:o});if(!a){this.browserErrors.report(Gn(n.machineId,n.originWorkspace.projectId,n.originWorkspace.id),s);return}let c=this.getState(),l=Cc(e,o,n.queuedSends.length),u=c.sessions.some(t=>t.id===e);this.setState({sessions:u?c.sessions:[n.session,...c.sessions],sessionActivities:{...c.sessionActivities,[e]:l},activity:c.selectedSession?.id===e?l:c.activity,...c.selectedSession?.id===e?{pendingDialogs:[]}:{}}),this.reportSessionError(n.session,n.machineId,s,this.captureSessionErrorOwner(n.session,n.originWorkspace)),this.applyReleasedCreatedSessions(i,n.machineId)}isCurrentPendingStart(e){let t=this.getState();return M(t)===e.machineId&&t.selectedWorkspace?.id===e.workspaceId&&t.selectedWorkspace.projectId===e.originWorkspace.projectId}hasPendingStartFor(e,t){return Array.from(this.pendingSessionStarts.values()).some(n=>n.cwd===e&&n.machineId===t)}isSuppressedCreatedSession(e,t){let n=this.suppressedCreatedSessions.get(e.id);return n?.session.cwd===e.cwd&&n.machineId===t}takeSuppressedCreatedSessionsFor(e,t,n){if(n!==void 0&&this.suppressedCreatedSessions.delete(n),this.hasPendingStartFor(e,t))return[];let r=[];for(let[n,i]of this.suppressedCreatedSessions)i.session.cwd===e&&i.machineId===t&&(this.suppressedCreatedSessions.delete(n),r.push(i.session));return r}applyReleasedCreatedSessions(e,t){if(e.length===0||M(this.getState())!==t)return;let n=this.getState();if(n.selectedWorkspace===void 0)return;let r=new Set(n.sessions.map(e=>e.id)),i=e.filter(e=>e.cwd===n.selectedWorkspace?.path&&!r.has(e.id));i.length!==0&&this.setState({sessions:[...i.reverse(),...n.sessions]})}mergePendingStartSessions(e,t,n){let r=this.getState().sessions.filter(t=>I(t)&&t.cwd===e&&t.machineId===n);if(r.length===0)return t;let i=new Set(r.map(e=>e.id));return[...r,...t.filter(e=>!i.has(e.id))]}async recreateCachedNewSession(e,t,n=this.selectionSeq,r=this.captureSessionErrorOwner(e)){let i=M(this.getState()),a=this.navigationSelection();try{let r=await this.api.startSession(e.cwd,i);if(!this.isCurrentSessionSelection(e.id,i,n)||!this.isSelectedSessionScope(e,i)||!Nc(t?.navigation))return;Yr(r,i),Va(j(i,e.id),j(i,r.id)),qa(j(i,e.id),j(i,r.id)),Zr(e.id,i);let o=Xr(r,i);if(this.setState({sessions:[o,...this.getState().sessions.filter(t=>t.id!==e.id&&t.id!==r.id)],error:``}),this.navigateToSession!==void 0){let r=this.navigationSelection();!await this.navigateToSession(o,{...t?.updateUrl===!1?{replace:!0}:{},expected:{...a,tool:r.tool,view:r.view}})&&this.isCurrentSessionSelection(e.id,i,n)&&this.clearActiveSession()}else await this.selectSession(o,{updateUrl:!1}),this.updateUrl(t?.updateUrl===!1?{replace:!0}:void 0)}catch(t){this.reportSessionError(e,i,t,r)}}markCachedNewSessionPersisted(e){if(!$r(e))return;let t=this.getState().sessions.find(t=>t.id===e.id)??e;this.replaceSession(ei(t))}async applyCommandResult(e,t){if(e.type===`select`){this.setState({commandDialog:e});return}if(e.type===`tree`){this.setState({treeDialog:e.tree});return}let n=(e.type,e.message);if(n!==void 0&&n!==``&&this.setState({messages:[...this.getState().messages,ui(e.type===`unsupported`?`system`:`tool`,n)]}),e.type===`done`&&e.session){e.promptDraft!==void 0&&za(this.sessionCacheKey(e.session.id),e.promptDraft);let n=this.getState().selectedSession,r=[e.session,...this.getState().sessions.filter(t=>t.id!==e.session?.id)];if(this.setState({sessions:r,...n?.id===e.session.id?{selectedSession:e.session}:{}}),n?.id===e.session.id||!this.navigationSelectionMatchesState(t))return;this.navigateToSession===void 0?await this.selectSession(e.session):await this.navigateToSession(e.session,{expected:t})}}applyCreatedSession(e){let t=this.getState();if(t.selectedWorkspace?.path!==e.cwd||t.sessions.some(t=>t.id===e.id))return;let n=M(t);this.hasPendingStartFor(e.cwd,n)?this.suppressedCreatedSessions.set(e.id,{session:e,machineId:n}):this.setState({sessions:[e,...t.sessions]})}applyActivity(e){this.setState({sessionActivities:{...this.getState().sessionActivities,[e.sessionId]:e},activity:this.getState().selectedSession?.id===e.sessionId?e:this.getState().activity})}applyStatus(e){let t=this.getState(),n=t.selectedSession?.id===e.sessionId,r=t.sessionActivities[e.sessionId]?.phase===`active`&&!rr(e);this.setState({sessionStatuses:{...t.sessionStatuses,[e.sessionId]:e},...Ac(t,e.sessionId,e.messageCount),...r?{sessionActivities:gc(t.sessionActivities,e.sessionId)}:{},status:n?e:t.status,activity:n&&r?void 0:t.activity,...n?{pendingDialogs:e.pendingDialogs??[]}:{}})}applyOpenedDialog(e){let t=this.getState();t.selectedSession===void 0||t.pendingDialogs.some(t=>t.dialogId===e.dialogId)||this.setState({pendingDialogs:[...t.pendingDialogs,e]})}applyClosedDialog(e,t,n){let r=this.getState().pendingDialogs.find(t=>t.dialogId===e);r!==void 0&&this.recordClosedDialog({dialog:r,reason:t,...n===void 0?{}:{answer:n}})}recordClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e.dialog.dialogId)||this.setState({pendingDialogs:t.pendingDialogs.filter(t=>t.dialogId!==e.dialog.dialogId),closedDialogs:[...t.closedDialogs,e]})}dismissClosedDialog(e){let t=this.getState();t.closedDialogs.some(t=>t.dialog.dialogId===e)&&this.setState({closedDialogs:t.closedDialogs.filter(t=>t.dialog.dialogId!==e)})}applySessionName(e,t){let n=n=>{if(n.id!==e)return n;let r={...n};return t===void 0||t===``?delete r.name:r.name=t,r},r=this.getState().selectedSession;this.setState({sessions:this.getState().sessions.map(n),selectedSession:r===void 0?void 0:n(r)})}applyEvent(e){if(e.type===`session.diagnostic`){console.warn(e.message);return}if(e.type===`notifications.inbox`){this.notifications?.applyInboxEvent(M(this.getState()),e);return}if(e.type===`command.output`&&this.notifications?.shouldFilterLegacyNotification(M(this.getState()),e.notificationId)===!0)return;let t=this.refreshEventBuffer;if(t!==void 0&&this.isCurrentRefreshTarget(t.target)){t.events.push(e);return}if(this.isStreamEventBelowWatermark(e))return;if(e.type===`session.tree.changed`){this.invalidateSessionTree();return}if(e.type===`status.update`){this.queueStatusUpdate(e.status);return}if(e.type===`activity.update`){this.queueActivityUpdate(e.activity);return}if(jc(e)){this.queueTranscriptEvent(e);return}if(this.flushPendingUpdates(),e.type===`dialog.opened`){this.applyOpenedDialog(e.dialog);return}if(e.type===`dialog.closed`){this.applyClosedDialog(e.dialogId,e.reason,e.answer);return}let n=this.transcripts.applyLiveEvent(this.getState().messages,e);n?this.setState({messages:n}):e.type===`session.name`&&this.applySessionName(e.sessionId,e.name)}queueTranscriptEvent(e){this.pendingTranscriptEvents.push(e),this.schedulePendingFlush()}queueStatusUpdate(e){this.pendingStatusBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueActivityUpdate(e){this.pendingActivityBySession.set(e.sessionId,e),this.schedulePendingFlush()}queueStartupProgress(e){if(this.getState().sessions.some(t=>t.id===e.activity.sessionId)){this.queueActivityUpdate(e.activity);return}let t=e.startupToken===void 0?void 0:this.pendingSessionStarts.get(e.startupToken);t===void 0||t.discarded||(this.learnPendingStartBackendSession(t,e.activity.sessionId),this.queueActivityUpdate(e.activity.phase===`idle`?Sc(t.tempId,t.queuedSends.length):xc(e.activity,t.tempId)))}learnPendingStartBackendSession(e,t){t!==``&&e.backendSessionId===void 0&&(e.backendSessionId=t,this.getState().selectedSession?.id===e.tempId&&this.connectPendingStartSocket(e))}connectPendingStartSocket(e){let t=e.backendSessionId;if(t===void 0||e.discarded)return;let n={id:t,cwd:e.cwd};this.socket.connect(n,t=>{this.applyPendingStartEvent(e,t)},()=>{this.resyncPendingStartDialogs(e)},e.machineId),this.resyncPendingStartDialogs(e)}resyncPendingStartDialogs(e){let t=e.backendSessionId;t!==void 0&&this.api.status({id:t,cwd:e.cwd},e.machineId).then(t=>{if(e.discarded||this.getState().selectedSession?.id!==e.tempId)return;this.applyStatus(t);let n=this.getState(),r=new Set([...n.pendingDialogs.map(e=>e.dialogId),...n.closedDialogs.map(e=>e.dialog.dialogId)]),i=(t.pendingDialogs??[]).filter(e=>!r.has(e.dialogId));i.length>0&&this.setState({pendingDialogs:[...n.pendingDialogs,...i]})},()=>void 0)}applyPendingStartEvent(e,t){e.discarded||this.getState().selectedSession?.id!==e.tempId||(t.type===`dialog.opened`?this.applyOpenedDialog(t.dialog):t.type===`dialog.closed`?this.applyClosedDialog(t.dialogId,t.reason,t.answer):t.type===`status.update`&&this.applyPendingStartStatus(e,t.status))}applyPendingStartStatus(e,t){this.applyStatus(t),!(e.discarded||this.getState().selectedSession?.id!==e.tempId)&&this.setState({pendingDialogs:t.pendingDialogs??[]})}schedulePendingFlush(){this.pendingFrame===void 0&&(this.pendingFrame=requestAnimationFrame(()=>{this.pendingFrame=void 0,this.flushPendingUpdates()}))}flushPendingUpdates(){if(this.pendingTranscriptEvents.length>0){let e=this.pendingTranscriptEvents;this.pendingTranscriptEvents=[];let t=this.getState().messages;for(let n of e)t=this.transcripts.applyLiveEvent(t,n)??t;t!==this.getState().messages&&this.setState({messages:t})}if(this.pendingActivityBySession.size>0){let e=Array.from(this.pendingActivityBySession.values());this.pendingActivityBySession.clear();for(let t of e)this.applyActivity(t)}if(this.pendingStatusBySession.size>0){let e=Array.from(this.pendingStatusBySession.values());this.pendingStatusBySession.clear();for(let t of e)this.applyStatus(t)}}clearPendingUpdates(){this.refreshEventBuffer=void 0,this.pendingTranscriptEvents=[],this.pendingStatusBySession.clear(),this.pendingActivityBySession.clear(),this.pendingFrame!==void 0&&(cancelAnimationFrame(this.pendingFrame),this.pendingFrame=void 0)}isStreamEventBelowWatermark(e){if(e.type===`session.name`||e.type===`session.error`||e.type===`command.output`||e.type===`session.tree.changed`)return!1;let t=this.streamWatermark;return t===void 0||t.sessionId!==this.getState().selectedSession?.id?!1:e.seq!==void 0&&e.seq<=t.seq}async selectSearchMatch(e,t,n){await this.selectSessionAfterNavigation(e,this.navigationSelection());let r=M(this.getState()),i=this.captureSessionErrorOwner(e),a=this.selectionSeq;try{for(;this.isCurrentSearchJump(e.id,r,a)&&this.getState().messagePageStart>t.messageIndex;){let t=this.getState().messagePageStart,n=await this.api.messages(e,{before:t,limit:uc},r);if(!this.isCurrentSearchJump(e.id,r,a))return;let i=this.transcripts.mergeHistory(this.sessionCacheKey(e.id),n);if(this.setState(i),i.messagePageStart>=t)break}}catch(t){this.reportSessionError(e,r,t,i);return}this.isCurrentSearchJump(e.id,r,a)&&this.setState({...this.transcripts.indexedView(this.sessionCacheKey(e.id)),sessionSearchTarget:{sessionId:e.id,messageIndex:t.messageIndex,query:n,requestId:++this.searchTargetSeq}})}isCurrentSearchJump(e,t,n){return this.selectionSeq===n&&M(this.getState())===t&&this.getState().selectedSession?.id===e}};function hc(e){return JSON.stringify(e.partial??null)}function gc(e,t){return _c(e,t)}function _c(e,t){return Object.fromEntries(Object.entries(e).filter(([e])=>e!==t))}function vc(e,t){if(t.length===0)return e;let n=new Set(t);return Object.fromEntries(Object.entries(e).filter(([e])=>!n.has(e)))}function yc(e,t,n){if(t===n||!(t in e))return e;let r=e[t];return r===void 0?e:{..._c(e,t),[n]:r}}function bc(e,t,n){let r=[],i=!1;for(let a of e)a.id===t?i||=(r.push(n),!0):a.id!==n.id&&r.push(a);return i?r:[n,...r]}function I(e){return e!==void 0&&`clientPendingStart`in e&&e.clientPendingStart===!0}function xc(e,t){return{sessionId:t,phase:e.phase,label:e.label,...e.detail===void 0?{}:{detail:e.detail},at:e.at}}function Sc(e,t=0){return{sessionId:e,phase:`active`,label:D(`activity.creating`,`Creating session`),detail:t>0?D(`client.sessionController.will.send.queued.messages.when.the.backend.session.is.ready.f49381`,`Will send {value1} queued messages when the backend session is ready`,{value1:String(t)}):D(`client.sessionController.waiting.for.the.backend.session.3a8a3d`,`Waiting for the backend session`),at:new Date().toISOString()}}function Cc(e,t,n=0){let r=n>0?D(`client.sessionController.queued.messages.retained.below.2194c6`,` · {value1} queued messages retained below`,{value1:String(n)}):``;return{sessionId:e,phase:`error`,label:D(`client.sessionController.session.creation.failed.aff35c`,`Session creation failed`),detail:`${t}${r}`,at:new Date().toISOString()}}function wc(e){if(e.type===`prompt`){let t=e.attachments?.length??0;return{kind:e.streamingBehavior===`steer`?`steer`:`followUp`,text:Tc(e.text,e.attachments),...t>0?{hasAttachments:!0,attachmentCount:t}:{}}}return{kind:`followUp`,text:e.text}}function Tc(e,t){let n=Ec(t);return n===void 0?e:e.trim()===``?n:`${e}\n\n${n}`}function Ec(e){if(e===void 0||e.length===0)return;let t=e.map(e=>e.name?.trim()).filter(e=>e!==void 0&&e!==``),n=e.length,r=D(`client.sessionController.attachments.092014`,`{value1} attachments`,{value1:String(n)});if(t.length===0)return D(`client.sessionController.queued.6fc044`,`[Queued {value1}]`,{value1:r});let i=t.slice(0,3).join(`、`),a=t.length>3?D(`client.sessionController.plus.more.675fd5`,`, plus {value1} more`,{value1:String(t.length-3)}):``;return D(`client.sessionController.queued.871266`,`[Queued {value1}: {value2}{value3}]`,{value1:r,value2:i,value3:a})}function Dc(e){let t=new Set,n=[];for(let r of e)t.has(r.id)||(t.add(r.id),n.push(r));return n}function Oc(e){return e.map(e=>`${e.sessionId}: ${e.error}`)}function kc(e){return e instanceof Error?e.message:String(e)}function Ac(e,t,n){if(n===void 0)return{};let r=e.sessions.some(e=>e.id===t&&e.messageCount!==n)?e.sessions.map(e=>e.id===t?{...e,messageCount:n}:e):void 0,i=e.selectedSession?.id===t&&e.selectedSession.messageCount!==n?{...e.selectedSession,messageCount:n}:e.selectedSession;return{...r===void 0?{}:{sessions:r},...i===e.selectedSession?{}:{selectedSession:i}}}function jc(e){return e.type===`assistant.delta`||e.type===`assistant.thinking.delta`||e.type===`shell.chunk`}function Mc(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`session not found`)||t.includes(D(`session.notFound`,`Session not found`))}function Nc(e){return e===void 0||e.isCurrent()}var Pc=class{constructor(){this.active=new Map,this.revisions=new Map,this.generation=0}observe(e,t){let n=t.type===`status.update`?t.status.sessionId:t.activity.sessionId,r=JSON.stringify([e,n]);this.revisions.set(r,(this.revisions.get(r)??0)+1);let i=this.active.get(r),a={statusActive:i?.statusActive??!1,activityActive:i?.activityActive??!1};if(t.type===`status.update`?(a.statusActive=rr(t.status),a.statusActive||(a.activityActive=!1)):a.activityActive=rr(void 0,t.activity),a.statusActive||a.activityActive)this.active.set(r,a);else return this.active.delete(r),i===void 0?void 0:n}snapshotObserver(e,t){let n=JSON.stringify([e,t]),r=this.revisions.get(n),i=this.generation;return a=>{if(a.sessionId===t&&i===this.generation&&this.revisions.get(n)===r)return this.observe(e,{type:`status.update`,status:a})}}clear(){this.active.clear(),this.revisions.clear(),this.generation+=1}};async function Fc(e){let t=await Promise.allSettled(e),n=[];for(let e of t)e.status===`rejected`&&n.push(e.reason);if(n.length===1)throw n[0];if(n.length>1)throw AggregateError(n,n.map(e=>e instanceof Error?e.message:String(e)).join(`; `))}var Ic={order:0,overflowWatermark:0};function Lc(e){return{...e,status:`loading`,catalogRevision:0,notifications:[],dismissThrough:Ic,optimisticDismissedIds:[],announcements:[]}}function Rc(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)throw Error(`Notification inbox snapshot does not match the selected session`);let r=e!==void 0&&Qc(e,t)&&e.daemonInstanceId===n.daemonInstanceId;return{...t,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:n.notifications,dismissThrough:n.dismissThrough,optimisticDismissedIds:r?e.optimisticDismissedIds:[],...r&&e.optimisticDismissAllThrough!==void 0?{optimisticDismissAllThrough:e.optimisticDismissAllThrough}:{},announcements:r?e.announcements:[]}}function zc(e,t,n){if(n.summary.sessionId!==t.sessionId||n.summary.cwd!==t.cwd)return{value:e??Lc(t),needsRefresh:!1,changed:!1};if(e===void 0||!Qc(e,t))return{value:el(t),needsRefresh:!0,changed:!0};if(e.daemonInstanceId!==n.daemonInstanceId)return{value:el(t),needsRefresh:!0,changed:e.status!==`stale`||e.daemonInstanceId!==void 0||e.notifications.length>0};let r=e.summary?.inboxRevision??0;if(n.summary.inboxRevision<=r)return{value:e,needsRefresh:!1,changed:!1};if(e.status!==`fresh`||n.summary.inboxRevision!==r+1||n.delta.kind===`resync`)return{value:{...e,status:`stale`},needsRefresh:!0,changed:e.status!==`stale`};let i,a;switch(n.delta.kind){case`added`:{let t=n.delta;if(e.notifications.some(e=>e.id===t.notification.id))return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};i=[t.notification,...e.notifications].filter(e=>e.id!==t.evictedNotificationId).sort((e,t)=>t.order-e.order).slice(0,100),a={id:`${n.daemonInstanceId}:${String(n.summary.inboxRevision)}:${t.notification.id}`,severity:t.notification.severity,message:t.notification.message};break}case`dismissed`:{let t=new Set(n.delta.notificationIds);i=e.notifications.filter(e=>!t.has(e.id));break}case`cleared`:i=[]}let o=i[0]?.order??0;if(!tl(i,n.summary)||n.dismissThrough.order!==o||n.dismissThrough.overflowWatermark<n.summary.discardedCount)return{value:{...e,status:`stale`},needsRefresh:!0,changed:!0};let s=a===void 0?e.announcements:[...e.announcements,a].slice(-100);return{value:{...e,status:`fresh`,daemonInstanceId:n.daemonInstanceId,catalogRevision:n.catalogRevision,summary:n.summary,notifications:i,dismissThrough:n.dismissThrough,announcements:s},needsRefresh:!1,changed:!0}}function Bc(e){if(e?.status!==`fresh`||e.daemonInstanceId===void 0||e.summary===void 0)return;let t=new Set(e.optimisticDismissedIds),n=e.optimisticDismissAllThrough,r=e.notifications.filter(e=>!t.has(e.id)&&(n===void 0||e.order>n.order)),i=rl(e.summary.discardedCount,e.dismissThrough.overflowWatermark,n?.overflowWatermark);return r.length===0&&t.size>0&&(i=0),{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd,daemonInstanceId:e.daemonInstanceId,notifications:r,retainedCount:r.length,discardedCount:i,...il(nl(r)),dismissThrough:e.dismissThrough,pendingDismissedIds:t,dismissAllPending:n!==void 0,announcements:e.announcements}}function Vc(e){return e===`error`?D(`client.sessionNotifications.error.0bc1fb`,`Error`):e===`warning`?D(`client.sessionNotifications.warning.a8b7a4`,`Warning`):D(`client.sessionNotifications.info.e70286`,`Info`)}function Hc(e){return D(`client.sessionNotifications.notification.received.0cb785`,`{value1} notification received.`,{value1:Vc(e.severity)})}function Uc(e){return e.retainedCount+e.discardedCount}function Wc(e){return D(`client.sessionNotifications.notifications.38c528`,`Notifications ({value1})`,{value1:String(Uc(e))})}function Gc(e){let t=e.message.replace(/\s+/gu,` `).trim();if(t===``)return D(`client.sessionNotifications.dismiss.notification.137f92`,`Dismiss {value1} notification`,{value1:Vc(e.severity)});let n=Array.from(t),r=n.length<=80?t:`${n.slice(0,79).join(``).trimEnd()}…`;return D(`client.sessionNotifications.dismiss.notification.600367`,`Dismiss notification: {value1}`,{value1:r})}function Kc(e,t){let n=e.findIndex(e=>e.id===t);if(n===-1)return{kind:`header`};let r=e[n+1];if(r!==void 0)return{kind:`notification`,notificationId:r.id};let i=e[n-1];return i===void 0?{kind:`header`}:{kind:`notification`,notificationId:i.id}}function qc(e){return JSON.stringify([e.machineId,e.cwd,e.sessionId])}function Jc(e,t){return e.has(qc(t))}function Yc(e,t,n){let r=new Set(e),i=qc(t);return n?r.add(i):r.delete(i),r}function Xc(e){return D(`client.sessionNotifications.older.notifications.not.shown.7c54ee`,`{value1} older notifications not shown.`,{value1:String(e)})}function Zc(e){if(!e.truncated)return;let t=Lt/1024;return D(`client.sessionNotifications.message.truncated.at.kib.ac3119`,`Message truncated at {value1} KiB.`,{value1:String(t)})}function Qc(e,t){return e.machineId===t.machineId&&e.sessionId===t.sessionId&&e.cwd===t.cwd}function $c(e,t){if(e===`error`||t===`error`)return`error`;if(e===`warning`||t===`warning`)return`warning`;if(e===`info`||t===`info`)return`info`}function el(e){return{...Lc(e),status:`stale`}}function tl(e,t){return e.length===t.retainedCount&&nl(e)===t.highestSeverity}function nl(e){let t;for(let n of e)t=$c(t,n.severity);return t}function rl(e,t,n){if(e===0||n===void 0)return e;let r=t-e+1;return e-Math.max(0,Math.min(e,n-r+1))}function il(e){return e===void 0?{}:{highestSeverity:e}}var al=class{constructor(e,t,n={}){this.getState=e,this.setState=t,this.acceptedSupportByMachine=new Set,this.selectedGeneration=0,this.dismissingNotificationIds=new Set,this.dismissAllPending=!1,this.disposed=!1,this.api=n.api??x,this.onBackgroundError=n.onBackgroundError??((e,t)=>{console.warn(e,t)})}dispose(){this.disposed=!0,this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.acceptedSupportByMachine.clear(),this.dismissingNotificationIds.clear(),this.dismissAllPending=!1}prepareSelectedSession(e,t){this.selectedGeneration+=1,this.selectedTarget=e.archived===!0?void 0:{machineId:t,sessionId:e.id,cwd:e.cwd},this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.selectedTarget===void 0||!this.machineSupportsNotifications(t)?this.setState({selectedNotificationInbox:void 0}):this.setState({selectedNotificationInbox:Lc(this.selectedTarget)})}clearSelectedSession(){this.selectedGeneration+=1,this.selectedTarget=void 0,this.selectedJoin=void 0,this.dismissingNotificationIds.clear(),this.dismissAllPending=!1,this.setState({selectedNotificationInbox:void 0})}refreshSelectedSession(e,t){let n=this.selectedTarget;if(this.disposed||n?.machineId!==t||n.sessionId!==e.id||n.cwd!==e.cwd||!this.machineSupportsNotifications(t)||!this.machineIsReachable(t))return Promise.resolve();let r=this.selectedGeneration,i=this.selectedRefresh;if(i?.generation===r)return i.trailing=!0,i.promise;this.ensureSelectedProjection(n);let a={generation:r,promise:Promise.resolve(),trailing:!1};return a.promise=this.runSelectedRefresh(a,n).finally(()=>{this.selectedRefresh===a&&(this.selectedRefresh=void 0)}),this.selectedRefresh=a,a.promise}applyInboxEvent(e,t){let n=this.selectedTarget;if(n?.machineId!==e||n.sessionId!==t.summary.sessionId||n.cwd!==t.summary.cwd)return;this.acceptedSupportByMachine.add(e);let r=this.selectedJoin;if(r?.generation===this.selectedGeneration){r.events.push(t);return}let i=zc(this.getState().selectedNotificationInbox,n,t);i.changed&&this.setState({selectedNotificationInbox:i.value}),i.needsRefresh&&this.scheduleSelectedRefresh(n)}syncEnvironment(e,t){if(this.disposed)return;e.machines!==t.machines&&this.pruneRemovedMachines(t.machines);let n=e.machines!==t.machines||e.machineStatuses!==t.machineStatuses||e.machineRuntimes!==t.machineRuntimes,r=this.selectedTarget;if(!n||r===void 0)return;let i=this.machineSupportsNotificationsInState(e,r.machineId)&&this.machineIsReachableInState(e,r.machineId);!this.machineSupportsNotifications(r.machineId)||!this.machineIsReachable(r.machineId)?this.markSelectedStale(r):(this.ensureSelectedProjection(r),i&&this.getState().selectedNotificationInbox?.status===`fresh`||this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId))}shouldFilterLegacyNotification(e,t){return t!==void 0&&t!==``&&this.machineSupportsNotifications(e)}async dismissNotification(e){let t=this.getState().selectedNotificationInbox,n=Bc(t);if(t===void 0||n===void 0||this.dismissAllPending||this.dismissingNotificationIds.has(e)||!n.notifications.some(t=>t.id===e))return;let r=ol(t),i=this.selectedGeneration;this.dismissingNotificationIds.add(e),this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:[...new Set([...t.optimisticDismissedIds,e])]}));try{let t=await this.api.dismissNotification({id:r.sessionId,cwd:r.cwd},n.daemonInstanceId,e,r.machineId);this.isCurrentTarget(r,i)&&this.applyMutationSnapshot(r,t,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)}))}catch(t){this.isCurrentTarget(r,i)&&(this.patchSelectedOverlay(r,t=>({...t,optimisticDismissedIds:t.optimisticDismissedIds.filter(t=>t!==e)})),this.setState({error:D(`client.sessionNotificationController.failed.to.dismiss.notification.080d8f`,`Failed to dismiss notification: {value1}`,{value1:cl(t)})}),await this.refreshSelectedSession({id:r.sessionId,cwd:r.cwd},r.machineId))}finally{this.dismissingNotificationIds.delete(e)}}async dismissAll(){let e=this.getState().selectedNotificationInbox,t=Bc(e);if(e===void 0||t===void 0||this.dismissAllPending||t.retainedCount+t.discardedCount===0)return;let n=ol(e),r=this.selectedGeneration,i={...e.dismissThrough};this.dismissAllPending=!0,this.patchSelectedOverlay(n,e=>({...e,optimisticDismissAllThrough:i}));try{let e=await this.api.dismissAllNotifications({id:n.sessionId,cwd:n.cwd},t.daemonInstanceId,i,n.machineId);this.isCurrentTarget(n,r)&&this.applyMutationSnapshot(n,e,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t})}catch(e){this.isCurrentTarget(n,r)&&(this.patchSelectedOverlay(n,e=>{let t={...e};return delete t.optimisticDismissAllThrough,t}),this.setState({error:D(`client.sessionNotificationController.failed.to.dismiss.session.notifications.5621de`,`Failed to dismiss session notifications: {value1}`,{value1:cl(e)})}),await this.refreshSelectedSession({id:n.sessionId,cwd:n.cwd},n.machineId))}finally{r===this.selectedGeneration&&(this.dismissAllPending=!1)}}async runSelectedRefresh(e,t){do{e.trailing=!1;let n={generation:e.generation,events:[]};this.selectedJoin=n;try{let r=await this.api.notificationInbox({id:t.sessionId,cwd:t.cwd},t.machineId);if(!this.isCurrentTarget(t,e.generation))return;if(!this.machineSupportsNotifications(t.machineId)||!this.machineIsReachable(t.machineId)){this.markSelectedStale(t);return}this.acceptedSupportByMachine.add(t.machineId);let i=this.getState().selectedNotificationInbox,a=i===void 0||sl(i,t,r)?Rc(i,t,r):i;for(let r of[...n.events].sort((e,t)=>e.summary.inboxRevision-t.summary.inboxRevision)){let n=zc(a,t,r);a=n.value,n.needsRefresh&&(e.trailing=!0)}this.setState({selectedNotificationInbox:a})}catch(n){if(this.isCurrentTarget(t,e.generation)){let e=this.getState().selectedNotificationInbox;e!==void 0&&Qc(e,t)&&e.status!==`stale`&&this.setState({selectedNotificationInbox:{...e,status:`stale`}}),this.onBackgroundError(`Failed to refresh notifications for session ${t.sessionId}`,n)}return}finally{this.selectedJoin===n&&(this.selectedJoin=void 0)}}while(e.trailing&&this.isCurrentTarget(t,e.generation)&&this.machineIsReachable(t.machineId))}applyMutationSnapshot(e,t,n){let r=this.getState().selectedNotificationInbox;if(r===void 0||!Qc(r,e))return;if(!this.machineSupportsNotifications(e.machineId)||!this.machineIsReachable(e.machineId)){this.setState({selectedNotificationInbox:{...n(r),status:`stale`}});return}let i=sl(r,e,t)?Rc(r,e,t):r;this.setState({selectedNotificationInbox:n(i)})}patchSelectedOverlay(e,t){let n=this.getState().selectedNotificationInbox;n!==void 0&&Qc(n,e)&&this.setState({selectedNotificationInbox:t(n)})}ensureSelectedProjection(e){let t=this.getState().selectedNotificationInbox;t!==void 0&&Qc(t,e)||this.setState({selectedNotificationInbox:Lc(e)})}scheduleSelectedRefresh(e){queueMicrotask(()=>{!this.disposed&&this.selectedTarget!==void 0&&Qc(this.selectedTarget,e)&&this.refreshSelectedSession({id:e.sessionId,cwd:e.cwd},e.machineId)})}markSelectedStale(e){let t=this.getState().selectedNotificationInbox;t!==void 0&&Qc(t,e)&&t.status!==`stale`&&this.setState({selectedNotificationInbox:{...t,status:`stale`}})}pruneRemovedMachines(e){let t=new Set(e.map(e=>e.id));t.size===0&&t.add(`local`);for(let e of[...this.acceptedSupportByMachine])t.has(e)||this.acceptedSupportByMachine.delete(e)}isCurrentTarget(e,t){return!this.disposed&&t===this.selectedGeneration&&this.selectedTarget!==void 0&&Qc(this.selectedTarget,e)}machineSupportsNotifications(e){return this.machineSupportsNotificationsInState(this.getState(),e)}machineSupportsNotificationsInState(e,t){return this.acceptedSupportByMachine.has(t)||e.machineRuntimes[t]?.ok===!0}machineIsReachable(e){return this.machineIsReachableInState(this.getState(),e)}machineIsReachableInState(e,t){let n=e.machines.find(e=>e.id===t);if(t===`local`||n?.kind===`local`)return!0;let r=e.machineStatuses[t]?.status??n?.status;return r===void 0||r===`unknown`||r===`online`}};function ol(e){return{machineId:e.machineId,sessionId:e.sessionId,cwd:e.cwd}}function sl(e,t,n){return!Qc(e,t)||e.daemonInstanceId!==n.daemonInstanceId||e.summary===void 0||n.summary.inboxRevision>=e.summary.inboxRevision}function cl(e){return e instanceof Error?e.message:String(e)}function ll(e){return e?.status!==`folder`}var ul=class{constructor(){this.workspaceIdsByProject=new Map}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}},dl=`pi-web:workspace-selection:v1`,fl=class{constructor(e=Vs()){this.workspaceIdsByProject=new Hs(dl,Us,e)}latestWorkspaceId(e){return this.workspaceIdsByProject.get(e)}rememberWorkspace(e){this.workspaceIdsByProject.set(e.projectId,e.id)}forgetProject(e){this.workspaceIdsByProject.delete(e)}};function pl(e,t){let n=t?.targetWorkspaceId;if(n!==void 0&&n!==``)return e.find(e=>e.id===n);let r=t?.latestWorkspaceId;return r!==void 0&&r!==``?e.find(e=>e.id===r)??e[0]:e[0]}var ml=50,hl=[`machine`,`project`,`workspace`,`session`],gl=class{constructor(e,t,n,r,i=new ul,a={}){this.getState=e,this.setState=t,this.updateUrl=n,this.sessions=r,this.workspaceSelection=i,this.workspaceListRequests=new Map,this.api=a.api??x,this.navigateToWorkspace=a.navigateToWorkspace,this.captureNavigation=a.captureNavigation,this.beginNavigationOperation=a.beginNavigationOperation,this.onBackgroundError=a.onBackgroundError??((e,t)=>{console.warn(e,t)}),this.browserErrors=new $n(e,t),this.topologyRefreshes=new gr(a.topologyRefreshDebounceMs??ml)}clearSelection(e){this.sessions.clearActiveSession(),this.setState({selectedProject:void 0,workspaceResolution:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!1,...Hn()}),e?.updateUrl!==!1&&this.updateUrl()}forgetProject(e){let t=M(this.getState());this.browserErrors.discard(Wn(t,e)),this.workspaceSelection.forgetProject(hr(t,e));let n=Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([t])=>t!==e));this.setState({workspacesByProjectId:n})}async selectProject(e,t){let n=t?.navigation??this.beginNavigationOperation?.(hl);if(!this.navigationIsCurrent(n)||!vl(t))return;let r=M(this.getState()),i=Wn(r,e.id);this.sessions.clearActiveSession(),this.setState({selectedProject:e,workspaceResolution:void 0,selectedWorkspace:void 0,workspaces:[],isLoadingWorkspaces:!0,...Hn()});let a=this.beginWorkspaceListRequest(e.id,r);try{let o=t?.signal===void 0?await this.api.workspaceResolution(e.id,r):await this.api.workspaceResolution(e.id,r,{signal:t.signal}),s=[...o.workspaces];if(!a()||!this.navigationIsCurrent(n)||!vl(t)||M(this.getState())!==r||this.getState().selectedProject?.id!==e.id)return;if(this.setState({workspaceResolution:o,workspaces:s,workspacesByProjectId:{...this.getState().workspacesByProjectId,[e.id]:s},isLoadingWorkspaces:!1}),o.status===`degraded`)throw Sl(o);let c=pl(s,{targetWorkspaceId:t?.workspaceId,latestWorkspaceId:this.workspaceSelection.latestWorkspaceId(hr(r,e.id))});if(c)return await this.selectWorkspace(c,{...t,sessionId:t?.sessionId,updateUrl:t?.updateUrl,navigation:n});if(t?.workspaceId!==void 0&&t.workspaceId!==``)return this.browserErrors.report(i,D(`ui.main.06529052d1e0`,`Workspace not found: {arg0}`,{arg0:t.workspaceId})),D(`ui.main.06529052d1e0`,`Workspace not found: {arg0}`,{arg0:t.workspaceId});t?.updateUrl!==!1&&this.navigationIsCurrent(n)&&this.updateUrl()}catch(a){return this.navigationIsCurrent(n)&&vl(t)&&M(this.getState())===r&&this.getState().selectedProject?.id===e.id&&this.setState({isLoadingWorkspaces:!1}),t?.signal?.aborted!==!0&&this.browserErrors.report(i,String(a)),String(a)}}async selectWorkspace(e,t){let n=t?.navigation??this.beginNavigationOperation?.(hl);if(!this.navigationIsCurrent(n)||!vl(t))return;let r=M(this.getState()),i=Gn(r,e.projectId,e.id);this.workspaceSelection.rememberWorkspace({...e,projectId:hr(r,e.projectId)}),this.sessions.clearActiveSession(),this.setState({selectedWorkspace:e,isLoadingWorkspaces:!1,...Hn()});try{let a=t?.signal===void 0?await this.api.sessions(e.path,r):await this.api.sessions(e.path,r,{signal:t.signal}),o=Qr(e.path,a,r);if(!this.navigationIsCurrent(n)||!vl(t)||M(this.getState())!==r||this.getState().selectedWorkspace?.id!==e.id||this.getState().selectedProject?.id!==e.projectId)return;this.setState({sessions:o});let s=this.sessions.preferredSession(e.path,o,t?.sessionId);if(!this.navigationIsCurrent(n)||!vl(t))return;if(s)await this.sessions.selectSession(s,{deferChatLoading:!0,updateUrl:t?.updateUrl,...n===void 0?{}:{navigation:n}});else if(t?.sessionId!==void 0&&t.sessionId!==``)return this.browserErrors.report(i,D(`ui.main.0041c3cf98cd`,`Session not found: {arg0}`,{arg0:t.sessionId})),D(`ui.main.0041c3cf98cd`,`Session not found: {arg0}`,{arg0:t.sessionId});else t?.updateUrl!==!1&&this.updateUrl()}catch(e){return t?.signal?.aborted!==!0&&this.browserErrors.report(i,String(e)),String(e)}}async refreshProjectWorkspaces(e,t=M(this.getState()),n){return(await this.refreshProjectWorkspaceList(e,t,n)).workspaces}async refreshProjectWorkspaceList(e,t,n){if(!vl(n))return{workspaces:[],isCurrent:()=>!1};let r=this.getState().projects.find(t=>t.id===e);if(r===void 0)throw Error(D(`client.workspaceController.project.not.found.3b6bf4`,`Project not found`));let i=this.beginWorkspaceListRequest(e,t),a=n?.signal===void 0?await this.api.workspaceResolution(r.id,t):await this.api.workspaceResolution(r.id,t,{signal:n.signal}),o=[...a.workspaces];if(i()&&vl(n)&&M(this.getState())===t){if(this.getState().selectedProject?.id===r.id&&this.setState({workspaceResolution:a}),a.status===`degraded`)throw Sl(a);this.applyProjectWorkspaces(r.id,o)}return{workspaces:o,isCurrent:i}}async refreshSelectedProjectTopology(){let e=this.getState(),t=e.selectedProject;if(t===void 0||e.isLoadingWorkspaces)return;let n=M(e);await this.topologyRefreshes.request(hr(n,t.id),async()=>{if(this.getState().isLoadingWorkspaces)return;let e=this.beginWorkspaceListRequest(t.id,n);try{let r=await this.api.workspaceResolution(t.id,n),i=this.getState();if(!e()||M(i)!==n||i.selectedProject?.id!==t.id)return;if(this.setState({workspaceResolution:r}),r.status===`degraded`)throw Sl(r);this.applyProjectWorkspaces(t.id,[...r.workspaces])}catch(e){this.onBackgroundError(`Failed to refresh workspaces for project ${t.id} on ${n}`,e)}})}async refreshAfterWorkspaceDeleted(e,t,n=M(this.getState()),r){if(!vl(r))return;let i=this.beginNavigationOperation?.(hl),{workspaces:a,isCurrent:o}=await this.refreshProjectWorkspaceList(e,n,r);if(!o()||!this.navigationIsCurrent(i)||!vl(r))return;let s=this.getState();if(M(s)!==n||s.selectedProject?.id!==e||s.selectedWorkspace?.id!==t)return;let c=_l(this.getState(),this.captureNavigation),l=yl(a);this.navigateToWorkspace===void 0?l===void 0?this.navigationIsCurrent(i)&&vl(r)&&this.clearSelection():await this.selectWorkspace(l,{...r,...i===void 0?{}:{navigation:i}}):await this.navigateToWorkspace(l,{expected:c})}beginWorkspaceListRequest(e,t){let n=hr(t,e),r=(this.workspaceListRequests.get(n)??0)+1;return this.workspaceListRequests.set(n,r),()=>this.workspaceListRequests.get(n)===r}applyProjectWorkspaces(e,t){let n=this.getState(),r={...n.workspacesByProjectId,[e]:t};n.selectedProject?.id===e?this.setState({workspaces:t,workspacesByProjectId:r,...this.refreshedSelection(n.selectedWorkspace,t)}):this.setState({workspacesByProjectId:r})}refreshedSelection(e,t){if(e===void 0)return;let n=t.find(t=>t.id===e.id);if(!(n===void 0||bl(e,n)))return{selectedWorkspace:n}}navigationIsCurrent(e){return e===void 0||e.isCurrent()}};function _l(e,t){return t?.()??{machineId:M(e),projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,...e.selectedSession===void 0||Reflect.get(e.selectedSession,`clientPendingStart`)!==!0?{sessionId:e.selectedSession?.id}:{}}}function vl(e){return e?.signal?.aborted!==!0&&e?.isCurrent?.()!==!1}function yl(e){return e.find(e=>e.isMain)??e[0]}function bl(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>bl(e,t[n]));if(!xl(e)||!xl(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&bl(e[n],t[n]))}function xl(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Sl(e){return Error(e.diagnostics.map(({message:e})=>e).join(`; `)||D(`client.workspaceController.authorityDegraded`,`Workspace authority is degraded`))}var Cl=`core.workspace.files--file`,wl=`core.workspace.terminal--terminal`,Tl=`pi-web:machine-navigation:v1`,El=class{constructor(e=Vs()){this.snapshotsByMachine=new Hs(Tl,jl,e)}latest(e){let t=this.snapshotsByMachine.get(e);return t?.machineId===e?Al(t):void 0}remember(e){this.snapshotsByMachine.set(e.machineId,Al(e))}forget(e){this.snapshotsByMachine.delete(e)}};function Dl(e){return{machineId:e,surface:{}}}function Ol(e,t={}){let n=e.selectedWorkspace===void 0?{}:ra(t),r=e.selectedSession?.id;return{machineId:e.selectedMachine?.id??`local`,projectId:e.selectedProject?.id,workspaceId:e.selectedWorkspace?.id,sessionId:r,tool:e.workspaceTool,view:e.mainView,surface:{...Object.keys(n).length===0?{}:{contributionQuery:n}}}}function kl(e){return{machineId:e.machineId,projectId:e.projectId,workspaceId:e.workspaceId,sessionId:e.sessionId,tool:e.tool,view:e.view}}function Al(e){let t=e.surface.contributionQuery;return{...e,surface:{...e.surface,...t===void 0?{}:{contributionQuery:ra(t)}}}}function jl(e){if(!Il(e))return;let t=Fl(e,`machineId`);if(t===void 0)return;let n=Fl(e,`view`),r=n===`files`||n===`core:workspace.files`?`core:workspace.files`:n===`git`||n===`core:workspace.git`?`core:workspace.git`:n===`terminal`||n===`core:workspace.terminal`?`core:workspace.terminal`:void 0,i=Nl(Fl(e,`tool`))??r,a=Sa(n)??(r===void 0?void 0:`workspace`);return{machineId:t,projectId:Fl(e,`projectId`),workspaceId:Fl(e,`workspaceId`),sessionId:Fl(e,`sessionId`),...i===void 0?{}:{tool:i},...a===void 0?{}:{view:a},surface:Ml(e.surface)}}function Ml(e){if(!Il(e))return{};let t=Il(e.contributionQuery)?e.contributionQuery:{},n=Fl(e,`selectedFilePath`),r=Fl(e,`selectedTerminalId`),i=Fl(e,`selectedDiffPath`),a=ra({...n===void 0?{}:{[Cl]:n},...r===void 0?{}:{[wl]:r},...i===void 0?{}:{"core.workspace.git--diff":i},...t});return{...Object.keys(a).length===0?{}:{contributionQuery:a}}}function Nl(e){return Pl(e)?e:void 0}function Pl(e){return e!==void 0&&/^[a-z][a-z0-9.-]*:[a-z][a-z0-9.-]*$/u.test(e)}function Fl(e,t){let n=e[t];return typeof n==`string`&&n!==``?n:void 0}function Il(e){return typeof e==`object`&&!!e}function Ll(e,t,n){if(t!==void 0&&zl(t.path)===zl(n.cwd))return{machineId:e,projectId:t.projectId,workspaceId:t.id,root:t.path}}function Rl(e,t){let n=e.trim();if(n===``||/^[#?]/.test(n)||n.startsWith(`//`)||/^[a-z][a-z\d+.-]*:/i.test(n))return;let r;try{r=decodeURIComponent(n.split(/[?#]/,1)[0]??``)}catch{return}if(r===``||/[\\\u0000-\u001f\u007f]/.test(r))return;if(r.startsWith(`/`)){let e=`${zl(t.root)}/`;if(!r.startsWith(e)||(r=r.slice(e.length),r===``))return}let i=r.split(`/`).filter(e=>e!==``&&e!==`.`).join(`/`);return i===``?void 0:i}function zl(e){return e.replace(/\/+$/,``)}var Bl={archiveIdleEnabled:!0,archiveIdleDays:`30`,deleteArchivedEnabled:!1,deleteArchivedDays:`90`};function Vl(e){if(!e.archiveIdleEnabled&&!e.deleteArchivedEnabled)return{ok:!1,error:D(`client.sessionCleanupUi.enable.at.least.one.cleanup.action.d2ce50`,`Enable at least one cleanup action.`)};let t={archiveIdleDays:null,deleteArchivedDays:null};if(e.archiveIdleEnabled){let n=Zl(e.archiveIdleDays,D(`client.sessionCleanupUi.archive.idle.sessions.after.6d41ea`,`Archive idle sessions after`));if(typeof n==`string`)return{ok:!1,error:n};t.archiveIdleDays=n}if(e.deleteArchivedEnabled){let n=Zl(e.deleteArchivedDays,D(`client.sessionCleanupUi.delete.archived.sessions.after.923bee`,`Delete archived sessions after`));if(typeof n==`string`)return{ok:!1,error:n};t.deleteArchivedDays=n}return{ok:!0,request:t}}function Hl(e){return JSON.stringify({archiveIdleDays:e?.archiveIdleDays??null,deleteArchivedDays:e?.deleteArchivedDays??null,projectId:e?.projectId??null})}function Ul(e){if(e.canCleanup===!1||e.loading===!0||e.running===!0||e.preview===void 0)return!1;let t=Vl(e.draft);if(!t.ok)return!1;if(e.previewRequest===void 0){if(e.canCleanup!==!0||!Wl(e.draft,e.preview))return!1}else if(Ql(t.request)!==Ql(e.previewRequest))return!1;return Gl(e.preview)}function Wl(e,t){let n=Vl(e);return n.ok?Ql(n.request)===Ql(t.thresholds):!1}function Gl(e){return e.totals.archiveCount>0||e.totals.deleteCount>0}function Kl(e,t){let n=e.projects.map(e=>e.cwd);if(t===void 0)return n;let r=new Set(t);return n.filter(e=>r.has(e))}function ql(e,t){let n=new Set(Kl(e,t)),r=e.projects.filter(e=>n.has(e.cwd));return{...e,projects:r,totals:r.reduce((e,t)=>({archiveCount:e.archiveCount+t.archiveCount,deleteCount:e.deleteCount+t.deleteCount}),{archiveCount:0,deleteCount:0})}}function Jl(e,t){return t(Yl(e))}function Yl(e){let t=e.totals.archiveCount,n=e.totals.deleteCount,r=[];t>0&&r.push(D(`client.sessionCleanupUi.archive.idle.sessions.27a4f1`,`archive {value1} idle sessions`,{value1:String(t)})),n>0&&r.push(D(`client.sessionCleanupUi.permanently.delete.archived.sessions.360209`,`permanently delete {value1} archived sessions`,{value1:String(n)}));let i=r.length===0?D(`client.sessionCleanupUi.run.cleanup.233f8e`,`run cleanup`):r.join(D(`client.sessionCleanupUi.and.2f4b60`,` and `));return D(`client.sessionCleanupUi.run.cleanup.and.permanent.deletion.only.applies.to.archived.sessions.a.9775e2`,`Run cleanup and {value1}?
|
|
28
28
|
|
|
29
29
|
Permanent deletion only applies to archived sessions and cannot be undone.`,{value1:i})}function Xl(e){return D(`client.sessionCleanupUi.update.and.restart.pi.web.on.before.cleaning.up.sessions.3c493f`,`Update and restart Pi-Web on {value1} before cleaning up sessions.`,{value1:e??D(`client.sessionCleanupUi.this.machine.74a83f`,`this machine`)})}function Zl(e,t){let n=e.trim();if(n===``)return D(`client.sessionCleanupUi.must.be.set.208394`,`{value1} must be set.`,{value1:t});let r=Number(n);return!Number.isInteger(r)||r<0?D(`client.sessionCleanupUi.must.be.a.non.negative.integer.number.of.days.7ed7a9`,`{value1} must be a non-negative integer number of days.`,{value1:t}):r}function Ql(e){return JSON.stringify({archiveIdleDays:e.archiveIdleDays??null,deleteArchivedDays:e.deleteArchivedDays??null})}var $l=new Set,eu=Nt+1,tu={unreadCatalog:e=>s.unreadCatalog(e),acknowledgeUnread:(e,t,n,r)=>s.acknowledgeUnread(e,t,n,r)},nu=class{constructor(e={}){this.machines=new Map,this.api=e.api??tu,this.onChange=e.onChange??(()=>void 0),this.onBackgroundError=e.onBackgroundError??(()=>void 0)}retainMachines(e){for(let[t,n]of this.machines){if(e.has(t))continue;let r=n.projection!==void 0;n.generation+=1,n.observers.clear(),n.acknowledgements.clear(),this.machines.delete(t),r&&this.onChange(t)}}projection(e){let t=this.machines.get(e),n=t?.projection;if(t!==void 0&&n!==void 0)return{status:t.status,catalogId:n.catalogId,catalogRevision:n.catalogRevision,sessions:[...n.summariesByIdentity.values()].sort((e,t)=>t.completionOrder-e.completionOrder).map(e=>({...e}))}}unreadSessionIds(e,t){let n=this.machines.get(e)?.projection;if(n===void 0||t.length===0)return $l;let r=new Set;for(let e of t)n.summariesByIdentity.has(cu(e))&&r.add(e.id);return r.size===0?$l:r}isUnread(e,t){return this.machines.get(e)?.projection?.summariesByIdentity.has(cu(t))===!0}applyEvent(e,t){let n=this.machine(e);this.recordObservedEvent(n,t);let r=ru(n.projection,n.status,t);this.installProjection(n,r.projection,r.status)&&this.onChange(e),r.requiresRefresh&&(n.refreshPromise===void 0?this.refresh(e):n.refreshQueued=!0)}refresh(e){let t=this.machine(e);if(t.refreshPromise!==void 0)return t.refreshQueued=!0,t.refreshPromise;let n=t.generation,r=this.runRefreshLoop(t,n);return t.refreshPromise=r,r.finally(()=>{if(!this.isCurrent(t,n)||t.refreshPromise!==r)return;t.refreshPromise=void 0;let e=t.refreshQueued;t.refreshQueued=!1,e&&this.refresh(t.machineId)}),r}async refreshAll(){await Promise.all([...this.machines.values()].map(async e=>{await this.refresh(e.machineId)}))}acknowledge(e,t){let n=this.machines.get(e),r=n?.projection;if(n===void 0||r===void 0)return Promise.resolve();let i=r.summariesByIdentity.get(cu(t));if(i===void 0)return Promise.resolve();let a=lu(r.catalogId,i),o=n.acknowledgements.get(a);if(o!==void 0)return o;let s=n.generation,c=this.runAcknowledgement(n,s,t,r.catalogId,i.completionOrder);return n.acknowledgements.set(a,c),c.finally(()=>{n.acknowledgements.get(a)===c&&n.acknowledgements.delete(a)}),c}acknowledgeLoaded(e,t,n){let r=this.machines.get(e),i=r?.projection?.summariesByIdentity.get(cu(t));if(r?.status!==`fresh`||i===void 0)return Promise.resolve();let a=i.messageRange;if(a===void 0){if(n.start!==0||n.end<n.total)return Promise.resolve()}else if(n.leafId!==a.leafId||n.start>a.start||n.end<a.end)return Promise.resolve();return this.acknowledge(e,t)}needsHistoryRefresh(e,t,n,r){let i=this.machines.get(e)?.projection?.summariesByIdentity.get(cu(t))?.messageRange;return i!==void 0&&(i.leafId!==r||i.end>n)}async runRefreshLoop(e,t){do{if(e.refreshQueued=!1,!this.isCurrent(e,t))return;let n=e.status;this.markRefreshStarted(e)&&this.onChange(e.machineId);let r=this.beginNetworkObservation(e,t,n);try{let n=await this.api.unreadCatalog(e.machineId);if(!this.isCurrent(e,t))return;this.applyNetworkSnapshot(e,n,r)&&(e.refreshQueued=!0)}catch(n){if(this.isCurrent(e,t)){let t=e.status!==`stale`;e.status=`stale`,t&&this.onChange(e.machineId),this.reportError(`snapshot`,e.machineId,n)}}finally{e.observers.delete(r)}}while(e.refreshQueued&&this.isCurrent(e,t))}async runAcknowledgement(e,t,n,r,i){let a=this.beginNetworkObservation(e,t);try{let o=await this.api.acknowledgeUnread(n,r,i,e.machineId);if(!this.isCurrent(e,t))return;this.applyNetworkSnapshot(e,o,a)&&this.refresh(e.machineId)}catch(n){this.isCurrent(e,t)&&this.reportError(`acknowledge`,e.machineId,n)}finally{e.observers.delete(a)}}applyNetworkSnapshot(e,t,n){let r=e.projection;if(e.projectionVersion!==n.projectionVersion&&r!==void 0&&r.catalogId!==t.catalogId||n.overflowed||n.events.some(e=>e.catalogId!==t.catalogId)){let t=e.status!==`stale`;return e.status=`stale`,t&&this.onChange(e.machineId),!0}let i=au(t),a=`fresh`,o=!1;for(let e of n.events){let t=ru(i,a,e);i=t.projection,a=t.status,o||=t.requiresRefresh}if(r?.catalogId===i.catalogId&&r.catalogRevision>i.catalogRevision){if(e.projectionVersion===n.projectionVersion&&n.projectionStatus===`fresh`){let t=e.status!==`fresh`;e.status=`fresh`,t&&this.onChange(e.machineId)}o||=e.status===`stale`}else this.installProjection(e,i,a)&&this.onChange(e.machineId);return o}beginNetworkObservation(e,t,n=e.status){let r={generation:t,projectionVersion:e.projectionVersion,projectionStatus:n,events:[],overflowed:!1};return e.observers.add(r),r}recordObservedEvent(e,t){for(let n of e.observers)n.generation!==e.generation||n.overflowed||(n.events.length>=eu?(n.events.length=0,n.overflowed=!0):n.events.push(t))}markRefreshStarted(e){let t=e.projection===void 0?`loading`:`stale`;return e.status!==t&&(e.status=t,!0)}installProjection(e,t,n){let r=!su(e.projection,t);return e.status===n&&!r?!1:(r&&(e.projection=t,e.projectionVersion+=1),e.status=n,!0)}machine(e){let t=this.machines.get(e);if(t!==void 0)return t;let n={machineId:e,status:`stale`,projection:void 0,projectionVersion:0,generation:0,observers:new Set,acknowledgements:new Map,refreshPromise:void 0,refreshQueued:!1};return this.machines.set(e,n),n}isCurrent(e,t){return this.machines.get(e.machineId)===e&&e.generation===t}reportError(e,t,n){this.onBackgroundError(e,t,n)}};function ru(e,t,n){if(e===void 0){let e=ou(n.catalogId);return n.catalogRevision===1?iu(e,`fresh`,n):{projection:e,status:`stale`,requiresRefresh:!0}}if(e.catalogId!==n.catalogId){let e=ou(n.catalogId);return n.catalogRevision===1?iu(e,`stale`,n):{projection:e,status:`stale`,requiresRefresh:!0}}return n.catalogRevision<=e.catalogRevision?{projection:e,status:t,requiresRefresh:t===`stale`}:n.catalogRevision===e.catalogRevision+1?iu(e,t,n):{projection:e,status:`stale`,requiresRefresh:!0}}function iu(e,t,n){let r=new Map(e.summariesByIdentity),i=cu(n);n.unread===null?r.delete(i):r.set(i,{...n.unread});let a=t===`stale`?`stale`:`fresh`;return{projection:{catalogId:n.catalogId,catalogRevision:n.catalogRevision,summariesByIdentity:r},status:a,requiresRefresh:a===`stale`}}function au(e){return{catalogId:e.catalogId,catalogRevision:e.catalogRevision,summariesByIdentity:new Map(e.sessions.map(e=>[cu(e),{...e}]))}}function ou(e){return{catalogId:e,catalogRevision:0,summariesByIdentity:new Map}}function su(e,t){if(e?.catalogId!==t.catalogId||e.catalogRevision!==t.catalogRevision||e.summariesByIdentity.size!==t.summariesByIdentity.size)return!1;for(let[n,r]of e.summariesByIdentity){let e=t.summariesByIdentity.get(n);if(e?.completionOrder!==r.completionOrder||e.completedAt!==r.completedAt)return!1}return!0}function cu(e){let t=`id`in e?e.id:e.sessionId;return JSON.stringify([t,e.cwd])}function lu(e,t){return JSON.stringify([e,t.sessionId,t.cwd,t.completionOrder])}var uu={machines:new Set,projects:new Set,workspaces:new Set};function du(e){let t=pu(e.projectionFor(e.selectedMachineId));return{machines:mu(e.machineIds,e.projectionFor),projects:gu(e.projects,e.workspacesByProjectId,t),workspaces:hu(e.workspaces,t)}}function fu(e){return e!==void 0&&e.sessions.length>0}function pu(e){return e===void 0||e.sessions.length===0?vu:new Set(e.sessions.map(e=>e.cwd))}function mu(e,t){let n=new Set;for(let r of e)fu(t(r))&&n.add(r);return n}function hu(e,t){let n=new Set;for(let r of e)t.has(r.path)&&n.add(r.id);return n}function gu(e,t,n){let r=new Set;for(let i of e)(t[i.id]??[]).some(e=>n.has(e.path))&&r.add(i.id);return r}function _u(e,t){return yu(e.machines,t.machines)&&yu(e.projects,t.projects)&&yu(e.workspaces,t.workspaces)}var vu=new Set;function yu(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function bu(){return{selectedSessionKey:void 0,warningSetSignature:xu(void 0),warningCount:0,collapsed:!1,collapsedWarningSets:new Map}}function xu(e){let t=(e??[]).map(e=>JSON.stringify([e.severity,e.message,e.source,e.path,e.dismiss?.id])).sort();return JSON.stringify(t)}function Su(e,t,n){let r=xu(n),i=n?.length??0,a=n!==void 0,o=t===void 0?void 0:e.collapsedWarningSets.get(t),s=e.collapsedWarningSets;if(a&&t!==void 0&&o!==void 0&&o!==r){let n=new Map(e.collapsedWarningSets);n.delete(t),s=n}let c=a&&i>0&&o===r;return e.selectedSessionKey===t&&e.warningSetSignature===r&&e.warningCount===i&&e.collapsed===c&&e.collapsedWarningSets===s?e:{selectedSessionKey:t,warningSetSignature:r,warningCount:i,collapsed:c,collapsedWarningSets:s}}function Cu(e){if(e.collapsed||e.warningCount===0||e.selectedSessionKey===void 0)return e;let t=new Map(e.collapsedWarningSets);return t.set(e.selectedSessionKey,e.warningSetSignature),{...e,collapsed:!0,collapsedWarningSets:t}}function wu(e){if(!e.collapsed)return e;let t=new Map(e.collapsedWarningSets);return e.selectedSessionKey!==void 0&&t.delete(e.selectedSessionKey),{...e,collapsed:!1,collapsedWarningSets:t}}function Tu(e){return e.collapsed?wu(e):Cu(e)}var Eu=100;function Du(e,t){return e.filter(e=>Au(e,t))}var Ou={snapshot:e=>Tt.snapshot(e),dismiss:(e,t,n)=>Tt.dismiss(e,t,n)},ku=class{constructor(e={}){this.machines=new Map,this.api=e.api??Ou,this.onChange=e.onChange??(()=>void 0),this.onBackgroundError=e.onBackgroundError??(()=>void 0)}retainMachines(e){for(let[t,n]of this.machines){if(e.has(t))continue;let r=n.projection!==void 0;n.generation+=1,n.observers.clear(),n.pendingDismissedIds.clear(),n.dismissals.clear(),this.machines.delete(t),r&&this.onChange(t)}}projection(e){let t=this.machines.get(e),n=t?.projection;if(t!==void 0&&n!==void 0)return{machineId:e,status:t.status,daemonInstanceId:n.daemonInstanceId,revision:n.revision,notices:n.notices.filter(e=>!t.pendingDismissedIds.has(e.id))}}hasNotice(e,t){let n=this.projection(e);return n?.status===`fresh`&&n.notices.some(t)}applyEvent(e,t){let n=this.machine(e);this.recordObservedEvent(n,t);let r=n.projection;if(r===void 0)this.installProjection(n,ju(t.snapshot),`fresh`)&&this.onChange(e);else if(r.daemonInstanceId!==t.snapshot.daemonInstanceId){let t=n.status!==`stale`;n.status=`stale`,t&&this.onChange(e),n.refreshPromise===void 0?this.refresh(e):n.refreshQueued=!0}else t.snapshot.revision<=r.revision?n.status===`stale`&&(n.refreshPromise===void 0?this.refresh(e):n.refreshQueued=!0):this.installProjection(n,ju(t.snapshot),`fresh`)&&this.onChange(e)}refresh(e){let t=this.machine(e);if(t.refreshPromise!==void 0)return t.refreshQueued=!0,t.refreshPromise;let n=t.generation,r=this.runRefreshLoop(t,n);return t.refreshPromise=r,r.finally(()=>{if(!this.isCurrent(t,n)||t.refreshPromise!==r)return;t.refreshPromise=void 0;let e=t.refreshQueued;t.refreshQueued=!1,e&&this.refresh(t.machineId)}),r}async refreshAll(){await Promise.all([...this.machines.values()].map(async e=>{await this.refresh(e.machineId)}))}dismiss(e,t){let n=this.machines.get(e),r=n?.projection;if(n===void 0||r===void 0||r.notices.find(e=>e.id===t)===void 0||n.pendingDismissedIds.has(t))return Promise.resolve();let i=`${r.daemonInstanceId}:${t}`,a=n.dismissals.get(i);if(a!==void 0)return a;let o=n.generation,s=this.beginNetworkObservation(n,o);n.pendingDismissedIds.add(t),this.onChange(e);let c=this.runDismissal(n,o,s,r.daemonInstanceId,t);return n.dismissals.set(i,c),c.finally(()=>{n.dismissals.get(i)===c&&n.dismissals.delete(i)}),c}async runRefreshLoop(e,t){do{if(e.refreshQueued=!1,!this.isCurrent(e,t))return;this.markRefreshStarted(e)&&this.onChange(e.machineId);let n=this.beginNetworkObservation(e,t);try{let r=await this.api.snapshot(e.machineId);if(!this.isCurrent(e,t))return;this.applyNetworkSnapshot(e,r,n)&&(e.refreshQueued=!0)}catch(n){if(this.isCurrent(e,t)){let t=e.status!==`stale`;e.status=`stale`,t&&this.onChange(e.machineId),this.onBackgroundError(`snapshot`,e.machineId,n)}}finally{e.observers.delete(n)}}while(e.refreshQueued&&this.isCurrent(e,t))}async runDismissal(e,t,n,r,i){try{let a=await this.api.dismiss(e.machineId,r,i);if(!this.isCurrent(e,t))return;let o=this.applyNetworkSnapshot(e,a,n);e.pendingDismissedIds.delete(i),o&&this.refresh(e.machineId)}catch(n){this.isCurrent(e,t)&&this.onBackgroundError(`dismiss`,e.machineId,n)}finally{e.observers.delete(n),this.isCurrent(e,t)&&(e.pendingDismissedIds.delete(i),this.onChange(e.machineId))}}applyNetworkSnapshot(e,t,n){if(n.overflowed)return this.markStale(e);let r=t;for(let t of n.events){if(t.snapshot.daemonInstanceId!==r.daemonInstanceId)return this.markStale(e);t.snapshot.revision>r.revision&&(r=t.snapshot)}let i=e.projection;if(i!==void 0&&e.projectionVersion!==n.projectionVersion){if(i.daemonInstanceId!==r.daemonInstanceId)return this.markStale(e);i.revision>r.revision&&(r={daemonInstanceId:i.daemonInstanceId,revision:i.revision,notices:i.notices})}return this.installProjection(e,ju(r),`fresh`)&&this.onChange(e.machineId),!1}beginNetworkObservation(e,t){let n={generation:t,projectionVersion:e.projectionVersion,events:[],overflowed:!1};return e.observers.add(n),n}recordObservedEvent(e,t){for(let n of e.observers)n.generation!==e.generation||n.overflowed||(n.events.length>=Eu?(n.events.length=0,n.overflowed=!0):n.events.push(t))}markRefreshStarted(e){let t=e.projection===void 0?`loading`:`stale`;return e.status!==t&&(e.status=t,!0)}markStale(e){let t=e.status!==`stale`;return e.status=`stale`,t&&this.onChange(e.machineId),!0}installProjection(e,t,n){let r=!Mu(e.projection,t);return e.status===n&&!r?!1:(r&&(e.projection=t,e.projectionVersion+=1),e.status=n,!0)}machine(e){let t=this.machines.get(e);if(t!==void 0)return t;let n={machineId:e,status:`stale`,projection:void 0,projectionVersion:0,generation:0,observers:new Set,pendingDismissedIds:new Set,dismissals:new Map,refreshPromise:void 0,refreshQueued:!1};return this.machines.set(e,n),n}isCurrent(e,t){return this.machines.get(e.machineId)===e&&e.generation===t}};function Au(e,t){let n=e.scope;return n===void 0||(n.projectId===void 0||n.projectId===t.projectId)&&(n.workspaceId===void 0||n.workspaceId===t.workspaceId)&&(n.sessionId===void 0||n.sessionId===t.sessionId)}function ju(e){return{daemonInstanceId:e.daemonInstanceId,revision:e.revision,notices:e.notices.map(e=>({...e,...e.scope===void 0?{}:{scope:{...e.scope}},...e.context===void 0?{}:{context:{...e.context}}}))}}function Mu(e,t){return e?.daemonInstanceId!==t.daemonInstanceId||e.revision!==t.revision||e.notices.length!==t.notices.length?!1:e.notices.every((e,n)=>JSON.stringify(e)===JSON.stringify(t.notices[n]))}function Nu(e,t,n,r,i,a,o){Iu(t);let s=t?.mode===`patch`;Lu(e,s);let c=e.machineId===void 0?o??(s?n.machineId??`local`:i):Fu(e.machineId)??`local`,l=!s||c!==(n.machineId??`local`),u=Pu(e.projectId,l?void 0:n.projectId),d=l||u!==n.projectId,f=Pu(e.workspaceId,d?void 0:n.workspaceId),p=d||f!==n.workspaceId,m={machineId:c,projectId:u,workspaceId:f,sessionId:Pu(e.sessionId,p?void 0:n.sessionId),tool:Pu(e.tool,l?void 0:n.tool),view:Pu(e.view,s?n.view:void 0)},h=ra(p?{}:r);if(e.query!==void 0){if(!Ru(e.query))throw TypeError(`Navigation query must be an object`);if(m.tool===void 0||m.projectId===void 0||m.workspaceId===void 0)throw TypeError(`Navigation query requires tool, projectId, and workspaceId`);try{let t=s?a?.(m.tool,c):void 0,n=t?.sourceContributionId===void 0||t.sourceContributionId===t.contributionId?[]:[t.sourceContributionId];h=ia(h,t?.contributionId??m.tool,n,e.query)}catch(e){throw TypeError(e instanceof Error?e.message:String(e),{cause:e})}}return{route:m,contributionQuery:h}}function Pu(e,t){return e===void 0?t:Fu(e)}function Fu(e){return e===null||e===``?void 0:e}function Iu(e){if(e!==void 0){if(!Ru(e))throw TypeError(`Navigation options must be an object`);if(e.mode!==void 0&&e.mode!==`replace`&&e.mode!==`patch`)throw TypeError(`Navigation mode must be replace or patch`);if(e.history!==void 0&&e.history!==`push`&&e.history!==`replace`)throw TypeError(`Navigation history must be push or replace`)}}function Lu(e,t){if(!Ru(e))throw TypeError(`Navigation destination must be an object`);for(let n of[`machineId`,`projectId`,`workspaceId`,`sessionId`,`tool`]){let r=e[n];if(r!==void 0&&typeof r!=`string`&&!(t&&r===null))throw TypeError(`Navigation ${n} must be a string${t?` or null`:``}`)}let n=e.view;if(n!==void 0&&!(t&&n===null)&&n!==`navigation`&&n!==`chat`&&n!==`workspace`)throw TypeError(`Navigation view must be navigation, chat, or workspace`)}function Ru(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function zu(e){return e?.removal!==void 0&&!e.isMain}function Bu(e){return e.removal?.confirmation}function Vu(e){return{...e===void 0?{}:{projectId:e},metadata:{[ar]:ir}}}function Hu(e){let t={};for(let n of e){let e=Gu(n);if(e===void 0)continue;let r=t[e];(r===void 0||n.createdAt.localeCompare(r.createdAt)>=0)&&(t[e]=n)}return t}function Uu(e){return Object.entries(e).filter(([,e])=>Ku(e)).map(([e])=>e)}function Wu(e,t){if(t===void 0)return!1;let n=e.workspaceDeletionRuns[t.id];return n!==void 0&&Ku(n)}function Gu(e){return e.metadata[or]}function Ku(e){return e.status===`queued`||e.status===`running`}function qu(){return[{id:`actions.show`,title:D(`client.actions.show.actions.a514ad`,`Show actions`),description:D(`client.actions.open.the.command.palette.36dd5f`,`Open the command palette`),shortcut:`mod+k`,group:D(`client.actions.general.835b70`,`General`),run:e=>{e.openActionPalette()}},{id:`prompt.focus`,title:D(`client.actions.focus.prompt.e171a7`,`Focus prompt`),description:D(`client.actions.move.keyboard.focus.to.the.message.editor.74d2ce`,`Move keyboard focus to the message editor`),shortcut:`mod+g c`,group:D(`client.actions.general.835b70`,`General`),run:e=>{e.focusPrompt()}},{id:`machine.add`,title:D(`client.actions.add.machine.e4ad1b`,`Add machine`),description:D(`client.actions.register.another.pi.web.runtime.reachable.from.this.gateway.d20488`,`Register another PI WEB runtime reachable from this gateway`),group:D(`bundled.info.machine.ece969`,`Machine`),run:e=>e.addMachine()},{id:`machine.refresh`,title:D(`client.actions.refresh.selected.machine.b85d96`,`Refresh selected machine`),description:D(`client.actions.check.whether.the.selected.pi.web.runtime.is.online.a856dd`,`Check whether the selected PI WEB runtime is online`),group:D(`bundled.info.machine.ece969`,`Machine`),run:e=>e.refreshSelectedMachine()},{id:`machine.open`,title:D(`client.actions.open.selected.machine.s.pi.web.15ce06`,`Open selected machine's PI WEB`),description:D(`client.actions.open.the.selected.remote.pi.web.directly.in.a.new.tab.a27228`,`Open the selected remote PI WEB directly in a new tab`),group:D(`bundled.info.machine.ece969`,`Machine`),enabled:e=>e.state.selectedMachine?.kind===`remote`&&e.state.selectedMachine.baseUrl!==void 0,run:e=>e.openSelectedMachine()},{id:`machine.remove`,title:D(`client.actions.remove.selected.machine.ca967c`,`Remove selected machine`),description:D(`client.actions.remove.the.selected.remote.machine.from.this.gateway.51ce12`,`Remove the selected remote machine from this gateway`),group:D(`bundled.info.machine.ece969`,`Machine`),enabled:e=>e.state.selectedMachine?.kind===`remote`,run:e=>e.removeSelectedMachine()},{id:`project.add`,title:D(`client.actions.add.project.8964f5`,`Add project`),group:D(`client.actions.project.79f326`,`Project`),run:e=>e.addProject()},{id:`auth.login`,title:D(`client.actions.configure.provider.authentication.for.this.project.3e0f43`,`Configure provider authentication for this project`),description:D(`client.actions.run.login.for.this.project.bab71f`,`Run /login for this project`),group:D(`client.actions.general.835b70`,`General`),run:e=>e.configureAuth()},{id:`auth.logout`,title:D(`client.actions.remove.provider.authentication.for.this.project.d527aa`,`Remove provider authentication for this project`),description:D(`client.actions.remove.saved.credentials.for.this.project.1a3567`,`Remove saved credentials for this project`),group:D(`client.actions.general.835b70`,`General`),run:e=>e.logoutAuth()},{id:`mcp.login`,title:D(`ui.mcp.loginAction`,`MCP login`),description:D(`ui.mcp.loginDescription`,`Choose an MCP server for the selected session and sign in`),group:`MCP`,enabled:e=>Xu(e)&&e.piWebUnstable?.openMcpAuth!==void 0,disabledReason:e=>Xu(e)?void 0:D(`ui.mcp.selectSession`,`Select a session to authenticate MCP servers.`),run:e=>e.piWebUnstable?.openMcpAuth?.(`login`)},{id:`mcp.logout`,title:D(`ui.mcp.logoutAction`,`MCP logout`),description:D(`ui.mcp.logoutDescription`,`Remove local MCP credentials without disabling the server or revoking provider access`),group:`MCP`,enabled:e=>Xu(e)&&e.piWebUnstable?.openMcpAuth!==void 0,disabledReason:e=>Xu(e)?void 0:D(`ui.mcp.selectSession`,`Select a session to authenticate MCP servers.`),run:e=>e.piWebUnstable?.openMcpAuth?.(`logout`)},{id:`theme.select`,title:D(`client.actions.choose.theme.07a79a`,`Choose theme`),description:D(`client.actions.choose.a.pi.web.color.theme.fdc708`,`Choose a PI WEB color theme`),group:D(`client.actions.preferences.57907a`,`Preferences`),run:e=>{e.openThemePicker()}},{id:`settings.open`,title:D(`client.actions.open.settings.37aa6a`,`Open settings`),description:D(`client.actions.manage.pi.web.configuration.and.keyboard.shortcuts.cb1723`,`Manage PI WEB configuration and keyboard shortcuts`),shortcut:`mod+,`,group:D(`client.actions.preferences.57907a`,`Preferences`),run:e=>{e.piWebUnstable?.openSettings?.()}},{id:`app.reload-page`,title:D(`ui.appRefreshControl.reloadEntirePage`,`Reload entire page`),description:D(`client.actions.reload.the.pi.web.browser.page.cc27a2`,`Reload the PI WEB browser page`),group:D(`client.actions.general.835b70`,`General`),run:e=>{e.reloadPage()}},{id:`view.chat`,title:D(`client.actions.go.to.chat.6ba944`,`Go to chat`),shortcut:`mod+1`,group:D(`client.actions.navigation.e72622`,`Navigation`),run:e=>{e.focusPrompt()}},{id:`workspace.delete`,title:D(`client.actions.delete.workspace.1bca7e`,`Delete workspace`),description:D(`ui.main.c3e7f4dcb44f`,`Run the owning provider's workspace removal operation`),group:D(`bundled.workspace-tasks.workspace.379798`,`Workspace`),enabled:Yu,run:e=>e.deleteWorkspace()},{id:`session.start`,title:D(`client.actions.start.session.21780f`,`Start session`),shortcut:`mod+enter`,group:D(`ui.sessionSearchDialog.sessions`,`Sessions`),enabled:Ju,run:e=>e.startSession()},{id:`model.select`,title:D(`client.actions.choose.model.1afed6`,`Choose model`),description:D(`client.actions.choose.a.model.for.the.selected.session.60aa76`,`Choose a model for the selected session`),group:D(`ui.sessionSearchDialog.sessions`,`Sessions`),enabled:Xu,run:e=>e.openModelPicker()},{id:`thinking.select`,title:D(`client.actions.choose.thinking.level.77e3b8`,`Choose thinking level`),description:D(`client.actions.choose.a.thinking.level.for.the.selected.session.403bab`,`Choose a thinking level for the selected session`),group:D(`ui.sessionSearchDialog.sessions`,`Sessions`),enabled:Xu,run:e=>e.openThinkingLevelPicker()},{id:`session.archive`,title:D(`client.actions.archive.session.0a3885`,`Archive session`),description:D(`client.actions.archive.the.selected.session.6d7088`,`Archive the selected session`),group:D(`ui.sessionSearchDialog.sessions`,`Sessions`),enabled:Zu,run:e=>e.archiveSession()},{id:`session.reload`,title:D(`client.actions.reload.session.05361c`,`Reload session`),description:D(`client.actions.close.and.reopen.the.selected.session.from.its.file.use.reload.in.the..869a6b`,`Close and reopen the selected session from its file; use /reload in the prompt to reload Pi runtime resources`),group:D(`ui.sessionSearchDialog.sessions`,`Sessions`),enabled:$u,disabledReason:ed,run:e=>e.reloadSession()},{id:`session.delete`,title:D(`client.actions.delete.new.session.4c6f58`,`Delete new session`),description:D(`client.actions.delete.the.selected.temporary.new.session.480813`,`Delete the selected temporary new session`),group:D(`ui.sessionSearchDialog.sessions`,`Sessions`),enabled:Qu,run:e=>e.deleteCachedNewSession()},{id:`session.stop`,title:D(`client.actions.stop.active.work.95304d`,`Stop active work`),shortcut:`mod+.`,group:D(`ui.sessionSearchDialog.sessions`,`Sessions`),enabled:e=>e.state.selectedSession!==void 0&&rr(e.state.status,e.state.activity),run:e=>e.stopActiveWork()}]}function Ju(e){return e.state.selectedWorkspace!==void 0}function Yu(e){let t=e.state.selectedWorkspace;return zu(t)&&!Wu(e.state,t)}function Xu(e){let t=e.state.selectedSession;return t!==void 0&&t.archived!==!0}function Zu(e){return zs(e.state.selectedSession,e.state.status,td(e.state))}function Qu(e){return Bs(e.state.selectedSession,e.state.status,td(e.state))}function $u(e){return!zs(e.state.selectedSession,e.state.status,td(e.state))||ed(e)!==void 0?!1:!rr(e.state.status,e.state.activity)}function ed(e){if(zs(e.state.selectedSession,e.state.status,td(e.state))&&!rr(e.state.status,e.state.activity))return nd(e.state,D(`client.actions.reload.the.session.from.disk.45d1dc`,`reload the session from disk`))}function td(e){return Ls(e.machineRuntimes[M(e)])}function nd(e,t){if(e.machineRuntimes[M(e)]?.ok===!0)return;let n=e.selectedMachine?.name;return n!==void 0&&n!==``?D(`client.actions.update.and.restart.pi.web.on.to.aa2e7e`,`Update and restart Pi-Web on {value1} to {value2}.`,{value1:n,value2:t}):D(`client.actions.update.and.restart.pi.web.on.this.machine.to.da2f57`,`Update and restart Pi-Web on this machine to {value1}.`,{value1:t})}async function rd(e,t=id()){if(!t.isSecureContext)return t.fallbackWriteText(e);if(t.writeText!==void 0)try{return await t.writeText(e),!0}catch{return t.fallbackWriteText(e)}return t.fallbackWriteText(e)}function id(){let e=e=>sd(e),t=od();return t===void 0?{isSecureContext:ad(),fallbackWriteText:e}:{isSecureContext:ad(),writeText:t,fallbackWriteText:e}}function ad(){return typeof window<`u`&&window.isSecureContext}function od(){if(typeof navigator<`u`&&`clipboard`in navigator)return navigator.clipboard.writeText.bind(navigator.clipboard)}function sd(e){if(typeof document>`u`)return!1;let t=document.activeElement,n=document.getSelection(),r=n===null?[]:cd(n),i=document.createElement(`textarea`);i.value=e,i.readOnly=!0,i.setAttribute(`aria-hidden`,`true`),i.style.position=`fixed`,i.style.top=`0`,i.style.left=`-9999px`,i.style.width=`1px`,i.style.height=`1px`,i.style.padding=`0`,i.style.border=`0`,i.style.opacity=`0`,i.style.pointerEvents=`none`,document.body.append(i),i.focus(),i.select(),i.setSelectionRange(0,i.value.length);try{return document.execCommand(`copy`)}catch{return!1}finally{i.remove(),ld(n,r),ud(t)}}function cd(e){let t=[];for(let n=0;n<e.rangeCount;n+=1)t.push(e.getRangeAt(n));return t}function ld(e,t){if(e!==null)try{e.removeAllRanges();for(let n of t)e.addRange(n)}catch{}}function ud(e){if(typeof HTMLElement<`u`&&e instanceof HTMLElement)try{e.focus({preventScroll:!0})}catch{e.focus()}}function dd(e=rd){let t={visible:({message:e})=>e.role===`user`||e.role===`assistant`||e.role===`tool`&&e.isQuestion===!0,enabled:({session:e})=>!e.archived&&!e.pending&&!e.busy};return[{...t,id:`message.fork`,title:D(`ui.main.4e737b072caa`,`Clone session from this message`),ariaLabel:()=>D(`session.fork`,`Fork`),icon:E`<span class="msg-fork-icon" aria-hidden="true">⑂</span>`,run:async({history:e})=>{window.confirm(D(`ui.main.5b7be2382217`,`Are you sure you want to fork this session?`))&&await e.fork()}},{...t,id:`message.back`,title:D(`ui.main.c99fd586dc20`,`Go back to this message`),ariaLabel:()=>D(`ui.main.dedece75f412`,`Go back to this message`),icon:E`<svg aria-hidden="true" width="16" height="16" viewBox="-3 -3 30 30" fill="none" stroke="currentColor" stroke-width="0.85" stroke-linecap="round" stroke-linejoin="round"><path vector-effect="non-scaling-stroke" d="M4 5h11a6 6 0 0 1 0 12H4m5-5-5 5 5 5" /></svg>`,run:async({history:e})=>{window.confirm(D(`ui.main.92fa96db248a`,`Are you sure you want to go back to this message?`))&&await e.goBack()}},{target:`display`,id:`message.copy`,title:D(`ui.chatView.copyMessage`,`Copy message`),ariaLabel:({message:e})=>D(`ui.chatView.message`,`{copied} {role} message`,{copied:D(`bundled.updates.copy.63d90d`,`Copy`),role:e.role===`user`?D(`ui.chatView.user`,`User`):D(`ui.chatView.assistant`,`Assistant`)}),icon:E`<span aria-hidden="true">⧉</span>`,visible:({message:e})=>(e.role===`user`||e.role===`assistant`)&&e.text!==``,run:async({message:t})=>{if(!await e(t.text))throw Error(D(`ui.messageActions.clipboardFailed`,`Unable to copy message to the clipboard.`));return{title:D(`ui.toolExecutionView.copied`,`Copied`),ariaLabel:D(`ui.chatView.message`,`{copied} {role} message`,{copied:D(`ui.toolExecutionView.copied`,`Copied`),role:t.role===`user`?D(`ui.chatView.user`,`User`):D(`ui.chatView.assistant`,`Assistant`)}),icon:E`<span aria-hidden="true">✓</span>`}}}]}var fd={apiVersion:5,name:D(`client.index.pi.web.core.d120ca`,`PI WEB Core`),activate:()=>({contributions:{actions:qu(),messageActions:dd()}})},pd={apiVersion:5,name:D(`client.index.pi.web.themes.9c5a30`,`PI WEB Themes`),activate:()=>({contributions:{themes:[{id:`pi-web-dark`,name:D(`client.index.pi.web.dark.91b604`,`PI WEB Dark`),description:D(`client.index.pi.web.dark.color.scheme.9d56a4`,`Dark PI WEB palette.`),order:10,colorScheme:`dark`,stylesheets:[{id:`palette`,url:new URL(new URL(`pi-web-dark-D_KtbM95.css`,import.meta.url).href,``+import.meta.url).href}]},{id:`pi-web-light`,name:D(`client.index.pi.web.light.081df9`,`PI WEB Light`),description:D(`client.index.pi.web.light.color.scheme.b51736`,`Light PI WEB palette.`),order:20,colorScheme:`light`,stylesheets:[{id:`palette`,url:new URL(new URL(`pi-web-light-DSNLMIBI.css`,import.meta.url).href,``+import.meta.url).href}]},{id:`classic`,name:D(`client.index.pi.web.classic.4793fe`,`PI WEB Classic`),description:D(`client.index.original.pi.web.dark.color.scheme.80bcd3`,`The original PI WEB dark palette.`),order:30,colorScheme:`dark`,stylesheets:[{id:`palette`,url:new URL(new URL(`classic-CyM97Akm.css`,import.meta.url).href,``+import.meta.url).href}]}],themePairs:[{id:`pi-web`,name:`PI WEB`,description:D(`client.index.follow.the.system.light.dark.preference.with.pi.web.themes.33941c`,`Follow the system light/dark preference with PI WEB themes.`),order:10,light:`pi-web-light`,dark:`pi-web-dark`}]}})};function md(e,t){return Object.freeze({machineId:t,listProjects:async()=>(await e.projects(t)).map(({id:e,name:t,path:n})=>({id:e,name:t,path:n})),suggestDirectories:async n=>(await e.projectDirectories(n,t)).map(({path:e})=>({path:e}))})}var hd=Object.freeze({pluginId:`pi-web.host`,id:`catalog`,version:1,parse:gd});function gd(e){let t=Cd(e);if(t.version!==1)throw Od();let n=_d(t.projects),r=_d(t.workspaces),i=_d(t.sessions);return Object.freeze({version:1,projects:Object.freeze({list:async e=>Sd(await n.list(e),vd),get:async(e,t)=>{let r=Td(e),i=vd(await n.get(r,t));if(i.id!==r)throw Od();return i}}),workspaces:Object.freeze({list:async(e,t)=>{let n=Td(e);return Sd(await r.list(n,t),e=>yd(e,n))},get:async(e,t)=>{let n=xd(e),i=yd(await r.get(n,t),n.projectId);if(i.id!==n.workspaceId)throw Od();return i}}),sessions:Object.freeze({list:async(e,t)=>Sd(await i.list(xd(e),t),bd),get:async(e,t)=>{let n=xd(e,!0),r=bd(await i.get(n,t));if(r.id!==n.sessionId)throw Od();return r}})})}function _d(e){let t=Cd(e),n=t.list,r=t.get;if(typeof n!=`function`||typeof r!=`function`)throw Od();return{list:(...e)=>Promise.resolve(Reflect.apply(n,t,e)),get:(...e)=>Promise.resolve(Reflect.apply(r,t,e))}}function vd(e){let t=Cd(e);return Object.freeze({id:Td(t.id),name:Td(t.name),path:Td(t.path)})}function yd(e,t){let n=Cd(e);if(n.projectId!==t||typeof n.isMain!=`boolean`)throw Od();let r;if(n.provider!==void 0){let e=Cd(n.provider),t=Cd(e.capabilities);if(typeof t.remove!=`boolean`)throw Od();r=Object.freeze({pluginId:Td(e.pluginId),capabilities:Object.freeze({remove:t.remove}),...e.metadata===void 0?{}:{metadata:Ed(e.metadata)}})}let i=n.removal===void 0?void 0:Cd(n.removal);return Object.freeze({id:Td(n.id),projectId:t,path:Td(n.path),label:Td(n.label),isMain:n.isMain,...r===void 0?{}:{provider:r},...i===void 0?{}:{removal:Object.freeze({actionLabel:Td(i.actionLabel),confirmation:Td(i.confirmation)})}})}function bd(e){let t=Cd(e),n=t.runtime;if(typeof t.archived!=`boolean`||n!==`not-hosted`&&n!==`idle`&&n!==`busy`)throw Od();let r;if(t.metadata!==void 0&&(r=Object.freeze(Object.fromEntries(Object.entries(Cd(t.metadata)).map(([e,t])=>[e,Ed(t)])))),t.name!==void 0&&typeof t.name!=`string`)throw Od();return Object.freeze({id:Td(t.id),cwd:Td(t.cwd),archived:t.archived,runtime:n,...t.name===void 0?{}:{name:t.name},...r===void 0?{}:{metadata:r}})}function xd(e,t=!1){let n=Cd(e),r=t?[`projectId`,`workspaceId`,`sessionId`]:[`projectId`,`workspaceId`];if(Reflect.ownKeys(n).some(e=>typeof e!=`string`||!r.includes(e)))throw Od();return Object.freeze({projectId:Td(n.projectId),workspaceId:Td(n.workspaceId),...t?{sessionId:Td(n.sessionId)}:{}})}function Sd(e,t){if(!Array.isArray(e))throw Od();return Object.freeze(e.map(t))}function Cd(e){if(!wd(e))throw Od();return e}function wd(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Td(e){if(typeof e!=`string`||e.trim()===``)throw Od();return e}function Ed(e,t=new Set){let n=Cd(e);if(t.has(n))throw Od();t.add(n);let r=Object.freeze(Object.fromEntries(Object.entries(n).map(([e,n])=>[e,Dd(n,t)])));return t.delete(n),r}function Dd(e,t){if(e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&Number.isFinite(e))return e;if(Array.isArray(e)){if(t.has(e))throw Od();t.add(e);let n=Object.freeze(e.map(e=>Dd(e,t)));return t.delete(e),n}return Ed(e,t)}function Od(){return Error(`Invalid PI WEB host catalog capability v1 data`)}function kd(e,t,n=(e,t)=>Ee(e,e=>e,t)){if(e===``)throw Error(`Catalog machine id is required`);let r=`api/machines/${encodeURIComponent(e)}/plugin-catalog/projects`,i=e=>`${r}/${encodeURIComponent(e)}`,a=({projectId:e,workspaceId:t})=>`${i(e)}/workspaces/${encodeURIComponent(t)}`,o=async(e,r)=>{let i=t===void 0?r?.signal:r?.signal===void 0?t:AbortSignal.any([t,r.signal]);i?.throwIfAborted();let a=await n(e,{cache:`no-store`,...i===void 0?{}:{signal:i}});return i?.throwIfAborted(),a},s=hd.parse({version:1,projects:{list:e=>o(r,e),get:(e,t)=>o(i(e),t)},workspaces:{list:(e,t)=>o(`${i(e)}/workspaces`,t),get:(e,t)=>o(a(e),t)},sessions:{list:(e,t)=>o(`${a(e)}/sessions`,t),get:(e,t)=>o(`${a(e)}/sessions/${encodeURIComponent(e.sessionId)}`,t)}});return Object.freeze({...s,machineId:e})}function Ad(e,t,n,r=vt,i=lt){if(e.pairedRequestVersion!==1&&e.pairedChannelVersion!==1)return;let a=Md(e,t,n);if(a!==void 0){if(e.pairedRequestVersion===1&&e.pairedChannelVersion===1)return{request:(e,t,n)=>r(a,e,t,n),openChannel:(e,t,n)=>i(a,e,t,n)};if(e.pairedRequestVersion===1)return{request:(e,t,n)=>r(a,e,t,n)};if(e.pairedChannelVersion===1)return{openChannel:(e,t,n)=>i(a,e,t,n)}}}function jd(e,t,n,r=vt,i=lt){if(e.backendRevision===void 0||e.pairedRequestVersion!==1&&e.pairedChannelVersion!==1)return;let a=e.backendRevision,o=e=>n===void 0?e:e===void 0?n:AbortSignal.any([n,e]);return Object.freeze({machineId:t,forScope(s){if(n?.throwIfAborted(),s.kind!==`machine`&&(typeof s.projectId!=`string`||s.projectId===``))throw Error(`Project id is required`);if(s.kind===`workspace`&&(typeof s.workspaceId!=`string`||s.workspaceId===``))throw Error(`Workspace id is required`);let c=Object.freeze({pluginId:e.sourcePluginId,backendRevision:a,machineId:t,scope:s.kind,...s.kind===`machine`?{}:{projectId:s.projectId},...s.kind===`workspace`?{workspaceId:s.workspaceId}:{}}),l=(e,t,n)=>{let i=o(n?.signal);return i?.throwIfAborted(),r(c,e,t,{...i===void 0?{}:{signal:i}})},u=(e,t,n)=>{let r=o(n.signal);return r?.throwIfAborted(),i(c,e,t,{...n,...r===void 0?{}:{signal:r}})};return e.pairedRequestVersion===1?Object.freeze({request:l,...e.pairedChannelVersion===1?{openChannel:u}:{}}):Object.freeze({openChannel:u})}})}function Md(e,t,n){let r=e.backendRevision;if(r!==void 0)return{pluginId:e.sourcePluginId,backendRevision:r,machineId:n,projectId:t.projectId,workspaceId:t.id}}var Nd=class{constructor(e){this.readSelection=e,this.subscribers=new Set,this.lastSelection=JSON.stringify(e())}notifyChanged(){let e=this.readSelection(),t=JSON.stringify(e);if(t!==this.lastSelection){this.lastSelection=t;for(let t of[...this.subscribers])this.subscribers.has(t)&&t(e)}}forPlugin(e,t){return Object.freeze({getSnapshot:()=>structuredClone(this.readSelection()),subscribe:n=>{if(t.aborted)return()=>void 0;let r=t=>{console.warn(`PI WEB plugin ${e} selection subscriber failed`,t)},i=e=>{try{let t=n(structuredClone(e));t!==void 0&&Promise.resolve(t).catch(r)}catch(e){r(e)}},a=()=>{this.subscribers.delete(i),t.removeEventListener(`abort`,a)};return this.subscribers.add(i),t.addEventListener(`abort`,a,{once:!0}),a}})}};function Pd(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n?.renderer.renderMode===`automatic`)return n}return e[0]}function Fd(e,t){let n=t.language?.trim().split(/\s/u)[0]?.toLowerCase(),r=t.filePath?.split(/[\\/]/u).at(-1)?.toLowerCase(),i=(e.languages?.length??0)+(e.fileExtensions?.length??0)>0,a=n!==void 0&&e.languages?.includes(n)===!0||r!==void 0&&e.fileExtensions?.some(e=>r.endsWith(`.${e}`))===!0;if(i&&!a)return!1;try{if(e.supports===void 0)return a;let n=e.supports(Object.freeze({...t}));if(typeof n==`object`&&n&&`then`in n&&typeof n.then==`function`&&Promise.resolve(n).catch(()=>{console.warn(`Content renderer eligibility failed`,{rendererId:e.id,category:`eligibility`})}),typeof n!=`boolean`)throw Error(`Content renderer supports must return a boolean synchronously`);return n}catch{return console.warn(`Content renderer eligibility failed`,{rendererId:e.id,category:`eligibility`}),!1}}function Id(e){if(typeof e.render!=`function`)throw Error(`Content renderer must have a synchronous render callback`);let t=e.renderMode;if(t!==void 0&&t!==`manual`&&t!==`automatic`)throw Error(`Content renderer renderMode must be manual or automatic`);if(e.supports!==void 0&&typeof e.supports!=`function`)throw Error(`Content renderer supports must be a callback`);if(e.title!==void 0&&(typeof e.title!=`string`||e.title.trim()===``))throw Error(`Content renderer title must be a non-empty string`);return Object.freeze({id:e.id,...Ld(e,e.supports!==void 0),...e.title===void 0?{}:{title:e.title},...e.supports===void 0?{}:{supports:e.supports.bind(e)},renderMode:e.renderMode??`manual`,render:e.render.bind(e)})}function Ld(e,t=!1){let n=e=>{if(e===void 0)return Object.freeze([]);if(!Array.isArray(e)||e.some(e=>typeof e!=`string`||!/^[a-z0-9][a-z0-9_+.-]*$/iu.test(e)))throw Error(`Content renderer selectors must be non-empty language names or extensions without a leading dot`);return Object.freeze([...new Set(e.map(e=>e.toLowerCase()))])},r=n(e.languages),i=n(e.fileExtensions);if(!t&&r.length+i.length===0)throw Error(`Content renderer must declare a selector`);return Object.freeze({languages:r,fileExtensions:i})}var Rd={pluginId:`pi-web`,id:`syntax-highlighting`,version:1,parse(e){if(!zd(e))throw Error(`Syntax highlighting capability v1 is unavailable`);return e}};function zd(e){return typeof e==`object`&&!!e&&`highlight`in e&&typeof e.highlight==`function`&&`supports`in e&&typeof e.supports==`function`}var Bd=new Set([`keyword`,`string`,`number`,`comment`,`type`,`function`,`variable`,`operator`,`punctuation`,`property`,`literal`,`meta`]);function Vd(e){return typeof e==`string`&&Bd.has(e)}function Hd(e,t){if(!Array.isArray(e))throw Error(`Syntax highlighter must return an array of tokens`);let n=0;return Object.freeze(Array.from(e,e=>{if(typeof e!=`object`||!e||!(`from`in e)||!(`to`in e)||!(`kind`in e)||typeof e.from!=`number`||typeof e.to!=`number`||!Number.isInteger(e.from)||!Number.isInteger(e.to)||e.from<n||e.to<=e.from||e.to>t.length||!Vd(e.kind))throw Error(`Invalid syntax highlight token: expected sorted, nonoverlapping UTF-16 bounds and a standard kind`);return n=e.to,Object.freeze({from:e.from,to:e.to,kind:e.kind})}))}function Ud(e){if(typeof e.highlight!=`function`)throw Error(`Syntax highlighter must have a highlight callback`);return Object.freeze({id:e.id,...Ld(e),highlight:e.highlight.bind(e)})}async function Wd(e,t,n){n.throwIfAborted();let r,i=new Promise((e,t)=>{r=()=>{t(n.reason)},n.addEventListener(`abort`,r,{once:!0})});try{let r=Promise.resolve().then(()=>(n.throwIfAborted(),e.highlight({text:t,signal:n}))),a=await Promise.race([r,i]);return n.throwIfAborted(),Hd(a,t)}catch(t){throw n.aborted?n.reason:Error(`Syntax highlighter ${e.id} failed`,{cause:t})}finally{r!==void 0&&n.removeEventListener(`abort`,r)}}function Gd(e){return Object.freeze({supports:t=>e(t)!==void 0,async highlight(t){if(t.signal.throwIfAborted(),!(t.text.length>1e5))return e(t)?.highlight({text:t.text,signal:t.signal})}})}var Kd=Symbol.for(``),qd=e=>{if(e?.r===Kd)return e?._$litStatic$},Jd=e=>({_$litStatic$:e,r:Kd}),Yd=new Map,Xd=(e=>(t,...n)=>{let r=n.length,i,a,o=[],s=[],c,l=0,u=!1;for(;l<r;){for(c=t[l];l<r&&(a=n[l],(i=qd(a))!==void 0);)c+=i+t[++l],u=!0;l!==r&&s.push(a),o.push(c),l++}if(l===r&&o.push(t[r]),u){let e=o.join(`$$lit$$`);(t=Yd.get(e))===void 0&&(o.raw=o,Yd.set(e,t=o)),n=s}return e(t,...n)})(E),Zd=(e,t)=>{let n=e._$AN;if(n===void 0)return!1;for(let e of n)e._$AO?.(t,!1),Zd(e,t);return!0},Qd=e=>{let t,n;do{if((t=e._$AM)===void 0)break;n=t._$AN,n.delete(e),e=t}while(n?.size===0)},$d=e=>{for(let t;t=e._$AM;e=t){let n=t._$AN;if(n===void 0)t._$AN=n=new Set;else if(n.has(e))break;n.add(e),nf(t)}};function ef(e){this._$AN===void 0?this._$AM=e:(Qd(this),this._$AM=e,$d(this))}function tf(e,t=!1,n=0){let r=this._$AH,i=this._$AN;if(i!==void 0&&i.size!==0){if(t){if(Array.isArray(r))for(let e=n;e<r.length;e++)Zd(r[e],!1),Qd(r[e]);else r!=null&&(Zd(r,!1),Qd(r))}else Zd(this,e)}}var nf=e=>{e.type==Ne.CHILD&&(e._$AP??=tf,e._$AQ??=ef)},rf=class extends Qe{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,n){super._$AT(e,t,n),$d(this),this.isConnected=e._$AU}_$AO(e,t=!0){e!==this.isConnected&&(this.isConnected=e,e?this.reconnected?.():this.disconnected?.()),t&&(Zd(this,e),Qd(this))}setValue(e){if(o(this._$Ct))this._$Ct._$AI(e,this);else{let t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}},af=new WeakMap,of=_t(class extends rf{render(e){return k}update(e,[t]){let n=t!==this.G;return n&&this.rt(void 0),(n||this.lt!==this.ct)&&(this.G=t,this.ht=e.options?.host,this.rt(this.ct=e.element)),k}rt(e){if(this.G!==void 0){if(this.isConnected||(e=void 0),typeof this.G==`function`){let t=this.ht??globalThis,n=af.get(t);n===void 0&&(n=new WeakMap,af.set(t,n)),n.get(this.G)!==void 0&&this.G.call(this.ht,void 0),n.set(this.G,e),e!==void 0&&this.G.call(this.ht,e)}else this.G.value=e}}get lt(){return typeof this.G==`function`?af.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}}),sf=class extends Qe{constructor(e){if(super(e),this.it=k,e.type!==Ne.CHILD)throw Error(this.constructor.directiveName+`() can only be used in child bindings`)}render(e){if(e===k||e==null)return this._t=void 0,this.it=e;if(e===It)return e;if(typeof e!=`string`)throw Error(this.constructor.directiveName+`() called with a non-string value`);if(e===this.it)return this._t;this.it=e;let t=[e];return t.raw=t,this._t={_$litType$:this.constructor.resultType,strings:t,values:[]}}};sf.directiveName=`unsafeHTML`,sf.resultType=1;var cf=_t(sf);function lf(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var uf=lf();function df(e){uf=e}var ff={exec:()=>null};function pf(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function L(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(R.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var mf=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),R={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,leadingSpaceTab:/^[ \t]+/,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,numericCharacterReferenceOrAmpersand:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:pf(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:pf(e=>RegExp(`^ {0,${e}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:pf(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:pf(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:pf(e=>RegExp(`^ {0,${e}}(?:</?(?:${kf})(?: +|$|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`,`i`)),blockquoteBeginRegex:pf(e=>RegExp(`^ {0,${e}}>`))},hf=/^(?:[ \t]*(?:\n|$))+/,gf=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,_f=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,vf=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,yf=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,bf=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,xf=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Sf=L(xf).replace(/bull/g,bf).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),Cf=L(xf).replace(/bull/g,bf).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),wf=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Tf=/^[^\n]+/,Ef=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Df=L(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,Ef).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),Of=L(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,bf).getRegex(),kf=`address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,Af=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,jf=L(`^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!(?:script|pre|style|textarea)(?![a-z0-9-]))([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</[a-z][a-z0-9-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,Af).replace(`tag`,kf).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Mf=e=>L(wf).replace(`hr`,vf).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,e).replace(`html`,` {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`).replace(`tag`,kf).getRegex(),Nf=Mf(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Pf=Mf(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Ff={blockquote:L(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,Pf).getRegex(),code:gf,def:Df,fences:_f,heading:yf,hr:vf,html:jf,lheading:Sf,list:Of,newline:hf,paragraph:Nf,table:ff,text:Tf},If=L(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,vf).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`blockquote`,` {0,3}>`).replace(`code`,`(?: {4}| {0,3} )[^\\n]`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]`).replace(`html`,` {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`).replace(`tag`,kf).getRegex(),Lf={...Ff,lheading:Cf,table:If,paragraph:L(wf).replace(`hr`,vf).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,If).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,` {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`).replace(`tag`,kf).getRegex()},Rf={...Ff,html:L(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,Af).replace(/tag/g,`(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b`).getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:ff,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:L(wf).replace(`hr`,vf).replace(`heading`,` *#{1,6} *[^
|
|
30
30
|
]`).replace(`lheading`,Sf).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},zf=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Bf=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Vf=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,Hf=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,Uf=/[\p{P}\p{S}]/u,Wf=/[\s\p{P}\p{S}]/u,Gf=/[^\s\p{P}\p{S}]/u,Kf=L(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,Wf).getRegex(),qf=/[\p{Pi}\p{Ps}"']/u,Jf=/(?!~)[\p{P}\p{S}]/u,Yf=/(?!~)[\s\p{P}\p{S}]/u,Xf=/(?:[^\s\p{P}\p{S}]|~)/u,Zf=L(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,mf?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),Qf=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,$f=L(Qf,`u`).replace(/punct/g,Uf).getRegex(),ep=L(Qf,`u`).replace(/punct/g,Jf).getRegex(),tp=L(/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,`u`).replace(/openQuote/g,qf).replace(/punct/g,Uf).getRegex(),np=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,rp=L(np,`gu`).replace(/notPunctSpace/g,Gf).replace(/punctSpace/g,Wf).replace(/punct/g,Uf).getRegex(),ip=L(np,`gu`).replace(/notPunctSpace/g,Xf).replace(/punctSpace/g,Yf).replace(/punct/g,Jf).getRegex(),ap=L(`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Gf).replace(/punctSpace/g,Wf).replace(/punct/g,Uf).getRegex(),op=L(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,Gf).replace(/punctSpace/g,Wf).replace(/punct/g,Uf).getRegex(),sp=L(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Gf).replace(/punctSpace/g,Wf).replace(/punct/g,Uf).getRegex(),cp=L(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,Uf).getRegex(),lp=L(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,Gf).replace(/punctSpace/g,Wf).replace(/punct/g,Uf).getRegex(),up=L(/\\(punct)/,`gu`).replace(/punct/g,Uf).getRegex(),dp=L(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,`gu`).replace(/punct/g,Uf).getRegex(),fp=L(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace(`scheme`,/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(`email`,/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),pp=L(Af).replace(`(?:-->|$)`,`-->`).getRegex(),mp=L(`^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\s*>|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,pp).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),hp=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,gp=L(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace(`brackets`,hp).getRegex(),_p=L(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace(`label`,gp).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),vp=L(/^!?\[(label)\]\[(ref)\]/).replace(`label`,gp).replace(`ref`,Ef).getRegex(),yp=L(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,Ef).getRegex(),bp=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,xp=L(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace(`brackets`,hp).getRegex(),Sp=L(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,L(/^!?\[(label)\]\[(ref)\]/).replace(`label`,xp).replace(`ref`,bp).getRegex()).replace(`nolink`,L(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,bp).getRegex()).getRegex(),Cp=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,wp=L(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),Tp={_backpedal:ff,anyPunctuation:up,anyPunctuationOutsideCode:dp,autolink:fp,blockSkip:Zf,br:Vf,code:Bf,del:ff,delLDelim:ff,delRDelim:ff,emStrongLDelim:$f,emStrongRDelimAst:rp,emStrongRDelimUnd:op,escape:zf,link:_p,nolink:yp,punctuation:Kf,reflink:vp,reflinkSearch:Sp,tag:mp,text:Hf,url:ff},Ep={...Tp,emStrongLDelim:tp,emStrongRDelimAst:ap,emStrongRDelimUnd:sp,link:L(/^!?\[(label)\]\((.*?)\)/).replace(`label`,gp).getRegex(),reflink:L(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,gp).getRegex()},Dp={...Tp,emStrongRDelimAst:ip,emStrongLDelim:ep,delLDelim:cp,delRDelim:lp,url:L(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`emailProtocol`,wp).replace(`protocol`,Cp).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:L(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9](?=emailProtocol)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))))/).replace(`protocol`,Cp).replace(/emailProtocol/g,/(?:mailto|xmpp):/).getRegex()},Op={...Dp,br:L(Vf).replace(`{2,}`,`*`).getRegex(),text:L(Dp.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},kp={normal:Ff,gfm:Lf,pedantic:Rf},Ap={normal:Tp,gfm:Dp,breaks:Op,pedantic:Ep},jp={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},Mp=e=>jp[e];function Np(e,t){if(t){if(R.escapeTest.test(e))return e.replace(R.escapeReplace,Mp)}else if(R.escapeTestNoEncode.test(e))return e.replace(R.escapeReplaceNoEncode,Mp);return e}function Pp(e){return R.numericCharacterReference.test(e)?e.replace(R.numericCharacterReferenceOrAmpersand,(e,t,n)=>{if(t===void 0&&n===void 0)return`&`;let r=t===void 0?Number.parseInt(n,16):Number.parseInt(t,10);return r===0||r>1114111||r>=55296&&r<=57343?`�`:r===38?`&`:String.fromCodePoint(r)}):e}function Fp(e){try{e=encodeURI(e).replace(R.percentDecode,`%`)}catch{return null}return e}function Ip(e,t){let n=e.replace(R.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(R.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t){if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``)}for(;r<n.length;r++)n[r]=n[r].trim().replace(R.slashPipe,`|`);return n}function Lp(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function Rp(e){let t=e.split(`
|
|
@@ -3671,7 +3671,7 @@ This only removes it from PI WEB. The project folder will not be changed.`,{name
|
|
|
3671
3671
|
`}visibleWorkspacePanels(){let e=this.createApplicationPanelContext(),t=this.plugins.getApplicationPanels().filter(t=>t.visible?.(e)??!0).map(t=>({...t,badge:()=>t.badge?.(e),render:()=>t.render(e)})),n=this.state.selectedWorkspace;if(n!==void 0){let e=this.createWorkspacePanelContext(n);t.push(...this.plugins.getWorkspacePanels().filter(t=>t.visible?.(e)??!0).map(t=>({...t,badge:()=>t.badge?.(e),render:()=>t.render(e)})))}return t.sort((e,t)=>(e.order??1e3)-(t.order??1e3)||e.title.localeCompare(t.title))}workspacePanelEmptyState(){let e=this.state.selectedProject;return this.state.isLoadingProjects?{title:D(`ui.piWebApp.loadingProjects`,`Loading projects…`),body:D(`ui.piWebApp.findingProjectsYouAddedToPiWeb`,`Finding projects you added to PI WEB.`)}:e===void 0?this.state.projects.length===0?{title:D(`ui.piWebApp.noProjectsYet`,`No projects yet`),body:D(`ui.piWebApp.useActionsAddProjectToAddAFolder`,`Use Actions → Add project to add a folder. Workspace tools appear here after you select a workspace.`)}:{title:D(`ui.piWebApp.selectProject`,`Select project`),body:D(`ui.piWebApp.selectAProjectInTheSidebarThenA`,`Select a project in the sidebar, then a workspace to view files, Git, or terminals.`)}:this.state.isLoadingWorkspaces?{title:D(`ui.piWebApp.loadingWorkspaces`,`Loading workspaces…`),body:D(`ui.piWebApp.preparingWorkspaceToolsFor`,`Preparing workspace tools for {name}.`,{name:e.name})}:this.state.workspaces.length===0?{title:D(`ui.piWebApp.noWorkspacesFound`,`No workspaces found`),body:D(`ui.piWebApp.noWorkspacesAvailableForTrySelectingOrAdding`,`No workspaces available for {name}. Try selecting or adding the project again.`,{name:e.name})}:{title:D(`ui.workspacePanel.selectWorkspace`,`Select workspace`),body:D(`ui.piWebApp.selectAWorkspaceInToViewFilesGit`,`Select a workspace in {name} to view files, Git, or terminals.`,{name:e.name})}}sessionEmptyMessage(){return this.contentError()===``?this.state.isLoadingProjects?D(`ui.piWebApp.loadingProjects`,`Loading projects…`):this.state.selectedWorkspace===void 0?this.state.selectedProject===void 0?this.state.projects.length===0?D(`ui.piWebApp.addAProjectToStartASession`,`Add a project to start a session.`):D(`ui.piWebApp.selectAProjectAndWorkspaceToStartA`,`Select a project and workspace to start a session.`):D(`ui.piWebApp.selectAWorkspaceToStartASession`,`Select a workspace to start a session.`):D(`ui.piWebApp.selectOrStartASession`,`Select or start a session.`):this.contentError()}workspaceLabelItems(e){return this.plugins.getWorkspaceLabelItems(this.createWorkspaceLabelContext(e))}createWorkspaceLabelContext(e){let t=kw(this.state),n=r=>{let i=Ad(r,e,t.id);return Lm({machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t),projects:md(_e,t.id),...i===void 0?{}:{peer:i},host:this.createWorkspaceHost()},n)};return n(Aw())}sessionLabelItems(e){let t=this.state.selectedWorkspace;if(t===void 0)return[];let n=kw(this.state),r=i=>{let a=Ad(i,t,n.id);return Rm({machine:n,workspace:t,session:Xt(e),state:this.state,files:this.createWorkspaceFiles(t,n),projects:md(_e,n.id),...a===void 0?{}:{peer:a},navigate:(e,t)=>this.navigate(e,t,n.id),host:this.createWorkspaceHost()},r)};return this.plugins.getSessionLabelItems(r(Aw()))}createWorkspaceFiles(e,t){return Dh(d,e,t.id,{defaultUploadFolder:Ve(e.effectiveConfig,this.workspaceUploadDefaultFolder),onInvalidate:n=>{this.invalidateWorkspaceResources(e,t,n)}})}createWorkspaceHost(){return{requestRender:()=>{this.invalidateWorkspaceSurface()}}}createApplicationPanelContext(){let e=kw(this.state),t=this.state.selectedWorkspace,n=r=>{let i=this.beginNavigationOperation(fw);return Fm({machine:e,state:this.state,projects:md(_e,e.id),...t===void 0?{}:{workspace:t},...t===void 0||!this.terminalAvailableForMachine(e.id)?{}:{terminal:this.workspaceTerminal(r,t,e.id,i)},navigate:(e,t)=>this.navigate(e,t),prompt:this.createPromptEditor(r,e.id),host:this.createWorkspaceHost()},n)};return n(`core`)}createWorkspacePanelContext(e,t=kw(this.state),n){let r=t.id,i=(a,o,s=[])=>{let c=this.beginNavigationOperation(fw),l=this.workspaceNavigationGeneration,u={...c,isCurrent:()=>c.isCurrent()&&l===this.workspaceNavigationGeneration},d=Ad(a,e,r);return Im({navigate:(n,r)=>this.workspacePanelContextIsCurrent(e,t,u)?this.navigate(n,r,t.id):Promise.resolve(),machine:t,workspace:e,state:this.state,files:this.createWorkspaceFiles(e,t),projects:md(_e,r),...d===void 0?{}:{peer:d},prompt:this.createPromptEditor(a.registrationPluginId,r),terminal:this.workspaceTerminal(a.registrationPluginId,e,r,u),...o===void 0?{}:{navigation:this.createWorkspacePanelNavigation(e,t,o,s,n,u)},openTerminal:t=>{this.workspaceTerminal(a.registrationPluginId,e,r,u).open(t)},piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(a.registrationPluginId,r)},host:this.createWorkspaceHost()},i)};return i(Aw())}invalidateWorkspacePanels(e,t){let n=this.state.selectedWorkspace;return n===void 0?Promise.resolve():this.plugins.invalidateWorkspacePanels(this.createWorkspacePanelContext(n,kw(this.state),t),e)}invalidateWorkspaceResources(e,t,n){return this.plugins.invalidateWorkspaceResources(this.createWorkspacePanelContext(e,t),n)}getActions(){return d_(this.getDefaultActions(),this.shortcutConfig)}getDefaultActions(){return[...this.plugins.getActions(this.createPluginRuntimeContext()),...this.normalAuthActions(),...this.workspaceSurfaceActions(),...this.sessionActions(),...this.navigationFocusActions(),...this.panelLayoutActions()]}normalAuthActions(){return this.apiScope===`management`?[]:[{id:`app.normal-auth.change-password`,title:D(`ui.piWebApp.changeNormalModePassword`,`Change normal-mode password`),description:D(`ui.piWebApp.changeTheLocalPasswordRequiredForNormalMode`,`Change the local password required for normal mode`),group:D(`client.actions.preferences.57907a`,`Preferences`),enabled:this.normalAuthStatus?.authenticated===!0,run:()=>{this.normalAuthDialogMode=`change`,this.normalAuthError=``}}]}sessionActions(){let e=this.canCleanupSessions();return[{id:`app.sessions.cleanup`,title:D(`ui.sessionCleanupDialog.cleanUpSessions`,`Clean up sessions`),description:D(`ui.piWebApp.previewAndManuallyCleanUpIdleOrArchived`,`Preview and manually clean up idle or archived sessions on the selected machine`),group:D(`ui.sessionSearchDialog.sessions`,`Sessions`),...e?{}:{enabled:!1,disabledReason:this.sessionCleanupUnavailableMessage()},run:()=>{this.openSessionCleanupDialog()}}]}panelLayoutActions(){return[{id:`app.layout.reset-navigation-panel-size`,title:D(`ui.piWebApp.resetNavigationPanelWidth`,`Reset navigation panel width`),description:D(`ui.piWebApp.restoreTheDefaultNavigationPanelWidth`,`Restore the default navigation panel width`),group:D(`ui.piWebApp.view`,`View`),run:()=>{this.resetResizablePanel(`navigation`)}},{id:`app.layout.reset-workspace-panel-size`,title:D(`ui.piWebApp.resetWorkspacePanelWidth`,`Reset workspace panel width`),description:D(`ui.piWebApp.restoreTheDefaultWorkspacePanelWidth`,`Restore the default workspace panel width`),group:D(`ui.piWebApp.view`,`View`),run:()=>{this.resetResizablePanel(`workspace`)}},{id:`app.layout.reset-panel-sizes`,title:D(`ui.piWebApp.resetPanelWidths`,`Reset panel widths`),description:D(`ui.piWebApp.restoreDefaultWidthsForAllSidePanels`,`Restore default widths for all side panels`),group:D(`ui.piWebApp.view`,`View`),run:()=>{this.resetResizablePanels()}}]}navigationFocusActions(){return[{id:`app.navigation.open`,title:D(`ui.main.99aaea15ca9e`,`Open Navigation`),description:D(`ui.main.bfb109bc500b`,`Find destinations and manage pinned tabs`),group:D(`client.actions.navigation.e72622`,`Navigation`),run:this.showNavigation},{id:`app.navigation.focus-machines`,title:D(`ui.piWebApp.focusMachines`,`Focus machines`),description:D(`ui.piWebApp.moveKeyboardFocusToTheMachineSelector`,`Move keyboard focus to the machine selector`),shortcut:`mod+g m`,group:D(`client.actions.navigation.e72622`,`Navigation`),run:()=>this.focusNavigationSection(`machines`)},{id:`app.navigation.focus-projects`,title:D(`ui.piWebApp.focusProjects`,`Focus projects`),description:D(`ui.piWebApp.moveKeyboardFocusToTheProjectList`,`Move keyboard focus to the project list`),shortcut:`mod+g p`,group:D(`client.actions.navigation.e72622`,`Navigation`),run:()=>this.focusNavigationSection(`projects`)},{id:`app.navigation.focus-workspaces`,title:D(`ui.piWebApp.focusWorkspaces`,`Focus workspaces`),description:D(`ui.piWebApp.moveKeyboardFocusToTheWorkspaceList`,`Move keyboard focus to the workspace list`),shortcut:`mod+g w`,group:D(`client.actions.navigation.e72622`,`Navigation`),run:()=>this.focusNavigationSection(`workspaces`)},{id:`app.navigation.focus-sessions`,title:D(`ui.piWebApp.focusSessions`,`Focus sessions`),description:D(`ui.piWebApp.moveKeyboardFocusToTheSessionList`,`Move keyboard focus to the session list`),shortcut:`mod+g s`,group:D(`client.actions.navigation.e72622`,`Navigation`),run:()=>this.focusNavigationSection(`sessions`)}]}ensureGatewayPluginsLoaded(){return this.pluginLoads.ensureGatewayLoaded().then(()=>void 0)}async loadPluginsForSelectedMachine(){await this.ensureGatewayPluginsLoaded();let e=this.state.selectedMachine;e?.kind===`remote`&&await this.loadPluginsForMachine(e)}async loadPluginsForMachine(e){let t=window.location.href;await this.ensureGatewayPluginsLoaded();let n=this.state.machineRuntimes[e.id];if(e.kind===`remote`&&n?.ok===!0&&!ht(n,Ut.pluginLifecycle)){let n=D(`ui.main.d5354f9f3542`,`PI WEB plugins from {arg0} require a compatible plugin lifecycle capability; update and restart PI WEB on that machine`,{arg0:e.name});console.warn(n),this.verifiedPluginModeByMachine.delete(e.id),this.clearRequiredTerminal(e.id),this.reconcilePluginLoadSelection(t),this.setRequiredPluginFailure(e.id,n)}else await this.pluginLoads.loadForMachine(e)}async registerExternalPlugins(e,t,n=`local`){let r=window.location.href;try{await this.builtInPluginsReady;let e=await t();if(this.apiScope===`management`){let t=e=>(e.sourcePluginId??e.id)!==Kt,r=e.declarations.filter(t),i=await this.plugins.registerBatch(e.registrations.filter(t),{declarations:r,failures:Gw(e,r)});this.pluginLoadErrors.delete(n),i.failures.length>0&&this.pluginLoadErrors.set(n,i.failures.map(e=>Jw(e.error)).join(`
|
|
3672
3672
|
`));for(let e of i.failures)console.warn(`Failed to register PI WEB plugin ${e.declaration.id} (${e.phase})`,e.error);return this.applyPreferredTheme(!1),this.invalidateWorkspaceSurface(),i.failures.length===0}e.terminalMode===`recovery-disabled`&&(this.clearRequiredTerminal(n),this.verifiedPluginModeByMachine.set(n,`recovery-disabled`),this.clearRequiredPluginFailure(n));let i=e.failures.map(e=>Jw(e.error));this.pluginLoadErrors.delete(n),i.length>0&&this.pluginLoadErrors.set(n,i.join(`
|
|
3673
3673
|
`));let a=e.failures.length===0;for(let t of e.failures)console.warn(`Failed to load PI WEB plugin ${t.entry.id} (${t.entry.module})`,t.error);let o=e.declarations,s=Gw(e,o),c=e.terminalMode===`required`?e.failures.find(({entry:e})=>e.id===Kt):void 0;if(c!==void 0)return this.verifiedPluginModeByMachine.delete(n),this.clearRequiredTerminal(n),this.reconcilePluginLoadSelection(r),this.applyPreferredTheme(!1),this.setRequiredPluginFailure(n,D(`ui.main.734a3e4d0393`,`The required terminal plugin failed to load: {arg0}. Open settings for recovery guidance.`,{arg0:Jw(c.error)})),this.requestUpdate(),!1;let l=n===`local`?Kt:Yt(n,Kt);if(e.terminalMode===`required`){let t=`validate`;try{let r=e.registrations.find(({id:e})=>e===l);if(this.plugins.hasPlugin(l)){let e=this.knownRequiredTerminalByMachine.get(n);if(e===void 0)throw Error(`Required Terminal browser capability was not retained after activation`);if(r!==void 0){let t=qw(r,n);if(!Kw(e.binding,t))throw Error(`Required Terminal revision changed after browser activation; reload PI WEB to activate the new paired revision`)}this.requiredTerminalByMachine.set(n,e)}else{if(r===void 0)throw Error(`Required Terminal browser registration is unavailable`);let e=qw(r,n),i=o.find(({id:e})=>e===l);if(i===void 0)throw Error(`Required Terminal browser declaration is unavailable`);let a=(await this.plugins.registerBatch([r],{declarations:[i],failures:s.filter(({declaration:e})=>e.id===l),requiredCapabilities:[{registrationPluginId:l,capability:Xh}]})).failures.find(({declaration:e})=>e.id===l);if(a!==void 0)throw t=a.phase,a.error;let c=this.plugins.resolveCapability(l,Xh),u=Object.freeze({binding:e,facade:c});this.knownRequiredTerminalByMachine.set(n,u),this.requiredTerminalByMachine.set(n,u)}}catch(e){a=!1,console.warn(`Failed to register PI WEB plugin ${l} during ${t}`,e),this.verifiedPluginModeByMachine.delete(n),this.clearRequiredTerminal(n),this.setRequiredPluginFailure(n,D(`ui.main.5abfc40d98a4`,`The required terminal plugin failed during browser {arg0}: {arg1}. Open settings for recovery guidance.`,{arg0:t,arg1:Jw(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(Jw(e.error)),this.pluginLoadErrors.set(n,i.join(`
|
|
3674
|
-
`)),console.warn(`Failed to register PI WEB plugin ${e.declaration.id} during ${e.phase}`,e.error))}return e.terminalMode===`required`&&(!this.plugins.hasPlugin(l)||!this.terminalAvailableForMachine(n))?(a=!1,this.verifiedPluginModeByMachine.delete(n),this.clearRequiredTerminal(n),this.requiredPluginFailureByMachine.has(n)||this.setRequiredPluginFailure(n,D(`ui.main.97f88bf8726e`,`Required Terminal plugin is unavailable after plugin activation. Open Settings for recovery guidance.`))):e.terminalMode===`required`&&(this.verifiedPluginModeByMachine.set(n,`required`),this.clearRequiredPluginFailure(n)),this.reconcilePluginLoadSelection(r),this.applyPreferredTheme(!1),this.invalidateWorkspaceSurface(),a}catch(t){return console.warn(`Failed to load ${e}`,t),this.pluginLoadErrors.set(n,Jw(t)),this.verifiedPluginModeByMachine.delete(n),this.clearRequiredTerminal(n),this.reconcilePluginLoadSelection(r),this.applyPreferredTheme(!1),this.setRequiredPluginFailure(n,D(`ui.main.d05cfde8b518`,`Failed to load {arg0}: {arg1}`,{arg0:e,arg1:Jw(t)})),this.invalidateWorkspaceSurface(),!1}}reconcilePluginLoadSelection(e){xw()===e&&this.reconcileWorkspacePanelSelection()}setRequiredPluginFailure(e,t){this.requiredPluginFailureByMachine.set(e,t),this.dismissedRequiredPluginFailureByMachine.delete(e),M(this.state)===e&&this.requestUpdate()}clearRequiredPluginFailure(e){this.requiredPluginFailureByMachine.delete(e)&&(this.dismissedRequiredPluginFailureByMachine.delete(e),M(this.state)===e&&this.requestUpdate())}displayedError(){if(this.state.error!==``)return this.state.error;let e=M(this.state),t=this.requiredPluginFailureByMachine.get(e);return t!==void 0&&this.dismissedRequiredPluginFailureByMachine.get(e)!==t?t:``}dismissDisplayedError(){if(this.state.error!==``){this.setState({error:``});return}let e=M(this.state),t=this.requiredPluginFailureByMachine.get(e);t!==void 0&&(this.dismissedRequiredPluginFailureByMachine.set(e,t),this.requestUpdate())}clearRequiredTerminal(e){this.requiredTerminalByMachine.delete(e),this.invalidateWorkspaceSurface(),this.pluginLoads.invalidateMachine(e),M(this.state)===e&&(this.cancelWorkspaceDeletionRefresh(),this.setState({workspaceDeletionRuns:{}}))}terminalAvailableForMachine(e){return this.requiredTerminalByMachine.has(e)}pluginContributionAvailable(e,t){if(e===`core`||e===`themes`||this.apiScope===`management`)return!0;if(t!==void 0&&t!==M(this.state))return!1;let n=t??`local`,r=this.verifiedPluginModeByMachine.get(n);return e===(n===`local`?`pi-web.terminal`:Yt(n,`pi-web.terminal`))?r===`required`&&this.terminalAvailableForMachine(n):r===`recovery-disabled`||r===`required`&&this.terminalAvailableForMachine(n)}createPromptEditor(e=`core`,t=M(this.state)){let n=this.state.selectedSession,r=n!==void 0&&n.archived!==!0&&!Ca(n.id)&&t===M(this.state)?{machineId:t,sessionId:n.id,cwd:n.cwd}:void 0;return{...this.plugins.promptChipMethods(e,r),insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){let e=t=>Pm({state:this.state,projects:md(_e,M(this.state)),prompt:this.createPromptEditor(t),piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:e=>{this.openSettings(e)},openMcpAuth:e=>this.auth.openMcpAuth(e)},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.openChatAndFocusComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},openModelPicker:()=>this.openModelDialog(),openThinkingLevelPicker:()=>this.openThinkingDialog(),selectMainView:e=>{this.selectMainView(e)},navigate:(e,t)=>this.navigate(e,t),selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.invalidateSelectedWorkspaceFiles(),refreshGit:()=>this.invalidateWorkspacePanels(),refreshWorkspacePanels:e=>this.invalidateWorkspacePanels(e),refreshAppData:()=>this.refreshAppData(),checkForPiWebUpdates:()=>this.piWebStatusController.checkForUpdates(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:e=>this.deleteWorkspace(e),startSession:()=>this.withChatScrollTransition(()=>this.startSessionAndOpenChat()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;let t=M(this.state),n=Gn(t,e.projectId,e.id);if(!zu(e)){this.browserErrors.report(n,D(`ui.main.669305830b1b`,`Workspace removal is not available`));return}if(Wu(this.state,e))return;let r=e.removal,i=Bu(e);if(r===void 0||i===void 0||!confirm(i))return;let a=this.beginNavigationOperation(uw);try{let n=await d.deleteWorkspace(e.projectId,e.id,r.precondition,t),i=this.apiScope===`management`?h(n):this.requiredTerminalComposition(t).facade.parseCommandRun(n);if(M(this.state)!==t||!this.recordWorkspaceDeletionRun(i,t))return;let o=await this.workspaceForCommandRun(i,t);if(M(this.state)!==t||!a.isCurrent())return;o!==void 0&&this.workspaceTerminal(`core`,o,t).open({terminalId:i.terminalId})}catch(r){await this.reportWorkspaceRemovalFailure(e,t,n,r)}}async reportWorkspaceRemovalFailure(e,t,n,r){let i=Jw(r);if(this.apiScope===`management`||!(r instanceof te)||i.startsWith(`Session daemon unavailable:`)){this.browserErrors.report(n,D(`ui.piWebApp.failedToStartWorkspaceDeletion`,`Failed to start workspace deletion: {errorMessageerror}`,{errorMessageerror:i}));return}let a=D(`ui.main.f658c452e075`,`Workspace removal failed: {arg0}`,{arg0:i}),o=()=>this.serverNotices.hasNotice(t,t=>{let n=t.context??{};return t.source===`workspace.delete`&&t.message===a&&t.scope?.projectId===e.projectId&&n.targetWorkspaceId===e.id});o()||await this.serverNotices.refresh(t),o()||this.browserErrors.report(n,D(`ui.piWebApp.failedToStartWorkspaceDeletion`,`Failed to start workspace deletion: {errorMessageerror}`,{errorMessageerror:i}))}async workspaceForCommandRun(e,t){let n=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];if((n===void 0||n.length===0)&&(n=await this.workspaces.refreshProjectWorkspaces(e.projectId,t)),M(this.state)===t&&this.state.selectedProject?.id===e.projectId)return n.find(t=>t.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(M(this.state)!==t||this.state.selectedProject?.id!==e.projectId)return!1;let n=Gu(e);return n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling(),!0)}async refreshWorkspaceDeletionRuns(){let e=M(this.state),t=this.state.selectedProject,n=Uw(this.state);if(t===void 0||n===void 0||this.apiScope===`normal`&&!this.terminalAvailableForMachine(e)){this.cancelWorkspaceDeletionRefresh(),this.setState({workspaceDeletionRuns:{}});return}if(this.workspaceDeletionRefreshAbort!==void 0){if(this.workspaceDeletionRefreshScope===n){this.workspaceDeletionRefreshQueued=!0;return}this.cancelWorkspaceDeletionRefresh()}let r=new AbortController,i=++this.workspaceDeletionRefreshGeneration;this.workspaceDeletionRefreshAbort=r,this.workspaceDeletionRefreshScope=n;try{let n=Object.values(this.state.workspaceDeletionRuns).filter(e=>e.projectId===t.id);for(let a of n)Ku(a)||await this.handleCompletedWorkspaceDeletionRun(a,e,t.id,i,r);if(!this.workspaceDeletionRefreshIsCurrent(e,t.id,i,r))return;let a=Object.values(this.state.workspaceDeletionRuns).filter(e=>e.projectId===t.id&&Ku(e));if(n.length>0&&a.length===0)return;let o=Vu(),s=a.length===0?this.state.workspaces.filter(e=>e.projectId===t.id):[...new Map(a.map(e=>[e.workspaceId,{id:e.workspaceId,projectId:e.projectId}])).values()],c=this.apiScope===`management`?void 0:this.requiredTerminalByMachine.get(e),l=this.state.workspaceDeletionRuns,u=await Promise.allSettled(s.map(async n=>{if(this.apiScope===`management`)return Dt.listCommandRuns({...o,projectId:t.id,workspaceId:n.id},e,{signal:r.signal});let i=c===void 0?void 0:Ad(c.binding,n,e);if(i===void 0||c===void 0)throw $h(e);return c.facade.listCommandRuns({peer:i,filter:{metadata:o.metadata},signal:r.signal})}));if(!this.workspaceDeletionRefreshIsCurrent(e,t.id,i,r))return;let d=u.filter(e=>e.status===`rejected`),f=u.filter(e=>e.status===`fulfilled`);if(f.length===0&&d.length>0)throw d[0]?.reason;for(let e of d)console.warn(`Failed to query workspace deletion runs for one workspace`,e.reason);let p=new Set(u.flatMap((e,t)=>{let n=e.status===`rejected`?s[t]:void 0;return n===void 0?[]:[n.id]})),m=Object.entries(this.state.workspaceDeletionRuns).filter(([e,n])=>n.projectId===t.id&&(n!==l[e]||Ku(n)&&p.has(n.workspaceId))).map(([,e])=>e),h=Hu([...f.flatMap(e=>e.value),...m].filter(t=>!this.handledWorkspaceDeletionRunIds.has(Hw(e,t.id))));this.setState({workspaceDeletionRuns:h});for(let n of Object.values(h))Ku(n)||await this.handleCompletedWorkspaceDeletionRun(n,e,t.id,i,r)}catch(n){!r.signal.aborted&&this.workspaceDeletionRefreshIsCurrent(e,t.id,i,r)&&console.warn(`Failed to refresh workspace deletion runs`,n)}finally{if(this.workspaceDeletionRefreshAbort===r){this.workspaceDeletionRefreshAbort=void 0,this.workspaceDeletionRefreshScope=void 0;let e=this.workspaceDeletionRefreshQueued;this.workspaceDeletionRefreshQueued=!1,e&&Uw(this.state)===n?(this.workspaceDeletionPollTimer!==void 0&&window.clearTimeout(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,queueMicrotask(()=>{i===this.workspaceDeletionRefreshGeneration&&Uw(this.state)===n&&this.refreshWorkspaceDeletionRuns()})):this.updateWorkspaceDeletionPolling()}}}workspaceDeletionRefreshIsCurrent(e,t,n,r){return this.workspaceDeletionRefreshAbort===r&&!r.signal.aborted&&n===this.workspaceDeletionRefreshGeneration&&M(this.state)===e&&this.state.selectedProject?.id===t}cancelWorkspaceDeletionRefresh(){this.workspaceDeletionRefreshGeneration+=1,this.workspaceDeletionRefreshAbort?.abort(new DOMException(`Workspace deletion scope changed`,`AbortError`)),this.workspaceDeletionRefreshAbort=void 0,this.workspaceDeletionRefreshScope=void 0,this.workspaceDeletionRefreshQueued=!1,this.workspaceDeletionReconcileRetries.clear(),this.workspaceDeletionPollTimer!==void 0&&window.clearTimeout(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0}updateWorkspaceDeletionPolling(){let e=M(this.state),t=Date.now(),n=1/0;for(let r of Object.values(this.state.workspaceDeletionRuns)){let i=Hw(e,r.id);if(this.handledWorkspaceDeletionRunIds.has(i))continue;if(Ku(r)){n=Math.min(n,1e3);continue}let a=this.workspaceDeletionReconcileRetries.get(i)?.retryAt??t;n=Math.min(n,Math.max(0,a-t))}Number.isFinite(n)&&this.workspaceDeletionPollTimer===void 0?this.workspaceDeletionPollTimer=window.setTimeout(()=>{this.workspaceDeletionPollTimer=void 0,this.refreshWorkspaceDeletionRuns()},n):!Number.isFinite(n)&&this.workspaceDeletionPollTimer!==void 0&&(window.clearTimeout(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t,n,r,i){if(!this.workspaceDeletionRefreshIsCurrent(t,n,r,i))return;let a=Hw(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(a))return;let o=Gu(e);if(o!==void 0){if(e.status===`succeeded`){let s=this.workspaceDeletionReconcileRetries.get(a);if(s!==void 0&&s.retryAt>Date.now())return;let c=Gn(t,e.projectId,o);try{await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,o,t,{signal:i.signal,isCurrent:()=>this.workspaceDeletionRefreshIsCurrent(t,n,r,i)})}catch(e){if(!this.workspaceDeletionRefreshIsCurrent(t,n,r,i))return;let o=(s?.attempt??0)+1,l=pw[Math.min(o-1,pw.length-1)]??1e4;this.workspaceDeletionReconcileRetries.set(a,{attempt:o,retryAt:Date.now()+l}),this.browserErrors.report(c,D(`ui.main.2a2bb7043324`,`Workspace removed, but refreshing the workspace list failed: {arg0}. Retrying...`,{arg0:Jw(e)}));return}if(!this.workspaceDeletionRefreshIsCurrent(t,n,r,i))return;this.workspaceDeletionReconcileRetries.delete(a),this.handledWorkspaceDeletionRunIds.add(a),this.browserErrors.discard(c),this.setState({workspaceDeletionRuns:Yw(this.state.workspaceDeletionRuns,o)})}else e.status===`failed`&&(this.workspaceDeletionReconcileRetries.delete(a),this.handledWorkspaceDeletionRunIds.add(a))}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(D(`ui.piWebApp.removeThisOnlyRemovesItFromTheCurrent`,`Remove {name}?
|
|
3674
|
+
`)),console.warn(`Failed to register PI WEB plugin ${e.declaration.id} during ${e.phase}`,e.error))}return e.terminalMode===`required`&&(!this.plugins.hasPlugin(l)||!this.terminalAvailableForMachine(n))?(a=!1,this.verifiedPluginModeByMachine.delete(n),this.clearRequiredTerminal(n),this.requiredPluginFailureByMachine.has(n)||this.setRequiredPluginFailure(n,D(`ui.main.97f88bf8726e`,`Required Terminal plugin is unavailable after plugin activation. Open Settings for recovery guidance.`))):e.terminalMode===`required`&&(this.verifiedPluginModeByMachine.set(n,`required`),this.clearRequiredPluginFailure(n)),this.reconcilePluginLoadSelection(r),this.applyPreferredTheme(!1),this.invalidateWorkspaceSurface(),a}catch(t){return console.warn(`Failed to load ${e}`,t),this.pluginLoadErrors.set(n,Jw(t)),this.verifiedPluginModeByMachine.delete(n),this.clearRequiredTerminal(n),this.reconcilePluginLoadSelection(r),this.applyPreferredTheme(!1),this.setRequiredPluginFailure(n,D(`ui.main.d05cfde8b518`,`Failed to load {arg0}: {arg1}`,{arg0:e,arg1:Jw(t)})),this.invalidateWorkspaceSurface(),!1}}reconcilePluginLoadSelection(e){xw()===e&&this.reconcileWorkspacePanelSelection()}setRequiredPluginFailure(e,t){this.requiredPluginFailureByMachine.set(e,t),this.dismissedRequiredPluginFailureByMachine.delete(e),M(this.state)===e&&this.requestUpdate()}clearRequiredPluginFailure(e){this.requiredPluginFailureByMachine.delete(e)&&(this.dismissedRequiredPluginFailureByMachine.delete(e),M(this.state)===e&&this.requestUpdate())}displayedError(){if(this.state.error!==``)return this.state.error;let e=M(this.state),t=this.requiredPluginFailureByMachine.get(e);return t!==void 0&&this.dismissedRequiredPluginFailureByMachine.get(e)!==t?t:``}dismissDisplayedError(){if(this.state.error!==``){this.setState({error:``});return}let e=M(this.state),t=this.requiredPluginFailureByMachine.get(e);t!==void 0&&(this.dismissedRequiredPluginFailureByMachine.set(e,t),this.requestUpdate())}clearRequiredTerminal(e){this.requiredTerminalByMachine.delete(e),this.invalidateWorkspaceSurface(),this.pluginLoads.invalidateMachine(e),M(this.state)===e&&(this.cancelWorkspaceDeletionRefresh(),this.setState({workspaceDeletionRuns:{}}))}terminalAvailableForMachine(e){return this.requiredTerminalByMachine.has(e)}pluginContributionAvailable(e,t){if(e===`core`||e===`themes`||this.apiScope===`management`)return!0;if(t!==void 0&&t!==M(this.state))return!1;let n=t??`local`,r=this.verifiedPluginModeByMachine.get(n);return e===(n===`local`?`pi-web.terminal`:Yt(n,`pi-web.terminal`))?r===`required`&&this.terminalAvailableForMachine(n):r===`recovery-disabled`||r===`required`&&this.terminalAvailableForMachine(n)}createPromptEditor(e=`core`,t=M(this.state)){let n=this.state.selectedSession,r=n!==void 0&&n.archived!==!0&&!Ca(n.id)&&t===M(this.state)?{machineId:t,sessionId:n.id,cwd:n.cwd}:void 0;return{...this.plugins.promptChipMethods(e,r),insertText:e=>{let t=this.promptEditor?.view;if(!t)return;t.hasFocus||t.focus();let n=t.state.selection.main;t.dispatch({changes:{from:n.from,to:n.to,insert:e},selection:{anchor:n.from+e.length}})},getText:()=>this.promptEditor?.view?.state.doc.toString()??``,getSelection:()=>{let e=this.promptEditor?.view;if(!e)return null;let t=e.state.selection.main;return t.empty?null:{start:t.from,end:t.to,text:e.state.sliceDoc(t.from,t.to)}}}}createPluginRuntimeContext(){let e=t=>Pm({state:this.state,projects:md(_e,M(this.state)),prompt:this.createPromptEditor(t),piWebUnstable:{terminalCommandRuns:this.terminalCommandRunsForOrigin(t),openSettings:e=>{this.openSettings(e)},openMcpAuth:e=>this.auth.openMcpAuth(e)},openActionPalette:()=>{this.setState({actionPaletteOpen:!0})},focusPrompt:()=>{this.openChatAndFocusComposer()},addProject:()=>{this.setState({projectDialogOpen:!0})},addMachine:()=>{this.openMachineDialog()},refreshSelectedMachine:async()=>{await Promise.all([this.machines.refreshMachineHealth(),this.machines.refreshMachineRuntime()])},removeSelectedMachine:()=>this.removeMachine(),openSelectedMachine:()=>{this.openSelectedMachine()},configureAuth:()=>this.auth.openLogin(),logoutAuth:()=>this.auth.openLogout(),openThemePicker:()=>{this.openThemeDialog()},openModelPicker:()=>this.openModelDialog(),openThinkingLevelPicker:()=>this.openThinkingDialog(),selectMainView:e=>{this.selectMainView(e)},navigate:(e,t)=>this.navigate(e,t),selectWorkspaceTool:e=>{this.openWorkspaceTool(e)},openTerminal:e=>{this.openTerminal(e)},refreshFiles:()=>this.invalidateSelectedWorkspaceFiles(),refreshGit:()=>this.invalidateWorkspacePanels(),refreshWorkspacePanels:e=>this.invalidateWorkspacePanels(e),refreshAppData:()=>this.refreshAppData(),checkForPiWebUpdates:()=>this.piWebStatusController.checkForUpdates(),reloadPage:()=>{this.hardReloadApp()},deleteWorkspace:e=>this.deleteWorkspace(e),startSession:()=>this.withChatScrollTransition(()=>this.startSessionAndOpenChat()),archiveSession:()=>this.sessions.archiveSession(),reloadSession:()=>this.sessions.reloadSession(),deleteCachedNewSession:()=>this.sessions.deleteCachedNewSession(),stopActiveWork:()=>this.sessions.stopActiveWork()},e);return e(`core`)}async deleteWorkspace(e=this.state.selectedWorkspace){if(e===void 0)return;let t=M(this.state),n=Gn(t,e.projectId,e.id);if(!zu(e)){this.browserErrors.report(n,D(`ui.main.669305830b1b`,`Workspace removal is not available`));return}if(Wu(this.state,e))return;let r=e.removal,i=Bu(e);if(r===void 0||i===void 0||!confirm(i))return;let a=this.beginNavigationOperation(uw);try{let n=await d.deleteWorkspace(e.projectId,e.id,r.precondition,t),i=this.apiScope===`management`?h(n):this.requiredTerminalComposition(t).facade.parseCommandRun(n);if(M(this.state)!==t||!this.recordWorkspaceDeletionRun(i,t))return;let o=await this.workspaceForCommandRun(i,t);if(M(this.state)!==t||!a.isCurrent())return;o!==void 0&&this.workspaceTerminal(`core`,o,t).open({terminalId:i.terminalId})}catch(r){await this.reportWorkspaceRemovalFailure(e,t,n,r)}}async reportWorkspaceRemovalFailure(e,t,n,r){let i=Jw(r);if(this.apiScope===`management`||!(r instanceof te)||i.startsWith(`Session daemon unavailable:`)){this.browserErrors.report(n,D(`ui.piWebApp.failedToStartWorkspaceDeletion`,`Failed to start workspace deletion: {errorMessageerror}`,{errorMessageerror:i}));return}let a=D(`ui.main.f658c452e075`,`Workspace removal failed: {arg0}`,{arg0:i}),o=()=>this.serverNotices.hasNotice(t,t=>{let n=t.context??{};return t.source===`workspace.delete`&&t.message===a&&t.scope?.projectId===e.projectId&&n.targetWorkspaceId===e.id});o()||await this.serverNotices.refresh(t),o()||this.browserErrors.report(n,D(`ui.piWebApp.failedToStartWorkspaceDeletion`,`Failed to start workspace deletion: {errorMessageerror}`,{errorMessageerror:i}))}async workspaceForCommandRun(e,t){let n=this.state.selectedProject?.id===e.projectId?this.state.workspaces:this.state.workspacesByProjectId[e.projectId];if((n===void 0||n.length===0)&&(n=await this.workspaces.refreshProjectWorkspaces(e.projectId,t)),M(this.state)===t&&this.state.selectedProject?.id===e.projectId)return n.find(t=>t.id===e.workspaceId)}recordWorkspaceDeletionRun(e,t){if(M(this.state)!==t||this.state.selectedProject?.id!==e.projectId)return!1;let n=Gu(e);return n!==void 0&&(this.setState({workspaceDeletionRuns:{...this.state.workspaceDeletionRuns,[n]:e}}),this.updateWorkspaceDeletionPolling(),!0)}async refreshWorkspaceDeletionRuns(){let e=M(this.state),t=this.state.selectedProject,n=Uw(this.state);if(t===void 0||n===void 0||this.apiScope===`normal`&&!this.terminalAvailableForMachine(e)||this.apiScope===`management`&&!this.state.workspaces.some(e=>e.projectId===t.id&&zu(e))&&!Object.values(this.state.workspaceDeletionRuns).some(e=>e.projectId===t.id)){this.cancelWorkspaceDeletionRefresh(),this.setState({workspaceDeletionRuns:{}});return}if(this.workspaceDeletionRefreshAbort!==void 0){if(this.workspaceDeletionRefreshScope===n){this.workspaceDeletionRefreshQueued=!0;return}this.cancelWorkspaceDeletionRefresh()}let r=new AbortController,i=++this.workspaceDeletionRefreshGeneration;this.workspaceDeletionRefreshAbort=r,this.workspaceDeletionRefreshScope=n;try{let n=Object.values(this.state.workspaceDeletionRuns).filter(e=>e.projectId===t.id);for(let a of n)Ku(a)||await this.handleCompletedWorkspaceDeletionRun(a,e,t.id,i,r);if(!this.workspaceDeletionRefreshIsCurrent(e,t.id,i,r))return;let a=Object.values(this.state.workspaceDeletionRuns).filter(e=>e.projectId===t.id&&Ku(e));if(n.length>0&&a.length===0)return;let o=Vu(),s=a.length===0?this.state.workspaces.filter(e=>e.projectId===t.id):[...new Map(a.map(e=>[e.workspaceId,{id:e.workspaceId,projectId:e.projectId}])).values()],c=this.apiScope===`management`?void 0:this.requiredTerminalByMachine.get(e),l=this.state.workspaceDeletionRuns,u=await Promise.allSettled(s.map(async n=>{if(this.apiScope===`management`)return Dt.listCommandRuns({...o,projectId:t.id,workspaceId:n.id},e,{signal:r.signal});let i=c===void 0?void 0:Ad(c.binding,n,e);if(i===void 0||c===void 0)throw $h(e);return c.facade.listCommandRuns({peer:i,filter:{metadata:o.metadata},signal:r.signal})}));if(!this.workspaceDeletionRefreshIsCurrent(e,t.id,i,r))return;let d=u.filter(e=>e.status===`rejected`),f=u.filter(e=>e.status===`fulfilled`);if(f.length===0&&d.length>0)throw d[0]?.reason;for(let e of d)console.warn(`Failed to query workspace deletion runs for one workspace`,e.reason);let p=new Set(u.flatMap((e,t)=>{let n=e.status===`rejected`?s[t]:void 0;return n===void 0?[]:[n.id]})),m=Object.entries(this.state.workspaceDeletionRuns).filter(([e,n])=>n.projectId===t.id&&(n!==l[e]||Ku(n)&&p.has(n.workspaceId))).map(([,e])=>e),h=Hu([...f.flatMap(e=>e.value),...m].filter(t=>!this.handledWorkspaceDeletionRunIds.has(Hw(e,t.id))));this.setState({workspaceDeletionRuns:h});for(let n of Object.values(h))Ku(n)||await this.handleCompletedWorkspaceDeletionRun(n,e,t.id,i,r)}catch(n){!r.signal.aborted&&this.workspaceDeletionRefreshIsCurrent(e,t.id,i,r)&&console.warn(`Failed to refresh workspace deletion runs`,n)}finally{if(this.workspaceDeletionRefreshAbort===r){this.workspaceDeletionRefreshAbort=void 0,this.workspaceDeletionRefreshScope=void 0;let e=this.workspaceDeletionRefreshQueued;this.workspaceDeletionRefreshQueued=!1,e&&Uw(this.state)===n?(this.workspaceDeletionPollTimer!==void 0&&window.clearTimeout(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0,queueMicrotask(()=>{i===this.workspaceDeletionRefreshGeneration&&Uw(this.state)===n&&this.refreshWorkspaceDeletionRuns()})):this.updateWorkspaceDeletionPolling()}}}workspaceDeletionRefreshIsCurrent(e,t,n,r){return this.workspaceDeletionRefreshAbort===r&&!r.signal.aborted&&n===this.workspaceDeletionRefreshGeneration&&M(this.state)===e&&this.state.selectedProject?.id===t}cancelWorkspaceDeletionRefresh(){this.workspaceDeletionRefreshGeneration+=1,this.workspaceDeletionRefreshAbort?.abort(new DOMException(`Workspace deletion scope changed`,`AbortError`)),this.workspaceDeletionRefreshAbort=void 0,this.workspaceDeletionRefreshScope=void 0,this.workspaceDeletionRefreshQueued=!1,this.workspaceDeletionReconcileRetries.clear(),this.workspaceDeletionPollTimer!==void 0&&window.clearTimeout(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0}updateWorkspaceDeletionPolling(){let e=M(this.state),t=Date.now(),n=1/0;for(let r of Object.values(this.state.workspaceDeletionRuns)){let i=Hw(e,r.id);if(this.handledWorkspaceDeletionRunIds.has(i))continue;if(Ku(r)){n=Math.min(n,1e3);continue}let a=this.workspaceDeletionReconcileRetries.get(i)?.retryAt??t;n=Math.min(n,Math.max(0,a-t))}Number.isFinite(n)&&this.workspaceDeletionPollTimer===void 0?this.workspaceDeletionPollTimer=window.setTimeout(()=>{this.workspaceDeletionPollTimer=void 0,this.refreshWorkspaceDeletionRuns()},n):!Number.isFinite(n)&&this.workspaceDeletionPollTimer!==void 0&&(window.clearTimeout(this.workspaceDeletionPollTimer),this.workspaceDeletionPollTimer=void 0)}async handleCompletedWorkspaceDeletionRun(e,t,n,r,i){if(!this.workspaceDeletionRefreshIsCurrent(t,n,r,i))return;let a=Hw(t,e.id);if(this.handledWorkspaceDeletionRunIds.has(a))return;let o=Gu(e);if(o!==void 0){if(e.status===`succeeded`){let s=this.workspaceDeletionReconcileRetries.get(a);if(s!==void 0&&s.retryAt>Date.now())return;let c=Gn(t,e.projectId,o);try{await this.workspaces.refreshAfterWorkspaceDeleted(e.projectId,o,t,{signal:i.signal,isCurrent:()=>this.workspaceDeletionRefreshIsCurrent(t,n,r,i)})}catch(e){if(!this.workspaceDeletionRefreshIsCurrent(t,n,r,i))return;let o=(s?.attempt??0)+1,l=pw[Math.min(o-1,pw.length-1)]??1e4;this.workspaceDeletionReconcileRetries.set(a,{attempt:o,retryAt:Date.now()+l}),this.browserErrors.report(c,D(`ui.main.2a2bb7043324`,`Workspace removed, but refreshing the workspace list failed: {arg0}. Retrying...`,{arg0:Jw(e)}));return}if(!this.workspaceDeletionRefreshIsCurrent(t,n,r,i))return;this.workspaceDeletionReconcileRetries.delete(a),this.handledWorkspaceDeletionRunIds.add(a),this.browserErrors.discard(c),this.setState({workspaceDeletionRuns:Yw(this.state.workspaceDeletionRuns,o)})}else e.status===`failed`&&(this.workspaceDeletionReconcileRetries.delete(a),this.handledWorkspaceDeletionRunIds.add(a))}}openMachineDialog(){this.setState({machineDialogOpen:!0,error:``})}async submitMachineDialog(e){await this.machines.addMachine(e)!==void 0&&(this.setState({machineDialogOpen:!1}),this.schedulePiWebStatusRefresh())}async removeMachine(e=this.state.selectedMachine){if(e===void 0||e.kind===`local`||!window.confirm(D(`ui.piWebApp.removeThisOnlyRemovesItFromTheCurrent`,`Remove {name}?
|
|
3675
3675
|
|
|
3676
3676
|
This only removes it from the current PI WEB gateway.`,{name:e.name})))return;let t=this.state.selectedMachine?.id===e.id;t&&this.rememberCurrentMachineNavigation();let n=await this.machines.deleteMachine(e,{selectFallback:!t});if(this.state.machines.some(t=>t.id===e.id)||this.machineNavigation.forget(e.id),this.state.selectedMachine?.id===e.id&&n!==void 0){let e=yw(this.state);await this.selectMachineWithMemory(n,{rememberCurrent:!1,expected:e})}}openSelectedMachine(){let e=this.state.selectedMachine;e?.kind===`remote`&&e.baseUrl!==void 0&&window.open(e.baseUrl,`_blank`,`noopener,noreferrer`)}runAction(e){Promise.resolve().then(()=>e.run()).catch(t=>{let n=t instanceof Error?t.message:String(t);console.warn(`Action failed: ${e.id}`,t),this.browserErrors.report({kind:`global`},D(`ui.piWebApp.operationFailed`,`Operation failed: {message}`,{message:n}))})}async openModelDialog(){let e=this.state.selectedSession;if(e===void 0)return;let t={machineId:M(this.state),sessionId:e.id,cwd:e.cwd},{models:n,catalog:r}=await this.loadModelDialogData();if(!this.modelDialogOriginIsCurrent(t))return;let i=this.currentModelValue();this.setState({modelDialog:{instanceId:++this.modelDialogInstanceId,origin:t,title:D(`client.actions.choose.model.1afed6`,`Choose model`),...i===void 0?{}:{selectedValue:i},options:this.modelDialogOptions(n),...r===void 0?{}:{catalog:r},defaultsLoading:!0}}),this.loadSessionDefaultPins(t,`model`)}async loadModelDialogData(){for(;;){let e=this.modelDialogScopeInvalidation,[t,n]=await Promise.all([this.sessions.listModels(),this.apiScope===`normal`?this.sessions.listModelCatalog():Promise.resolve(void 0)]);if(e===this.modelDialogScopeInvalidation)return{models:t,...n===void 0?{}:{catalog:n}}}}async refreshOpenModelDialog(){if(this.modelDialogMutationInFlight>0){this.modelDialogRefreshPending=!0;return}let e=this.currentModelDialog();if(e===void 0)return;let{origin:t,instanceId:n}=e,{models:r,catalog:i}=await this.loadModelDialogData();if(this.modelDialogMutationInFlight>0||this.state.modelDialog?.instanceId!==n||!this.modelDialogOriginIsCurrent(t))return;let a={...e,options:this.modelDialogOptions(r),...i===void 0?{}:{catalog:i}},o=this.currentModelValue();o===void 0?delete a.selectedValue:a.selectedValue=o,this.setState({modelDialog:a})}currentModelValue(){return Dw(this.state.status)}modelDialogOptions(e){let t=this.currentModelValue();return e.map(e=>{let n=e.provider??``,r=e.id??``,i=`${n}/${r}`;return{value:i,label:`${r}${i===t?D(`ui.piWebApp.current`,` ✓ Current`):``}`,description:n}})}async pickModel(e){this.setState({modelDialog:void 0});let t=e.indexOf(`/`);t<=0||await this.sessions.setModel(e.slice(0,t),e.slice(t+1))}openThemeDialog(){this.navigateSettings(`general`)}pickTheme(e){this.plugins.getThemes().some(t=>t.id===e.themeId)&&(this.localThemePreference={...e},this.applyPreferredTheme(!0))}useDefaultTheme(){this.localThemePreference=void 0,be(),this.applyPreferredTheme(!1)}syncPluginStylesheets(){if(!this.isConnected)return;let e=this.resolveCurrentThemePreference().activeTheme;this.stylesheetRuntime.update([...this.plugins.getStylesheets(M(this.state)),...e?.stylesheets??[]])}applyPreferredTheme(e){this.syncPluginStylesheets();let t=this.resolveCurrentThemePreference().activeTheme;t!==void 0&&(this.activeThemeId=t.id,m(t),e&&_(this.themePreference))}resolveCurrentThemePreference(e=this.plugins.getThemes()){return mt({themes:e,themePairs:this.plugins.getThemePairs(),preference:this.themePreference,prefersLight:this.systemPrefersLight()})}systemPrefersLight(){return this.systemLightThemeMedia?.matches??!1}async openThinkingDialog(){let e=this.state.selectedSession===void 0?{machineId:M(this.state),sessionId:``,cwd:``}:{machineId:M(this.state),sessionId:this.state.selectedSession.id,cwd:this.state.selectedSession.cwd},t=await this.sessions.listThinkingLevels();if(!this.modelDialogOriginIsCurrent(e))return;let n=this.state.status?.thinkingLevel??`off`;this.setState({thinkingDialog:{instanceId:++this.modelDialogInstanceId,origin:e,title:D(`client.actions.choose.thinking.level.77e3b8`,`Choose thinking level`),selectedValue:n,defaultsLoading:!0,options:t.map(e=>{let t=xt(e,D);return{value:e,label:`${ct(e,D)}${e===n?D(`ui.piWebApp.current`,` ✓ Current`):``}`,...t===void 0?{}:{description:t}}})}}),this.loadSessionDefaultPins(e,`thinking`)}async loadSessionDefaultPins(e,t){let n=t===`model`?this.state.modelDialog?.instanceId:this.state.thinkingDialog?.instanceId,r=await this.sessions.getSessionDefaults();if(t===`model`){let t=this.state.modelDialog;if(t===void 0||t.instanceId!==n||!this.modelDialogOriginIsCurrent(e))return;let i=r?.defaultProvider!==void 0&&r.defaultModel!==void 0?`${r.defaultProvider}/${r.defaultModel}`:void 0;this.setState({modelDialog:{...t,defaultsLoading:!1,...i===void 0?{}:{defaultValue:i}}});return}let i=this.state.thinkingDialog;i!==void 0&&i.instanceId===n&&this.modelDialogOriginIsCurrent(e)&&this.setState({thinkingDialog:{...i,defaultsLoading:!1,...r?.defaultThinkingLevel===void 0?{}:{defaultValue:r.defaultThinkingLevel}}})}async pinSessionDefault(e,n){let r=e===`model`?this.state.modelDialog:this.state.thinkingDialog;if(r===void 0||!this.modelDialogOriginIsCurrent(r.origin))return;let{instanceId:i,origin:a}=r;if(e===`model`){let e=n.indexOf(`/`);if(e<=0)return;let t=await this.sessions.setSessionDefaults({provider:n.slice(0,e),modelId:n.slice(e+1)}),r=this.state.modelDialog;if(t?.defaultProvider===void 0||t.defaultModel===void 0||r?.instanceId!==i||!this.modelDialogOriginIsCurrent(a))return;this.setState({modelDialog:{...r,defaultValue:`${t.defaultProvider}/${t.defaultModel}`,defaultsLoading:!1}});return}if(!t(n))return;let o=await this.sessions.setSessionDefaults({thinkingLevel:n}),s=this.state.thinkingDialog;o?.defaultThinkingLevel!==void 0&&s?.instanceId===i&&this.modelDialogOriginIsCurrent(a)&&this.setState({thinkingDialog:{...s,defaultValue:o.defaultThinkingLevel,defaultsLoading:!1}})}async pickThinking(e){this.setState({thinkingDialog:void 0}),e!==``&&await this.sessions.setThinkingLevel(e)}async sendPrompt(e,t,n,r,i,a=[]){if(this.unacknowledgedActivitySessionKey()!==void 0)return!1;let o=n!==void 0&&n.length>0;if(a.length===0)return!o&&t===void 0&&this.auth.handleSlashCommand(e)?!1:!o&&t===void 0&&(e.trim()===`/model`||e.trim()===`/scoped-models`)?(this.openModelDialog(),!1):this.sessions.send(e,t,n,r,i);let s=a[0]?.target;if(s===void 0||a.some(e=>!Ma(e.target,s)||!this.plugins.promptChipOwnerAvailable(e.pluginId,s.machineId)))return!1;let c=await this.sessions.send(Na(e,a),t,n,r,i,s);return c&&this.plugins.promptChips.consume(a),c}selectedPromptChips(){let e=M(this.state),t=this.state.selectedSession,n=t===void 0?[]:this.plugins.promptChips.list({machineId:e,sessionId:t.id,cwd:t.cwd}).filter(t=>this.plugins.promptChipOwnerAvailable(t.pluginId,e));return(n.length!==this.visiblePromptChips.length||n.some((e,t)=>e!==this.visiblePromptChips[t]))&&(this.visiblePromptChips=n),this.visiblePromptChips}isReplacingPrompt(e){let t=e.selectedSession;if(t===void 0)return!1;let n=M(e),r=this.queuedMessageActionTarget,i=this.messageRevertTarget;return r?.action===`edit`&&r.machineId===n&&r.sessionId===t.id&&r.cwd===t.cwd||i?.machineId===n&&i.sessionId===t.id&&i.cwd===t.cwd&&i.path===t.path||e.pendingTreeActions.some(e=>e.machineId===n&&e.sessionId===t.id)}finishModelDialogMutation(){--this.modelDialogMutationInFlight,this.modelDialogMutationInFlight===0&&this.modelDialogRefreshPending&&(this.modelDialogRefreshPending=!1,this.refreshOpenModelDialog())}currentModelDialog(){let e=this.state.modelDialog;if(e!==void 0&&this.modelDialogOriginIsCurrent(e.origin))return e;e!==void 0&&this.setState({modelDialog:void 0})}modelDialogOriginIsCurrent(e){let t=this.state.selectedSession;return t!==void 0&&e.machineId===M(this.state)&&e.sessionId===t.id&&e.cwd===t.cwd}applyModelDialogCatalog(e,t){t!==void 0&&this.state.modelDialog?.instanceId===e.instanceId&&this.modelDialogOriginIsCurrent(e.origin)&&this.setState({modelDialog:{...e,catalog:t,options:this.modelDialogOptions(t.filter(e=>e.enabled))}})}renderChatView(e,t){let n=Ll(M(e),e.selectedWorkspace,t),r=JSON.stringify(n);return r!==this.chatWorkspaceContextKey&&(this.chatWorkspaceContextKey=r,this.chatWorkspaceContext=n),this.notificationViewInput!==e.selectedNotificationInbox&&(this.notificationViewInput=e.selectedNotificationInbox,this.notificationView=Bc(e.selectedNotificationInbox)),E`
|
|
3677
3677
|
<chat-view .onNavigationChange=${this.handleChatNavigationChange} .behaviors=${this.chatBehaviors} .canMutateQueuedMessages=${this.canMutateQueueMessage(t,M(e))} .queuedMessageActionPending=${this.queuedMessageActionTarget!==void 0||this.messageRevertTarget!==void 0||this.isReplacingPrompt(e)} .onQueuedMessageAction=${t.archived===!0?void 0:this.handleQueuedMessageAction} .onUseSuggestedInput=${t.archived===!0?void 0:this.handleUseSuggestedInput} .sessionCwd=${t.cwd} .onTranscriptRendered=${this.handleTranscriptRendered} .contentRendering=${this.plugins.chatContentRendering} .contentRendererVersion=${this.plugins.contentRendererVersion} .machineId=${M(e)} @workspace-file-open=${this.handleWorkspaceFileOpen} .workspaceContext=${this.chatWorkspaceContext} .sessionId=${t.id} .messages=${e.messages} .messageStart=${e.messagePageStart} .messageEnd=${e.messagePageEnd} .messageTotal=${e.messagePageTotal} .searchTarget=${e.sessionSearchTarget} .hasMore=${e.messagePageStart>0} .loadingMore=${e.isLoadingEarlierMessages} .isSendingPrompt=${e.sendingPrompts[t.id]===!0} .isCompacting=${e.status?.isCompacting===!0} .pendingMessageCount=${e.status?.pendingMessageCount??0} .clientQueuedMessages=${e.clientQueuedSessionMessages[t.id]??this.emptyClientQueue} .status=${e.status} .activity=${e.activity} .historyReady=${this.readyChatIdentity===Mw(e)} .pendingDialogs=${e.pendingDialogs} .closedDialogs=${e.closedDialogs} .onAnswerDialog=${this.handleAnswerDialog} .onCancelDialog=${this.handleCancelDialog} .onDismissClosedDialog=${this.handleDismissClosedDialog} .askDraftSessionId=${j(M(e),t.id)} .onSubmitAsk=${t.archived===!0?void 0:this.handleSubmitAsk} .notificationInbox=${this.notificationView} .canClearServerQueue=${this.canClearServerQueue()} .onClearServerQueue=${this.handleClearServerQueue} .onMessageAction=${this.handleMessageAction} .onDisplayedMessageAction=${this.handleDisplayedMessageAction} .messageActions=${this.plugins.getMessageActions(M(e))} .messageActionContext=${this.messageActionContext(e)} .onDismissWarning=${this.handleDismissWarning} .onDismissNotification=${this.handleDismissNotification} .onDismissAllNotifications=${this.handleDismissAllNotifications} .warningsVisible=${!this.sessionWarningVisibility.collapsed} .onToggleWarnings=${this.handleToggleWarnings} .onLoadMore=${this.handleLoadEarlierMessages}></chat-view>
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./PiWebApp-
|
|
2
|
-
import{I as e,J as t,L as n,R as r,V as i,X as a}from"./managementEmbed-Bx8Mwzdw.js";import{n as o,t as s}from"./preload-helper-XpATwJ5c.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();async function c(e=async()=>(await o(`pi-web-plugins/localization.json`,{shouldLoadPlugin:e=>e.id===`zh-cn`})).registrations){n(`en`,{});try{let i=(await e()).find(e=>e.id===`zh-cn`&&e.machineId===void 0);if(i!==void 0){let e=new AbortController,o=(await i.plugin.activate({apiVersion:4,pluginId:i.id,runtimePluginId:i.id,html:t,svg:a,translate:r,signal:e.signal,lifetimeSignal:e.signal})).contributions.localizations?.find(e=>e.locale===`zh-CN`);o!==void 0&&n(o.locale,o.messages)}}catch(e){console.warn(`Could not initialize UI localization; using English`,e)}}function l(t){t.documentElement.lang=e();let n=t.querySelector(`meta[name="description"]`);n!==null&&(n.content=r(`app.description`,`Remote web UI and browser control plane for persistent Pi Coding Agent sessions.`));let a=t.querySelector(`link[rel="manifest"]`);a!==null&&(a.href=i(e()===`zh-CN`?`pi-web-plugins/zh-cn/manifest.webmanifest`:`manifest.webmanifest`))}await c(),l(document),await s(()=>import(`./PiWebApp-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./PiWebApp-Do_8tp5d.js","./CommandPicker-gK2biReF.js","./managementEmbed-Bx8Mwzdw.js","./preload-helper-XpATwJ5c.js","./vendor-editor-core-BfnHL1Dg.js","./vendor-editor-languages-bNquDJP0.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{I as e,J as t,L as n,R as r,V as i,X as a}from"./managementEmbed-Bx8Mwzdw.js";import{n as o,t as s}from"./preload-helper-XpATwJ5c.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();async function c(e=async()=>(await o(`pi-web-plugins/localization.json`,{shouldLoadPlugin:e=>e.id===`zh-cn`})).registrations){n(`en`,{});try{let i=(await e()).find(e=>e.id===`zh-cn`&&e.machineId===void 0);if(i!==void 0){let e=new AbortController,o=(await i.plugin.activate({apiVersion:4,pluginId:i.id,runtimePluginId:i.id,html:t,svg:a,translate:r,signal:e.signal,lifetimeSignal:e.signal})).contributions.localizations?.find(e=>e.locale===`zh-CN`);o!==void 0&&n(o.locale,o.messages)}}catch(e){console.warn(`Could not initialize UI localization; using English`,e)}}function l(t){t.documentElement.lang=e();let n=t.querySelector(`meta[name="description"]`);n!==null&&(n.content=r(`app.description`,`Remote web UI and browser control plane for persistent Pi Coding Agent sessions.`));let a=t.querySelector(`link[rel="manifest"]`);a!==null&&(a.href=i(e()===`zh-CN`?`pi-web-plugins/zh-cn/manifest.webmanifest`:`manifest.webmanifest`))}await c(),l(document),await s(()=>import(`./PiWebApp-Do_8tp5d.js`),__vite__mapDeps([0,1,2,3,4,5]),import.meta.url);
|
package/dist/client/index.html
CHANGED
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
<link rel="apple-touch-icon" href="./apple-touch-icon.png" />
|
|
11
11
|
<link rel="manifest" crossorigin="use-credentials" href="./manifest.webmanifest" />
|
|
12
12
|
<style>:root{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark;--pi-control-font-size:16px;--pi-control-font-family:var(--pi-font,system-ui, sans-serif);--pi-control-monospace-font-family:var(--pi-mono,ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);--pi-bg:#0d1117;--pi-surface:#161b22;--pi-surface-hover:#21262d;--pi-terminal-bg:#05070a;--pi-terminal-text:#e6edf3;--pi-border:#30363d;--pi-border-muted:#21262d;--pi-text:#e6edf3;--pi-text-secondary:#c9d1d9;--pi-text-bright:#f0f6fc;--pi-muted:#8b949e;--pi-dim:#6e7681;--pi-accent:#58a6ff;--pi-accent-border:#2f81f7;--pi-selection-bg:#0d2847;--pi-success:#3fb950;--pi-success-border:#238636;--pi-success-bg:#0f1b12;--pi-success-surface:#0f2a16;--pi-success-ring:#3fb95055;--pi-warning:#d29922;--pi-warning-border:#6e5200;--pi-warning-surface:#1f1a10;--pi-danger:#ff7b72;--pi-purple:#d2a8ff;--pi-purple-border:#a371f7;--pi-purple-surface:#21132f;--pi-overlay:#0008;--pi-shadow-soft:#0006;--pi-shadow:#0008;--pi-shadow-strong:#000b;--pi-bg-overlay-soft:#0d1117dd;--pi-bg-overlay:#0d1117e6;--pi-success-bg-overlay:#0f1b12ee;--pi-terminal-selection:#264f78}html,body{background:var(--pi-bg);height:100%;color:var(--pi-text);margin:0;overflow:hidden}body{min-height:100dvh}</style>
|
|
13
|
-
<script type="module" crossorigin src="./assets/index-
|
|
13
|
+
<script type="module" crossorigin src="./assets/index-Ura0RJyr.js"></script>
|
|
14
14
|
<link rel="modulepreload" crossorigin href="./assets/managementEmbed-Bx8Mwzdw.js">
|
|
15
15
|
<link rel="modulepreload" crossorigin href="./assets/preload-helper-XpATwJ5c.js">
|
|
16
16
|
</head>
|
package/package.json
CHANGED